@telnyx/ai-agent-widget 0.36.1 → 0.36.2-beta.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.
Files changed (2) hide show
  1. package/dist/bundle.min.js +15 -15
  2. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,configurable:!0,writable:!0,value:ni}):vt[J]=ni;var B=(vt,J,ni)=>US(vt,typeof J!="symbol"?J+"":J,ni);(function(){"use strict";var vt,J,ni,si,Ra,xa,Da,La,Ks,Ys,Xs,Ma,Ji={},Oa=[],sp=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Qi=Array.isArray;function Ct(t,e){for(var i in e)t[i]=e[i];return t}function Js(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function lt(t,e,i){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?vt.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Zi(t,r,n,s,null)}function Zi(t,e,i,n,s){var o={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++ni,__i:-1,__u:0};return s==null&&J.vnode!=null&&J.vnode(o),o}function _t(t){return t.children}function yt(t,e){this.props=t,this.context=e}function Ci(t,e){if(e==null)return t.__?Ci(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?Ci(t):null}function Pa(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return Pa(t)}}function Qs(t){(!t.__d&&(t.__d=!0)&&si.push(t)&&!jn.__r++||Ra!=J.debounceRendering)&&((Ra=J.debounceRendering)||xa)(jn)}function jn(){for(var t,e,i,n,s,o,r,a=1;si.length;)si.length>a&&si.sort(Da),t=si.shift(),a=si.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=Ct({},n)).__v=n.__v+1,J.vnode&&J.vnode(i),Zs(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??Ci(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,Va(o,i,r),i.__e!=s&&Pa(i)));jn.__r=0}function Na(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,m,v,b,y=n&&n.__k||Oa,C=e.length;for(l=op(i,e,y,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Ji:y[p.__i]||Ji,p.__i=d,b=Zs(t,p,h,s,o,r,a,l,c,u),m=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&eo(h.ref,null,p),u.push(p.ref,p.__c||m,p)),v==null&&m!=null&&(v=m),4&p.__u||h.__k===p.__k?l=Fa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:m&&(l=m.nextSibling),p.__u&=-7);return i.__e=v,l}function op(t,e,i,n,s){var o,r,a,l,c,u=i.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Zi(null,r,null,null,null):Qi(r)?Zi(_t,{children:r},null,null,null):r.constructor==null&&r.__b>0?Zi(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=rp(r,i,l,d))!=-1&&(d--,(a=i[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=i[o])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=Ci(a)),ja(a,a));return n}function Fa(t,e,i){var n,s;if(typeof t.type=="function"){for(n=t.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=t,e=Fa(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=Ci(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Tt(t,e){return e=e||[],t==null||typeof t=="boolean"||(Qi(t)?t.some(function(i){Tt(i,e)}):e.push(t)),e}function rp(t,e,i,n){var s,o,r=t.key,a=t.type,l=e[i];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return i;if(n>(l!=null&&(2&l.__u)==0?1:0))for(s=i-1,o=i+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function Ua(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||sp.test(e)?i:i+"px"}function Hn(t,e,i,n,s){var o,r;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||Ua(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||Ua(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(La,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=i,i?n?i.u=n.u:(i.u=Ks,t.addEventListener(e,o?Xs:Ys,o)):t.removeEventListener(e,o?Xs:Ys,o);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function Ba(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Ks++;else if(e.t<i.u)return;return i(J.event?J.event(e):e)}}}function Zs(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,m,v,b,y,C,T,A,x,N,E,k,f,_,g=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=J.__b)&&u(e);e:if(typeof g=="function")try{if(y=e.props,C="prototype"in g&&g.prototype.render,T=(u=g.contextType)&&n[u.__c],A=u?T?T.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new g(y,A):(e.__c=d=new yt(y,A),d.constructor=g,d.render=lp),T&&T.sub(d),d.props=y,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&g.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Ct({},d.__s)),Ct(d.__s,g.getDerivedStateFromProps(y,d.__s))),p=d.props,m=d.state,d.__v=e,h)C&&g.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&g.getDerivedStateFromProps==null&&y!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,m,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,N=J.__r,E=0,C){for(d.state=d.__s,d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[]}else do d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(n=Ct(Ct({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,m)),f=u,u!=null&&u.type===_t&&u.key==null&&(f=$a(u.props.children)),a=Na(t,Qi(f)?f:[f],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(S){if(e.__v=null,l||o!=null)if(S.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(_=o.length;_--;)Js(o[_]);else e.__e=i.__e,e.__k=i.__k;J.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=ap(i.__e,e,i,n,s,o,r,l,c);return(u=J.diffed)&&u(e),128&e.__u?void 0:a}function Va(t,e,i){for(var n=0;n<i.length;n++)eo(i[n],i[++n],i[++n]);J.__c&&J.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){J.__e(o,s.__v)}})}function $a(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Qi(t)?t.map($a):Ct({},t)}function ap(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,m,v,b=i.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(J.__m&&J.__m(e,o),a=!1),o=null}if(C==null)b===y||a&&t.data==y||(t.data=y);else{if(o=o&&vt.call(t.childNodes),b=i.props||Ji,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Hn(t,c,null,p,s)}}for(c in y)p=y[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?m=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||Hn(t,c,p,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Na(e.type=="template"?t.content:t,Qi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&Ci(i,0),a,l),o!=null)for(c=o.length;c--;)Js(o[c]);a||(c="value",C=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[c]||C=="progress"&&!m||C=="option"&&m!=b[c])&&Hn(t,c,m,b[c],s),c="checked",v!=null&&v!=t[c]&&Hn(t,c,v,b[c],s))}return t}function eo(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){J.__e(s,i)}}function ja(t,e,i){var n,s;if(J.unmount&&J.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||eo(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){J.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&ja(n[s],e,i||typeof t.type!="function");i||Js(t.__e),t.__c=t.__=t.__e=void 0}function lp(t,e,i){return this.constructor(t,i)}function Wn(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),J.__&&J.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Zs(e,t=(!n&&i||e).__k=lt(_t,null,[t]),s||Ji,Ji,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?vt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),Va(o,t,r)}function Ha(t,e){Wn(t,e,Ha)}function to(t,e,i){var n,s,o,r,a=Ct({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?n=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?vt.call(arguments,2):i),Zi(t.type,a,n||t.key,s||t.ref,null)}function Nt(t){function e(i){var n,s;return this.getChildContext||(n=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&n.forEach(function(r){r.__e=!0,Qs(r)})},this.sub=function(o){n.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){n&&n.delete(o),r&&r.call(o)}}),i.children}return e.__c="__cC"+Ma++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}vt=Oa.slice,J={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},ni=0,yt.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ct({},this.state),typeof t=="function"&&(t=t(Ct({},i),this.props)),t&&Ct(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Qs(this))},yt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Qs(this))},yt.prototype.render=_t,si=[],xa=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Da=function(t,e){return t.__v.__b-e.__v.__b},jn.__r=0,La=/(PointerCapture)$|Capture$/i,Ks=0,Ys=Ba(!1),Xs=Ba(!0),Ma=0;var cp=0;function D(t,e,i,n,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cp,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return J.vnode&&J.vnode(c),c}function io(){return(io=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t}).apply(this,arguments)}var dp=["context","children"];function up(t){this.getChildContext=function(){return t.context};var e=t.children,i=function(n,s){if(n==null)return{};var o,r,a={},l=Object.keys(n);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=n[o]);return a}(t,dp);return to(e,i)}function hp(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=lt(up,io({},this._props,{context:t.detail.context}),function e(i,n){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;var s=[],o={},r=0,a=i.attributes,l=i.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Wa(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=lt(Ga,{name:u},c):s[r]=c}var d=n?lt(Ga,null,s):s;return lt(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ha:Wn)(this._vdom,this._root)}function Wa(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function fp(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[Wa(t)]=i,this._vdom=to(this._vdom,n),Wn(this._vdom,this._root)}}function pp(){Wn(this._vdom=null,this._root)}function Ga(t,e){var i=this;return lt("slot",io({},t,{ref:function(n){n?(i.ref=n,i._listener||(i._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function gp(t,e,i,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=hp,s.prototype.attributeChangedCallback=fp,s.prototype.disconnectedCallback=pp,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=i,i.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var Gt,we,no,qa,en=0,za=[],Te=J,Ka=Te.__b,Ya=Te.__r,Xa=Te.diffed,Ja=Te.__c,Qa=Te.unmount,Za=Te.__;function Ti(t,e){Te.__h&&Te.__h(we,t,en||e),en=0;var i=we.__H||(we.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function ve(t){return en=1,el(il,t)}function el(t,e,i){var n=Ti(Gt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):il(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=we,!we.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};we.__f=!0;var o=we.shouldComponentUpdate,r=we.componentWillUpdate;we.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},we.shouldComponentUpdate=s}return n.__N||n.__}function Le(t,e){var i=Ti(Gt++,3);!Te.__s&&ao(i.__H,e)&&(i.__=t,i.u=e,we.__H.__h.push(i))}function so(t,e){var i=Ti(Gt++,4);!Te.__s&&ao(i.__H,e)&&(i.__=t,i.u=e,we.__h.push(i))}function ce(t){return en=5,ct(function(){return{current:t}},[])}function ct(t,e){var i=Ti(Gt++,7);return ao(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ne(t,e){return en=8,ct(function(){return t},e)}function Fe(t){var e=we.context[t.__c],i=Ti(Gt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(we)),e.props.value):t.__}function mp(t,e){Te.useDebugValue&&Te.useDebugValue(e?e(t):t)}function oo(){var t=Ti(Gt++,11);if(!t.__){for(var e=we.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var i=e.__m||(e.__m=[0,0]);t.__="P"+i[0]+"-"+i[1]++}return t.__}function vp(){for(var t;t=za.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Gn),t.__H.__h.forEach(ro),t.__H.__h=[]}catch(e){t.__H.__h=[],Te.__e(e,t.__v)}}Te.__b=function(t){we=null,Ka&&Ka(t)},Te.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Za&&Za(t,e)},Te.__r=function(t){Ya&&Ya(t),Gt=0;var e=(we=t.__c).__H;e&&(no===we?(e.__h=[],we.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Gn),e.__h.forEach(ro),e.__h=[],Gt=0)),no=we},Te.diffed=function(t){Xa&&Xa(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(za.push(e)!==1&&qa===Te.requestAnimationFrame||((qa=Te.requestAnimationFrame)||_p)(vp)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),no=we=null},Te.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Gn),i.__h=i.__h.filter(function(n){return!n.__||ro(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Te.__e(n,i.__v)}}),Ja&&Ja(t,e)},Te.unmount=function(t){Qa&&Qa(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Gn(n)}catch(s){e=s}}),i.__H=void 0,e&&Te.__e(e,i.__v))};var tl=typeof requestAnimationFrame=="function";function _p(t){var e,i=function(){clearTimeout(n),tl&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);tl&&(e=requestAnimationFrame(i))}function Gn(t){var e=we,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),we=e}function ro(t){var e=we;t.__c=t.__(),we=e}function ao(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function il(t,e){return typeof e=="function"?e(t):e}const tn={},nl=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,sl=t=>"init"in t,lo=t=>!!t.write,ol=t=>"v"in t||"e"in t,qn=t=>{if("e"in t)throw t.e;if((tn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},zn=new WeakMap,rl=t=>{var e;return Kn(t)&&!!((e=zn.get(t))!=null&&e[0])},yp=t=>{const e=zn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},al=(t,e)=>{let i=zn.get(t);if(!i){i=[!0,new Set],zn.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Kn=t=>typeof(t==null?void 0:t.then)=="function",ll=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},co=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Kn(e))for(const r of n.d.keys())ll(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Kn(o)&&yp(o))},cl=(t,e,i)=>{var n;const s=new Set;for(const o of((n=i.get(t))==null?void 0:n.t)||[])i.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},bp=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},uo=()=>{const t={},e=new WeakMap,i=n=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(n)),(o=e.get(n))==null||o.forEach(r=>r())};return i.add=(n,s)=>{const o=n||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},i},wp=t=>(t.c||(t.c=uo()),t.m||(t.m=uo()),t.u||(t.u=uo()),t.f||(t.f=bp()),t),Sp=Symbol(),dl=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...p)=>h.read(...p),l=(h,...p)=>h.write(...p),c=(h,p)=>{var m;return(m=h.unstable_onInit)==null?void 0:m.call(h,p)},u=(h,p)=>{var m;return(m=h.onMount)==null?void 0:m.call(h,p)},...d)=>{const h=d[0]||(E=>{if((tn?"production":void 0)!=="production"&&!E)throw new Error("Atom is undefined or null");let k=t.get(E);return k||(k={d:new Map,p:new Set,n:0},t.set(E,k),c==null||c(E,N)),k}),p=d[1]||(()=>{const E=[],k=f=>{try{f()}catch(_){E.push(_)}};do{r.f&&k(r.f);const f=new Set,_=f.add.bind(f);n.forEach(g=>{var S;return(S=e.get(g))==null?void 0:S.l.forEach(_)}),n.clear(),o.forEach(_),o.clear(),s.forEach(_),s.clear(),f.forEach(k),n.size&&m()}while(n.size||o.size||s.size);if(E.length)throw new AggregateError(E)}),m=d[2]||(()=>{const E=[],k=new WeakSet,f=new WeakSet,_=Array.from(n);for(;_.length;){const g=_[_.length-1],S=h(g);if(f.has(g)){_.pop();continue}if(k.has(g)){if(i.get(g)===S.n)E.push([g,S]);else if((tn?"production":void 0)!=="production"&&i.has(g))throw new Error("[Bug] invalidated atom exists");f.add(g),_.pop();continue}k.add(g);for(const I of cl(g,S,e))k.has(I)||_.push(I)}for(let g=E.length-1;g>=0;--g){const[S,I]=E[g];let M=!1;for(const R of I.d.keys())if(R!==S&&n.has(R)){M=!0;break}M&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(E=>{var k;const f=h(E);if(ol(f)&&(e.has(E)&&i.get(E)!==f.n||Array.from(f.d).every(([O,L])=>v(O).n===L)))return f;f.d.clear();let _=!0;const g=()=>{e.has(E)&&(C(E),m(),p())},S=O=>{var L;if(nl(E,O)){const $=h(O);if(!ol($))if(sl(O))co(O,O.init,h);else throw new Error("no atom init");return qn($)}const V=v(O);try{return qn(V)}finally{f.d.set(O,V.n),rl(f.v)&&ll(E,f.v,V),(L=e.get(O))==null||L.t.add(E),_||g()}};let I,M;const R={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(tn?"production":void 0)!=="production"&&!lo(E)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&lo(E)&&(M=(...O)=>{if((tn?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return y(E,...O)}finally{m(),p()}}),M}},P=f.n;try{const O=a(E,S,R);return co(E,O,h),Kn(O)&&(al(O,()=>I==null?void 0:I.abort()),O.then(g,g)),f}catch(O){return delete f.v,f.e=O,++f.n,f}finally{_=!1,P!==f.n&&i.get(E)===P&&(i.set(E,f.n),n.add(E),(k=r.c)==null||k.call(r,E))}}),b=d[4]||(E=>{const k=[E];for(;k.length;){const f=k.pop(),_=h(f);for(const g of cl(f,_,e)){const S=h(g);i.set(g,S.n),k.push(g)}}}),y=d[5]||((E,...k)=>{let f=!0;const _=S=>qn(v(S)),g=(S,...I)=>{var M;const R=h(S);try{if(nl(E,S)){if(!sl(S))throw new Error("atom not writable");const P=R.n,O=I[0];co(S,O,h),C(S),P!==R.n&&(n.add(S),(M=r.c)==null||M.call(r,S),b(S));return}else return y(S,...I)}finally{f||(m(),p())}};try{return l(E,_,g,...k)}finally{f=!1}}),C=d[6]||(E=>{var k;const f=h(E),_=e.get(E);if(_&&!rl(f.v)){for(const[g,S]of f.d)if(!_.d.has(g)){const I=h(g);T(g).t.add(E),_.d.add(g),S!==I.n&&(n.add(g),(k=r.c)==null||k.call(r,g),b(g))}for(const g of _.d||[])if(!f.d.has(g)){_.d.delete(g);const S=A(g);S==null||S.t.delete(E)}}}),T=d[7]||(E=>{var k;const f=h(E);let _=e.get(E);if(!_){v(E);for(const g of f.d.keys())T(g).t.add(E);if(_={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(E,_),(k=r.m)==null||k.call(r,E),lo(E)){const g=()=>{let S=!0;const I=(...M)=>{try{return y(E,...M)}finally{S||(m(),p())}};try{const M=u(E,I);M&&(_.u=()=>{S=!0;try{M()}finally{S=!1}})}finally{S=!1}};s.add(g)}}return _}),A=d[8]||(E=>{var k;const f=h(E);let _=e.get(E);if(_&&!_.l.size&&!Array.from(_.t).some(g=>{var S;return(S=e.get(g))==null?void 0:S.d.has(E)})){_.u&&o.add(_.u),_=void 0,e.delete(E),(k=r.u)==null||k.call(r,E);for(const g of f.d.keys()){const S=A(g);S==null||S.t.delete(E)}return}return _}),x=[t,e,i,n,s,o,r,a,l,c,u,h,p,m,v,b,y,C,T,A],N={get:E=>qn(v(E)),set:(E,...k)=>{try{return y(E,...k)}finally{m(),p()}},sub:(E,k)=>{const _=T(E).l;return _.add(k),p(),()=>{_.delete(k),A(E),p()}}};return Object.defineProperty(N,Sp,{value:x}),N},Cp=wp,ul=al,ho={};let Tp=0;function Yn(t,e){const i=`atom${++Tp}`,n={toString(){return(ho?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=kp,n.write=Ep),n}function kp(t){return t(this)}function Ep(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const Ip=()=>{let t=0;const e=Cp({}),i=new WeakMap,n=new WeakMap,s=dl(i,n,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=i.get(a);l.m=n.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=i.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),i),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function Ap(){return(ho?"production":void 0)!=="production"?Ip():dl()}let nn;function Rp(){return nn||(nn=Ap(),(ho?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=nn),globalThis.__JOTAI_DEFAULT_STORE__!==nn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),nn}function hl(t,e){for(var i in e)t[i]=e[i];return t}function fl(t,e){for(var i in t)if(i!=="__source"&&!(i in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}var pl=so;function gl(t,e){this.props=t,this.context=e}(gl.prototype=new yt).isPureReactComponent=!0,gl.prototype.shouldComponentUpdate=function(t,e){return fl(this.props,t)||fl(this.state,e)};var ml=J.__b;J.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ml&&ml(t)};var xp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Dp(t){function e(i){var n=hl({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=xp,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var vl=function(t,e){return t==null?null:Tt(Tt(t).map(e))},Lp={map:vl,forEach:vl,count:function(t){return t?Tt(t).length:0},only:function(t){var e=Tt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Tt},Mp=J.__e;J.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}Mp(t,e,i,n)};var _l=J.unmount;function yl(t,e,i){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=hl({},t)).__c!=null&&(t.__c.__P===i&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return yl(n,e,i)})),t}function bl(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return bl(n,e,i)}),t.__c&&t.__c.__P===e&&(t.__e&&i.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=i)),t}function fo(){this.__u=0,this.o=null,this.__b=null}function wl(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Xn(){this.i=null,this.l=null}J.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),_l&&_l(t)},(fo.prototype=new yt).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=wl(n.__v),o=!1,r=function(){o||(o=!0,i.__R=null,s?s(a):a())};i.__R=r;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=bl(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(r,r)},fo.prototype.componentWillUnmount=function(){this.o=[]},fo.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var i=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=yl(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&lt(_t,null,t.fallback);return s&&(s.__u&=-33),[lt(_t,null,e.__a?null:t.children),s]};var Sl=function(t,e,i){if(++i[1]===i[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(i=t.i;i;){for(;i.length>3;)i.pop()();if(i[1]<i[0])break;t.i=i=i[2]}};(Xn.prototype=new yt).__a=function(t){var e=this,i=wl(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Sl(e,t,n)):s()};i?i(o):o()}},Xn.prototype.render=function(t){this.i=null,this.l=new Map;var e=Tt(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var i=e.length;i--;)this.l.set(e[i],this.i=[1,0,this.i]);return t.children},Xn.prototype.componentDidUpdate=Xn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Sl(t,i,e)})};var Cl=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Op=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Pp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Np=/[A-Z0-9]/g,Fp=typeof document<"u",Up=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};yt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(yt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Tl=J.event;function Bp(){}function Vp(){return this.cancelBubble}function $p(){return this.defaultPrevented}J.event=function(t){return Tl&&(t=Tl(t)),t.persist=Bp,t.isPropagationStopped=Vp,t.isDefaultPrevented=$p,t.nativeEvent=t};var jp={enumerable:!1,configurable:!0,get:function(){return this.class}},kl=J.vnode;J.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||Fp&&r==="children"&&n==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in i&&i.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||n!=="input"&&n!=="textarea"||Up(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Pp.test(r)&&(r=l):l=r="oninput":o&&Op.test(r)?r=r.replace(Np,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}n=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=Tt(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=Tt(i.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),i.class&&!i.className?(s.class=i.class,Object.defineProperty(s,"className",jp)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=Cl,kl&&kl(t)};var El=J.__r;J.__r=function(t){El&&El(t),t.__c};var Il=J.diffed;J.diffed=function(t){Il&&Il(t);var e=t.props,i=t.__e;i!=null&&t.type==="textarea"&&"value"in e&&e.value!==i.value&&(i.value=e.value==null?"":e.value)};function Al(t){return!!t&&t.$$typeof===Cl}function Hp(t){return Al(t)?to.apply(null,arguments):t}var Rl={};const Wp={},Gp=Nt(void 0);function xl(t){return Fe(Gp)||Rp()}const po=t=>typeof(t==null?void 0:t.then)=="function",go=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},qp=Rl.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(go(t),t)}),mo=new WeakMap,Dl=(t,e)=>{let i=mo.get(t);return i||(i=new Promise((n,s)=>{let o=t;const r=c=>u=>{o===c&&n(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();po(c)?(mo.set(c,i),o=c,c.then(r(c),a(c)),ul(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),ul(t,l)}),mo.set(t,i)),i};function vo(t,e){const{delay:i,unstable_promiseStatus:n=!Rl.use}={},s=xl(),[[o,r,a],l]=el(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),Le(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);po(d)&&go(Dl(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),mp(c),po(c)){const u=Dl(c,()=>s.get(t));return n&&go(u),qp(u)}return c}function Jn(t,e){const i=xl();return Ne((...s)=>{if((Wp?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Ll(t,e){return[vo(t),Jn(t)]}const _o=Nt({});function Qn(t){const e=ce(null);return e.current===null&&(e.current=t()),e.current}const yo=typeof window<"u",Ml=yo?so:Le,Zn=Nt(null);function bo(t,e){t.indexOf(e)===-1&&t.push(e)}function wo(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const Ft=(t,e,i)=>i>e?e:i<t?t:i;let So=()=>{};const Ut={},Ol=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Pl(t){return typeof t=="object"&&t!==null}const Nl=t=>/^0[^.\s]+$/u.test(t);function Co(t){let e;return()=>(e===void 0&&(e=t()),e)}const dt=t=>t,zp=(t,e)=>i=>e(t(i)),sn=(...t)=>t.reduce(zp),on=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class To{constructor(){this.subscriptions=[]}add(e){return bo(this.subscriptions,e),()=>wo(this.subscriptions,e)}notify(e,i,n){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,i,n);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,i,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const kt=t=>t*1e3,Et=t=>t/1e3;function Fl(t,e){return e?t*(1e3/e):0}const Ul=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Kp=1e-7,Yp=12;function Xp(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=Ul(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Kp&&++a<Yp);return r}function rn(t,e,i,n){if(t===e&&i===n)return dt;const s=o=>Xp(o,0,1,t,i);return o=>o===0||o===1?o:Ul(s(o),e,n)}const Bl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Vl=t=>e=>1-t(1-e),$l=rn(.33,1.53,.69,.99),ko=Vl($l),jl=Bl(ko),Hl=t=>(t*=2)<1?.5*ko(t):.5*(2-Math.pow(2,-10*(t-1))),Eo=t=>1-Math.sin(Math.acos(t)),Wl=Vl(Eo),Gl=Bl(Eo),Jp=rn(.42,0,1,1),Qp=rn(0,0,.58,1),ql=rn(.42,0,.58,1),Zp=t=>Array.isArray(t)&&typeof t[0]!="number",zl=t=>Array.isArray(t)&&typeof t[0]=="number",eg={linear:dt,easeIn:Jp,easeInOut:ql,easeOut:Qp,circIn:Eo,circInOut:Gl,circOut:Wl,backIn:ko,backInOut:jl,backOut:$l,anticipate:Hl},tg=t=>typeof t=="string",Kl=t=>{if(zl(t)){So(t.length===4);const[e,i,n,s]=t;return rn(e,i,n,s)}else if(tg(t))return eg[t];return t},es=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Yl={value:null};function ig(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,p=!1)=>{const v=p&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&Yl.value&&Yl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const ng=40;function Xl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=es.reduce((T,A)=>(T[A]=ig(o,e?A:void 0),T),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:m}=r,v=()=>{const T=Ut.useManualTiming?s.timestamp:performance.now();i=!1,Ut.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(T-s.timestamp,ng),1)),s.timestamp=T,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),m.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:es.reduce((T,A)=>{const x=r[A];return T[A]=(N,E=!1,k=!1)=>(i||b(),x.schedule(N,E,k)),T},{}),cancel:T=>{for(let A=0;A<es.length;A++)r[es[A]].cancel(T)},state:s,steps:r}}const{schedule:Ce,cancel:qt,state:$e,steps:Io}=Xl(typeof requestAnimationFrame<"u"?requestAnimationFrame:dt,!0);let ts;function sg(){ts=void 0}const tt={now:()=>(ts===void 0&&tt.set($e.isProcessing||Ut.useManualTiming?$e.timestamp:performance.now()),ts),set:t=>{ts=t,queueMicrotask(sg)}},Jl=t=>e=>typeof e=="string"&&e.startsWith(t),Ao=Jl("--"),og=Jl("var(--"),Ro=t=>og(t)?rg.test(t.split("/*")[0].trim()):!1,rg=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ki={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},an={...ki,transform:t=>Ft(0,1,t)},is={...ki,default:1},ln=t=>Math.round(t*1e5)/1e5,xo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ag(t){return t==null}const lg=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Do=(t,e)=>i=>!!(typeof i=="string"&&lg.test(i)&&i.startsWith(t)||e&&!ag(i)&&Object.prototype.hasOwnProperty.call(i,e)),Ql=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(xo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},cg=t=>Ft(0,255,t),Lo={...ki,transform:t=>Math.round(cg(t))},oi={test:Do("rgb","red"),parse:Ql("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+Lo.transform(t)+", "+Lo.transform(e)+", "+Lo.transform(i)+", "+ln(an.transform(n))+")"};function dg(t){let e="",i="",n="",s="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),n=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),n=t.substring(3,4),s=t.substring(4,5),e+=e,i+=i,n+=n,s+=s),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:s?parseInt(s,16)/255:1}}const Mo={test:Do("#"),parse:dg,transform:oi.transform},cn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),zt=cn("deg"),It=cn("%"),Q=cn("px"),ug=cn("vh"),hg=cn("vw"),Zl={...It,parse:t=>It.parse(t)/100,transform:t=>It.transform(t*100)},Ei={test:Do("hsl","hue"),parse:Ql("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+It.transform(ln(e))+", "+It.transform(ln(i))+", "+ln(an.transform(n))+")"},Me={test:t=>oi.test(t)||Mo.test(t)||Ei.test(t),parse:t=>oi.test(t)?oi.parse(t):Ei.test(t)?Ei.parse(t):Mo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?oi.transform(t):Ei.transform(t),getAnimatableNone:t=>{const e=Me.parse(t);return e.alpha=0,Me.transform(e)}},fg=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function pg(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(xo))==null?void 0:e.length)||0)+(((i=t.match(fg))==null?void 0:i.length)||0)>0}const ec="number",tc="color",gg="var",mg="var(",ic="${}",vg=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function dn(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(vg,l=>(Me.test(l)?(n.color.push(o),s.push(tc),i.push(Me.parse(l))):l.startsWith(mg)?(n.var.push(o),s.push(gg),i.push(l)):(n.number.push(o),s.push(ec),i.push(parseFloat(l))),++o,ic)).split(ic);return{values:i,split:a,indexes:n,types:s}}function nc(t){return dn(t).values}function sc(t){const{split:e,types:i}=dn(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===ec?o+=ln(s[r]):a===tc?o+=Me.transform(s[r]):o+=s[r]}return o}}const _g=t=>typeof t=="number"?0:Me.test(t)?Me.getAnimatableNone(t):t;function yg(t){const e=nc(t);return sc(t)(e.map(_g))}const Kt={test:pg,parse:nc,createTransformer:sc,getAnimatableNone:yg};function Oo(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function bg({hue:t,saturation:e,lightness:i,alpha:n}){t/=360,e/=100,i/=100;let s=0,o=0,r=0;if(!e)s=o=r=i;else{const a=i<.5?i*(1+e):i+e-i*e,l=2*i-a;s=Oo(l,a,t+1/3),o=Oo(l,a,t),r=Oo(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function ns(t,e){return i=>i>0?e:t}const ke=(t,e,i)=>t+(e-t)*i,Po=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},wg=[Mo,oi,Ei],Sg=t=>wg.find(e=>e.test(t));function oc(t){const e=Sg(t);if(!e)return!1;let i=e.parse(t);return e===Ei&&(i=bg(i)),i}const rc=(t,e)=>{const i=oc(t),n=oc(e);if(!i||!n)return ns(t,e);const s={...i};return o=>(s.red=Po(i.red,n.red,o),s.green=Po(i.green,n.green,o),s.blue=Po(i.blue,n.blue,o),s.alpha=ke(i.alpha,n.alpha,o),oi.transform(s))},No=new Set(["none","hidden"]);function Cg(t,e){return No.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function Tg(t,e){return i=>ke(t,e,i)}function Fo(t){return typeof t=="number"?Tg:typeof t=="string"?Ro(t)?ns:Me.test(t)?rc:Ig:Array.isArray(t)?ac:typeof t=="object"?Me.test(t)?rc:kg:ns}function ac(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>Fo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function kg(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=Fo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function Eg(t,e){const i=[],n={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][n[o]],a=t.values[r]??0;i[s]=a,n[o]++}return i}const Ig=(t,e)=>{const i=Kt.createTransformer(e),n=dn(t),s=dn(e);return n.indexes.var.length===s.indexes.var.length&&n.indexes.color.length===s.indexes.color.length&&n.indexes.number.length>=s.indexes.number.length?No.has(t)&&!s.values.length||No.has(e)&&!n.values.length?Cg(t,e):sn(ac(Eg(n,s),s.values),i):ns(t,e)};function lc(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?ke(t,e,i):Fo(t)(t,e)}const Ag=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>Ce.update(e,i),stop:()=>qt(e),now:()=>$e.isProcessing?$e.timestamp:tt.now()}},cc=(t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let o=0;o<s;o++)n+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${n.substring(0,n.length-2)})`},ss=2e4;function Uo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<ss;)e+=i,n=t.next(e);return e>=ss?1/0:e}function Rg(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(Uo(n),ss);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:Et(s)}}const xg=5;function dc(t,e,i){const n=Math.max(e-xg,0);return Fl(i-t(n),e-n)}const Ie={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Bo=.001;function Dg({duration:t=Ie.duration,bounce:e=Ie.bounce,velocity:i=Ie.velocity,mass:n=Ie.mass}){let s,o,r=1-e;r=Ft(Ie.minDamping,Ie.maxDamping,r),t=Ft(Ie.minDuration,Ie.maxDuration,Et(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,p=Vo(c,r),m=Math.exp(-d);return Bo-h/p*m},o=c=>{const d=c*r*t,h=d*i+i,p=Math.pow(r,2)*Math.pow(c,2)*t,m=Math.exp(-d),v=Vo(Math.pow(c,2),r);return(-s(c)+Bo>0?-1:1)*((h-p)*m)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-Bo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Mg(s,o,a);if(t=kt(t),isNaN(l))return{stiffness:Ie.stiffness,damping:Ie.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const Lg=12;function Mg(t,e,i){let n=i;for(let s=1;s<Lg;s++)n=n-t(n)/e(n);return n}function Vo(t,e){return t*Math.sqrt(1-e*e)}const Og=["duration","bounce"],Pg=["stiffness","damping","mass"];function uc(t,e){return e.some(i=>t[i]!==void 0)}function Ng(t){let e={velocity:Ie.velocity,stiffness:Ie.stiffness,damping:Ie.damping,mass:Ie.mass,isResolvedFromDuration:!1,...t};if(!uc(t,Pg)&&uc(t,Og))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*Ft(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ie.mass,stiffness:s,damping:o}}else{const i=Dg(t);e={...e,...i,mass:Ie.mass},e.isResolvedFromDuration=!0}return e}function os(t=Ie.visualDuration,e=Ie.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:p}=Ng({...i,velocity:-Et(i.velocity||0)}),m=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,y=Et(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Ie.restSpeed.granular:Ie.restSpeed.default),s||(s=C?Ie.restDelta.granular:Ie.restDelta.default);let T;if(v<1){const x=Vo(y,v);T=N=>{const E=Math.exp(-v*y*N);return r-E*((m+v*y*b)/x*Math.sin(x*N)+b*Math.cos(x*N))}}else if(v===1)T=x=>r-Math.exp(-y*x)*(b+(m+y*b)*x);else{const x=y*Math.sqrt(v*v-1);T=N=>{const E=Math.exp(-v*y*N),k=Math.min(x*N,300);return r-E*((m+v*y*b)*Math.sinh(k)+x*b*Math.cosh(k))/x}}const A={calculatedDuration:p&&d||null,next:x=>{const N=T(x);if(p)a.done=x>=d;else{let E=x===0?m:0;v<1&&(E=x===0?kt(m):dc(T,x,N));const k=Math.abs(E)<=n,f=Math.abs(r-N)<=s;a.done=k&&f}return a.value=a.done?r:N,a},toString:()=>{const x=Math.min(Uo(A),ss),N=cc(E=>A.next(x*E).value,x,30);return x+"ms "+N},toTransition:()=>{}};return A}os.applyToOptions=t=>{const e=Rg(t,100,os);return t.ease=e.ease,t.duration=kt(e.duration),t.type="keyframes",t};function $o({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=k=>a!==void 0&&k<a||l!==void 0&&k>l,m=k=>a===void 0?l:l===void 0||Math.abs(a-k)<Math.abs(l-k)?a:l;let v=i*e;const b=d+v,y=r===void 0?b:r(b);y!==b&&(v=y-d);const C=k=>-v*Math.exp(-k/n),T=k=>y+C(k),A=k=>{const f=C(k),_=T(k);h.done=Math.abs(f)<=c,h.value=h.done?y:_};let x,N;const E=k=>{p(h.value)&&(x=k,N=os({keyframes:[h.value,m(h.value)],velocity:dc(T,k,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return E(0),{calculatedDuration:null,next:k=>{let f=!1;return!N&&x===void 0&&(f=!0,A(k),E(k)),x!==void 0&&k>=x?N.next(k-x):(!f&&A(k),h)}}}function Fg(t,e,i){const n=[],s=i||Ut.mix||lc,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||dt:e;a=sn(l,a)}n.push(a)}return n}function Ug(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(So(o===e.length),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Fg(e,n,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=on(t[d],t[d+1],u);return a[d](h)};return i?u=>c(Ft(t[0],t[o-1],u)):c}function Bg(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=on(0,e,n);t.push(ke(i,1,s))}}function Vg(t){const e=[0];return Bg(e,t.length-1),e}function $g(t,e){return t.map(i=>i*e)}function jg(t,e){return t.map(()=>e||ql).splice(0,t.length-1)}function un({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Zp(n)?n.map(Kl):Kl(n),o={done:!1,value:e[0]},r=$g(i&&i.length===e.length?i:Vg(e),t),a=Ug(r,e,{ease:Array.isArray(s)?s:jg(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Hg=t=>t!==null;function jo(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Hg),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Wg={decay:$o,inertia:$o,tween:un,keyframes:un,spring:os};function hc(t){typeof t.type=="string"&&(t.type=Wg[t.type])}class Ho{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const Gg=t=>t/100;class Wo extends Ho{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==tt.now()&&this.tick(tt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(n=this.options).onStop)==null||s.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;hc(e);const{type:i=un,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||un;l!==un&&typeof a[0]!="number"&&(this.mixKeyframes=sn(Gg,lc(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=Uo(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:p,type:m,onUpdate:v,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),i?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let T=this.currentTime,A=n;if(d){const k=Math.min(this.currentTime,s)/a;let f=Math.floor(k),_=k%1;!_&&k>=1&&(_=1),_===1&&f--,f=Math.min(f,d+1),!!(f%2)&&(h==="reverse"?(_=1-_,p&&(_-=p/a)):h==="mirror"&&(A=r)),T=Ft(0,1,_)*a}const x=C?{done:!1,value:u[0]}:A.next(T);o&&(x.value=o(x.value));let{done:N}=x;!C&&l!==null&&(N=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return E&&m!==$o&&(x.value=jo(u,this.options,b,this.speed)),v&&v(x.value),E&&this.finish(),x}then(e,i){return this.finished.then(e,i)}get duration(){return Et(this.calculatedDuration)}get time(){return Et(this.currentTime)}set time(e){var i;e=kt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(i=this.driver)==null||i.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(tt.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=Et(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Ag,startTime:i}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=i??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(tt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function qg(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const ri=t=>t*180/Math.PI,Go=t=>{const e=ri(Math.atan2(t[1],t[0]));return qo(e)},zg={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Go,rotateZ:Go,skewX:t=>ri(Math.atan(t[1])),skewY:t=>ri(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},qo=t=>(t=t%360,t<0&&(t+=360),t),fc=Go,pc=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),gc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Kg={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:pc,scaleY:gc,scale:t=>(pc(t)+gc(t))/2,rotateX:t=>qo(ri(Math.atan2(t[6],t[5]))),rotateY:t=>qo(ri(Math.atan2(-t[2],t[0]))),rotateZ:fc,rotate:fc,skewX:t=>ri(Math.atan(t[4])),skewY:t=>ri(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function zo(t){return t.includes("scale")?1:0}function Ko(t,e){if(!t||t==="none")return zo(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Kg,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=zg,s=a}if(!s)return zo(e);const o=n[e],r=s[1].split(",").map(Xg);return typeof o=="function"?o(r):r[o]}const Yg=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Ko(i,e)};function Xg(t){return parseFloat(t.trim())}const Ii=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ai=new Set(Ii),mc=t=>t===ki||t===Q,Jg=new Set(["x","y","z"]),Qg=Ii.filter(t=>!Jg.has(t));function Zg(t){const e=[];return Qg.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const ai={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Ko(e,"x"),y:(t,{transform:e})=>Ko(e,"y")};ai.translateX=ai.x,ai.translateY=ai.y;const li=new Set;let Yo=!1,Xo=!1,Jo=!1;function vc(){if(Xo){const t=Array.from(li).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=Zg(n);s.length&&(i.set(n,s),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const s=i.get(n);s&&s.forEach(([o,r])=>{var a;(a=n.getValue(o))==null||a.set(r)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}Xo=!1,Yo=!1,li.forEach(t=>t.complete(Jo)),li.clear()}function _c(){li.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Xo=!0)})}function em(){Jo=!0,_c(),vc(),Jo=!1}class Qo{constructor(e,i,n,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=n,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(li.add(this),Yo||(Yo=!0,Ce.read(_c),Ce.resolveKeyframes(vc))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:n,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(n&&i){const a=n.readValue(i,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}qg(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),li.delete(this)}cancel(){this.state==="scheduled"&&(li.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const tm=t=>t.startsWith("--");function im(t,e,i){tm(e)?t.style.setProperty(e,i):t.style[e]=i}const nm=Co(()=>window.ScrollTimeline!==void 0),sm={};function om(t,e){const i=Co(t);return()=>sm[e]??i()}const yc=om(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),hn=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,bc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:hn([0,.65,.55,1]),circOut:hn([.55,0,1,.45]),backIn:hn([.31,.01,.66,-.59]),backOut:hn([.33,1.53,.69,.99])};function wc(t,e){if(t)return typeof t=="function"?yc()?cc(t,e):"ease-out":zl(t)?hn(t):Array.isArray(t)?t.map(i=>wc(i,e)||bc.easeOut):bc[t]}function rm(t,e,i,{delay:n=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:i};l&&(u.offset=l);const d=wc(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function Sc(t){return typeof t=="function"&&"applyToOptions"in t}function am({type:t,...e}){return Sc(t)&&yc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class lm extends Ho{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,So(typeof e.type!="string");const c=am(e);this.animation=rm(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=jo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):im(i,n,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,i;this.isPseudoElement||(i=(e=this.animation).commitStyles)==null||i.call(e)}get duration(){var i,n;const e=((n=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:n.call(i).duration)||0;return Et(Number(e))}get time(){return Et(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=kt(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:i}){var n;return this.allowFlatten&&((n=this.animation.effect)==null||n.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&nm()?(this.animation.timeline=e,dt):i(this)}}const Cc={anticipate:Hl,backInOut:jl,circInOut:Gl};function cm(t){return t in Cc}function dm(t){typeof t.ease=="string"&&cm(t.ease)&&(t.ease=Cc[t.ease])}const Tc=10;class um extends lm{constructor(e){dm(e),hc(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:n,onComplete:s,element:o,...r}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const a=new Wo({...r,autoplay:!1}),l=kt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Tc).value,a.sample(l).value,Tc),a.stop()}}const kc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Kt.test(t)||t==="0")&&!t.startsWith("url("));function hm(t){const e=t[0];if(t.length===1)return!0;for(let i=0;i<t.length;i++)if(t[i]!==e)return!0}function fm(t,e,i,n){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=kc(s,e),a=kc(o,e);return!r||!a?!1:hm(t)||(i==="spring"||Sc(i))&&n}function Zo(t){return Pl(t)&&"offsetHeight"in t}const pm=new Set(["opacity","clipPath","filter","transform"]),gm=Co(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function mm(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Zo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return gm()&&i&&pm.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const vm=40;class _m extends Ho{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var m;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=tt.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},p=(u==null?void 0:u.KeyframeResolver)||Qo;this.keyframeResolver=new p(a,(v,b,y)=>this.onKeyframesResolved(v,b,h,!y),l,c,u),(m=this.keyframeResolver)==null||m.scheduleResolve()}onKeyframesResolved(e,i,n,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=n;this.resolvedAt=tt.now(),fm(e,o,r,a)||((Ut.instantAnimations||!l)&&(u==null||u(jo(e,n,i))),e[0]=e[e.length-1],n.duration=0,n.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>vm?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&mm(h)?new um({...h,element:h.motionValue.owner.current}):new Wo(h);p.finished.then(()=>this.notifyFinished()).catch(dt),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),em()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const ym=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function bm(t){const e=ym.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Ec(t,e,i=1){const[n,s]=bm(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Ol(r)?parseFloat(r):r}return Ro(s)?Ec(s,e,i+1):s}function er(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Ic=new Set(["width","height","top","left","right","bottom",...Ii]),wm={test:t=>t==="auto",parse:t=>t},Ac=t=>e=>e.test(t),Rc=[ki,Q,It,zt,hg,ug,wm],xc=t=>Rc.find(Ac(t));function Sm(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Nl(t):!0}const Cm=new Set(["brightness","contrast","saturate","opacity"]);function Tm(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(xo)||[];if(!n)return t;const s=i.replace(n,"");let o=Cm.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const km=/\b([a-z-]*)\(.*?\)/gu,tr={...Kt,getAnimatableNone:t=>{const e=t.match(km);return e?e.map(Tm).join(" "):t}},Dc={...ki,transform:Math.round},ir={borderWidth:Q,borderTopWidth:Q,borderRightWidth:Q,borderBottomWidth:Q,borderLeftWidth:Q,borderRadius:Q,radius:Q,borderTopLeftRadius:Q,borderTopRightRadius:Q,borderBottomRightRadius:Q,borderBottomLeftRadius:Q,width:Q,maxWidth:Q,height:Q,maxHeight:Q,top:Q,right:Q,bottom:Q,left:Q,padding:Q,paddingTop:Q,paddingRight:Q,paddingBottom:Q,paddingLeft:Q,margin:Q,marginTop:Q,marginRight:Q,marginBottom:Q,marginLeft:Q,backgroundPositionX:Q,backgroundPositionY:Q,...{rotate:zt,rotateX:zt,rotateY:zt,rotateZ:zt,scale:is,scaleX:is,scaleY:is,scaleZ:is,skew:zt,skewX:zt,skewY:zt,distance:Q,translateX:Q,translateY:Q,translateZ:Q,x:Q,y:Q,z:Q,perspective:Q,transformPerspective:Q,opacity:an,originX:Zl,originY:Zl,originZ:Q},zIndex:Dc,fillOpacity:an,strokeOpacity:an,numOctaves:Dc},Em={...ir,color:Me,backgroundColor:Me,outlineColor:Me,fill:Me,stroke:Me,borderColor:Me,borderTopColor:Me,borderRightColor:Me,borderBottomColor:Me,borderLeftColor:Me,filter:tr,WebkitFilter:tr},Lc=t=>Em[t];function Mc(t,e){let i=Lc(t);return i!==tr&&(i=Kt),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const Im=new Set(["auto","none","0"]);function Am(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!Im.has(o)&&dn(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Mc(i,s)}class Rm extends Qo{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),Ro(c))){const u=Ec(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ic.has(n)||e.length!==2)return;const[s,o]=e,r=xc(s),a=xc(o);if(r!==a)if(mc(r)&&mc(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else ai[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||Sm(e[s]))&&n.push(s);n.length&&Am(e,n,i)}measureInitialState(){const{element:e,unresolvedKeyframes:i,name:n}=this;if(!e||!e.current)return;n==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=ai[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i[0]=this.measuredOrigin;const s=i[i.length-1];s!==void 0&&e.getValue(n,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:i,unresolvedKeyframes:n}=this;if(!e||!e.current)return;const s=e.getValue(i);s&&s.jump(this.measuredOrigin,!1);const o=n.length-1,r=n[o];n[o]=ai[i](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function xm(t,e,i){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let n=document;const s=(i==null?void 0:i[t])??n.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Oc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Pc=30,Dm=t=>!isNaN(parseFloat(t));class Lm{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=tt.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=i.owner}setCurrent(e){this.current=e,this.updatedAt=tt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Dm(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new To);const n=this.events[e].add(i);return e==="change"?()=>{n(),Ce.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e,i=!0){!i||!this.passiveEffect?this.updateAndNotify(e,i):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,i,n){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=tt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Pc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,Pc);return Fl(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ri(t,e){return new Lm(t,e)}const{schedule:nr}=Xl(queueMicrotask,!1),bt={x:!1,y:!1};function Nc(){return bt.x||bt.y}function Mm(t){return t==="x"||t==="y"?bt[t]?null:(bt[t]=!0,()=>{bt[t]=!1}):bt.x||bt.y?null:(bt.x=bt.y=!0,()=>{bt.x=bt.y=!1})}function Fc(t,e){const i=xm(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function Uc(t){return!(t.pointerType==="touch"||Nc())}function Om(t,e,i={}){const[n,s,o]=Fc(t,i),r=a=>{if(!Uc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Uc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Bc=(t,e)=>e?t===e?!0:Bc(t,e.parentElement):!1,sr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Pm=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Nm(t){return Pm.has(t.tagName)||t.tabIndex!==-1}const rs=new WeakSet;function Vc(t){return e=>{e.key==="Enter"&&t(e)}}function or(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Fm=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=Vc(()=>{if(rs.has(i))return;or(i,"down");const s=Vc(()=>{or(i,"up")}),o=()=>or(i,"cancel");i.addEventListener("keyup",s,e),i.addEventListener("blur",o,e)});i.addEventListener("keydown",n,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),e)};function $c(t){return sr(t)&&!Nc()}function Um(t,e,i={}){const[n,s,o]=Fc(t,i),r=a=>{const l=a.currentTarget;if(!$c(a))return;rs.add(l);const c=e(l,a),u=(p,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),rs.has(l)&&rs.delete(l),$c(p)&&typeof c=="function"&&c(p,{success:m})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||Bc(l,p.target))},h=p=>{u(p,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Zo(a)&&(a.addEventListener("focus",c=>Fm(c,s)),!Nm(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function jc(t){return Pl(t)&&"ownerSVGElement"in t}function Bm(t){return jc(t)&&t.tagName==="svg"}const Ge=t=>!!(t&&t.getVelocity),Vm=[...Rc,Me,Kt],$m=t=>Vm.find(Ac(t)),fn=Nt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class jm extends yt{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Zo(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=i.offsetHeight||0,o.width=i.offsetWidth||0,o.top=i.offsetTop,o.left=i.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Hm({children:t,isPresent:e,anchorX:i,root:n}){const s=oo(),o=ce(null),r=ce({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Fe(fn);return pl(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const p=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const m=document.createElement("style");a&&(m.nonce=a);const v=n??document.head;return v.appendChild(m),m.sheet&&m.sheet.insertRule(`
1
+ var FS=Object.defineProperty;var US=(_t,Z,sn)=>Z in _t?FS(_t,Z,{enumerable:!0,configurable:!0,writable:!0,value:sn}):_t[Z]=sn;var B=(_t,Z,sn)=>US(_t,typeof Z!="symbol"?Z+"":Z,sn);(function(){"use strict";var _t,Z,sn,on,Ra,xa,Da,La,Ks,Ys,Xs,Ma,Zn={},Oa=[],sp=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,ei=Array.isArray;function Ct(t,e){for(var n in e)t[n]=e[n];return t}function Js(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ct(t,e,n){var i,s,o,r={};for(o in e)o=="key"?i=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?_t.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return ti(t,r,i,s,null)}function ti(t,e,n,i,s){var o={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++sn,__i:-1,__u:0};return s==null&&Z.vnode!=null&&Z.vnode(o),o}function yt(t){return t.children}function bt(t,e){this.props=t,this.context=e}function En(t,e){if(e==null)return t.__?En(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?En(t):null}function Pa(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Pa(t)}}function Qs(t){(!t.__d&&(t.__d=!0)&&on.push(t)&&!ji.__r++||Ra!=Z.debounceRendering)&&((Ra=Z.debounceRendering)||xa)(ji)}function ji(){for(var t,e,n,i,s,o,r,a=1;on.length;)on.length>a&&on.sort(Da),t=on.shift(),a=on.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=Ct({},i)).__v=i.__v+1,Z.vnode&&Z.vnode(n),Zs(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??En(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,Va(o,n,r),n.__e!=s&&Pa(n)));ji.__r=0}function Na(t,e,n,i,s,o,r,a,l,c,u){var d,h,p,m,v,b,y=i&&i.__k||Oa,C=e.length;for(l=op(n,e,y,l,C),d=0;d<C;d++)(p=n.__k[d])!=null&&(h=p.__i==-1?Zn:y[p.__i]||Zn,p.__i=d,b=Zs(t,p,h,s,o,r,a,l,c,u),m=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&eo(h.ref,null,p),u.push(p.ref,p.__c||m,p)),v==null&&m!=null&&(v=m),4&p.__u||h.__k===p.__k?l=Fa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:m&&(l=m.nextSibling),p.__u&=-7);return n.__e=v,l}function op(t,e,n,i,s){var o,r,a,l,c,u=n.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?ti(null,r,null,null,null):ei(r)?ti(yt,{children:r},null,null,null):r.constructor==null&&r.__b>0?ti(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=rp(r,n,l,d))!=-1&&(d--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=En(a)),ja(a,a));return i}function Fa(t,e,n){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Fa(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=En(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Tt(t,e){return e=e||[],t==null||typeof t=="boolean"||(ei(t)?t.some(function(n){Tt(n,e)}):e.push(t)),e}function rp(t,e,n,i){var s,o,r=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function Ua(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||sp.test(e)?n:n+"px"}function Hi(t,e,n,i,s){var o,r;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Ua(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Ua(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(La,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?i?n.u=i.u:(n.u=Ks,t.addEventListener(e,o?Xs:Ys,o)):t.removeEventListener(e,o?Xs:Ys,o);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Ba(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Ks++;else if(e.t<n.u)return;return n(Z.event?Z.event(e):e)}}}function Zs(t,e,n,i,s,o,r,a,l,c){var u,d,h,p,m,v,b,y,C,T,A,x,N,k,E,f,_,g=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(u=Z.__b)&&u(e);e:if(typeof g=="function")try{if(y=e.props,C="prototype"in g&&g.prototype.render,T=(u=g.contextType)&&i[u.__c],A=u?T?T.props.value:u.__:i,n.__c?b=(d=e.__c=n.__c).__=d.__E:(C?e.__c=d=new g(y,A):(e.__c=d=new bt(y,A),d.constructor=g,d.render=lp),T&&T.sub(d),d.props=y,d.state||(d.state={}),d.context=A,d.__n=i,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&g.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Ct({},d.__s)),Ct(d.__s,g.getDerivedStateFromProps(y,d.__s))),p=d.props,m=d.state,d.__v=e,h)C&&g.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&g.getDerivedStateFromProps==null&&y!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,A)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(S){S&&(S.__=e)}),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,m,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,N=Z.__r,k=0,C){for(d.state=d.__s,d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),E=0;E<d._sb.length;E++)d.__h.push(d._sb[E]);d._sb=[]}else do d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++k<25);d.state=d.__s,d.getChildContext!=null&&(i=Ct(Ct({},i),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,m)),f=u,u!=null&&u.type===yt&&u.key==null&&(f=$a(u.props.children)),a=Na(t,ei(f)?f:[f],e,n,i,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(S){if(e.__v=null,l||o!=null)if(S.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(_=o.length;_--;)Js(o[_]);else e.__e=n.__e,e.__k=n.__k;Z.__e(S,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=ap(n.__e,e,n,i,s,o,r,l,c);return(u=Z.diffed)&&u(e),128&e.__u?void 0:a}function Va(t,e,n){for(var i=0;i<n.length;i++)eo(n[i],n[++i],n[++i]);Z.__c&&Z.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){Z.__e(o,s.__v)}})}function $a(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:ei(t)?t.map($a):Ct({},t)}function ap(t,e,n,i,s,o,r,a,l){var c,u,d,h,p,m,v,b=n.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(Z.__m&&Z.__m(e,o),a=!1),o=null}if(C==null)b===y||a&&t.data==y||(t.data=y);else{if(o=o&&_t.call(t.childNodes),b=n.props||Zn,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Hi(t,c,null,p,s)}}for(c in y)p=y[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?m=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||Hi(t,c,p,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Na(e.type=="template"?t.content:t,ei(h)?h:[h],e,n,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&En(n,0),a,l),o!=null)for(c=o.length;c--;)Js(o[c]);a||(c="value",C=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[c]||C=="progress"&&!m||C=="option"&&m!=b[c])&&Hi(t,c,m,b[c],s),c="checked",v!=null&&v!=t[c]&&Hi(t,c,v,b[c],s))}return t}function eo(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){Z.__e(s,n)}}function ja(t,e,n){var i,s;if(Z.unmount&&Z.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||eo(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){Z.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&ja(i[s],e,n||typeof t.type!="function");n||Js(t.__e),t.__c=t.__=t.__e=void 0}function lp(t,e,n){return this.constructor(t,n)}function Wi(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),Z.__&&Z.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],Zs(e,t=(!i&&n||e).__k=ct(yt,null,[t]),s||Zn,Zn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?_t.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),Va(o,t,r)}function Ha(t,e){Wi(t,e,Ha)}function to(t,e,n){var i,s,o,r,a=Ct({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?i=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?_t.call(arguments,2):n),ti(t.type,a,i||t.key,s||t.ref,null)}function Nt(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&i.forEach(function(r){r.__e=!0,Qs(r)})},this.sub=function(o){i.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){i&&i.delete(o),r&&r.call(o)}}),n.children}return e.__c="__cC"+Ma++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}_t=Oa.slice,Z={__e:function(t,e,n,i){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},sn=0,bt.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ct({},this.state),typeof t=="function"&&(t=t(Ct({},n),this.props)),t&&Ct(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Qs(this))},bt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Qs(this))},bt.prototype.render=yt,on=[],xa=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Da=function(t,e){return t.__v.__b-e.__v.__b},ji.__r=0,La=/(PointerCapture)$|Capture$/i,Ks=0,Ys=Ba(!1),Xs=Ba(!0),Ma=0;var cp=0;function D(t,e,n,i,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cp,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return Z.vnode&&Z.vnode(c),c}function no(){return(no=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var dp=["context","children"];function up(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(t,dp);return to(e,n)}function hp(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=ct(up,no({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Wa(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=ct(Ga,{name:u},c):s[r]=c}var d=i?ct(Ga,null,s):s;return ct(i||n.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ha:Wi)(this._vdom,this._root)}function Wa(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function fp(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Wa(t)]=n,this._vdom=to(this._vdom,i),Wi(this._vdom,this._root)}}function pp(){Wi(this._vdom=null,this._root)}function Ga(t,e){var n=this;return ct("slot",no({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function gp(t,e,n,i){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=i&&i.shadow?o.attachShadow({mode:i.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=hp,s.prototype.attributeChangedCallback=fp,s.prototype.disconnectedCallback=pp,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=n,n.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var Gt,Se,io,qa,ni=0,za=[],Ee=Z,Ka=Ee.__b,Ya=Ee.__r,Xa=Ee.diffed,Ja=Ee.__c,Qa=Ee.unmount,Za=Ee.__;function kn(t,e){Ee.__h&&Ee.__h(Se,t,ni||e),ni=0;var n=Se.__H||(Se.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function me(t){return ni=1,el(nl,t)}function el(t,e,n){var i=kn(Gt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):nl(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=Se,!Se.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=i.__c.props!==a;return u.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};Se.__f=!0;var o=Se.shouldComponentUpdate,r=Se.componentWillUpdate;Se.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},Se.shouldComponentUpdate=s}return i.__N||i.__}function Ie(t,e){var n=kn(Gt++,3);!Ee.__s&&ao(n.__H,e)&&(n.__=t,n.u=e,Se.__H.__h.push(n))}function so(t,e){var n=kn(Gt++,4);!Ee.__s&&ao(n.__H,e)&&(n.__=t,n.u=e,Se.__h.push(n))}function ue(t){return ni=5,dt(function(){return{current:t}},[])}function dt(t,e){var n=kn(Gt++,7);return ao(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ne(t,e){return ni=8,dt(function(){return t},e)}function Ue(t){var e=Se.context[t.__c],n=kn(Gt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(Se)),e.props.value):t.__}function mp(t,e){Ee.useDebugValue&&Ee.useDebugValue(e?e(t):t)}function oo(){var t=kn(Gt++,11);if(!t.__){for(var e=Se.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function vp(){for(var t;t=za.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Gi),t.__H.__h.forEach(ro),t.__H.__h=[]}catch(e){t.__H.__h=[],Ee.__e(e,t.__v)}}Ee.__b=function(t){Se=null,Ka&&Ka(t)},Ee.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Za&&Za(t,e)},Ee.__r=function(t){Ya&&Ya(t),Gt=0;var e=(Se=t.__c).__H;e&&(io===Se?(e.__h=[],Se.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Gi),e.__h.forEach(ro),e.__h=[],Gt=0)),io=Se},Ee.diffed=function(t){Xa&&Xa(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(za.push(e)!==1&&qa===Ee.requestAnimationFrame||((qa=Ee.requestAnimationFrame)||_p)(vp)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),io=Se=null},Ee.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Gi),n.__h=n.__h.filter(function(i){return!i.__||ro(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Ee.__e(i,n.__v)}}),Ja&&Ja(t,e)},Ee.unmount=function(t){Qa&&Qa(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{Gi(i)}catch(s){e=s}}),n.__H=void 0,e&&Ee.__e(e,n.__v))};var tl=typeof requestAnimationFrame=="function";function _p(t){var e,n=function(){clearTimeout(i),tl&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);tl&&(e=requestAnimationFrame(n))}function Gi(t){var e=Se,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),Se=e}function ro(t){var e=Se;t.__c=t.__(),Se=e}function ao(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function nl(t,e){return typeof e=="function"?e(t):e}const ii={},il=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,sl=t=>"init"in t,lo=t=>!!t.write,ol=t=>"v"in t||"e"in t,qi=t=>{if("e"in t)throw t.e;if((ii?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},zi=new WeakMap,rl=t=>{var e;return Ki(t)&&!!((e=zi.get(t))!=null&&e[0])},yp=t=>{const e=zi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},al=(t,e)=>{let n=zi.get(t);if(!n){n=[!0,new Set],zi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},Ki=t=>typeof(t==null?void 0:t.then)=="function",ll=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},co=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(Ki(e))for(const r of i.d.keys())ll(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,Ki(o)&&yp(o))},cl=(t,e,n)=>{var i;const s=new Set;for(const o of((i=n.get(t))==null?void 0:i.t)||[])n.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},bp=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},uo=()=>{const t={},e=new WeakMap,n=i=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(i)),(o=e.get(i))==null||o.forEach(r=>r())};return n.add=(i,s)=>{const o=i||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},n},wp=t=>(t.c||(t.c=uo()),t.m||(t.m=uo()),t.u||(t.u=uo()),t.f||(t.f=bp()),t),Sp=Symbol(),dl=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(h,...p)=>h.read(...p),l=(h,...p)=>h.write(...p),c=(h,p)=>{var m;return(m=h.unstable_onInit)==null?void 0:m.call(h,p)},u=(h,p)=>{var m;return(m=h.onMount)==null?void 0:m.call(h,p)},...d)=>{const h=d[0]||(k=>{if((ii?"production":void 0)!=="production"&&!k)throw new Error("Atom is undefined or null");let E=t.get(k);return E||(E={d:new Map,p:new Set,n:0},t.set(k,E),c==null||c(k,N)),E}),p=d[1]||(()=>{const k=[],E=f=>{try{f()}catch(_){k.push(_)}};do{r.f&&E(r.f);const f=new Set,_=f.add.bind(f);i.forEach(g=>{var S;return(S=e.get(g))==null?void 0:S.l.forEach(_)}),i.clear(),o.forEach(_),o.clear(),s.forEach(_),s.clear(),f.forEach(E),i.size&&m()}while(i.size||o.size||s.size);if(k.length)throw new AggregateError(k)}),m=d[2]||(()=>{const k=[],E=new WeakSet,f=new WeakSet,_=Array.from(i);for(;_.length;){const g=_[_.length-1],S=h(g);if(f.has(g)){_.pop();continue}if(E.has(g)){if(n.get(g)===S.n)k.push([g,S]);else if((ii?"production":void 0)!=="production"&&n.has(g))throw new Error("[Bug] invalidated atom exists");f.add(g),_.pop();continue}E.add(g);for(const I of cl(g,S,e))E.has(I)||_.push(I)}for(let g=k.length-1;g>=0;--g){const[S,I]=k[g];let P=!1;for(const R of I.d.keys())if(R!==S&&i.has(R)){P=!0;break}P&&(v(S),C(S)),n.delete(S)}}),v=d[3]||(k=>{var E;const f=h(k);if(ol(f)&&(e.has(k)&&n.get(k)!==f.n||Array.from(f.d).every(([O,L])=>v(O).n===L)))return f;f.d.clear();let _=!0;const g=()=>{e.has(k)&&(C(k),m(),p())},S=O=>{var L;if(il(k,O)){const j=h(O);if(!ol(j))if(sl(O))co(O,O.init,h);else throw new Error("no atom init");return qi(j)}const V=v(O);try{return qi(V)}finally{f.d.set(O,V.n),rl(f.v)&&ll(k,f.v,V),(L=e.get(O))==null||L.t.add(k),_||g()}};let I,P;const R={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(ii?"production":void 0)!=="production"&&!lo(k)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&lo(k)&&(P=(...O)=>{if((ii?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return y(k,...O)}finally{m(),p()}}),P}},M=f.n;try{const O=a(k,S,R);return co(k,O,h),Ki(O)&&(al(O,()=>I==null?void 0:I.abort()),O.then(g,g)),f}catch(O){return delete f.v,f.e=O,++f.n,f}finally{_=!1,M!==f.n&&n.get(k)===M&&(n.set(k,f.n),i.add(k),(E=r.c)==null||E.call(r,k))}}),b=d[4]||(k=>{const E=[k];for(;E.length;){const f=E.pop(),_=h(f);for(const g of cl(f,_,e)){const S=h(g);n.set(g,S.n),E.push(g)}}}),y=d[5]||((k,...E)=>{let f=!0;const _=S=>qi(v(S)),g=(S,...I)=>{var P;const R=h(S);try{if(il(k,S)){if(!sl(S))throw new Error("atom not writable");const M=R.n,O=I[0];co(S,O,h),C(S),M!==R.n&&(i.add(S),(P=r.c)==null||P.call(r,S),b(S));return}else return y(S,...I)}finally{f||(m(),p())}};try{return l(k,_,g,...E)}finally{f=!1}}),C=d[6]||(k=>{var E;const f=h(k),_=e.get(k);if(_&&!rl(f.v)){for(const[g,S]of f.d)if(!_.d.has(g)){const I=h(g);T(g).t.add(k),_.d.add(g),S!==I.n&&(i.add(g),(E=r.c)==null||E.call(r,g),b(g))}for(const g of _.d||[])if(!f.d.has(g)){_.d.delete(g);const S=A(g);S==null||S.t.delete(k)}}}),T=d[7]||(k=>{var E;const f=h(k);let _=e.get(k);if(!_){v(k);for(const g of f.d.keys())T(g).t.add(k);if(_={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(k,_),(E=r.m)==null||E.call(r,k),lo(k)){const g=()=>{let S=!0;const I=(...P)=>{try{return y(k,...P)}finally{S||(m(),p())}};try{const P=u(k,I);P&&(_.u=()=>{S=!0;try{P()}finally{S=!1}})}finally{S=!1}};s.add(g)}}return _}),A=d[8]||(k=>{var E;const f=h(k);let _=e.get(k);if(_&&!_.l.size&&!Array.from(_.t).some(g=>{var S;return(S=e.get(g))==null?void 0:S.d.has(k)})){_.u&&o.add(_.u),_=void 0,e.delete(k),(E=r.u)==null||E.call(r,k);for(const g of f.d.keys()){const S=A(g);S==null||S.t.delete(k)}return}return _}),x=[t,e,n,i,s,o,r,a,l,c,u,h,p,m,v,b,y,C,T,A],N={get:k=>qi(v(k)),set:(k,...E)=>{try{return y(k,...E)}finally{m(),p()}},sub:(k,E)=>{const _=T(k).l;return _.add(E),p(),()=>{_.delete(E),A(k),p()}}};return Object.defineProperty(N,Sp,{value:x}),N},Cp=wp,ul=al,ho={};let Tp=0;function Yi(t,e){const n=`atom${++Tp}`,i={toString(){return(ho?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=Ep,i.write=kp),i}function Ep(t){return t(this)}function kp(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const Ip=()=>{let t=0;const e=Cp({}),n=new WeakMap,i=new WeakMap,s=dl(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function Ap(){return(ho?"production":void 0)!=="production"?Ip():dl()}let si;function Rp(){return si||(si=Ap(),(ho?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=si),globalThis.__JOTAI_DEFAULT_STORE__!==si&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),si}function hl(t,e){for(var n in e)t[n]=e[n];return t}function fl(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}var pl=so;function gl(t,e){this.props=t,this.context=e}(gl.prototype=new bt).isPureReactComponent=!0,gl.prototype.shouldComponentUpdate=function(t,e){return fl(this.props,t)||fl(this.state,e)};var ml=Z.__b;Z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ml&&ml(t)};var xp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Dp(t){function e(n){var i=hl({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=xp,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var vl=function(t,e){return t==null?null:Tt(Tt(t).map(e))},Lp={map:vl,forEach:vl,count:function(t){return t?Tt(t).length:0},only:function(t){var e=Tt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Tt},Mp=Z.__e;Z.__e=function(t,e,n,i){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}Mp(t,e,n,i)};var _l=Z.unmount;function yl(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=hl({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return yl(i,e,n)})),t}function bl(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return bl(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function fo(){this.__u=0,this.o=null,this.__b=null}function wl(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Xi(){this.i=null,this.l=null}Z.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),_l&&_l(t)},(fo.prototype=new bt).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=wl(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=bl(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},fo.prototype.componentWillUnmount=function(){this.o=[]},fo.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=yl(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&ct(yt,null,t.fallback);return s&&(s.__u&=-33),[ct(yt,null,e.__a?null:t.children),s]};var Sl=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(Xi.prototype=new bt).__a=function(t){var e=this,n=wl(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),Sl(e,t,i)):s()};n?n(o):o()}},Xi.prototype.render=function(t){this.i=null,this.l=new Map;var e=Tt(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Xi.prototype.componentDidUpdate=Xi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Sl(t,n,e)})};var Cl=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Op=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Pp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Np=/[A-Z0-9]/g,Fp=typeof document<"u",Up=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};bt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(bt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Tl=Z.event;function Bp(){}function Vp(){return this.cancelBubble}function $p(){return this.defaultPrevented}Z.event=function(t){return Tl&&(t=Tl(t)),t.persist=Bp,t.isPropagationStopped=Vp,t.isDefaultPrevented=$p,t.nativeEvent=t};var jp={enumerable:!1,configurable:!0,get:function(){return this.class}},El=Z.vnode;Z.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||Fp&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Up(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Pp.test(r)&&(r=l):l=r="oninput":o&&Op.test(r)?r=r.replace(Np,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=Tt(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=Tt(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",jp)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=Cl,El&&El(t)};var kl=Z.__r;Z.__r=function(t){kl&&kl(t),t.__c};var Il=Z.diffed;Z.diffed=function(t){Il&&Il(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value)};function Al(t){return!!t&&t.$$typeof===Cl}function Hp(t){return Al(t)?to.apply(null,arguments):t}var Rl={};const Wp={},Gp=Nt(void 0);function xl(t){return Ue(Gp)||Rp()}const po=t=>typeof(t==null?void 0:t.then)=="function",go=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},qp=Rl.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(go(t),t)}),mo=new WeakMap,Dl=(t,e)=>{let n=mo.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=c=>u=>{o===c&&i(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();po(c)?(mo.set(c,n),o=c,c.then(r(c),a(c)),ul(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),ul(t,l)}),mo.set(t,n)),n};function vo(t,e){const{delay:n,unstable_promiseStatus:i=!Rl.use}={},s=xl(),[[o,r,a],l]=el(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),Ie(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);po(d)&&go(Dl(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),u},[s,t,n,i]),mp(c),po(c)){const u=Dl(c,()=>s.get(t));return i&&go(u),qp(u)}return c}function Ji(t,e){const n=xl();return Ne((...s)=>{if((Wp?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function Ll(t,e){return[vo(t),Ji(t)]}const _o=Nt({});function Qi(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const yo=typeof window<"u",Ml=yo?so:Ie,Zi=Nt(null);function bo(t,e){t.indexOf(e)===-1&&t.push(e)}function wo(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Ft=(t,e,n)=>n>e?e:n<t?t:n;let So=()=>{};const Ut={},Ol=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Pl(t){return typeof t=="object"&&t!==null}const Nl=t=>/^0[^.\s]+$/u.test(t);function Co(t){let e;return()=>(e===void 0&&(e=t()),e)}const ut=t=>t,zp=(t,e)=>n=>e(t(n)),oi=(...t)=>t.reduce(zp),ri=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class To{constructor(){this.subscriptions=[]}add(e){return bo(this.subscriptions,e),()=>wo(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Et=t=>t*1e3,kt=t=>t/1e3;function Fl(t,e){return e?t*(1e3/e):0}const Ul=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Kp=1e-7,Yp=12;function Xp(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=Ul(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>Kp&&++a<Yp);return r}function ai(t,e,n,i){if(t===e&&n===i)return ut;const s=o=>Xp(o,0,1,t,n);return o=>o===0||o===1?o:Ul(s(o),e,i)}const Bl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Vl=t=>e=>1-t(1-e),$l=ai(.33,1.53,.69,.99),Eo=Vl($l),jl=Bl(Eo),Hl=t=>(t*=2)<1?.5*Eo(t):.5*(2-Math.pow(2,-10*(t-1))),ko=t=>1-Math.sin(Math.acos(t)),Wl=Vl(ko),Gl=Bl(ko),Jp=ai(.42,0,1,1),Qp=ai(0,0,.58,1),ql=ai(.42,0,.58,1),Zp=t=>Array.isArray(t)&&typeof t[0]!="number",zl=t=>Array.isArray(t)&&typeof t[0]=="number",eg={linear:ut,easeIn:Jp,easeInOut:ql,easeOut:Qp,circIn:ko,circInOut:Gl,circOut:Wl,backIn:Eo,backInOut:jl,backOut:$l,anticipate:Hl},tg=t=>typeof t=="string",Kl=t=>{if(zl(t)){So(t.length===4);const[e,n,i,s]=t;return ai(e,n,i,s)}else if(tg(t))return eg[t];return t},es=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Yl={value:null};function ng(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,p=!1)=>{const v=p&&s?n:i;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{i.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&Yl.value&&Yl.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const ig=40;function Xl(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=es.reduce((T,A)=>(T[A]=ng(o,e?A:void 0),T),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:m}=r,v=()=>{const T=Ut.useManualTiming?s.timestamp:performance.now();n=!1,Ut.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(T-s.timestamp,ig),1)),s.timestamp=T,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),m.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},b=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:es.reduce((T,A)=>{const x=r[A];return T[A]=(N,k=!1,E=!1)=>(n||b(),x.schedule(N,k,E)),T},{}),cancel:T=>{for(let A=0;A<es.length;A++)r[es[A]].cancel(T)},state:s,steps:r}}const{schedule:Te,cancel:qt,state:$e,steps:Io}=Xl(typeof requestAnimationFrame<"u"?requestAnimationFrame:ut,!0);let ts;function sg(){ts=void 0}const tt={now:()=>(ts===void 0&&tt.set($e.isProcessing||Ut.useManualTiming?$e.timestamp:performance.now()),ts),set:t=>{ts=t,queueMicrotask(sg)}},Jl=t=>e=>typeof e=="string"&&e.startsWith(t),Ao=Jl("--"),og=Jl("var(--"),Ro=t=>og(t)?rg.test(t.split("/*")[0].trim()):!1,rg=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,In={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},li={...In,transform:t=>Ft(0,1,t)},ns={...In,default:1},ci=t=>Math.round(t*1e5)/1e5,xo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ag(t){return t==null}const lg=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Do=(t,e)=>n=>!!(typeof n=="string"&&lg.test(n)&&n.startsWith(t)||e&&!ag(n)&&Object.prototype.hasOwnProperty.call(n,e)),Ql=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(xo);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},cg=t=>Ft(0,255,t),Lo={...In,transform:t=>Math.round(cg(t))},rn={test:Do("rgb","red"),parse:Ql("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Lo.transform(t)+", "+Lo.transform(e)+", "+Lo.transform(n)+", "+ci(li.transform(i))+")"};function dg(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const Mo={test:Do("#"),parse:dg,transform:rn.transform},di=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),zt=di("deg"),It=di("%"),ee=di("px"),ug=di("vh"),hg=di("vw"),Zl={...It,parse:t=>It.parse(t)/100,transform:t=>It.transform(t*100)},An={test:Do("hsl","hue"),parse:Ql("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+It.transform(ci(e))+", "+It.transform(ci(n))+", "+ci(li.transform(i))+")"},Oe={test:t=>rn.test(t)||Mo.test(t)||An.test(t),parse:t=>rn.test(t)?rn.parse(t):An.test(t)?An.parse(t):Mo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?rn.transform(t):An.transform(t),getAnimatableNone:t=>{const e=Oe.parse(t);return e.alpha=0,Oe.transform(e)}},fg=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function pg(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(xo))==null?void 0:e.length)||0)+(((n=t.match(fg))==null?void 0:n.length)||0)>0}const ec="number",tc="color",gg="var",mg="var(",nc="${}",vg=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function ui(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(vg,l=>(Oe.test(l)?(i.color.push(o),s.push(tc),n.push(Oe.parse(l))):l.startsWith(mg)?(i.var.push(o),s.push(gg),n.push(l)):(i.number.push(o),s.push(ec),n.push(parseFloat(l))),++o,nc)).split(nc);return{values:n,split:a,indexes:i,types:s}}function ic(t){return ui(t).values}function sc(t){const{split:e,types:n}=ui(t),i=e.length;return s=>{let o="";for(let r=0;r<i;r++)if(o+=e[r],s[r]!==void 0){const a=n[r];a===ec?o+=ci(s[r]):a===tc?o+=Oe.transform(s[r]):o+=s[r]}return o}}const _g=t=>typeof t=="number"?0:Oe.test(t)?Oe.getAnimatableNone(t):t;function yg(t){const e=ic(t);return sc(t)(e.map(_g))}const Kt={test:pg,parse:ic,createTransformer:sc,getAnimatableNone:yg};function Oo(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function bg({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Oo(l,a,t+1/3),o=Oo(l,a,t),r=Oo(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function is(t,e){return n=>n>0?e:t}const ke=(t,e,n)=>t+(e-t)*n,Po=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},wg=[Mo,rn,An],Sg=t=>wg.find(e=>e.test(t));function oc(t){const e=Sg(t);if(!e)return!1;let n=e.parse(t);return e===An&&(n=bg(n)),n}const rc=(t,e)=>{const n=oc(t),i=oc(e);if(!n||!i)return is(t,e);const s={...n};return o=>(s.red=Po(n.red,i.red,o),s.green=Po(n.green,i.green,o),s.blue=Po(n.blue,i.blue,o),s.alpha=ke(n.alpha,i.alpha,o),rn.transform(s))},No=new Set(["none","hidden"]);function Cg(t,e){return No.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Tg(t,e){return n=>ke(t,e,n)}function Fo(t){return typeof t=="number"?Tg:typeof t=="string"?Ro(t)?is:Oe.test(t)?rc:Ig:Array.isArray(t)?ac:typeof t=="object"?Oe.test(t)?rc:Eg:is}function ac(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Fo(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function Eg(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Fo(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function kg(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][i[o]],a=t.values[r]??0;n[s]=a,i[o]++}return n}const Ig=(t,e)=>{const n=Kt.createTransformer(e),i=ui(t),s=ui(e);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?No.has(t)&&!s.values.length||No.has(e)&&!i.values.length?Cg(t,e):oi(ac(kg(i,s),s.values),n):is(t,e)};function lc(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ke(t,e,n):Fo(t)(t,e)}const Ag=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>Te.update(e,n),stop:()=>qt(e),now:()=>$e.isProcessing?$e.timestamp:tt.now()}},cc=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},ss=2e4;function Uo(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<ss;)e+=n,i=t.next(e);return e>=ss?1/0:e}function Rg(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Uo(i),ss);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:kt(s)}}const xg=5;function dc(t,e,n){const i=Math.max(e-xg,0);return Fl(n-t(i),e-i)}const Ae={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Bo=.001;function Dg({duration:t=Ae.duration,bounce:e=Ae.bounce,velocity:n=Ae.velocity,mass:i=Ae.mass}){let s,o,r=1-e;r=Ft(Ae.minDamping,Ae.maxDamping,r),t=Ft(Ae.minDuration,Ae.maxDuration,kt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-n,p=Vo(c,r),m=Math.exp(-d);return Bo-h/p*m},o=c=>{const d=c*r*t,h=d*n+n,p=Math.pow(r,2)*Math.pow(c,2)*t,m=Math.exp(-d),v=Vo(Math.pow(c,2),r);return(-s(c)+Bo>0?-1:1)*((h-p)*m)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-Bo+u*d},o=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const a=5/t,l=Mg(s,o,a);if(t=Et(t),isNaN(l))return{stiffness:Ae.stiffness,damping:Ae.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const Lg=12;function Mg(t,e,n){let i=n;for(let s=1;s<Lg;s++)i=i-t(i)/e(i);return i}function Vo(t,e){return t*Math.sqrt(1-e*e)}const Og=["duration","bounce"],Pg=["stiffness","damping","mass"];function uc(t,e){return e.some(n=>t[n]!==void 0)}function Ng(t){let e={velocity:Ae.velocity,stiffness:Ae.stiffness,damping:Ae.damping,mass:Ae.mass,isResolvedFromDuration:!1,...t};if(!uc(t,Pg)&&uc(t,Og))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*Ft(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ae.mass,stiffness:s,damping:o}}else{const n=Dg(t);e={...e,...n,mass:Ae.mass},e.isResolvedFromDuration=!0}return e}function os(t=Ae.visualDuration,e=Ae.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:p}=Ng({...n,velocity:-kt(n.velocity||0)}),m=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,y=kt(Math.sqrt(l/u)),C=Math.abs(b)<5;i||(i=C?Ae.restSpeed.granular:Ae.restSpeed.default),s||(s=C?Ae.restDelta.granular:Ae.restDelta.default);let T;if(v<1){const x=Vo(y,v);T=N=>{const k=Math.exp(-v*y*N);return r-k*((m+v*y*b)/x*Math.sin(x*N)+b*Math.cos(x*N))}}else if(v===1)T=x=>r-Math.exp(-y*x)*(b+(m+y*b)*x);else{const x=y*Math.sqrt(v*v-1);T=N=>{const k=Math.exp(-v*y*N),E=Math.min(x*N,300);return r-k*((m+v*y*b)*Math.sinh(E)+x*b*Math.cosh(E))/x}}const A={calculatedDuration:p&&d||null,next:x=>{const N=T(x);if(p)a.done=x>=d;else{let k=x===0?m:0;v<1&&(k=x===0?Et(m):dc(T,x,N));const E=Math.abs(k)<=i,f=Math.abs(r-N)<=s;a.done=E&&f}return a.value=a.done?r:N,a},toString:()=>{const x=Math.min(Uo(A),ss),N=cc(k=>A.next(x*k).value,x,30);return x+"ms "+N},toTransition:()=>{}};return A}os.applyToOptions=t=>{const e=Rg(t,100,os);return t.ease=e.ease,t.duration=Et(e.duration),t.type="keyframes",t};function $o({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=E=>a!==void 0&&E<a||l!==void 0&&E>l,m=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let v=n*e;const b=d+v,y=r===void 0?b:r(b);y!==b&&(v=y-d);const C=E=>-v*Math.exp(-E/i),T=E=>y+C(E),A=E=>{const f=C(E),_=T(E);h.done=Math.abs(f)<=c,h.value=h.done?y:_};let x,N;const k=E=>{p(h.value)&&(x=E,N=os({keyframes:[h.value,m(h.value)],velocity:dc(T,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return k(0),{calculatedDuration:null,next:E=>{let f=!1;return!N&&x===void 0&&(f=!0,A(E),k(E)),x!==void 0&&E>=x?N.next(E-x):(!f&&A(E),h)}}}function Fg(t,e,n){const i=[],s=n||Ut.mix||lc,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||ut:e;a=oi(l,a)}i.push(a)}return i}function Ug(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(So(o===e.length),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Fg(e,i,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=ri(t[d],t[d+1],u);return a[d](h)};return n?u=>c(Ft(t[0],t[o-1],u)):c}function Bg(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=ri(0,e,i);t.push(ke(n,1,s))}}function Vg(t){const e=[0];return Bg(e,t.length-1),e}function $g(t,e){return t.map(n=>n*e)}function jg(t,e){return t.map(()=>e||ql).splice(0,t.length-1)}function hi({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Zp(i)?i.map(Kl):Kl(i),o={done:!1,value:e[0]},r=$g(n&&n.length===e.length?n:Vg(e),t),a=Ug(r,e,{ease:Array.isArray(s)?s:jg(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Hg=t=>t!==null;function jo(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Hg),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Wg={decay:$o,inertia:$o,tween:hi,keyframes:hi,spring:os};function hc(t){typeof t.type=="string"&&(t.type=Wg[t.type])}class Ho{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const Gg=t=>t/100;class Wo extends Ho{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,s;const{motionValue:n}=this.options;n&&n.updatedAt!==tt.now()&&this.tick(tt.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;hc(e);const{type:n=hi,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||hi;l!==hi&&typeof a[0]!="number"&&(this.mixKeyframes=oi(Gg,lc(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=Uo(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:p,type:m,onUpdate:v,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let T=this.currentTime,A=i;if(d){const E=Math.min(this.currentTime,s)/a;let f=Math.floor(E),_=E%1;!_&&E>=1&&(_=1),_===1&&f--,f=Math.min(f,d+1),!!(f%2)&&(h==="reverse"?(_=1-_,p&&(_-=p/a)):h==="mirror"&&(A=r)),T=Ft(0,1,_)*a}const x=C?{done:!1,value:u[0]}:A.next(T);o&&(x.value=o(x.value));let{done:N}=x;!C&&l!==null&&(N=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const k=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return k&&m!==$o&&(x.value=jo(u,this.options,b,this.speed)),v&&v(x.value),k&&this.finish(),x}then(e,n){return this.finished.then(e,n)}get duration(){return kt(this.calculatedDuration)}get time(){return kt(this.currentTime)}set time(e){var n;e=Et(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(tt.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=kt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Ag,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(tt.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function qg(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const an=t=>t*180/Math.PI,Go=t=>{const e=an(Math.atan2(t[1],t[0]));return qo(e)},zg={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Go,rotateZ:Go,skewX:t=>an(Math.atan(t[1])),skewY:t=>an(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},qo=t=>(t=t%360,t<0&&(t+=360),t),fc=Go,pc=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),gc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Kg={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:pc,scaleY:gc,scale:t=>(pc(t)+gc(t))/2,rotateX:t=>qo(an(Math.atan2(t[6],t[5]))),rotateY:t=>qo(an(Math.atan2(-t[2],t[0]))),rotateZ:fc,rotate:fc,skewX:t=>an(Math.atan(t[4])),skewY:t=>an(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function zo(t){return t.includes("scale")?1:0}function Ko(t,e){if(!t||t==="none")return zo(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Kg,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=zg,s=a}if(!s)return zo(e);const o=i[e],r=s[1].split(",").map(Xg);return typeof o=="function"?o(r):r[o]}const Yg=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return Ko(n,e)};function Xg(t){return parseFloat(t.trim())}const Rn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],xn=new Set(Rn),mc=t=>t===In||t===ee,Jg=new Set(["x","y","z"]),Qg=Rn.filter(t=>!Jg.has(t));function Zg(t){const e=[];return Qg.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const ln={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Ko(e,"x"),y:(t,{transform:e})=>Ko(e,"y")};ln.translateX=ln.x,ln.translateY=ln.y;const cn=new Set;let Yo=!1,Xo=!1,Jo=!1;function vc(){if(Xo){const t=Array.from(cn).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Zg(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([o,r])=>{var a;(a=i.getValue(o))==null||a.set(r)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}Xo=!1,Yo=!1,cn.forEach(t=>t.complete(Jo)),cn.clear()}function _c(){cn.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Xo=!0)})}function em(){Jo=!0,_c(),vc(),Jo=!1}class Qo{constructor(e,n,i,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(cn.add(this),Yo||(Yo=!0,Te.read(_c),Te.resolveKeyframes(vc))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(i&&n){const a=i.readValue(n,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}qg(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),cn.delete(this)}cancel(){this.state==="scheduled"&&(cn.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const tm=t=>t.startsWith("--");function nm(t,e,n){tm(e)?t.style.setProperty(e,n):t.style[e]=n}const im=Co(()=>window.ScrollTimeline!==void 0),sm={};function om(t,e){const n=Co(t);return()=>sm[e]??n()}const yc=om(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),fi=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,bc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:fi([0,.65,.55,1]),circOut:fi([.55,0,1,.45]),backIn:fi([.31,.01,.66,-.59]),backOut:fi([.33,1.53,.69,.99])};function wc(t,e){if(t)return typeof t=="function"?yc()?cc(t,e):"ease-out":zl(t)?fi(t):Array.isArray(t)?t.map(n=>wc(n,e)||bc.easeOut):bc[t]}function rm(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=wc(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function Sc(t){return typeof t=="function"&&"applyToOptions"in t}function am({type:t,...e}){return Sc(t)&&yc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class lm extends Ho{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,So(typeof e.type!="string");const c=am(e);this.animation=rm(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=jo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):nm(n,i,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return kt(Number(e))}get time(){return kt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=Et(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&im()?(this.animation.timeline=e,ut):n(this)}}const Cc={anticipate:Hl,backInOut:jl,circInOut:Gl};function cm(t){return t in Cc}function dm(t){typeof t.ease=="string"&&cm(t.ease)&&(t.ease=Cc[t.ease])}const Tc=10;class um extends lm{constructor(e){dm(e),hc(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:o,...r}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new Wo({...r,autoplay:!1}),l=Et(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-Tc).value,a.sample(l).value,Tc),a.stop()}}const Ec=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Kt.test(t)||t==="0")&&!t.startsWith("url("));function hm(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function fm(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=Ec(s,e),a=Ec(o,e);return!r||!a?!1:hm(t)||(n==="spring"||Sc(n))&&i}function Zo(t){return Pl(t)&&"offsetHeight"in t}const pm=new Set(["opacity","clipPath","filter","transform"]),gm=Co(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function mm(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!Zo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return gm()&&n&&pm.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const vm=40;class _m extends Ho{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var m;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=tt.now();const h={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},p=(u==null?void 0:u.KeyframeResolver)||Qo;this.keyframeResolver=new p(a,(v,b,y)=>this.onKeyframesResolved(v,b,h,!y),l,c,u),(m=this.keyframeResolver)==null||m.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=i;this.resolvedAt=tt.now(),fm(e,o,r,a)||((Ut.instantAnimations||!l)&&(u==null||u(jo(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>vm?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},p=!c&&mm(h)?new um({...h,element:h.motionValue.owner.current}):new Wo(h);p.finished.then(()=>this.notifyFinished()).catch(ut),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),em()),this._animation}get duration(){return this.animation.duration}get time(){return this.animation.time}set time(e){this.animation.time=e}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(e){this.animation.speed=e}get startTime(){return this.animation.startTime}attachTimeline(e){return this._animation?this.stopTimeline=this.animation.attachTimeline(e):this.pendingTimeline=e,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){var e;this._animation&&this.animation.cancel(),(e=this.keyframeResolver)==null||e.cancel()}}const ym=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function bm(t){const e=ym.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function kc(t,e,n=1){const[i,s]=bm(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Ol(r)?parseFloat(r):r}return Ro(s)?kc(s,e,n+1):s}function er(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Ic=new Set(["width","height","top","left","right","bottom",...Rn]),wm={test:t=>t==="auto",parse:t=>t},Ac=t=>e=>e.test(t),Rc=[In,ee,It,zt,hg,ug,wm],xc=t=>Rc.find(Ac(t));function Sm(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Nl(t):!0}const Cm=new Set(["brightness","contrast","saturate","opacity"]);function Tm(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(xo)||[];if(!i)return t;const s=n.replace(i,"");let o=Cm.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const Em=/\b([a-z-]*)\(.*?\)/gu,tr={...Kt,getAnimatableNone:t=>{const e=t.match(Em);return e?e.map(Tm).join(" "):t}},Dc={...In,transform:Math.round},nr={borderWidth:ee,borderTopWidth:ee,borderRightWidth:ee,borderBottomWidth:ee,borderLeftWidth:ee,borderRadius:ee,radius:ee,borderTopLeftRadius:ee,borderTopRightRadius:ee,borderBottomRightRadius:ee,borderBottomLeftRadius:ee,width:ee,maxWidth:ee,height:ee,maxHeight:ee,top:ee,right:ee,bottom:ee,left:ee,padding:ee,paddingTop:ee,paddingRight:ee,paddingBottom:ee,paddingLeft:ee,margin:ee,marginTop:ee,marginRight:ee,marginBottom:ee,marginLeft:ee,backgroundPositionX:ee,backgroundPositionY:ee,...{rotate:zt,rotateX:zt,rotateY:zt,rotateZ:zt,scale:ns,scaleX:ns,scaleY:ns,scaleZ:ns,skew:zt,skewX:zt,skewY:zt,distance:ee,translateX:ee,translateY:ee,translateZ:ee,x:ee,y:ee,z:ee,perspective:ee,transformPerspective:ee,opacity:li,originX:Zl,originY:Zl,originZ:ee},zIndex:Dc,fillOpacity:li,strokeOpacity:li,numOctaves:Dc},km={...nr,color:Oe,backgroundColor:Oe,outlineColor:Oe,fill:Oe,stroke:Oe,borderColor:Oe,borderTopColor:Oe,borderRightColor:Oe,borderBottomColor:Oe,borderLeftColor:Oe,filter:tr,WebkitFilter:tr},Lc=t=>km[t];function Mc(t,e){let n=Lc(t);return n!==tr&&(n=Kt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Im=new Set(["auto","none","0"]);function Am(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!Im.has(o)&&ui(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=Mc(n,s)}class Rm extends Qo{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),Ro(c))){const u=kc(c,n.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ic.has(i)||e.length!==2)return;const[s,o]=e,r=xc(s),a=xc(o);if(r!==a)if(mc(r)&&mc(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else ln[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Sm(e[s]))&&i.push(s);i.length&&Am(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=ln[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const o=i.length-1,r=i[o];i[o]=ln[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function xm(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const s=(n==null?void 0:n[t])??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Oc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Pc=30,Dm=t=>!isNaN(parseFloat(t));class Lm{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=tt.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=tt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Dm(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new To);const i=this.events[e].add(n);return e==="change"?()=>{i(),Te.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e,n=!0){!n||!this.passiveEffect?this.updateAndNotify(e,n):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=tt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Pc)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Pc);return Fl(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Dn(t,e){return new Lm(t,e)}const{schedule:ir}=Xl(queueMicrotask,!1),wt={x:!1,y:!1};function Nc(){return wt.x||wt.y}function Mm(t){return t==="x"||t==="y"?wt[t]?null:(wt[t]=!0,()=>{wt[t]=!1}):wt.x||wt.y?null:(wt.x=wt.y=!0,()=>{wt.x=wt.y=!1})}function Fc(t,e){const n=xm(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Uc(t){return!(t.pointerType==="touch"||Nc())}function Om(t,e,n={}){const[i,s,o]=Fc(t,n),r=a=>{if(!Uc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Uc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Bc=(t,e)=>e?t===e?!0:Bc(t,e.parentElement):!1,sr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Pm=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Nm(t){return Pm.has(t.tagName)||t.tabIndex!==-1}const rs=new WeakSet;function Vc(t){return e=>{e.key==="Enter"&&t(e)}}function or(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Fm=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Vc(()=>{if(rs.has(n))return;or(n,"down");const s=Vc(()=>{or(n,"up")}),o=()=>or(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function $c(t){return sr(t)&&!Nc()}function Um(t,e,n={}){const[i,s,o]=Fc(t,n),r=a=>{const l=a.currentTarget;if(!$c(a))return;rs.add(l);const c=e(l,a),u=(p,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),rs.has(l)&&rs.delete(l),$c(p)&&typeof c=="function"&&c(p,{success:m})},d=p=>{u(p,l===window||l===document||n.useGlobalTarget||Bc(l,p.target))},h=p=>{u(p,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Zo(a)&&(a.addEventListener("focus",c=>Fm(c,s)),!Nm(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function jc(t){return Pl(t)&&"ownerSVGElement"in t}function Bm(t){return jc(t)&&t.tagName==="svg"}const Ge=t=>!!(t&&t.getVelocity),Vm=[...Rc,Oe,Kt],$m=t=>Vm.find(Ac(t)),pi=Nt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class jm extends bt{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=Zo(i)&&i.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Hm({children:t,isPresent:e,anchorX:n,root:i}){const s=oo(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Ue(pi);return pl(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const p=n==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const m=document.createElement("style");a&&(m.nonce=a);const v=i??document.head;return v.appendChild(m),m.sheet&&m.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
@@ -6,19 +6,19 @@ var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,co
6
6
  ${p}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{v.removeChild(m),v.contains(m)&&v.removeChild(m)}},[e]),D(jm,{isPresent:e,childRef:o,sizeRef:r,children:Hp(t,{ref:o})})}const Wm=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Qn(Gm),u=oo();let d=!0,h=ct(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:p=>{c.set(p,!0);for(const m of c.values())if(!m)return;n&&n()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[i,c,n]);return o&&d&&(h={...h}),ct(()=>{c.forEach((p,m)=>c.set(m,!1))},[i]),Le(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Hm,{isPresent:i,anchorX:a,root:l,children:t})),D(Zn.Provider,{value:h,children:t})};function Gm(){return new Map}function Hc(t=!0){const e=Fe(Zn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=oo();Le(()=>{if(t)return s(o)},[t]);const r=Ne(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const as=t=>t.key||"";function Wc(t){const e=[];return Lp.forEach(t,i=>{Al(i)&&e.push(i)}),e}const Gc=({children:t,custom:e,initial:i=!0,onExitComplete:n,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=Hc(r),d=ct(()=>Wc(t),[t]),h=r&&!c?[]:d.map(as),p=ce(!0),m=ce(d),v=Qn(()=>new Map),[b,y]=ve(d),[C,T]=ve(d);Ml(()=>{p.current=!1,m.current=d;for(let N=0;N<C.length;N++){const E=as(C[N]);h.includes(E)?v.delete(E):v.get(E)!==!0&&v.set(E,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let N=[...d];for(let E=0;E<C.length;E++){const k=C[E],f=as(k);h.includes(f)||(N.splice(E,0,k),A.push(k))}return o==="wait"&&A.length&&(N=A),T(Wc(N)),y(d),null}const{forceRender:x}=Fe(_o);return D(_t,{children:C.map(N=>{const E=as(N),k=r&&!c?!1:d===C||h.includes(E),f=()=>{if(v.has(E))v.set(E,!0);else return;let _=!0;v.forEach(g=>{g||(_=!1)}),_&&(x==null||x(),T(m.current),r&&(u==null||u()),n&&n())};return D(Wm,{isPresent:k,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:k?void 0:f,anchorX:a,children:N},E)})})},qc=Nt({strict:!1}),zc={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},xi={};for(const t in zc)xi[t]={isEnabled:e=>zc[t].some(i=>!!e[i])};function qm(t){for(const e in t)xi[e]={...xi[e],...t[e]}}const zm=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ls(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||zm.has(t)}let Kc=t=>!ls(t);function Yc(t){typeof t=="function"&&(Kc=e=>e.startsWith("on")?!ls(e):t(e))}try{Yc(require("@emotion/is-prop-valid").default)}catch{}function Km(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(Kc(s)||i===!0&&ls(s)||!e&&!ls(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Ym({children:t,isValidProp:e,...i}){e&&Yc(e),i={...Fe(fn),...i},i.isStatic=Qn(()=>i.isStatic);const n=ct(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(fn.Provider,{value:n,children:t})}function Xm(t){if(typeof Proxy>"u")return t;const e=new Map,i=(...n)=>t(...n);return new Proxy(i,{get:(n,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const cs=Nt({});function ds(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function pn(t){return typeof t=="string"||Array.isArray(t)}const rr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ar=["initial",...rr];function us(t){return ds(t.animate)||ar.some(e=>pn(t[e]))}function Xc(t){return!!(us(t)||t.variants)}function Jm(t,e){if(us(t)){const{initial:i,animate:n}=t;return{initial:i===!1||pn(i)?i:void 0,animate:pn(n)?n:void 0}}return t.inherit!==!1?e:{}}function Qm(t){const{initial:e,animate:i}=Jm(t,Fe(cs));return ct(()=>({initial:e,animate:i}),[Jc(e),Jc(i)])}function Jc(t){return Array.isArray(t)?t.join(" "):t}const Zm=Symbol.for("motionComponentSymbol");function Di(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function ev(t,e,i){return Ne(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):Di(i)&&(i.current=n))},[e])}const lr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Qc="data-"+lr("framerAppearId"),Zc=Nt({});function tv(t,e,i,n,s){var v,b;const{visualElement:o}=Fe(cs),r=Fe(qc),a=Fe(Zn),l=Fe(fn).reducedMotion,c=ce(null);n=n||r.renderer,!c.current&&n&&(c.current=n(t,{visualState:e,parent:o,props:i,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Fe(Zc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&iv(c.current,i,s,d);const h=ce(!1);pl(()=>{u&&h.current&&u.update(i,a)});const p=i[Qc],m=ce(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return Ml(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),nr.render(u.render),m.current&&u.animationState&&u.animationState.animateChanges())}),Le(()=>{u&&(!m.current&&u.animationState&&u.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),m.current=!1))}),u}function iv(t,e,i,n){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new i(t.latestValues,e["data-framer-portal-id"]?void 0:ed(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Di(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function ed(t){if(t)return t.options.allowProjection!==!1?t.projection:ed(t.parent)}function nv({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&qm(t);function o(a,l){let c;const u={...Fe(fn),...a,layoutId:sv(a)},{isStatic:d}=u,h=Qm(a),p=n(a,d);if(!d&&yo){ov();const m=rv(u);c=m.MeasureLayout,h.visualElement=tv(s,p,u,e,m.ProjectionNode)}return D(cs.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,ev(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Dp(o);return r[Zm]=s,r}function sv({layoutId:t}){const e=Fe(_o).id;return e&&t!==void 0?e+"-"+t:t}function ov(t,e){Fe(qc).strict}function rv(t){const{drag:e,layout:i}=xi;if(!e&&!i)return{};const n={...e,...i};return{MeasureLayout:e!=null&&e.isEnabled(t)||i!=null&&i.isEnabled(t)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}const gn={};function av(t){for(const e in t)gn[e]=t[e],Ao(e)&&(gn[e].isCSSVariable=!0)}function td(t,{layout:e,layoutId:i}){return Ai.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!gn[t]||t==="opacity")}const lv={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},cv=Ii.length;function dv(t,e,i){let n="",s=!0;for(let o=0;o<cv;o++){const r=Ii[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||i){const c=Oc(a,ir[r]);if(!l){s=!1;const u=lv[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function cr(t,e,i){const{style:n,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(Ai.has(l)){r=!0;continue}else if(Ao(l)){s[l]=c;continue}else{const u=Oc(c,ir[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=dv(e,t.transform,i):n.transform&&(n.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;n.transformOrigin=`${l} ${c} ${u}`}}const dr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function id(t,e,i){for(const n in e)!Ge(e[n])&&!td(n,i)&&(t[n]=e[n])}function uv({transformTemplate:t},e){return ct(()=>{const i=dr();return cr(i,e,t),Object.assign({},i.vars,i.style)},[e])}function hv(t,e){const i=t.style||{},n={};return id(n,i,t),Object.assign(n,uv(t,e)),n}function fv(t,e){const i={},n=hv(t,e);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=n,i}const pv={offset:"stroke-dashoffset",array:"stroke-dasharray"},gv={offset:"strokeDashoffset",array:"strokeDasharray"};function mv(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?pv:gv;t[o.offset]=Q.transform(-n);const r=Q.transform(e),a=Q.transform(i);t[o.array]=`${r} ${a}`}function nd(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(cr(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),i!==void 0&&(d.y=i),n!==void 0&&(d.scale=n),s!==void 0&&mv(d,s,o,r,!1)}const sd=()=>({...dr(),attrs:{}}),od=t=>typeof t=="string"&&t.toLowerCase()==="svg";function vv(t,e,i,n){const s=ct(()=>{const o=sd();return nd(o,e,od(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};id(o,t.style,t),s.style={...o,...s.style}}return s}const _v=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function ur(t){return typeof t!="string"||t.includes("-")?!1:!!(_v.indexOf(t)>-1||/[A-Z]/u.test(t))}function yv(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(ur(i)?vv:fv)(n,o,r,i),c=Km(n,typeof i=="string",t),u=i!==_t?{...c,...l,ref:s}:{},{children:d}=n,h=ct(()=>Ge(d)?d.get():d,[d]);return lt(i,{...u,children:h})}}function rd(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function hr(t,e,i,n){if(typeof e=="function"){const[s,o]=rd(n);e=e(i!==void 0?i:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=rd(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function hs(t){return Ge(t)?t.get():t}function bv({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:wv(i,n,s,t),renderState:e()}}const ad=t=>(e,i)=>{const n=Fe(cs),s=Fe(Zn),o=()=>bv(t,e,n,s);return i?o():Qn(o)};function wv(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=hs(o[h]);let{initial:r,animate:a}=t;const l=us(t),c=Xc(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=i?i.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!ds(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const m=hr(t,h[p]);if(m){const{transitionEnd:v,transition:b,...y}=m;for(const C in y){let T=y[C];if(Array.isArray(T)){const A=u?T.length-1:0;T=T[A]}T!==null&&(s[C]=T)}for(const C in v)s[C]=v[C]}}}return s}function fr(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ge(n[r])||e.style&&Ge(e.style[r])||td(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const Sv={useVisualState:ad({scrapeMotionValuesFromProps:fr,createRenderState:dr})};function ld(t,e,i){const n=fr(t,e,i);for(const s in t)if(Ge(t[s])||Ge(e[s])){const o=Ii.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const Cv={useVisualState:ad({scrapeMotionValuesFromProps:ld,createRenderState:sd})};function Tv(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...ur(n)?Cv:Sv,preloadedFeatures:t,useRender:yv(s),createVisualElement:e,Component:n};return nv(r)}}function mn(t,e,i){const n=t.getProps();return hr(n,e,i!==void 0?i:n.custom,t)}const pr=t=>Array.isArray(t);function kv(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,Ri(i))}function Ev(t){return pr(t)?t[t.length-1]||0:t}function Iv(t,e){const i=mn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=Ev(o[r]);kv(t,r,a)}}function Av(t){return!!(Ge(t)&&t.add)}function gr(t,e){const i=t.getValue("willChange");if(Av(i))return i.add(e);if(!i&&Ut.WillChange){const n=new Ut.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function cd(t){return t.props[Qc]}const Rv=t=>t!==null;function xv(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Rv),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Dv={type:"spring",stiffness:500,damping:25,restSpeed:10},Lv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Mv={type:"keyframes",duration:.8},Ov={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Pv=(t,{keyframes:e})=>e.length>2?Mv:Ai.has(t)?t.startsWith("scale")?Lv(e[1]):Dv:Ov;function Nv({when:t,delay:e,delayChildren:i,staggerChildren:n,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const mr=(t,e,i,n={},s,o)=>r=>{const a=er(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-kt(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Nv(a)||Object.assign(u,Pv(t,u)),u.duration&&(u.duration=kt(u.duration)),u.repeatDelay&&(u.repeatDelay=kt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(Ut.instantAnimations||Ut.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=xv(u.keyframes,a);if(h!==void 0){Ce.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Wo(u):new _m(u)};function Fv({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function dd(t,e,{delay:i=0,transitionOverride:n,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;n&&(o=n);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&Fv(c,u))continue;const p={delay:i,...er(o||{},u)},m=d.get();if(m!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===m&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=cd(t);if(y){const C=window.MotionHandoffAnimation(y,u,Ce);C!==null&&(p.startTime=C,v=!0)}}gr(t,u),d.start(mr(u,d,h,t.shouldReduceMotion&&Ic.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{Ce.update(()=>{r&&Iv(t,r)})}),l}function vr(t,e,i={}){var l;const n=mn(t,e,i.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=n||{};i.transitionOverride&&(s=i.transitionOverride);const o=n?()=>Promise.all(dd(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Uv(t,e,c,u,d,h,i)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(i.delay)])}function Uv(t,e,i=0,n=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof n=="function",d=u?h=>n(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(Bv).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(vr(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Bv(t,e){return t.sortNodePosition(e)}function Vv(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>vr(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=vr(t,e,i);else{const s=typeof e=="function"?mn(t,e,i.custom):e;n=Promise.all(dd(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function ud(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(e[n]!==t[n])return!1;return!0}const $v=ar.length;function hd(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?hd(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<$v;i++){const n=ar[i],s=t.props[n];(pn(s)||s===!1)&&(e[n]=s)}return e}const jv=[...rr].reverse(),Hv=rr.length;function Wv(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Vv(t,i,n)))}function Gv(t){let e=Wv(t),i=fd(),n=!0;const s=l=>(c,u)=>{var h;const d=mn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:m,...v}=d;c={...c,...v,...m}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=hd(t.parent)||{},d=[],h=new Set;let p={},m=1/0;for(let b=0;b<Hv;b++){const y=jv[b],C=i[y],T=c[y]!==void 0?c[y]:u[y],A=pn(T),x=y===l?C.isActive:null;x===!1&&(m=b);let N=T===u[y]&&T!==c[y]&&A;if(N&&n&&t.manuallyAnimateOnMount&&(N=!1),C.protectedKeys={...p},!C.isActive&&x===null||!T&&!C.prevProp||ds(T)||typeof T=="boolean")continue;const E=qv(C.prevProp,T);let k=E||y===l&&C.isActive&&!N&&A||b>m&&A,f=!1;const _=Array.isArray(T)?T:[T];let g=_.reduce(s(y),{});x===!1&&(g={});const{prevResolvedValues:S={}}=C,I={...S,...g},M=O=>{k=!0,h.has(O)&&(f=!0,h.delete(O)),C.needsAnimating[O]=!0;const L=t.getValue(O);L&&(L.liveStyle=!1)};for(const O in I){const L=g[O],V=S[O];if(p.hasOwnProperty(O))continue;let $=!1;pr(L)&&pr(V)?$=!ud(L,V):$=L!==V,$?L!=null?M(O):h.add(O):L!==void 0&&h.has(O)?M(O):C.protectedKeys[O]=!0}C.prevProp=T,C.prevResolvedValues=g,C.isActive&&(p={...p,...g}),n&&t.blockInitialAnimation&&(k=!1),k&&(!(N&&E)||f)&&d.push(..._.map(O=>({animation:O,options:{type:y}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const y=mn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(b.transition=y.transition)}h.forEach(y=>{const C=t.getBaseTarget(y),T=t.getValue(y);T&&(T.liveStyle=!0),b[y]=C??null}),d.push({animation:b})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var p;return(p=h.animationState)==null?void 0:p.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=fd(),n=!0}}}function qv(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!ud(e,t):!1}function ci(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fd(){return{animate:ci(!0),whileInView:ci(),whileHover:ci(),whileTap:ci(),whileDrag:ci(),whileFocus:ci(),exit:ci()}}class Yt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class zv extends Yt{constructor(e){super(e),e.animationState||(e.animationState=Gv(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();ds(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Kv=0;class Yv extends Yt{constructor(){super(...arguments),this.id=Kv++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const s=this.node.animationState.setActive("exit",!e);i&&!e&&s.then(()=>{i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Xv={animation:{Feature:zv},exit:{Feature:Yv}};function vn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function _n(t){return{point:{x:t.pageX,y:t.pageY}}}const Jv=t=>e=>sr(e)&&t(e,_n(e));function yn(t,e,i,n){return vn(t,e,Jv(i),n)}function pd({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Qv({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Zv(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}const gd=1e-4,e_=1-gd,t_=1+gd,md=.01,i_=0-md,n_=0+md;function Ke(t){return t.max-t.min}function s_(t,e,i){return Math.abs(t-e)<=i}function vd(t,e,i,n=.5){t.origin=n,t.originPoint=ke(e.min,e.max,t.origin),t.scale=Ke(i)/Ke(e),t.translate=ke(i.min,i.max,t.origin)-t.originPoint,(t.scale>=e_&&t.scale<=t_||isNaN(t.scale))&&(t.scale=1),(t.translate>=i_&&t.translate<=n_||isNaN(t.translate))&&(t.translate=0)}function bn(t,e,i,n){vd(t.x,e.x,i.x,n?n.originX:void 0),vd(t.y,e.y,i.y,n?n.originY:void 0)}function _d(t,e,i){t.min=i.min+e.min,t.max=t.min+Ke(e)}function o_(t,e,i){_d(t.x,e.x,i.x),_d(t.y,e.y,i.y)}function yd(t,e,i){t.min=e.min-i.min,t.max=t.min+Ke(e)}function wn(t,e,i){yd(t.x,e.x,i.x),yd(t.y,e.y,i.y)}const bd=()=>({translate:0,scale:1,origin:0,originPoint:0}),Li=()=>({x:bd(),y:bd()}),wd=()=>({min:0,max:0}),De=()=>({x:wd(),y:wd()});function ut(t){return[t("x"),t("y")]}function _r(t){return t===void 0||t===1}function yr({scale:t,scaleX:e,scaleY:i}){return!_r(t)||!_r(e)||!_r(i)}function di(t){return yr(t)||Sd(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Sd(t){return Cd(t.x)||Cd(t.y)}function Cd(t){return t&&t!=="0%"}function fs(t,e,i){const n=t-i,s=e*n;return i+s}function Td(t,e,i,n,s){return s!==void 0&&(t=fs(t,s,n)),fs(t,i,n)+e}function br(t,e=0,i=1,n,s){t.min=Td(t.min,e,i,n,s),t.max=Td(t.max,e,i,n,s)}function kd(t,{x:e,y:i}){br(t.x,e.translate,e.scale,e.originPoint),br(t.y,i.translate,i.scale,i.originPoint)}const Ed=.999999999999,Id=1.0000000000001;function r_(t,e,i,n=!1){const s=i.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=i[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(n&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Oi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,kd(t,r)),n&&di(o.latestValues)&&Oi(t,o.latestValues))}e.x<Id&&e.x>Ed&&(e.x=1),e.y<Id&&e.y>Ed&&(e.y=1)}function Mi(t,e){t.min=t.min+e,t.max=t.max+e}function Ad(t,e,i,n,s=.5){const o=ke(t.min,t.max,s);br(t,e,i,o,n)}function Oi(t,e){Ad(t.x,e.x,e.scaleX,e.scale,e.originX),Ad(t.y,e.y,e.scaleY,e.scale,e.originY)}function Rd(t,e){return pd(Zv(t.getBoundingClientRect(),e))}function a_(t,e,i){const n=Rd(t,i),{scroll:s}=e;return s&&(Mi(n.x,s.offset.x),Mi(n.y,s.offset.y)),n}const xd=({current:t})=>t?t.ownerDocument.defaultView:null,Dd=(t,e)=>Math.abs(t-e);function l_(t,e){const i=Dd(t.x,e.x),n=Dd(t.y,e.y);return Math.sqrt(i**2+n**2)}class Ld{constructor(e,i,{transformPagePoint:n,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=Sr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,m=l_(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!m)return;const{point:v}=h,{timestamp:b}=$e;this.history.push({...v,timestamp:b});const{onStart:y,onMove:C}=this.handlers;p||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=wr(p,this.transformPagePoint),Ce.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:m,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Sr(h.type==="pointercancel"?this.lastMoveEventInfo:wr(p,this.transformPagePoint),this.history);this.startEvent&&m&&m(h,y),v&&v(h,y)},!sr(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=_n(e),l=wr(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=$e;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,Sr(l,this.history)),this.removeListeners=sn(yn(this.contextWindow,"pointermove",this.handlePointerMove),yn(this.contextWindow,"pointerup",this.handlePointerUp),yn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),qt(this.updatePoint)}}function wr(t,e){return e?{point:e(t.point)}:t}function Md(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Sr({point:t},e){return{point:t,delta:Md(t,Od(e)),offset:Md(t,c_(e)),velocity:d_(e,.1)}}function c_(t){return t[0]}function Od(t){return t[t.length-1]}function d_(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Od(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>kt(e)));)i--;if(!n)return{x:0,y:0};const o=Et(s.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-n.x)/o,y:(s.y-n.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function u_(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?ke(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?ke(i,t,n.max):Math.min(t,i)),t}function Pd(t,e,i){return{min:e!==void 0?t.min+e:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function h_(t,{top:e,left:i,bottom:n,right:s}){return{x:Pd(t.x,i,s),y:Pd(t.y,e,n)}}function Nd(t,e){let i=e.min-t.min,n=e.max-t.max;return e.max-e.min<t.max-t.min&&([i,n]=[n,i]),{min:i,max:n}}function f_(t,e){return{x:Nd(t.x,e.x),y:Nd(t.y,e.y)}}function p_(t,e){let i=.5;const n=Ke(t),s=Ke(e);return s>n?i=on(e.min,e.max-n,t.min):n>s&&(i=on(t.min,t.max-s,e.min)),Ft(0,1,i)}function g_(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const Cr=.35;function m_(t=Cr){return t===!1?t=0:t===!0&&(t=Cr),{x:Fd(t,"left","right"),y:Fd(t,"top","bottom")}}function Fd(t,e,i){return{min:Ud(t,e),max:Ud(t,i)}}function Ud(t,e){return typeof t=="number"?t:t[e]||0}const v_=new WeakMap;class __{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=De(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:n}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),i&&this.snapToCursor(_n(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:m,onDragStart:v}=this.getProps();if(p&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mm(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ut(y=>{let C=this.getAxisMotionValue(y).get()||0;if(It.test(C)){const{projection:T}=this.visualElement;if(T&&T.layout){const A=T.layout.layoutBox[y];A&&(C=Ke(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&Ce.postRender(()=>v(d,h)),gr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:m,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=h;if(m&&this.currentDirection===null){this.currentDirection=y_(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),this.visualElement.render(),b&&b(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>ut(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Ld(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:xd(this.visualElement)})}stop(e,i){const n=e||this.latestPointerEvent,s=i||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!n)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&Ce.postRender(()=>a(n,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}updateAxis(e,i,n){const{drag:s}=this.getProps();if(!n||!ps(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=u_(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:i}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;e&&Di(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=h_(n.layoutBox,e):this.constraints=!1,this.elastic=m_(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&ut(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=g_(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!Di(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=a_(n,s.root,this.visualElement.getTransformPagePoint());let r=f_(s.layout.layoutBox,o);if(i){const a=i(Qv(r));this.hasMutatedConstraints=!!a,a&&(r=pd(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=ut(u=>{if(!ps(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,p=s?40:1e7,m={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,m)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return gr(this.visualElement,e),n.start(mr(e,n,0,i,this.visualElement,!1))}stopAnimation(){ut(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ut(e=>{var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.pause()})}getAnimationState(e){var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.state}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),s=n[i];return s||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){ut(i=>{const{drag:n}=this.getProps();if(!ps(i,n,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(i);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[i];o.set(e[i]-ke(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!Di(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};ut(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=p_({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),ut(r=>{if(!ps(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ke(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;v_.set(this.visualElement,this);const e=this.visualElement.current,i=yn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();Di(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",n);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),Ce.read(n);const r=vn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(ut(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Cr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function ps(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function y_(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class b_ extends Yt{constructor(e){super(e),this.removeGroupControls=dt,this.removeListeners=dt,this.controls=new __(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||dt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bd=t=>(e,i)=>{t&&Ce.postRender(()=>t(e,i))};class w_ extends Yt{constructor(){super(...arguments),this.removePointerDownListener=dt}onPointerDown(e){this.session=new Ld(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xd(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:Bd(e),onStart:Bd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&Ce.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=yn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const gs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vd(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Sn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(Q.test(t))t=parseFloat(t);else return t;const i=Vd(t,e.target.x),n=Vd(t,e.target.y);return`${i}% ${n}%`}},S_={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Kt.parse(t);if(s.length>5)return n;const o=Kt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=ke(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let $d=!1;class C_ extends yt{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;av(T_),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),$d&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),gs.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,$d=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||Ce.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),nr.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(s),n&&n.deregister&&n.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function jd(t){const[e,i]=Hc(),n=Fe(_o);return D(C_,{...t,layoutGroup:n,switchLayoutGroup:Fe(Zc),isPresent:e,safeToRemove:i})}const T_={borderRadius:{...Sn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Sn,borderTopRightRadius:Sn,borderBottomLeftRadius:Sn,borderBottomRightRadius:Sn,boxShadow:S_};function k_(t,e,i){const n=Ge(t)?t:Ri(t);return n.start(mr("",n,e,i)),n.animation}const E_=(t,e)=>t.depth-e.depth;class I_{constructor(){this.children=[],this.isDirty=!1}add(e){bo(this.children,e),this.isDirty=!0}remove(e){wo(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(E_),this.isDirty=!1,this.children.forEach(e)}}function A_(t,e){const i=tt.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(qt(n),t(o-e))};return Ce.setup(n,!0),()=>qt(n)}const Hd=["TopLeft","TopRight","BottomLeft","BottomRight"],R_=Hd.length,Wd=t=>typeof t=="string"?parseFloat(t):t,Gd=t=>typeof t=="number"||Q.test(t);function x_(t,e,i,n,s,o){s?(t.opacity=ke(0,i.opacity??1,D_(n)),t.opacityExit=ke(e.opacity??1,0,L_(n))):o&&(t.opacity=ke(e.opacity??1,i.opacity??1,n));for(let r=0;r<R_;r++){const a=`border${Hd[r]}Radius`;let l=qd(e,a),c=qd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Gd(l)===Gd(c)?(t[a]=Math.max(ke(Wd(l),Wd(c),n),0),(It.test(c)||It.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=ke(e.rotate||0,i.rotate||0,n))}function qd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const D_=zd(0,.5,Wl),L_=zd(.5,.95,dt);function zd(t,e,i){return n=>n<t?0:n>e?1:i(on(t,e,n))}function Kd(t,e){t.min=e.min,t.max=e.max}function ht(t,e){Kd(t.x,e.x),Kd(t.y,e.y)}function Yd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Xd(t,e,i,n,s){return t-=e,t=fs(t,1/i,n),s!==void 0&&(t=fs(t,1/s,n)),t}function M_(t,e=0,i=1,n=.5,s,o=t,r=t){if(It.test(e)&&(e=parseFloat(e),e=ke(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ke(o.min,o.max,n);t===o&&(a-=e),t.min=Xd(t.min,e,i,a,s),t.max=Xd(t.max,e,i,a,s)}function Jd(t,e,[i,n,s],o,r){M_(t,e[i],e[n],e[s],e.scale,o,r)}const O_=["x","scaleX","originX"],P_=["y","scaleY","originY"];function Qd(t,e,i,n){Jd(t.x,e,O_,i?i.x:void 0,n?n.x:void 0),Jd(t.y,e,P_,i?i.y:void 0,n?n.y:void 0)}function Zd(t){return t.translate===0&&t.scale===1}function eu(t){return Zd(t.x)&&Zd(t.y)}function tu(t,e){return t.min===e.min&&t.max===e.max}function N_(t,e){return tu(t.x,e.x)&&tu(t.y,e.y)}function iu(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function nu(t,e){return iu(t.x,e.x)&&iu(t.y,e.y)}function su(t){return Ke(t.x)/Ke(t.y)}function ou(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class F_{constructor(){this.members=[]}add(e){bo(this.members,e),e.scheduleRender()}remove(e){if(wo(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){const i=this.members.findIndex(s=>e===s);if(i===0)return!1;let n;for(let s=i;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){n=o;break}}return n?(this.promote(n),!0):!1}promote(e,i){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,i&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:i,resumingFrom:n}=e;i.onExitComplete&&i.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function U_(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:p,skewY:m}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),p&&(n+=`skewX(${p}deg) `),m&&(n+=`skewY(${m}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(n+=`scale(${a}, ${l})`),n||"none"}const Tr=["","X","Y","Z"],B_=1e3;let V_=0;function kr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function ru(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=cd(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",Ce,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&ru(n)}function au({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=V_++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(H_),this.nodes.forEach(z_),this.nodes.forEach(K_),this.nodes.forEach(W_)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new I_)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new To),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=jc(r)&&!Bm(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;Ce.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=A_(h,250),gs.hasAnimatedSinceResize&&(gs.hasAnimatedSinceResize=!1,this.nodes.forEach(du)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const m=this.options.transition||c.getDefaultTransition()||Z_,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),y=!this.targetLayout||!nu(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...er(m,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(u,C)}else d||du(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),qt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Y_),this.animationId++)}getTransformTemplate(){const{visualElement:r}=this.options;return r&&r.getProps().transformTemplate}willUpdate(r=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&ru(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(lu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(cu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(q_),this.nodes.forEach($_),this.nodes.forEach(j_)):this.nodes.forEach(cu),this.clearAllSnapshots();const a=tt.now();$e.delta=Ft(0,1e3/60,a-$e.timestamp),$e.timestamp=a,$e.isProcessing=!0,Io.update.process($e),Io.preRender.process($e),Io.render.process($e),$e.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,nr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(G_),this.sharedNodes.forEach(X_)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Ce.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Ce.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ke(this.snapshot.measuredBox.x)&&!Ke(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=De(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=n(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:i(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!eu(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||di(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),ey(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return De();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(ty))){const{scroll:u}=this.root;u&&(Mi(a.x,u.offset.x),Mi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=De();if(ht(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&ht(a,r),Mi(a.x,d.offset.x),Mi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=De();ht(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&Oi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),di(u.latestValues)&&Oi(l,u.latestValues)}return di(this.latestValues)&&Oi(l,this.latestValues),l}removeTransform(r){const a=De();ht(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!di(c.latestValues))continue;yr(c.latestValues)&&c.updateSnapshot();const u=De(),d=c.measurePageBox();ht(u,d),Qd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return di(this.latestValues)&&Qd(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==$e.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=$e.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=De(),this.relativeTargetOrigin=De(),wn(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),ht(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=De(),this.targetWithTransforms=De()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),o_(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ht(this.target,this.layout.layoutBox),kd(this.target,this.targetDelta)):ht(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=De(),this.relativeTargetOrigin=De(),wn(this.relativeTargetOrigin,this.target,p.target),ht(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||yr(this.parent.latestValues)||Sd(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var m;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===$e.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;ht(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;r_(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=De());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Yd(this.prevProjectionDelta.x,this.projectionDelta.x),Yd(this.prevProjectionDelta.y,this.projectionDelta.y)),bn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!ou(this.projectionDelta.x,this.prevProjectionDelta.x)||!ou(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Li(),this.projectionDelta=Li(),this.projectionDeltaWithTransform=Li()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Li();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=De(),p=l?l.source:void 0,m=this.layout?this.layout.source:void 0,v=p!==m,b=this.getStack(),y=!b||b.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Q_));this.animationProgress=0;let T;this.mixTargetDelta=A=>{const x=A/1e3;uu(d.x,r.x,x),uu(d.y,r.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(wn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),J_(this.relativeTarget,this.relativeTargetOrigin,h,x),T&&N_(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=De()),ht(T,this.relativeTarget)),v&&(this.animationValues=u,x_(u,c,this.latestValues,x,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(qt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ce.update(()=>{gs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Ri(0)),this.currentAnimation=k_(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(B_),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&mu(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||De();const d=Ke(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=Ke(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}ht(a,l),Oi(a,u),bn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new F_),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&kr("z",r,c,this.animationValues);for(let u=0;u<Tr.length;u++)kr(`rotate${Tr[u]}`,r,c,this.animationValues),kr(`skew${Tr[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=hs(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=hs(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!di(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=U_(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:p}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const m in gn){if(u[m]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:y}=gn[m],C=d==="none"?u[m]:v(u[m],c);if(b){const T=b.length;for(let A=0;A<T;A++)r[b[A]]=C}else y?this.options.visualElement.renderState.vars[m]=C:r[m]=C}this.options.layoutId&&(r.pointerEvents=c===this?hs(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(r=>{var a;return(a=r.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(lu),this.root.sharedNodes.clear()}}}function $_(t){t.updateLayout()}function j_(t){var i;const e=((i=t.resumeFrom)==null?void 0:i.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?ut(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(h);h.min=n[d].min,h.max=h.min+p}):mu(o,e.layoutBox,n)&&ut(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(n[d]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+p)});const a=Li();bn(a,n,e.layoutBox);const l=Li();r?bn(l,t.applyTransform(s,!0),e.measuredBox):bn(l,n,e.layoutBox);const c=!eu(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:p}=d;if(h&&p){const m=De();wn(m,e.layoutBox,h.layoutBox);const v=De();wn(v,n,p.layoutBox),nu(m,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=m,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function H_(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function W_(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function G_(t){t.clearSnapshot()}function lu(t){t.clearMeasurements()}function cu(t){t.isLayoutDirty=!1}function q_(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function du(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function z_(t){t.resolveTargetDelta()}function K_(t){t.calcProjection()}function Y_(t){t.resetSkewAndRotation()}function X_(t){t.removeLeadSnapshot()}function uu(t,e,i){t.translate=ke(e.translate,0,i),t.scale=ke(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function hu(t,e,i,n){t.min=ke(e.min,i.min,n),t.max=ke(e.max,i.max,n)}function J_(t,e,i,n){hu(t.x,e.x,i.x,n),hu(t.y,e.y,i.y,n)}function Q_(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Z_={duration:.45,ease:[.4,0,.1,1]},fu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),pu=fu("applewebkit/")&&!fu("chrome/")?Math.round:dt;function gu(t){t.min=pu(t.min),t.max=pu(t.max)}function ey(t){gu(t.x),gu(t.y)}function mu(t,e,i){return t==="position"||t==="preserve-aspect"&&!s_(su(e),su(i),.2)}function ty(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const iy=au({attachResizeListener:(t,e)=>vn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Er={current:void 0},vu=au({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Er.current){const t=new iy({});t.mount(window),t.setOptions({layoutScroll:!0}),Er.current=t}return Er.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),ny={pan:{Feature:w_},drag:{Feature:b_,ProjectionNode:vu,MeasureLayout:jd}};function _u(t,e,i){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",i==="Start");const s="onHover"+i,o=n[s];o&&Ce.postRender(()=>o(e,_n(e)))}class sy extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Om(e,(i,n)=>(_u(this.node,n,"Start"),s=>_u(this.node,s,"End"))))}unmount(){}}class oy extends Yt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=sn(vn(this.node.current,"focus",()=>this.onFocus()),vn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function yu(t,e,i){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",i==="Start");const s="onTap"+(i==="End"?"":i),o=n[s];o&&Ce.postRender(()=>o(e,_n(e)))}class ry extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Um(e,(i,n)=>(yu(this.node,n,"Start"),(s,{success:o})=>yu(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ir=new WeakMap,Ar=new WeakMap,ay=t=>{const e=Ir.get(t.target);e&&e(t)},ly=t=>{t.forEach(ay)};function cy({root:t,...e}){const i=t||document;Ar.has(i)||Ar.set(i,{});const n=Ar.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(ly,{root:t,...e})),n[s]}function dy(t,e,i){const n=cy(e);return Ir.set(t,i),n.observe(t),()=>{Ir.delete(t),n.unobserve(t)}}const uy={some:0,all:1};class hy extends Yt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:i,margin:n,amount:s="some",once:o}=e,r={root:i?i.current:void 0,rootMargin:n,threshold:typeof s=="number"?s:uy[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return dy(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(fy(e,i))&&this.startObserver()}unmount(){}}function fy({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const py={inView:{Feature:hy},tap:{Feature:ry},focus:{Feature:oy},hover:{Feature:sy}},gy={layout:{ProjectionNode:vu,MeasureLayout:jd}},Rr={current:null},bu={current:!1};function my(){if(bu.current=!0,!!yo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Rr.current=t.matches;t.addEventListener("change",e),e()}else Rr.current=!1}const vy=new WeakMap;function _y(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ge(s))t.addValue(n,s);else if(Ge(o))t.addValue(n,Ri(s,{owner:t}));else if(o!==s)if(t.hasValue(n)){const r=t.getValue(n);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(n);t.addValue(n,Ri(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const wu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class yy{scrapeMotionValuesFromProps(e,i,n){return{}}constructor({parent:e,props:i,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=tt.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Ce.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=i.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=i,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=us(i),this.isVariantNode=Xc(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const p=d[h];l[h]!==void 0&&Ge(p)&&p.set(l[h],!1)}}mount(e){this.current=e,vy.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,n)=>this.bindToMotionValue(n,i)),bu.current||my(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Rr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),qt(this.notifyUpdate),qt(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const i=this.features[e];i&&(i.unmount(),i.isMounted=!1)}this.current=null}bindToMotionValue(e,i){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=Ai.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&Ce.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),o=i.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),i.owner&&i.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in xi){const i=xi[e];if(!i)continue;const{isEnabled:n,Feature:s}=i;if(!this.features[e]&&s&&n(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):De()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let n=0;n<wu.length;n++){const s=wu[n];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=_y(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const i=this.getClosestVariantNode();if(i)return i.variantChildren&&i.variantChildren.add(e),()=>i.variantChildren.delete(e)}addValue(e,i){const n=this.values.get(e);i!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&i!==void 0&&(n=Ri(i===null?void 0:i,{owner:this}),this.addValue(e,n)),n}readValue(e,i){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(Ol(n)||Nl(n))?n=parseFloat(n):!$m(n)&&Kt.test(i)&&(n=Mc(e,i)),this.setBaseTarget(e,Ge(n)?n.get():n)),Ge(n)?n.get():n}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var o;const{initial:i}=this.props;let n;if(typeof i=="string"||typeof i=="object"){const r=hr(this.props,i,(o=this.presenceContext)==null?void 0:o.custom);r&&(n=r[e])}if(i&&n!==void 0)return n;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ge(s)?s:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new To),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Su extends yy{constructor(){super(...arguments),this.KeyframeResolver=Rm}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){return e.style?e.style[i]:void 0}removeValueFromRenderState(e,{vars:i,style:n}){delete i[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ge(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function Cu(t,{style:e,vars:i},n,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,n);for(r in i)o.setProperty(r,i[r])}function by(t){return window.getComputedStyle(t)}class wy extends Su{constructor(){super(...arguments),this.type="html",this.renderInstance=Cu}readValueFromInstance(e,i){var n;if(Ai.has(i))return(n=this.projection)!=null&&n.isProjecting?zo(i):Yg(e,i);{const s=by(e),o=(Ao(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Rd(e,i)}build(e,i,n){cr(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return fr(e,i,n)}}const Tu=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Sy(t,e,i,n){Cu(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(Tu.has(s)?s:lr(s),e.attrs[s])}class Cy extends Su{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=De}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(Ai.has(i)){const n=Lc(i);return n&&n.default||0}return i=Tu.has(i)?i:lr(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return ld(e,i,n)}build(e,i,n){nd(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){Sy(e,i,n,s)}mount(e){this.isSVGTag=od(e.tagName),super.mount(e)}}const Ty=(t,e)=>ur(t)?new Cy(e):new wy(e,{allowProjection:t!==_t}),ky=Tv({...Xv,...py,...ny,...gy},Ty),Xt=Xm(ky),Ey=["agent-id","debug","environment","position","version-id","trickle-ice","prefetch-ice-candidates","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","text-only","text-chat-url","region","rtc-ip","rtc-port","skip-last-voice-sdk-id","streaming-audio"],Cn="widget-layout-id";function ku(t){var e,i,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=ku(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function Bt(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=ku(t))&&(n&&(n+=" "),n+=e);return n}const Iy=Yn("listening"),ms=()=>Ll(Iy);function Eu(t){var i;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((i=e.params)==null?void 0:i.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Tn={theme:"dark",audio_visualizer_config:{color:"verdant",preset:"roundBars"},start_call_text:"Let's chat",default_state:"collapsed",position:"fixed",view_history_url:null,report_issue_url:null,give_feedback_url:null,agent_thinking_text:"Thinking...",speak_to_interrupt_text:"Speak to interrupt",logo_icon_url:null},Iu=Yn(Tn),Au=()=>{const t=Jn(Iu);return Ne(e=>t(()=>{const i={...Tn,...e};return i.start_call_text||(i.start_call_text=Tn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Tn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Tn.speak_to_interrupt_text),i}),[t])},ui=()=>vo(Iu),xr=({size:t="large",className:e})=>{const i=ui(),[n]=ms();return D("h1",{className:Bt({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Ru=({stream:t,chatMode:e})=>{const i=ce(null);return Le(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(m),v.contains(m)&&v.removeChild(m)}},[e]),D(jm,{isPresent:e,childRef:o,sizeRef:r,children:Hp(t,{ref:o})})}const Wm=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Qi(Gm),u=oo();let d=!0,h=dt(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:p=>{c.set(p,!0);for(const m of c.values())if(!m)return;i&&i()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[n,c,i]);return o&&d&&(h={...h}),dt(()=>{c.forEach((p,m)=>c.set(m,!1))},[n]),Ie(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=D(Hm,{isPresent:n,anchorX:a,root:l,children:t})),D(Zi.Provider,{value:h,children:t})};function Gm(){return new Map}function Hc(t=!0){const e=Ue(Zi);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=oo();Ie(()=>{if(t)return s(o)},[t]);const r=Ne(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const as=t=>t.key||"";function Wc(t){const e=[];return Lp.forEach(t,n=>{Al(n)&&e.push(n)}),e}const Gc=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=Hc(r),d=dt(()=>Wc(t),[t]),h=r&&!c?[]:d.map(as),p=ue(!0),m=ue(d),v=Qi(()=>new Map),[b,y]=me(d),[C,T]=me(d);Ml(()=>{p.current=!1,m.current=d;for(let N=0;N<C.length;N++){const k=as(C[N]);h.includes(k)?v.delete(k):v.get(k)!==!0&&v.set(k,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let N=[...d];for(let k=0;k<C.length;k++){const E=C[k],f=as(E);h.includes(f)||(N.splice(k,0,E),A.push(E))}return o==="wait"&&A.length&&(N=A),T(Wc(N)),y(d),null}const{forceRender:x}=Ue(_o);return D(yt,{children:C.map(N=>{const k=as(N),E=r&&!c?!1:d===C||h.includes(k),f=()=>{if(v.has(k))v.set(k,!0);else return;let _=!0;v.forEach(g=>{g||(_=!1)}),_&&(x==null||x(),T(m.current),r&&(u==null||u()),i&&i())};return D(Wm,{isPresent:E,initial:!p.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:f,anchorX:a,children:N},k)})})},qc=Nt({strict:!1}),zc={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Ln={};for(const t in zc)Ln[t]={isEnabled:e=>zc[t].some(n=>!!e[n])};function qm(t){for(const e in t)Ln[e]={...Ln[e],...t[e]}}const zm=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function ls(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||zm.has(t)}let Kc=t=>!ls(t);function Yc(t){typeof t=="function"&&(Kc=e=>e.startsWith("on")?!ls(e):t(e))}try{Yc(require("@emotion/is-prop-valid").default)}catch{}function Km(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Kc(s)||n===!0&&ls(s)||!e&&!ls(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Ym({children:t,isValidProp:e,...n}){e&&Yc(e),n={...Ue(pi),...n},n.isStatic=Qi(()=>n.isStatic);const i=dt(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return D(pi.Provider,{value:i,children:t})}function Xm(t){if(typeof Proxy>"u")return t;const e=new Map,n=(...i)=>t(...i);return new Proxy(n,{get:(i,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const cs=Nt({});function ds(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function gi(t){return typeof t=="string"||Array.isArray(t)}const rr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],ar=["initial",...rr];function us(t){return ds(t.animate)||ar.some(e=>gi(t[e]))}function Xc(t){return!!(us(t)||t.variants)}function Jm(t,e){if(us(t)){const{initial:n,animate:i}=t;return{initial:n===!1||gi(n)?n:void 0,animate:gi(i)?i:void 0}}return t.inherit!==!1?e:{}}function Qm(t){const{initial:e,animate:n}=Jm(t,Ue(cs));return dt(()=>({initial:e,animate:n}),[Jc(e),Jc(n)])}function Jc(t){return Array.isArray(t)?t.join(" "):t}const Zm=Symbol.for("motionComponentSymbol");function Mn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function ev(t,e,n){return Ne(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):Mn(n)&&(n.current=i))},[e])}const lr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Qc="data-"+lr("framerAppearId"),Zc=Nt({});function tv(t,e,n,i,s){var v,b;const{visualElement:o}=Ue(cs),r=Ue(qc),a=Ue(Zi),l=Ue(pi).reducedMotion,c=ue(null);i=i||r.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Ue(Zc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&nv(c.current,n,s,d);const h=ue(!1);pl(()=>{u&&h.current&&u.update(n,a)});const p=n[Qc],m=ue(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return Ml(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),ir.render(u.render),m.current&&u.animationState&&u.animationState.animateChanges())}),Ie(()=>{u&&(!m.current&&u.animationState&&u.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),m.current=!1))}),u}function nv(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:ed(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Mn(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:c})}function ed(t){if(t)return t.options.allowProjection!==!1?t.projection:ed(t.parent)}function iv({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&qm(t);function o(a,l){let c;const u={...Ue(pi),...a,layoutId:sv(a)},{isStatic:d}=u,h=Qm(a),p=i(a,d);if(!d&&yo){ov();const m=rv(u);c=m.MeasureLayout,h.visualElement=tv(s,p,u,e,m.ProjectionNode)}return D(cs.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,n(s,a,ev(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Dp(o);return r[Zm]=s,r}function sv({layoutId:t}){const e=Ue(_o).id;return e&&t!==void 0?e+"-"+t:t}function ov(t,e){Ue(qc).strict}function rv(t){const{drag:e,layout:n}=Ln;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e!=null&&e.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const mi={};function av(t){for(const e in t)mi[e]=t[e],Ao(e)&&(mi[e].isCSSVariable=!0)}function td(t,{layout:e,layoutId:n}){return xn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!mi[t]||t==="opacity")}const lv={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},cv=Rn.length;function dv(t,e,n){let i="",s=!0;for(let o=0;o<cv;o++){const r=Rn[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Oc(a,nr[r]);if(!l){s=!1;const u=lv[r]||r;i+=`${u}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function cr(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(xn.has(l)){r=!0;continue}else if(Ao(l)){s[l]=c;continue}else{const u=Oc(c,nr[l]);l.startsWith("origin")?(a=!0,o[l]=u):i[l]=u}}if(e.transform||(r||n?i.transform=dv(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;i.transformOrigin=`${l} ${c} ${u}`}}const dr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function nd(t,e,n){for(const i in e)!Ge(e[i])&&!td(i,n)&&(t[i]=e[i])}function uv({transformTemplate:t},e){return dt(()=>{const n=dr();return cr(n,e,t),Object.assign({},n.vars,n.style)},[e])}function hv(t,e){const n=t.style||{},i={};return nd(i,n,t),Object.assign(i,uv(t,e)),i}function fv(t,e){const n={},i=hv(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const pv={offset:"stroke-dashoffset",array:"stroke-dasharray"},gv={offset:"strokeDashoffset",array:"strokeDasharray"};function mv(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?pv:gv;t[o.offset]=ee.transform(-i);const r=ee.transform(e),a=ee.transform(n);t[o.array]=`${r} ${a}`}function id(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(cr(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),s!==void 0&&mv(d,s,o,r,!1)}const sd=()=>({...dr(),attrs:{}}),od=t=>typeof t=="string"&&t.toLowerCase()==="svg";function vv(t,e,n,i){const s=dt(()=>{const o=sd();return id(o,e,od(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};nd(o,t.style,t),s.style={...o,...s.style}}return s}const _v=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function ur(t){return typeof t!="string"||t.includes("-")?!1:!!(_v.indexOf(t)>-1||/[A-Z]/u.test(t))}function yv(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(ur(n)?vv:fv)(i,o,r,n),c=Km(i,typeof n=="string",t),u=n!==yt?{...c,...l,ref:s}:{},{children:d}=i,h=dt(()=>Ge(d)?d.get():d,[d]);return ct(n,{...u,children:h})}}function rd(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function hr(t,e,n,i){if(typeof e=="function"){const[s,o]=rd(i);e=e(n!==void 0?n:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=rd(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function hs(t){return Ge(t)?t.get():t}function bv({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:wv(n,i,s,t),renderState:e()}}const ad=t=>(e,n)=>{const i=Ue(cs),s=Ue(Zi),o=()=>bv(t,e,i,s);return n?o():Qi(o)};function wv(t,e,n,i){const s={},o=i(t,{});for(const h in o)s[h]=hs(o[h]);let{initial:r,animate:a}=t;const l=us(t),c=Xc(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!ds(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const m=hr(t,h[p]);if(m){const{transitionEnd:v,transition:b,...y}=m;for(const C in y){let T=y[C];if(Array.isArray(T)){const A=u?T.length-1:0;T=T[A]}T!==null&&(s[C]=T)}for(const C in v)s[C]=v[C]}}}return s}function fr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Ge(i[r])||e.style&&Ge(e.style[r])||td(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const Sv={useVisualState:ad({scrapeMotionValuesFromProps:fr,createRenderState:dr})};function ld(t,e,n){const i=fr(t,e,n);for(const s in t)if(Ge(t[s])||Ge(e[s])){const o=Rn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const Cv={useVisualState:ad({scrapeMotionValuesFromProps:ld,createRenderState:sd})};function Tv(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...ur(i)?Cv:Sv,preloadedFeatures:t,useRender:yv(s),createVisualElement:e,Component:i};return iv(r)}}function vi(t,e,n){const i=t.getProps();return hr(i,e,n!==void 0?n:i.custom,t)}const pr=t=>Array.isArray(t);function Ev(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,Dn(n))}function kv(t){return pr(t)?t[t.length-1]||0:t}function Iv(t,e){const n=vi(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=kv(o[r]);Ev(t,r,a)}}function Av(t){return!!(Ge(t)&&t.add)}function gr(t,e){const n=t.getValue("willChange");if(Av(n))return n.add(e);if(!n&&Ut.WillChange){const i=new Ut.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function cd(t){return t.props[Qc]}const Rv=t=>t!==null;function xv(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Rv),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Dv={type:"spring",stiffness:500,damping:25,restSpeed:10},Lv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Mv={type:"keyframes",duration:.8},Ov={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Pv=(t,{keyframes:e})=>e.length>2?Mv:xn.has(t)?t.startsWith("scale")?Lv(e[1]):Dv:Ov;function Nv({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const mr=(t,e,n,i={},s,o)=>r=>{const a=er(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-Et(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Nv(a)||Object.assign(u,Pv(t,u)),u.duration&&(u.duration=Et(u.duration)),u.repeatDelay&&(u.repeatDelay=Et(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(Ut.instantAnimations||Ut.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=xv(u.keyframes,a);if(h!==void 0){Te.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Wo(u):new _m(u)};function Fv({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function dd(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&Fv(c,u))continue;const p={delay:n,...er(o||{},u)},m=d.get();if(m!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===m&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=cd(t);if(y){const C=window.MotionHandoffAnimation(y,u,Te);C!==null&&(p.startTime=C,v=!0)}}gr(t,u),d.start(mr(u,d,h,t.shouldReduceMotion&&Ic.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{Te.update(()=>{r&&Iv(t,r)})}),l}function vr(t,e,n={}){var l;const i=vi(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(dd(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Uv(t,e,c,u,d,h,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(n.delay)])}function Uv(t,e,n=0,i=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof i=="function",d=u?h=>i(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(Bv).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(vr(h,e,{...r,delay:n+(u?0:i)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Bv(t,e){return t.sortNodePosition(e)}function Vv(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>vr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=vr(t,e,n);else{const s=typeof e=="function"?vi(t,e,n.custom):e;i=Promise.all(dd(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function ud(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const $v=ar.length;function hd(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?hd(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<$v;n++){const i=ar[n],s=t.props[i];(gi(s)||s===!1)&&(e[i]=s)}return e}const jv=[...rr].reverse(),Hv=rr.length;function Wv(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Vv(t,n,i)))}function Gv(t){let e=Wv(t),n=fd(),i=!0;const s=l=>(c,u)=>{var h;const d=vi(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:m,...v}=d;c={...c,...v,...m}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=hd(t.parent)||{},d=[],h=new Set;let p={},m=1/0;for(let b=0;b<Hv;b++){const y=jv[b],C=n[y],T=c[y]!==void 0?c[y]:u[y],A=gi(T),x=y===l?C.isActive:null;x===!1&&(m=b);let N=T===u[y]&&T!==c[y]&&A;if(N&&i&&t.manuallyAnimateOnMount&&(N=!1),C.protectedKeys={...p},!C.isActive&&x===null||!T&&!C.prevProp||ds(T)||typeof T=="boolean")continue;const k=qv(C.prevProp,T);let E=k||y===l&&C.isActive&&!N&&A||b>m&&A,f=!1;const _=Array.isArray(T)?T:[T];let g=_.reduce(s(y),{});x===!1&&(g={});const{prevResolvedValues:S={}}=C,I={...S,...g},P=O=>{E=!0,h.has(O)&&(f=!0,h.delete(O)),C.needsAnimating[O]=!0;const L=t.getValue(O);L&&(L.liveStyle=!1)};for(const O in I){const L=g[O],V=S[O];if(p.hasOwnProperty(O))continue;let j=!1;pr(L)&&pr(V)?j=!ud(L,V):j=L!==V,j?L!=null?P(O):h.add(O):L!==void 0&&h.has(O)?P(O):C.protectedKeys[O]=!0}C.prevProp=T,C.prevResolvedValues=g,C.isActive&&(p={...p,...g}),i&&t.blockInitialAnimation&&(E=!1),E&&(!(N&&k)||f)&&d.push(..._.map(O=>({animation:O,options:{type:y}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const y=vi(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(b.transition=y.transition)}h.forEach(y=>{const C=t.getBaseTarget(y),T=t.getValue(y);T&&(T.liveStyle=!0),b[y]=C??null}),d.push({animation:b})}let v=!!d.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),i=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var p;return(p=h.animationState)==null?void 0:p.setActive(l,c)}),n[l].isActive=c;const u=r(l);for(const h in n)n[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=fd(),i=!0}}}function qv(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!ud(e,t):!1}function dn(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fd(){return{animate:dn(!0),whileInView:dn(),whileHover:dn(),whileTap:dn(),whileDrag:dn(),whileFocus:dn(),exit:dn()}}class Yt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class zv extends Yt{constructor(e){super(e),e.animationState||(e.animationState=Gv(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();ds(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Kv=0;class Yv extends Yt{constructor(){super(...arguments),this.id=Kv++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Xv={animation:{Feature:zv},exit:{Feature:Yv}};function _i(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function yi(t){return{point:{x:t.pageX,y:t.pageY}}}const Jv=t=>e=>sr(e)&&t(e,yi(e));function bi(t,e,n,i){return _i(t,e,Jv(n),i)}function pd({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Qv({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Zv(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const gd=1e-4,e_=1-gd,t_=1+gd,md=.01,n_=0-md,i_=0+md;function Ke(t){return t.max-t.min}function s_(t,e,n){return Math.abs(t-e)<=n}function vd(t,e,n,i=.5){t.origin=i,t.originPoint=ke(e.min,e.max,t.origin),t.scale=Ke(n)/Ke(e),t.translate=ke(n.min,n.max,t.origin)-t.originPoint,(t.scale>=e_&&t.scale<=t_||isNaN(t.scale))&&(t.scale=1),(t.translate>=n_&&t.translate<=i_||isNaN(t.translate))&&(t.translate=0)}function wi(t,e,n,i){vd(t.x,e.x,n.x,i?i.originX:void 0),vd(t.y,e.y,n.y,i?i.originY:void 0)}function _d(t,e,n){t.min=n.min+e.min,t.max=t.min+Ke(e)}function o_(t,e,n){_d(t.x,e.x,n.x),_d(t.y,e.y,n.y)}function yd(t,e,n){t.min=e.min-n.min,t.max=t.min+Ke(e)}function Si(t,e,n){yd(t.x,e.x,n.x),yd(t.y,e.y,n.y)}const bd=()=>({translate:0,scale:1,origin:0,originPoint:0}),On=()=>({x:bd(),y:bd()}),wd=()=>({min:0,max:0}),De=()=>({x:wd(),y:wd()});function ht(t){return[t("x"),t("y")]}function _r(t){return t===void 0||t===1}function yr({scale:t,scaleX:e,scaleY:n}){return!_r(t)||!_r(e)||!_r(n)}function un(t){return yr(t)||Sd(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Sd(t){return Cd(t.x)||Cd(t.y)}function Cd(t){return t&&t!=="0%"}function fs(t,e,n){const i=t-n,s=e*i;return n+s}function Td(t,e,n,i,s){return s!==void 0&&(t=fs(t,s,i)),fs(t,n,i)+e}function br(t,e=0,n=1,i,s){t.min=Td(t.min,e,n,i,s),t.max=Td(t.max,e,n,i,s)}function Ed(t,{x:e,y:n}){br(t.x,e.translate,e.scale,e.originPoint),br(t.y,n.translate,n.scale,n.originPoint)}const kd=.999999999999,Id=1.0000000000001;function r_(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&Nn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Ed(t,r)),i&&un(o.latestValues)&&Nn(t,o.latestValues))}e.x<Id&&e.x>kd&&(e.x=1),e.y<Id&&e.y>kd&&(e.y=1)}function Pn(t,e){t.min=t.min+e,t.max=t.max+e}function Ad(t,e,n,i,s=.5){const o=ke(t.min,t.max,s);br(t,e,n,o,i)}function Nn(t,e){Ad(t.x,e.x,e.scaleX,e.scale,e.originX),Ad(t.y,e.y,e.scaleY,e.scale,e.originY)}function Rd(t,e){return pd(Zv(t.getBoundingClientRect(),e))}function a_(t,e,n){const i=Rd(t,n),{scroll:s}=e;return s&&(Pn(i.x,s.offset.x),Pn(i.y,s.offset.y)),i}const xd=({current:t})=>t?t.ownerDocument.defaultView:null,Dd=(t,e)=>Math.abs(t-e);function l_(t,e){const n=Dd(t.x,e.x),i=Dd(t.y,e.y);return Math.sqrt(n**2+i**2)}class Ld{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=Sr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,m=l_(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!m)return;const{point:v}=h,{timestamp:b}=$e;this.history.push({...v,timestamp:b});const{onStart:y,onMove:C}=this.handlers;p||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=wr(p,this.transformPagePoint),Te.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:m,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Sr(h.type==="pointercancel"?this.lastMoveEventInfo:wr(p,this.transformPagePoint),this.history);this.startEvent&&m&&m(h,y),v&&v(h,y)},!sr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=yi(e),l=wr(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=$e;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,Sr(l,this.history)),this.removeListeners=oi(bi(this.contextWindow,"pointermove",this.handlePointerMove),bi(this.contextWindow,"pointerup",this.handlePointerUp),bi(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),qt(this.updatePoint)}}function wr(t,e){return e?{point:e(t.point)}:t}function Md(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Sr({point:t},e){return{point:t,delta:Md(t,Od(e)),offset:Md(t,c_(e)),velocity:d_(e,.1)}}function c_(t){return t[0]}function Od(t){return t[t.length-1]}function d_(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=Od(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>Et(e)));)n--;if(!i)return{x:0,y:0};const o=kt(s.timestamp-i.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-i.x)/o,y:(s.y-i.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function u_(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ke(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ke(n,t,i.max):Math.min(t,n)),t}function Pd(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function h_(t,{top:e,left:n,bottom:i,right:s}){return{x:Pd(t.x,n,s),y:Pd(t.y,e,i)}}function Nd(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function f_(t,e){return{x:Nd(t.x,e.x),y:Nd(t.y,e.y)}}function p_(t,e){let n=.5;const i=Ke(t),s=Ke(e);return s>i?n=ri(e.min,e.max-i,t.min):i>s&&(n=ri(t.min,t.max-s,e.min)),Ft(0,1,n)}function g_(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const Cr=.35;function m_(t=Cr){return t===!1?t=0:t===!0&&(t=Cr),{x:Fd(t,"left","right"),y:Fd(t,"top","bottom")}}function Fd(t,e,n){return{min:Ud(t,e),max:Ud(t,n)}}function Ud(t,e){return typeof t=="number"?t:t[e]||0}const v_=new WeakMap;class __{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=De(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(yi(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:m,onDragStart:v}=this.getProps();if(p&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mm(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ht(y=>{let C=this.getAxisMotionValue(y).get()||0;if(It.test(C)){const{projection:T}=this.visualElement;if(T&&T.layout){const A=T.layout.layoutBox[y];A&&(C=Ke(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&Te.postRender(()=>v(d,h)),gr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:m,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=h;if(m&&this.currentDirection===null){this.currentDirection=y_(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),this.visualElement.render(),b&&b(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>ht(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Ld(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:xd(this.visualElement)})}stop(e,n){const i=e||this.latestPointerEvent,s=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!i)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&Te.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,i){const{drag:s}=this.getProps();if(!i||!ps(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=u_(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;e&&Mn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=h_(i.layoutBox,e):this.constraints=!1,this.elastic=m_(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ht(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=g_(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!Mn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=a_(i,s.root,this.visualElement.getTransformPagePoint());let r=f_(s.layout.layoutBox,o);if(n){const a=n(Qv(r));this.hasMutatedConstraints=!!a,a&&(r=pd(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=ht(u=>{if(!ps(u,n,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,p=s?40:1e7,m={type:"inertia",velocity:i?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,m)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return gr(this.visualElement,e),i.start(mr(e,i,0,n,this.visualElement,!1))}stopAnimation(){ht(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ht(e=>{var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.pause()})}getAnimationState(e){var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){ht(n=>{const{drag:i}=this.getProps();if(!ps(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(n);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[n];o.set(e[n]-ke(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!Mn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};ht(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=p_({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),ht(r=>{if(!ps(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ke(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;v_.set(this.visualElement,this);const e=this.visualElement.current,n=bi(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();Mn(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),Te.read(i);const r=_i(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(ht(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Cr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function ps(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function y_(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class b_ extends Yt{constructor(e){super(e),this.removeGroupControls=ut,this.removeListeners=ut,this.controls=new __(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ut}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bd=t=>(e,n)=>{t&&Te.postRender(()=>t(e,n))};class w_ extends Yt{constructor(){super(...arguments),this.removePointerDownListener=ut}onPointerDown(e){this.session=new Ld(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xd(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Bd(e),onStart:Bd(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&Te.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=bi(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const gs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vd(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Ci={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(ee.test(t))t=parseFloat(t);else return t;const n=Vd(t,e.target.x),i=Vd(t,e.target.y);return`${n}% ${i}%`}},S_={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Kt.parse(t);if(s.length>5)return i;const o=Kt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=ke(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let $d=!1;class C_ extends bt{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;av(T_),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),$d&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),gs.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,$d=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||Te.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),ir.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function jd(t){const[e,n]=Hc(),i=Ue(_o);return D(C_,{...t,layoutGroup:i,switchLayoutGroup:Ue(Zc),isPresent:e,safeToRemove:n})}const T_={borderRadius:{...Ci,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Ci,borderTopRightRadius:Ci,borderBottomLeftRadius:Ci,borderBottomRightRadius:Ci,boxShadow:S_};function E_(t,e,n){const i=Ge(t)?t:Dn(t);return i.start(mr("",i,e,n)),i.animation}const k_=(t,e)=>t.depth-e.depth;class I_{constructor(){this.children=[],this.isDirty=!1}add(e){bo(this.children,e),this.isDirty=!0}remove(e){wo(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(k_),this.isDirty=!1,this.children.forEach(e)}}function A_(t,e){const n=tt.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(qt(i),t(o-e))};return Te.setup(i,!0),()=>qt(i)}const Hd=["TopLeft","TopRight","BottomLeft","BottomRight"],R_=Hd.length,Wd=t=>typeof t=="string"?parseFloat(t):t,Gd=t=>typeof t=="number"||ee.test(t);function x_(t,e,n,i,s,o){s?(t.opacity=ke(0,n.opacity??1,D_(i)),t.opacityExit=ke(e.opacity??1,0,L_(i))):o&&(t.opacity=ke(e.opacity??1,n.opacity??1,i));for(let r=0;r<R_;r++){const a=`border${Hd[r]}Radius`;let l=qd(e,a),c=qd(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Gd(l)===Gd(c)?(t[a]=Math.max(ke(Wd(l),Wd(c),i),0),(It.test(c)||It.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ke(e.rotate||0,n.rotate||0,i))}function qd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const D_=zd(0,.5,Wl),L_=zd(.5,.95,ut);function zd(t,e,n){return i=>i<t?0:i>e?1:n(ri(t,e,i))}function Kd(t,e){t.min=e.min,t.max=e.max}function ft(t,e){Kd(t.x,e.x),Kd(t.y,e.y)}function Yd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Xd(t,e,n,i,s){return t-=e,t=fs(t,1/n,i),s!==void 0&&(t=fs(t,1/s,i)),t}function M_(t,e=0,n=1,i=.5,s,o=t,r=t){if(It.test(e)&&(e=parseFloat(e),e=ke(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ke(o.min,o.max,i);t===o&&(a-=e),t.min=Xd(t.min,e,n,a,s),t.max=Xd(t.max,e,n,a,s)}function Jd(t,e,[n,i,s],o,r){M_(t,e[n],e[i],e[s],e.scale,o,r)}const O_=["x","scaleX","originX"],P_=["y","scaleY","originY"];function Qd(t,e,n,i){Jd(t.x,e,O_,n?n.x:void 0,i?i.x:void 0),Jd(t.y,e,P_,n?n.y:void 0,i?i.y:void 0)}function Zd(t){return t.translate===0&&t.scale===1}function eu(t){return Zd(t.x)&&Zd(t.y)}function tu(t,e){return t.min===e.min&&t.max===e.max}function N_(t,e){return tu(t.x,e.x)&&tu(t.y,e.y)}function nu(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function iu(t,e){return nu(t.x,e.x)&&nu(t.y,e.y)}function su(t){return Ke(t.x)/Ke(t.y)}function ou(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class F_{constructor(){this.members=[]}add(e){bo(this.members,e),e.scheduleRender()}remove(e){if(wo(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===s);if(n===0)return!1;let i;for(let s=n;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){i=o;break}}return i?(this.promote(i),!0):!1}promote(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function U_(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:p,skewY:m}=n;c&&(i=`perspective(${c}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),h&&(i+=`rotateY(${h}deg) `),p&&(i+=`skewX(${p}deg) `),m&&(i+=`skewY(${m}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Tr=["","X","Y","Z"],B_=1e3;let V_=0;function Er(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function ru(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=cd(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",Te,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&ru(i)}function au({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=V_++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(H_),this.nodes.forEach(z_),this.nodes.forEach(K_),this.nodes.forEach(W_)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new I_)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new To),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=jc(r)&&!Bm(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;Te.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=A_(h,250),gs.hasAnimatedSinceResize&&(gs.hasAnimatedSinceResize=!1,this.nodes.forEach(du)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const m=this.options.transition||c.getDefaultTransition()||Z_,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),y=!this.targetLayout||!iu(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...er(m,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(u,C)}else d||du(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),qt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Y_),this.animationId++)}getTransformTemplate(){const{visualElement:r}=this.options;return r&&r.getProps().transformTemplate}willUpdate(r=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&ru(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(lu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(cu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(q_),this.nodes.forEach($_),this.nodes.forEach(j_)):this.nodes.forEach(cu),this.clearAllSnapshots();const a=tt.now();$e.delta=Ft(0,1e3/60,a-$e.timestamp),$e.timestamp=a,$e.isProcessing=!0,Io.update.process($e),Io.preRender.process($e),Io.render.process($e),$e.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ir.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(G_),this.sharedNodes.forEach(X_)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Te.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Te.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ke(this.snapshot.measuredBox.x)&&!Ke(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=De(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!eu(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||un(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),ey(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return De();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(ty))){const{scroll:u}=this.root;u&&(Pn(a.x,u.offset.x),Pn(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=De();if(ft(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&ft(a,r),Pn(a.x,d.offset.x),Pn(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=De();ft(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&Nn(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),un(u.latestValues)&&Nn(l,u.latestValues)}return un(this.latestValues)&&Nn(l,this.latestValues),l}removeTransform(r){const a=De();ft(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!un(c.latestValues))continue;yr(c.latestValues)&&c.updateSnapshot();const u=De(),d=c.measurePageBox();ft(u,d),Qd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return un(this.latestValues)&&Qd(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==$e.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=$e.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=De(),this.relativeTargetOrigin=De(),Si(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),ft(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=De(),this.targetWithTransforms=De()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),o_(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ft(this.target,this.layout.layoutBox),Ed(this.target,this.targetDelta)):ft(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=De(),this.relativeTargetOrigin=De(),Si(this.relativeTargetOrigin,this.target,p.target),ft(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||yr(this.parent.latestValues)||Sd(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var m;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===$e.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;ft(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;r_(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=De());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Yd(this.prevProjectionDelta.x,this.projectionDelta.x),Yd(this.prevProjectionDelta.y,this.projectionDelta.y)),wi(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!ou(this.projectionDelta.x,this.prevProjectionDelta.x)||!ou(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=On(),this.projectionDelta=On(),this.projectionDeltaWithTransform=On()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=On();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=De(),p=l?l.source:void 0,m=this.layout?this.layout.source:void 0,v=p!==m,b=this.getStack(),y=!b||b.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Q_));this.animationProgress=0;let T;this.mixTargetDelta=A=>{const x=A/1e3;uu(d.x,r.x,x),uu(d.y,r.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Si(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),J_(this.relativeTarget,this.relativeTargetOrigin,h,x),T&&N_(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=De()),ft(T,this.relativeTarget)),v&&(this.animationValues=u,x_(u,c,this.latestValues,x,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(qt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Te.update(()=>{gs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=Dn(0)),this.currentAnimation=E_(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(B_),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&mu(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||De();const d=Ke(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=Ke(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}ft(a,l),Nn(a,u),wi(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new F_),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Er("z",r,c,this.animationValues);for(let u=0;u<Tr.length;u++)Er(`rotate${Tr[u]}`,r,c,this.animationValues),Er(`skew${Tr[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=hs(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=hs(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!un(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=U_(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:p}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const m in mi){if(u[m]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:y}=mi[m],C=d==="none"?u[m]:v(u[m],c);if(b){const T=b.length;for(let A=0;A<T;A++)r[b[A]]=C}else y?this.options.visualElement.renderState.vars[m]=C:r[m]=C}this.options.layoutId&&(r.pointerEvents=c===this?hs(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(r=>{var a;return(a=r.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(lu),this.root.sharedNodes.clear()}}}function $_(t){t.updateLayout()}function j_(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?ht(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(h);h.min=i[d].min,h.max=h.min+p}):mu(o,e.layoutBox,i)&&ht(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(i[d]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+p)});const a=On();wi(a,i,e.layoutBox);const l=On();r?wi(l,t.applyTransform(s,!0),e.measuredBox):wi(l,i,e.layoutBox);const c=!eu(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:p}=d;if(h&&p){const m=De();Si(m,e.layoutBox,h.layoutBox);const v=De();Si(v,i,p.layoutBox),iu(m,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=m,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function H_(t){t.parent&&(t.isProjecting()||(t.isProjectionDirty=t.parent.isProjectionDirty),t.isSharedProjectionDirty||(t.isSharedProjectionDirty=!!(t.isProjectionDirty||t.parent.isProjectionDirty||t.parent.isSharedProjectionDirty)),t.isTransformDirty||(t.isTransformDirty=t.parent.isTransformDirty))}function W_(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function G_(t){t.clearSnapshot()}function lu(t){t.clearMeasurements()}function cu(t){t.isLayoutDirty=!1}function q_(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function du(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function z_(t){t.resolveTargetDelta()}function K_(t){t.calcProjection()}function Y_(t){t.resetSkewAndRotation()}function X_(t){t.removeLeadSnapshot()}function uu(t,e,n){t.translate=ke(e.translate,0,n),t.scale=ke(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function hu(t,e,n,i){t.min=ke(e.min,n.min,i),t.max=ke(e.max,n.max,i)}function J_(t,e,n,i){hu(t.x,e.x,n.x,i),hu(t.y,e.y,n.y,i)}function Q_(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Z_={duration:.45,ease:[.4,0,.1,1]},fu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),pu=fu("applewebkit/")&&!fu("chrome/")?Math.round:ut;function gu(t){t.min=pu(t.min),t.max=pu(t.max)}function ey(t){gu(t.x),gu(t.y)}function mu(t,e,n){return t==="position"||t==="preserve-aspect"&&!s_(su(e),su(n),.2)}function ty(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const ny=au({attachResizeListener:(t,e)=>_i(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),kr={current:void 0},vu=au({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!kr.current){const t=new ny({});t.mount(window),t.setOptions({layoutScroll:!0}),kr.current=t}return kr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),iy={pan:{Feature:w_},drag:{Feature:b_,ProjectionNode:vu,MeasureLayout:jd}};function _u(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,o=i[s];o&&Te.postRender(()=>o(e,yi(e)))}class sy extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Om(e,(n,i)=>(_u(this.node,i,"Start"),s=>_u(this.node,s,"End"))))}unmount(){}}class oy extends Yt{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=oi(_i(this.node.current,"focus",()=>this.onFocus()),_i(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function yu(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),o=i[s];o&&Te.postRender(()=>o(e,yi(e)))}class ry extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Um(e,(n,i)=>(yu(this.node,i,"Start"),(s,{success:o})=>yu(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ir=new WeakMap,Ar=new WeakMap,ay=t=>{const e=Ir.get(t.target);e&&e(t)},ly=t=>{t.forEach(ay)};function cy({root:t,...e}){const n=t||document;Ar.has(n)||Ar.set(n,{});const i=Ar.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(ly,{root:t,...e})),i[s]}function dy(t,e,n){const i=cy(e);return Ir.set(t,n),i.observe(t),()=>{Ir.delete(t),i.unobserve(t)}}const uy={some:0,all:1};class hy extends Yt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:o}=e,r={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:uy[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return dy(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(fy(e,n))&&this.startObserver()}unmount(){}}function fy({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const py={inView:{Feature:hy},tap:{Feature:ry},focus:{Feature:oy},hover:{Feature:sy}},gy={layout:{ProjectionNode:vu,MeasureLayout:jd}},Rr={current:null},bu={current:!1};function my(){if(bu.current=!0,!!yo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Rr.current=t.matches;t.addEventListener("change",e),e()}else Rr.current=!1}const vy=new WeakMap;function _y(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Ge(s))t.addValue(i,s);else if(Ge(o))t.addValue(i,Dn(s,{owner:t}));else if(o!==s)if(t.hasValue(i)){const r=t.getValue(i);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(i);t.addValue(i,Dn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const wu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class yy{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Qo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=tt.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Te.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=us(n),this.isVariantNode=Xc(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const h in d){const p=d[h];l[h]!==void 0&&Ge(p)&&p.set(l[h],!1)}}mount(e){this.current=e,vy.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),bu.current||my(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Rr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),qt(this.notifyUpdate),qt(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=xn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&Te.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in Ln){const n=Ln[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):De()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<wu.length;i++){const s=wu[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=_y(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=Dn(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(Ol(i)||Nl(i))?i=parseFloat(i):!$m(i)&&Kt.test(n)&&(i=Mc(e,n)),this.setBaseTarget(e,Ge(i)?i.get():i)),Ge(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var o;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const r=hr(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);r&&(i=r[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ge(s)?s:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new To),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class Su extends yy{constructor(){super(...arguments),this.KeyframeResolver=Rm}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ge(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Cu(t,{style:e,vars:n},i,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,i);for(r in n)o.setProperty(r,n[r])}function by(t){return window.getComputedStyle(t)}class wy extends Su{constructor(){super(...arguments),this.type="html",this.renderInstance=Cu}readValueFromInstance(e,n){var i;if(xn.has(n))return(i=this.projection)!=null&&i.isProjecting?zo(n):Yg(e,n);{const s=by(e),o=(Ao(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return Rd(e,n)}build(e,n,i){cr(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return fr(e,n,i)}}const Tu=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function Sy(t,e,n,i){Cu(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(Tu.has(s)?s:lr(s),e.attrs[s])}class Cy extends Su{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=De}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(xn.has(n)){const i=Lc(n);return i&&i.default||0}return n=Tu.has(n)?n:lr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return ld(e,n,i)}build(e,n,i){id(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){Sy(e,n,i,s)}mount(e){this.isSVGTag=od(e.tagName),super.mount(e)}}const Ty=(t,e)=>ur(t)?new Cy(e):new wy(e,{allowProjection:t!==yt}),Ey=Tv({...Xv,...py,...iy,...gy},Ty),Xt=Xm(Ey),ky=["agent-id","debug","environment","position","version-id","trickle-ice","prefetch-ice-candidates","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","text-only","text-chat-url","region","rtc-ip","rtc-port","skip-last-voice-sdk-id","streaming-audio"],Ti="widget-layout-id";function Eu(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=Eu(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function Bt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=Eu(t))&&(i&&(i+=" "),i+=e);return i}const Iy=Yi("listening"),ms=()=>Ll(Iy);function ku(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Ei={theme:"dark",audio_visualizer_config:{color:"verdant",preset:"roundBars"},start_call_text:"Let's chat",default_state:"collapsed",position:"fixed",view_history_url:null,report_issue_url:null,give_feedback_url:null,agent_thinking_text:"Thinking...",speak_to_interrupt_text:"Speak to interrupt",logo_icon_url:null},Iu=Yi(Ei),Au=()=>{const t=Ji(Iu);return Ne(e=>t(()=>{const n={...Ei,...e};return n.start_call_text||(n.start_call_text=Ei.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Ei.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Ei.speak_to_interrupt_text),n}),[t])},hn=()=>vo(Iu),xr=({size:t="large",className:e})=>{const n=hn(),[i]=ms();return D("h1",{className:Bt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},Ru=({stream:t,chatMode:e})=>{const n=ue(null);return Ie(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const Ay="4.5.1",Dr=Math.PI,Pi=2*Dr,Lr=Dr/2,xu=8.17579892,Du="dual-combined",vs="dual-horizontal",Vt="single",At="dual-vertical",Lu="bar-index",Mu="bar-level",_s="gradient",Ou=60,Pu="click",Ry="fullscreenchange",Nu="resize",xy="#111",Fu="",Uu="A",Bu="B",Vu="C",$u="D",ju="468",ys="sans-serif",Dy="#0f0",Ly="#7f7f7f22",Ni=10,Hu="create",Wu="fschange",My="lores",Oy=Nu,Mr="user",Py="#000c",Gu="#fff",Ny="#4f4",qu="#888",Fy="#555",Or="bark",kn="linear",Fi="log",Pr="mel",zu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Ku=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:zu}],["rainbow",{dir:"h",colorStops:["#817",...zu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],En={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Vt,colorMode:_s,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Fi,gradient:Ku[0][0],gravity:3.8,height:void 0,ledBars:!1,linearAmplitude:!1,linearBoost:1,lineWidth:0,loRes:!1,lumiBars:!1,maxDecibels:-25,maxFPS:0,maxFreq:22e3,minDecibels:-85,minFreq:20,mirror:0,mode:0,noteLabels:!1,outlineBars:!1,overlay:!1,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.3,reflexAlpha:.15,reflexBright:1,reflexFit:!0,reflexRatio:0,roundBars:!1,showBgColor:!0,showFPS:!1,showPeaks:!0,showScaleX:!0,showScaleY:!1,smoothing:.5,spinSpeed:0,splitGradient:!1,start:!0,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:Fu,width:void 0},Uy=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],By=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Vy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Nr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],$y=["ERR_INVALID_MODE","Invalid mode"],jy=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Hy=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Wy=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Gy=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],qy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class ft extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const Yu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Xu=t=>{for(const e in t)return!1;return!0},bs=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],zy=(t,e,i,n,s)=>e+(n-e)*(s-t)/(i-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class Ky{constructor(e,i={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(Xu(i)&&!Xu(e)&&(i=e),e=null),this._ownCanvas=!(i.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):i.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[d,h]of Ku)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(i.source&&(s=i.source.context))){if(!(s=i.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new ft(Uy)}}if(!s.createGain)throw new ft(By);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),i.source&&this.connectInput(i.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),i.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=i.fsElement||n;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Oy),this._fsTimeout=0)},Ou))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Nu,l,{signal:c}),n.addEventListener(Ry,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Wu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ou)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Pu,u))};window.addEventListener(Pu,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(i,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(Hu)}get alphaBars(){return this._alphaBars}set alphaBars(e){this._alphaBars=!!e,this._calcBars()}get ansiBands(){return this._ansiBands}set ansiBands(e){this._ansiBands=!!e,this._calcBars()}get barSpace(){return this._barSpace}set barSpace(e){this._barSpace=+e||0,this._calcBars()}get channelLayout(){return this._chLayout}set channelLayout(e){this._chLayout=bs(e,[Vt,vs,At,Du]),this._input.disconnect(),this._input.connect(this._chLayout!=Vt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Vt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=bs(e,[_s,Lu,Mu])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const i=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(i),new Float32Array(i)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=bs(e,[Fi,Or,Pr,kn]),this._calcBars()}get gradient(){return this._selectedGrads[0]}set gradient(e){this._setGradient(e)}get gradientLeft(){return this._selectedGrads[0]}set gradientLeft(e){this._setGradient(e,0)}get gradientRight(){return this._selectedGrads[1]}set gradientRight(e){this._setGradient(e,1)}get gravity(){return this._gravity}set gravity(e){this._gravity=e>0?+e:this._gravity||En.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Mr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(My)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const i of[0,1])this._analyzer[i].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new ft(Nr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const i of[0,1])this._analyzer[i].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new ft(Nr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const i=e|0;if(i>=0&&i<=10&&i!=9)this._mode=i,this._calcBars(),this._makeGrad();else throw new ft($y,e)}get noteLabels(){return this._noteLabels}set noteLabels(e){this._noteLabels=!!e,this._createScales()}get outlineBars(){return this._outlineBars}set outlineBars(e){this._outlineBars=!!e,this._calcBars()}get peakFadeTime(){return this._peakFadeTime}set peakFadeTime(e){this._peakFadeTime=e>=0?+e:this._peakFadeTime||En.peakFadeTime}get peakHoldTime(){return this._peakHoldTime}set peakHoldTime(e){this._peakHoldTime=+e||0}get peakLine(){return this._peakLine}set peakLine(e){this._peakLine=!!e}get radial(){return this._radial}set radial(e){this._radial=!!e,this._calcBars(),this._makeGrad()}get radialInvert(){return this._radialInvert}set radialInvert(e){this._radialInvert=!!e,this._calcBars(),this._makeGrad()}get radius(){return this._radius}set radius(e){this._radius=+e||0,this._calcBars(),this._makeGrad()}get reflexRatio(){return this._reflexRatio}set reflexRatio(e){if(e=+e||0,e<0||e>=1)throw new ft(jy);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const i of[0,1])this._analyzer[i].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Lr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Yu("stereo","channelLayout"),this._chLayout!=Vt}set stereo(e){Yu("stereo","channelLayout"),this.channelLayout=e?At:Vt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=bs(e,[Fu,Uu,Bu,Vu,$u,ju],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Mr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return Ay}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new ft(Hy);const n=i?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const i of[0,1])this._analyzer[i].connect(this._chLayout==Vt&&!i?this._output:this._merger,0,i)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:i,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&i.remove(),this._calcBars()}disconnectInput(e,i){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(i&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(i=>i!==e):[],this._outNodes.length==0))for(const i of[0,1])this._analyzer[i].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,i){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,i]=a[e]}const n=this._freqToBin(e),s=i?this._freqToBin(i):n,o=this._chLayout==Vt?1:2;let r=0;for(let a=0;a<o;a++)for(let l=n;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let i={};for(const n of Object.keys(En))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(i.gradientLeft=this.gradientLeft,i.gradientRight=this.gradientRight):n!="start"&&(i[n]=this[n]));return i}registerGradient(e,i){if(typeof e!="string"||e.trim().length==0)throw new ft(Wy);if(typeof i!="object")throw new ft(Gy);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new ft(qy);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?n[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(n[a].level=1-a/s)}),n.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:i.bgColor||xy,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(Mr)}setFreqRange(e,i){if(e<1||i<1)throw new ft(Nr);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,p=s.width>>1,m=s.height>>1,v=o==At&&!u,b=o==vs,y=c%10!=0,C=y&&this._frequencyScale==Fi,T=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,x=this._alphaBars&&!A&&c!=Ni,N=this._outlineBars&&y&&!A&&!T,E=this._roundBars&&y&&!A&&!T,k=o!=At||h>0&&!A,f=s.height-(v&&!T?.5:0)>>v,_=f*(A||u?1:1-h)|0,g=s.width-p*(b||l!=0),S=v?s.height-f*2:0,I=p*(l==-1&&!b&&!u);let M=Math.min(s.width,s.height)*.375*(o==At?1:this._radius)|0,R=Math.min(p,m);d&&o!=At&&([M,R]=[R,M]);const P=K=>e.push({...K,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=K=>{const Z=this._freqToBin(K,"floor"),Y=this._binToFreq(Z),te=this._binToFreq(Z+1),me=Math.log2(K/Y)/Math.log2(te/Y);return[Z,me]};let L,V,$;if(C){const K=(he,de,fe)=>+he.toPrecision(fe?Math.max(de,1+Math.log10(he)|0):de),Z=he=>{const de=[1,1.12,1.25,1.4,1.6,1.8,2,2.24,2.5,2.8,3.15,3.55,4,4.5,5,5.6,6.3,7.1,8,9,10],fe=Math.log10(he)|0,Je=he/10**fe;let Qe=1;for(;Qe<de.length&&Je>de[Qe];)Qe++;return Je-de[Qe-1]<de[Qe]-Je&&Qe--,(de[Qe]*10**(fe+5)|0)/1e5},Y=[0,24,12,8,6,4,3,2,1][c],te=i?10**(3/(Y*10)):2**(1/Y),me=te**.5;let Oe=i?7.94328235/(Y%2?1:me):xu;do{let he=Oe;const de=K(he/me,4,!0),fe=K(he*me,4,!0),[Je,Qe]=O(de),[Mt,Ze]=O(fe);i?he=Y<4?Z(he):K(he,he.toString()[0]<5?3:2):he=K(he,4,!0),he>=a&&P({posX:0,freq:he,freqLo:de,freqHi:fe,binLo:Je,binHi:Mt,ratioLo:Qe,ratioHi:Ze}),Oe*=te}while(Oe<=r);L=g/e.length,e.forEach((he,de)=>he.posX=I+de*L);const _e=e[0],xe=e[e.length-1];V=this._freqScaling(_e.freqLo),$=g/(this._freqScaling(xe.freqHi)-V),_e.freqLo<a&&(_e.freqLo=a,[_e.binLo,_e.ratioLo]=O(a)),xe.freqHi>r&&(xe.freqHi=r,[xe.binHi,xe.ratioHi]=O(r))}else if(y){const K=[0,24,12,8,6,4,3,2,1][c]*10,Z=Y=>{switch(this._frequencyScale){case Or:return 1960/(26.81/(Y+.53)-1);case Pr:return 700*(2**Y-1);case kn:return Y}};L=g/K,V=this._freqScaling(a),$=g/(this._freqScaling(r)-V);for(let Y=0,te=0;Y<K;Y++,te+=L){const me=Z(V+te/$),Oe=Z(V+(te+L/2)/$),_e=Z(V+(te+L)/$),[xe,he]=O(me),[de,fe]=O(_e);P({posX:I+te,freq:Oe,freqLo:me,freqHi:_e,binLo:xe,binHi:de,ratioLo:he,ratioHi:fe})}}else{L=1,V=this._freqScaling(a),$=g/(this._freqScaling(r)-V);const K=this._freqToBin(a,"floor"),Z=this._freqToBin(r);let Y=-999;for(let te=K;te<=Z;te++){const me=this._binToFreq(te),Oe=I+Math.round($*(this._freqScaling(me)-V));if(Oe>Y)P({posX:Oe,freq:me,freqLo:me,freqHi:me,binLo:te,binHi:te,ratioLo:0,ratioHi:0}),Y=Oe;else if(e.length){const _e=e[e.length-1];_e.binHi=te,_e.freqHi=me,_e.freq=(_e.freqLo*me)**.5}}}let W=0,q=0;if(T){const K=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Z=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Y=this._ledParams,[te,me,Oe]=Y||Z[c];let _e,xe=_;if(Y){const he=2*K;let de;_e=te+1;do _e--,de=xe/_e/(1+me),q=de*me;while((de<he||q<he)&&_e>1)}else{const he=540/me;q=Math.min(me*K,Math.max(2,xe/he+.1|0))}k&&(xe+=q),Y||(_e=Math.min(te,xe/(q*2)|0)),W=Oe>=1?Oe:L*Oe,this._leds=[_e,W,q,xe/_e-q]}const G=Math.min(L-1,n*(n>0&&n<1?L:1));y&&(L-=Math.max(T?W:0,G)),e.forEach((K,Z)=>{let Y=K.posX,te=L;y&&(n==0&&!T?(Y|=0,te|=0,Z>0&&Y>e[Z-1].posX+e[Z-1].width&&(Y--,te++)):Y+=Math.max(T?W:0,G)/2,K.posX=Y),K.barCenter=Y+(L==1?0:te/2),K.width=te});const oe=[];for(const K of[0,1]){const Z=o==At?(f+S)*K:0,Y=Z+f,te=Z+_-(!T||k?0:q);oe.push({channelTop:Z,channelBottom:Y,analyzerBottom:te})}this._aux={analyzerHeight:_,analyzerWidth:g,centerX:p,centerY:m,channelCoords:oe,channelHeight:f,channelGap:S,initialX:I,innerRadius:M,outerRadius:R,scaleMin:V,unitWidth:$},this._flg={isAlpha:x,isBands:y,isLeds:T,isLumi:A,isOctaves:C,isOutline:N,isRound:E,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,m=h.canvas,v=[],b=this._chLayout==vs,y=this._chLayout==At,C=Math.min(r.width,r.height),T=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,x=p.height>>1,N=A>>1,E=x*(c?.7:1.5),k=N*(c?1:2),f=2**(1/12);if(!c&&(this._ansiBands||a!=Fi))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==kn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let R=xu;for(let P=-1;P<11;P++)for(let O=0;O<12;O++){if(R>=this._minFreq&&R<=this._maxFreq){const L=T[O],V=L=="C";(L&&c&&!l&&!b||V)&&v.push(c?[R,L+(V?P:"")]:R)}R*=f}}m.width=m.height=Math.max(C*.15,(n<<1)+y*A);const _=m.width>>1,g=_-A*.7,S=(R,P)=>{const O=Pi*(R/r.width),L=O-Lr,V=g*Math.cos(L),$=g*Math.sin(L);h.save(),h.translate(_+V,_+$),h.rotate(O),h.fillText(P,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=Py,d.fillRect(0,0,p.width,p.height),h.arc(_,_,_-A/2,0,Pi),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=Gu,d.font=`${x}px ${ys}`,h.font=`${N}px ${ys}`,d.textAlign=h.textAlign="center";let I=-E/4,M=-k;for(const R of v){const[P,O]=Array.isArray(R)?R:[R,R<1e3?R|0:`${(R/100|0)/10}k`],L=o*(this._freqScaling(P)-s),V=p.height*.75,$=O[0]=="C",W=x*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?Ny:Gu,c){const q=a==Fi,G=a==kn;let oe=["C"];if((q||P>2e3||!G&&P>250||(!u||y)&&(!G&&P>125||P>1e3))&&oe.push("G"),(q||P>4e3||!G&&P>500||(!u||y)&&(!G&&P>250||P>2e3))&&oe.push("E"),(G&&P>4e3||(!u||y)&&(q||P>2e3||!G&&P>500))&&oe.push("D","F","A","B"),!oe.includes(O[0]))continue}L>=I+E/2&&L<=e&&(d.fillText(O,b&&l==-1?e-L:i+L,V,W),(b||l&&(L>E||l==1))&&d.fillText(O,b&&l!=1?e+L:(i||r.width)-L,V,W),I=L+Math.min(W,d.measureText(O).width)/2),L>=M+k&&L<e-k&&(S(b&&l==1?e-L:L,O),(b||l&&(L>k||l==1))&&S(b&&l!=-1?e+L:-L,O),M=L)}}_draw(e){this._runId=requestAnimationFrame(H=>this._draw(H));const i=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,i>=1e3&&(this._fps=this._frames/i*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:p,centerX:m,centerY:v,channelCoords:b,channelHeight:y,channelGap:C,initialX:T,innerRadius:A,outerRadius:x}=this._aux,{_bars:N,canvas:E,_canvasGradients:k,_chLayout:f,_colorMode:_,_ctx:g,_energy:S,_fadePeaks:I,fillAlpha:M,_fps:R,_linearAmplitude:P,_lineWidth:O,maxDecibels:L,minDecibels:V,_mirror:$,_mode:W,overlay:q,_radial:G,showBgColor:oe,showPeaks:K,useCanvas:Z,_weightingFilter:Y}=this,te=this._scaleX.canvas,me=this._scaleR.canvas,Oe=R*this._peakFadeTime/1e3,_e=R**2,xe=this._gravity*1e3,he=R*this._peakHoldTime/1e3,de=f==Du,fe=f==vs,Je=f==At,Qe=f==Vt,Mt=a&&this._trueLeds&&_==_s,Ze=G?E.width:this._aux.analyzerWidth,ne=T+Ze,ye=K&&this._peakLine&&W==Ni,Be=G?x-A:p,Ee=Be/this._pixelRatio,[Ht,Vn,wt,Sa]=this._leds||[];S.val>0&&R>0&&(this._spinAngle+=this._spinSpeed*Pi/60/R);const MS=H=>{if(this._reflexRatio>0&&!l&&!G){let ge,Ot;this.reflexFit||Je?(ge=Je&&H==0?y+C:0,Ot=y-p):(ge=E.height-p*2,Ot=p),g.save(),g.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(g.filter=`brightness(${this.reflexBright})`),g.setTransform(1,0,0,-1,0,E.height),g.drawImage(E,0,b[H].channelTop,E.width,p,0,ge,E.width,Ot),g.restore()}},OS=()=>{this.showScaleX&&(G?(g.save(),g.translate(m,v),this._spinSpeed&&g.rotate(this._spinAngle+Lr),g.drawImage(me,-me.width>>1,-me.width>>1),g.restore()):g.drawImage(te,0,E.height-te.height))},PS=H=>{const ge=H**2,Ot=424.36,We=11599.29,Gs=25122.25,ei=544496.41,Wt=148693636,_i=yi=>20*Math.log10(yi);switch(Y){case Uu:const yi=Wt*ge**2/((ge+Ot)*Math.sqrt((ge+We)*(ge+ei))*(ge+Wt));return 2+_i(yi);case Bu:const bi=Wt*ge*H/((ge+Ot)*Math.sqrt(ge+Gs)*(ge+Wt));return .17+_i(bi);case Vu:const ka=Wt*ge/((ge+Ot)*(ge+Wt));return .06+_i(ka);case $u:const qs=((103791848e-2-ge)**2+108076816e-2*ge)/((9837328-ge)**2+11723776*ge),Ea=H/68966888496476e-18*Math.sqrt(qs/((ge+79919.29)*(ge+1345600)));return _i(Ea);case ju:const zs=-4737338981378384e-39*H**6+2043828333606125e-30*H**4-1363894795463638e-22*ge+1,wi=1306612257412824e-34*H**5-2118150887518656e-26*H**3+.0005559488023498642*H,at=.0001246332637532143*H/Math.hypot(zs,wi);return 18.2+_i(at)}return 0},Ca=(H,ge,Ot)=>{g.beginPath(),g.moveTo(H,ge),g.lineTo(H,Ot),g.stroke()},Ta=H=>{if(H&&O){const ge=g.globalAlpha;g.globalAlpha=1,g.stroke(),g.globalAlpha=ge}},vi=H=>Math.max(0,(H*Ht|0)*(Sa+wt)-wt),NS=H=>{S.val=H,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*xe/_e/E.height*this._pixelRatio)),H>=S.peak&&(S.peak=H,S.hold=he)};q&&g.clearRect(0,0,E.width,E.height);let Zf=0;const ep=N.length,tp=Qe?1:2;for(let H=0;H<tp;H++){const{channelTop:ge,channelBottom:Ot,analyzerBottom:We}=b[H],Gs=this._gradients[this._selectedGrads[H]],ei=Gs.colorStops,Wt=ei.length,_i=!oe||a&&!q?"#000":Gs.bgColor,yi=Je&&G&&H?-1:1,bi=!H&&$==-1||H&&$==1,ka=!fe||H&&$!=1?0:Ze>>(H||!bi),qs=fe&&bi?-1:1,Ea=()=>{const X=te.height,ee=X>>1,se=P?100:L,Se=P?0:V,Pe=P?20:5,st=p/(se-Se),Pt=$!=-1&&(!fe||H==0||$==1),ti=$!=1&&(!fe||H!=$);g.save(),g.fillStyle=qu,g.font=`${ee}px ${ys}`,g.textAlign="right",g.lineWidth=1;for(let ii=se;ii>Se;ii-=Pe){const Yi=ge+(se-ii)*st,Ve=ii%2==0|0;if(Ve){const et=Yi+ee*(Yi==ge?.8:.35);Pt&&g.fillText(ii,X*.85,et),ti&&g.fillText(ii,(fe?Ze:E.width)-X*.1,et),g.strokeStyle=qu,g.setLineDash([2,4]),g.lineDashOffset=0}else g.strokeStyle=Fy,g.setLineDash([2,8]),g.lineDashOffset=1;g.beginPath(),g.moveTo(T+X*Ve*Pt,~~Yi+.5),g.lineTo(ne-X*Ve*ti,~~Yi+.5),g.stroke()}g.restore()},zs=(X,ee)=>{const se=St[X]+(X<St.length-1?(St[X+1]-St[X])*ee:0);return isNaN(se)?-1/0:se},wi=(X,ee=qs)=>ee*Pi*((X+ka)/E.width)+this._spinAngle,at=(X,ee,se)=>{const Se=A+ee*yi,Pe=wi(X,se);return[m+Se*Math.cos(Pe),v+Se*Math.sin(Pe)]},Ia=(X,ee,se,Se,Pe)=>{g.beginPath();for(const st of $&&!fe?[1,-1]:[qs]){const[Pt,ti]=d?[wi(X,st),wi(X+se,st)]:[];g.moveTo(...at(X,ee,st)),g.lineTo(...at(X,ee+Se,st)),d?g.arc(m,v,A+(ee+Se)*yi,Pt,ti,st!=1):g.lineTo(...at(X+se,ee+Se,st)),g.lineTo(...at(X+se,ee,st)),d&&!Pe&&g.arc(m,v,A+ee*yi,ti,Pt,st==1)}Ta(Pe),g.fill()},Aa=(X=0,ee=0)=>{let se;if(_==_s&&!Mt||W==Ni)se=k[H];else{const Se=_==Lu?ee%Wt:ei.findLastIndex(Pe=>a?vi(X)<=vi(Pe.level):X<=Pe.level);se=ei[Se].color}g.fillStyle=g.strokeStyle=se};if(Z){if(fe&&!G){const X=Ze*(H+bi),ee=bi?-1:1;g.setTransform(ee,0,0,1,X,0)}if((!q||oe)&&(q&&(g.globalAlpha=this.bgAlpha),g.fillStyle=_i,(H==0||!G&&!de)&&g.fillRect(T,ge-C,Ze,(q&&this.reflexAlpha==1?p:y)+C),g.globalAlpha=1),this.showScaleY&&!l&&!G&&(H==0||!de)&&Ea(),a?(g.setLineDash([Sa,wt]),g.lineWidth=N[0].width):g.lineWidth=u?Math.min(O,N[0].width/2):O,g.save(),!G){const X=new Path2D;X.rect(0,ge,E.width,p),g.clip(X)}}let St=this._fftData[H];this._analyzer[H].getFloatFrequencyData(St),Y&&(St=St.map((X,ee)=>X+PS(this._binToFreq(ee)))),g.beginPath();let $n=[];for(let X=0;X<ep;X++){const ee=N[X],{posX:se,barCenter:Se,width:Pe,freq:st,binLo:Pt,binHi:ti,ratioLo:ii,ratioHi:Yi}=ee;let Ve=Math.max(zs(Pt,ii),zs(ti,Yi));for(let be=Pt+1;be<ti;be++)St[be]>Ve&&(Ve=St[be]);if(Ve=this._normalizedB(Ve),ee.value[H]=Ve,Zf+=Ve,ee.peak[H]>0&&ee.alpha[H]>0&&(ee.hold[H]--,ee.hold[H]<0)){if(I&&!ye){const be=!o||u&&O>0?1:o?ee.peak[H]:M;ee.alpha[H]=be*(1+ee.hold[H]/Oe)}else ee.peak[H]+=ee.hold[H]*xe/_e/Ee;ee.alpha[H]<=0&&(ee.peak[H]=0)}if(Ve>=ee.peak[H]&&(ee.peak[H]=Ve,ee.hold[H]=he,ee.alpha[H]=!o||u&&O>0?1:o?Ve:M),!Z)continue;g.globalAlpha=l||o?Ve:u?M:1,Aa(Ve,X);const et=l?Be:a?vi(Ve):Ve*Be|0;if(W==Ni){const be=X?0:(this._normalizedB(St[N[1].binLo])*Be+et)/2;if(G){if(X==0&&(fe&&g.moveTo(...at(0,0)),g.lineTo(...at(0,se<0?be:et))),se>=0){const mt=[se,et];g.lineTo(...at(...mt)),$n.push(mt)}}else{if(X==0)if($==-1&&!fe)g.moveTo(T,We-(se<T?be:et));else{const mt=Pt?this._normalizedB(St[Pt-1])*Be:et;g.moveTo(T-O,We-mt)}(fe||$!=-1||se>=T)&&g.lineTo(se,We-et)}}else if(a){if(oe&&!q&&(H==0||!de)){const be=g.globalAlpha;g.strokeStyle=Ly,g.globalAlpha=1,Ca(Se,ge,We),g.strokeStyle=g.fillStyle,g.globalAlpha=be}if(Mt){const be=l?0:ei.findLastIndex(Si=>vi(Ve)<=vi(Si.level));let mt=We;for(let Si=Wt-1;Si>=be;Si--){g.strokeStyle=ei[Si].color;let np=We-(Si==be?et:vi(ei[Si].level));Ca(Se,mt,np),mt=np-wt}}else Ca(Se,We,We-et)}else if(se>=T)if(G)Ia(se,0,Pe,et,u);else if(d){const be=Pe/2,mt=We+be;g.beginPath(),g.moveTo(se,mt),g.lineTo(se,mt-et),g.arc(Se,mt-et,be,Dr,Pi),g.lineTo(se+Pe,mt),Ta(u),g.fill()}else{const be=u?g.lineWidth:0;g.beginPath(),g.rect(se,We+be,Pe,-et-be),Ta(u),g.fill()}const Xi=ee.peak[H],ip=ee.alpha[H];if(Xi>0&&ip>0&&K&&!ye&&!l&&se>=T&&se<ne){if(I?g.globalAlpha=ip:u&&O>0?g.globalAlpha=1:o&&(g.globalAlpha=Xi),(_==Mu||Mt)&&Aa(Xi),a){const be=vi(Xi);be>=wt&&g.fillRect(se,We-be,Pe,Sa)}else if(!G)g.fillRect(se,We-Xi*Be,Pe,2);else if(W!=Ni){const be=Xi*Be;Ia(se,be,Pe,!this._radialInvert||Je||be+A>=2?-2:2)}}}if(Z){if(g.globalAlpha=1,W==Ni){if(Aa(),G&&!fe){if($){let X;for(;X=$n.pop();)g.lineTo(...at(...X,-1))}g.closePath()}if(O>0&&g.stroke(),M>0){if(G){const X=fe?wi(Ze>>1):0,ee=fe?wi(Ze):Pi;g.moveTo(...at(fe?Ze>>1:0,0)),g.arc(m,v,A,X,ee,fe?!bi:!0)}else g.lineTo(ne,We),g.lineTo(T,We);g.globalAlpha=M,g.fill(),g.globalAlpha=1}if((ye||G&&K)&&($n=[],g.beginPath(),N.forEach((X,ee)=>{let se=X.posX,Se=X.peak[H],Pe=ee?"lineTo":"moveTo";if(G&&se<0){const st=N[ee+1];Se=zy(se,Se,st.posX,st.peak[H],0),se=0}Se*=Be,ye?(g[Pe](...G?at(se,Se):[se,We-Se]),G&&$&&!fe&&$n.push([se,Se])):Se>0&&Ia(se,Se,1,-2)}),ye)){let X;for(;X=$n.pop();)g.lineTo(...at(...X,-1));g.lineWidth=1,g.stroke()}}g.restore(),fe&&!G&&g.setTransform(1,0,0,1,0,0),(!fe&&!de||H)&&MS(H)}}if(NS(Zf/(ep<<tp-1)),Z&&($&&!G&&!fe&&(g.setTransform(-1,0,0,1,E.width-T,0),g.drawImage(E,T,0,m,E.height,0,0,m,E.height),g.setTransform(1,0,0,1,0,0)),g.setLineDash([]),OS()),this.showFPS){const H=te.height;g.font=`bold ${H}px ${ys}`,g.fillStyle=Dy,g.textAlign="right",g.fillText(Math.round(R),E.width-H,H*2)}this.onCanvasDraw&&(g.save(),g.fillStyle=g.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),g.restore())}_freqScaling(e){switch(this._frequencyScale){case Fi:return Math.log2(e);case Or:return 26.81*e/(1960+e)-.53;case Pr:return Math.log2(1+e/700);case kn:return e}}_freqToBin(e,i="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[i](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:i,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==At,p=1-s,m=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],y=b.colorStops,C=b.dir=="h";let T;if(n?T=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):T=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,m]),y){const A=h&&!this._splitGradient&&(!C||n);for(let x=0;x<1+A;x++){const N=y.length-1;y.forEach((E,k)=>{let f=E.pos;if(A&&(f/=2),h&&!d&&!n&&!C&&(f*=p,!A&&f>.5*p&&(f+=.5*s)),x==1)if(n||d){const _=N-k;E=y[_],f=1-E.pos/2}else k==0&&f>0&&T.addColorStop(.5,E.color),f+=.5;T.addColorStop(f,E.color),h&&k==N&&f<.5&&T.addColorStop(.5,E.color)})}}this._canvasGradients[v]=T}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Hu&&i.width==u&&i.height==d)&&(i.width=u,i.height=d,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,u,d)),n.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Wu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new ft(Vy,e);[0,1].includes(i)||(this._selectedGrads[1]=e,i=0),this._selectedGrads[i]=e,this._makeGrad()}_setProps(e,i){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(En).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...En,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const Yy={verdant:{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]},twilight:{colorStops:[{color:"#81B9FF",pos:0},{color:"#371A5E",pos:.5},{color:"#81B9FF",pos:1}]},bloom:{colorStops:[{color:"#FFD4FE",pos:0},{color:"#FD05F9",pos:.5},{color:"#FFD4FE",pos:1}]},mystic:{colorStops:[{color:"#1F023A",pos:0},{color:"#CA76FF",pos:.5},{color:"#1F023A",pos:1}]},flare:{colorStops:[{color:"#FFFFFF",pos:0},{color:"#FC5F00",pos:.5},{color:"#FFFFFF",pos:1}]},glacier:{colorStops:[{color:"#4CE5F2",pos:0},{color:"#005A98",pos:.5},{color:"#4CE5F2",pos:1}]}},Ju=({stream:t,className:e,onClick:i})=>{var o;const n=ce(null),s=ui();return Le(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Ky(n.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",Yy[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),D("div",{onClick:i,className:Bt("w-full",e),ref:n})},Qu=Yn(null),Fr=({className:t,debug:e=!1})=>{const i=vo(Qu);return!e||!i||!(i.region||i.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&D("span",{children:" · "}),i.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
16
+ */const Ay="4.5.1",Dr=Math.PI,Fn=2*Dr,Lr=Dr/2,xu=8.17579892,Du="dual-combined",vs="dual-horizontal",Vt="single",At="dual-vertical",Lu="bar-index",Mu="bar-level",_s="gradient",Ou=60,Pu="click",Ry="fullscreenchange",Nu="resize",xy="#111",Fu="",Uu="A",Bu="B",Vu="C",$u="D",ju="468",ys="sans-serif",Dy="#0f0",Ly="#7f7f7f22",Un=10,Hu="create",Wu="fschange",My="lores",Oy=Nu,Mr="user",Py="#000c",Gu="#fff",Ny="#4f4",qu="#888",Fy="#555",Or="bark",ki="linear",Bn="log",Pr="mel",zu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Ku=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:zu}],["rainbow",{dir:"h",colorStops:["#817",...zu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Ii={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Vt,colorMode:_s,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Bn,gradient:Ku[0][0],gravity:3.8,height:void 0,ledBars:!1,linearAmplitude:!1,linearBoost:1,lineWidth:0,loRes:!1,lumiBars:!1,maxDecibels:-25,maxFPS:0,maxFreq:22e3,minDecibels:-85,minFreq:20,mirror:0,mode:0,noteLabels:!1,outlineBars:!1,overlay:!1,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.3,reflexAlpha:.15,reflexBright:1,reflexFit:!0,reflexRatio:0,roundBars:!1,showBgColor:!0,showFPS:!1,showPeaks:!0,showScaleX:!0,showScaleY:!1,smoothing:.5,spinSpeed:0,splitGradient:!1,start:!0,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:Fu,width:void 0},Uy=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],By=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Vy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Nr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],$y=["ERR_INVALID_MODE","Invalid mode"],jy=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Hy=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Wy=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Gy=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],qy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class pt extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Yu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Xu=t=>{for(const e in t)return!1;return!0},bs=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],zy=(t,e,n,i,s)=>e+(i-e)*(s-t)/(n-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class Ky{constructor(e,n={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(Xu(n)&&!Xu(e)&&(n=e),e=null),this._ownCanvas=!(n.canvas instanceof HTMLCanvasElement);const i=this._ownCanvas?document.createElement("canvas"):n.canvas;i.style="max-width: 100%;",this._ctx=i.getContext("2d");for(const[d,h]of Ku)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new pt(Uy)}}if(!s.createGain)throw new pt(By);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Oy),this._fsTimeout=0)},Ou))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Nu,l,{signal:c}),i.addEventListener(Ry,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Wu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ou)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Pu,u))};window.addEventListener(Pu,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Hu)}get alphaBars(){return this._alphaBars}set alphaBars(e){this._alphaBars=!!e,this._calcBars()}get ansiBands(){return this._ansiBands}set ansiBands(e){this._ansiBands=!!e,this._calcBars()}get barSpace(){return this._barSpace}set barSpace(e){this._barSpace=+e||0,this._calcBars()}get channelLayout(){return this._chLayout}set channelLayout(e){this._chLayout=bs(e,[Vt,vs,At,Du]),this._input.disconnect(),this._input.connect(this._chLayout!=Vt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Vt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=bs(e,[_s,Lu,Mu])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const i of[0,1])this._analyzer[i].fftSize=e;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=bs(e,[Bn,Or,Pr,ki]),this._calcBars()}get gradient(){return this._selectedGrads[0]}set gradient(e){this._setGradient(e)}get gradientLeft(){return this._selectedGrads[0]}set gradientLeft(e){this._setGradient(e,0)}get gradientRight(){return this._selectedGrads[1]}set gradientRight(e){this._setGradient(e,1)}get gravity(){return this._gravity}set gravity(e){this._gravity=e>0?+e:this._gravity||Ii.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Mr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(My)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const n of[0,1])this._analyzer[n].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new pt(Nr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const n of[0,1])this._analyzer[n].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new pt(Nr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const n=e|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new pt($y,e)}get noteLabels(){return this._noteLabels}set noteLabels(e){this._noteLabels=!!e,this._createScales()}get outlineBars(){return this._outlineBars}set outlineBars(e){this._outlineBars=!!e,this._calcBars()}get peakFadeTime(){return this._peakFadeTime}set peakFadeTime(e){this._peakFadeTime=e>=0?+e:this._peakFadeTime||Ii.peakFadeTime}get peakHoldTime(){return this._peakHoldTime}set peakHoldTime(e){this._peakHoldTime=+e||0}get peakLine(){return this._peakLine}set peakLine(e){this._peakLine=!!e}get radial(){return this._radial}set radial(e){this._radial=!!e,this._calcBars(),this._makeGrad()}get radialInvert(){return this._radialInvert}set radialInvert(e){this._radialInvert=!!e,this._calcBars(),this._makeGrad()}get radius(){return this._radius}set radius(e){this._radius=+e||0,this._calcBars(),this._makeGrad()}get reflexRatio(){return this._reflexRatio}set reflexRatio(e){if(e=+e||0,e<0||e>=1)throw new pt(jy);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const n of[0,1])this._analyzer[n].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Lr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Yu("stereo","channelLayout"),this._chLayout!=Vt}set stereo(e){Yu("stereo","channelLayout"),this.channelLayout=e?At:Vt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=bs(e,[Fu,Uu,Bu,Vu,$u,ju],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Mr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return Ay}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new pt(Hy);const i=n?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==Vt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const o of i.mediaStream.getAudioTracks())o.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==Vt?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Ii))e.includes(i)||(i=="gradient"&&this.gradientLeft!=this.gradientRight?(n.gradientLeft=this.gradientLeft,n.gradientRight=this.gradientRight):i!="start"&&(n[i]=this[i]));return n}registerGradient(e,n){if(typeof e!="string"||e.trim().length==0)throw new pt(Wy);if(typeof n!="object")throw new pt(Gy);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new pt(qy);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||xy,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Mr)}setFreqRange(e,n){if(e<1||n<1)throw new pt(Nr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,p=s.width>>1,m=s.height>>1,v=o==At&&!u,b=o==vs,y=c%10!=0,C=y&&this._frequencyScale==Bn,T=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,x=this._alphaBars&&!A&&c!=Un,N=this._outlineBars&&y&&!A&&!T,k=this._roundBars&&y&&!A&&!T,E=o!=At||h>0&&!A,f=s.height-(v&&!T?.5:0)>>v,_=f*(A||u?1:1-h)|0,g=s.width-p*(b||l!=0),S=v?s.height-f*2:0,I=p*(l==-1&&!b&&!u);let P=Math.min(s.width,s.height)*.375*(o==At?1:this._radius)|0,R=Math.min(p,m);d&&o!=At&&([P,R]=[R,P]);const M=q=>e.push({...q,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=q=>{const X=this._freqToBin(q,"floor"),te=this._binToFreq(X),J=this._binToFreq(X+1),he=Math.log2(q/te)/Math.log2(J/te);return[X,he]};let L,V,j;if(C){const q=(de,ve,oe)=>+de.toPrecision(oe?Math.max(ve,1+Math.log10(de)|0):ve),X=de=>{const ve=[1,1.12,1.25,1.4,1.6,1.8,2,2.24,2.5,2.8,3.15,3.55,4,4.5,5,5.6,6.3,7.1,8,9,10],oe=Math.log10(de)|0,Je=de/10**oe;let Qe=1;for(;Qe<ve.length&&Je>ve[Qe];)Qe++;return Je-ve[Qe-1]<ve[Qe]-Je&&Qe--,(ve[Qe]*10**(oe+5)|0)/1e5},te=[0,24,12,8,6,4,3,2,1][c],J=n?10**(3/(te*10)):2**(1/te),he=J**.5;let be=n?7.94328235/(te%2?1:he):xu;do{let de=be;const ve=q(de/he,4,!0),oe=q(de*he,4,!0),[Je,Qe]=O(ve),[Mt,Ze]=O(oe);n?de=te<4?X(de):q(de,de.toString()[0]<5?3:2):de=q(de,4,!0),de>=a&&M({posX:0,freq:de,freqLo:ve,freqHi:oe,binLo:Je,binHi:Mt,ratioLo:Qe,ratioHi:Ze}),be*=J}while(be<=r);L=g/e.length,e.forEach((de,ve)=>de.posX=I+ve*L);const ye=e[0],Le=e[e.length-1];V=this._freqScaling(ye.freqLo),j=g/(this._freqScaling(Le.freqHi)-V),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=O(a)),Le.freqHi>r&&(Le.freqHi=r,[Le.binHi,Le.ratioHi]=O(r))}else if(y){const q=[0,24,12,8,6,4,3,2,1][c]*10,X=te=>{switch(this._frequencyScale){case Or:return 1960/(26.81/(te+.53)-1);case Pr:return 700*(2**te-1);case ki:return te}};L=g/q,V=this._freqScaling(a),j=g/(this._freqScaling(r)-V);for(let te=0,J=0;te<q;te++,J+=L){const he=X(V+J/j),be=X(V+(J+L/2)/j),ye=X(V+(J+L)/j),[Le,de]=O(he),[ve,oe]=O(ye);M({posX:I+J,freq:be,freqLo:he,freqHi:ye,binLo:Le,binHi:ve,ratioLo:de,ratioHi:oe})}}else{L=1,V=this._freqScaling(a),j=g/(this._freqScaling(r)-V);const q=this._freqToBin(a,"floor"),X=this._freqToBin(r);let te=-999;for(let J=q;J<=X;J++){const he=this._binToFreq(J),be=I+Math.round(j*(this._freqScaling(he)-V));if(be>te)M({posX:be,freq:he,freqLo:he,freqHi:he,binLo:J,binHi:J,ratioLo:0,ratioHi:0}),te=be;else if(e.length){const ye=e[e.length-1];ye.binHi=J,ye.freqHi=he,ye.freq=(ye.freqLo*he)**.5}}}let H=0,K=0;if(T){const q=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),X=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],te=this._ledParams,[J,he,be]=te||X[c];let ye,Le=_;if(te){const de=2*q;let ve;ye=J+1;do ye--,ve=Le/ye/(1+he),K=ve*he;while((ve<de||K<de)&&ye>1)}else{const de=540/he;K=Math.min(he*q,Math.max(2,Le/de+.1|0))}E&&(Le+=K),te||(ye=Math.min(J,Le/(K*2)|0)),H=be>=1?be:L*be,this._leds=[ye,H,K,Le/ye-K]}const W=Math.min(L-1,i*(i>0&&i<1?L:1));y&&(L-=Math.max(T?H:0,W)),e.forEach((q,X)=>{let te=q.posX,J=L;y&&(i==0&&!T?(te|=0,J|=0,X>0&&te>e[X-1].posX+e[X-1].width&&(te--,J++)):te+=Math.max(T?H:0,W)/2,q.posX=te),q.barCenter=te+(L==1?0:J/2),q.width=J});const Y=[];for(const q of[0,1]){const X=o==At?(f+S)*q:0,te=X+f,J=X+_-(!T||E?0:K);Y.push({channelTop:X,channelBottom:te,analyzerBottom:J})}this._aux={analyzerHeight:_,analyzerWidth:g,centerX:p,centerY:m,channelCoords:Y,channelHeight:f,channelGap:S,initialX:I,innerRadius:P,outerRadius:R,scaleMin:V,unitWidth:j},this._flg={isAlpha:x,isBands:y,isLeds:T,isLumi:A,isOctaves:C,isOutline:N,isRound:k,noLedGap:E},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,m=h.canvas,v=[],b=this._chLayout==vs,y=this._chLayout==At,C=Math.min(r.width,r.height),T=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,x=p.height>>1,N=A>>1,k=x*(c?.7:1.5),E=N*(c?1:2),f=2**(1/12);if(!c&&(this._ansiBands||a!=Bn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ki?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let R=xu;for(let M=-1;M<11;M++)for(let O=0;O<12;O++){if(R>=this._minFreq&&R<=this._maxFreq){const L=T[O],V=L=="C";(L&&c&&!l&&!b||V)&&v.push(c?[R,L+(V?M:"")]:R)}R*=f}}m.width=m.height=Math.max(C*.15,(i<<1)+y*A);const _=m.width>>1,g=_-A*.7,S=(R,M)=>{const O=Fn*(R/r.width),L=O-Lr,V=g*Math.cos(L),j=g*Math.sin(L);h.save(),h.translate(_+V,_+j),h.rotate(O),h.fillText(M,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=Py,d.fillRect(0,0,p.width,p.height),h.arc(_,_,_-A/2,0,Fn),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=Gu,d.font=`${x}px ${ys}`,h.font=`${N}px ${ys}`,d.textAlign=h.textAlign="center";let I=-k/4,P=-E;for(const R of v){const[M,O]=Array.isArray(R)?R:[R,R<1e3?R|0:`${(R/100|0)/10}k`],L=o*(this._freqScaling(M)-s),V=p.height*.75,j=O[0]=="C",H=x*(c&&!l&&!b?j?1.2:.6:3);if(d.fillStyle=h.fillStyle=j&&!l&&!b?Ny:Gu,c){const K=a==Bn,W=a==ki;let Y=["C"];if((K||M>2e3||!W&&M>250||(!u||y)&&(!W&&M>125||M>1e3))&&Y.push("G"),(K||M>4e3||!W&&M>500||(!u||y)&&(!W&&M>250||M>2e3))&&Y.push("E"),(W&&M>4e3||(!u||y)&&(K||M>2e3||!W&&M>500))&&Y.push("D","F","A","B"),!Y.includes(O[0]))continue}L>=I+k/2&&L<=e&&(d.fillText(O,b&&l==-1?e-L:n+L,V,H),(b||l&&(L>k||l==1))&&d.fillText(O,b&&l!=1?e+L:(n||r.width)-L,V,H),I=L+Math.min(H,d.measureText(O).width)/2),L>=P+E&&L<e-E&&(S(b&&l==1?e-L:L,O),(b||l&&(L>E||l==1))&&S(b&&l!=-1?e+L:-L,O),P=L)}}_draw(e){this._runId=requestAnimationFrame(G=>this._draw(G));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:p,centerX:m,centerY:v,channelCoords:b,channelHeight:y,channelGap:C,initialX:T,innerRadius:A,outerRadius:x}=this._aux,{_bars:N,canvas:k,_canvasGradients:E,_chLayout:f,_colorMode:_,_ctx:g,_energy:S,_fadePeaks:I,fillAlpha:P,_fps:R,_linearAmplitude:M,_lineWidth:O,maxDecibels:L,minDecibels:V,_mirror:j,_mode:H,overlay:K,_radial:W,showBgColor:Y,showPeaks:q,useCanvas:X,_weightingFilter:te}=this,J=this._scaleX.canvas,he=this._scaleR.canvas,be=R*this._peakFadeTime/1e3,ye=R**2,Le=this._gravity*1e3,de=R*this._peakHoldTime/1e3,ve=f==Du,oe=f==vs,Je=f==At,Qe=f==Vt,Mt=a&&this._trueLeds&&_==_s,Ze=W?k.width:this._aux.analyzerWidth,re=T+Ze,Me=q&&this._peakLine&&H==Un,_e=W?x-A:p,Ht=_e/this._pixelRatio,[Fe,_n,st,Sa]=this._leds||[];S.val>0&&R>0&&(this._spinAngle+=this._spinSpeed*Fn/60/R);const MS=G=>{if(this._reflexRatio>0&&!l&&!W){let ge,Ot;this.reflexFit||Je?(ge=Je&&G==0?y+C:0,Ot=y-p):(ge=k.height-p*2,Ot=p),g.save(),g.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(g.filter=`brightness(${this.reflexBright})`),g.setTransform(1,0,0,-1,0,k.height),g.drawImage(k,0,b[G].channelTop,k.width,p,0,ge,k.width,Ot),g.restore()}},OS=()=>{this.showScaleX&&(W?(g.save(),g.translate(m,v),this._spinSpeed&&g.rotate(this._spinAngle+Lr),g.drawImage(he,-he.width>>1,-he.width>>1),g.restore()):g.drawImage(J,0,k.height-J.height))},PS=G=>{const ge=G**2,Ot=424.36,We=11599.29,Gs=25122.25,en=544496.41,Wt=148693636,bn=wn=>20*Math.log10(wn);switch(te){case Uu:const wn=Wt*ge**2/((ge+Ot)*Math.sqrt((ge+We)*(ge+en))*(ge+Wt));return 2+bn(wn);case Bu:const Sn=Wt*ge*G/((ge+Ot)*Math.sqrt(ge+Gs)*(ge+Wt));return .17+bn(Sn);case Vu:const Ea=Wt*ge/((ge+Ot)*(ge+Wt));return .06+bn(Ea);case $u:const qs=((103791848e-2-ge)**2+108076816e-2*ge)/((9837328-ge)**2+11723776*ge),ka=G/68966888496476e-18*Math.sqrt(qs/((ge+79919.29)*(ge+1345600)));return bn(ka);case ju:const zs=-4737338981378384e-39*G**6+2043828333606125e-30*G**4-1363894795463638e-22*ge+1,Cn=1306612257412824e-34*G**5-2118150887518656e-26*G**3+.0005559488023498642*G,lt=.0001246332637532143*G/Math.hypot(zs,Cn);return 18.2+bn(lt)}return 0},Ca=(G,ge,Ot)=>{g.beginPath(),g.moveTo(G,ge),g.lineTo(G,Ot),g.stroke()},Ta=G=>{if(G&&O){const ge=g.globalAlpha;g.globalAlpha=1,g.stroke(),g.globalAlpha=ge}},yn=G=>Math.max(0,(G*Fe|0)*(Sa+st)-st),NS=G=>{S.val=G,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*Le/ye/k.height*this._pixelRatio)),G>=S.peak&&(S.peak=G,S.hold=de)};K&&g.clearRect(0,0,k.width,k.height);let Zf=0;const ep=N.length,tp=Qe?1:2;for(let G=0;G<tp;G++){const{channelTop:ge,channelBottom:Ot,analyzerBottom:We}=b[G],Gs=this._gradients[this._selectedGrads[G]],en=Gs.colorStops,Wt=en.length,bn=!Y||a&&!K?"#000":Gs.bgColor,wn=Je&&W&&G?-1:1,Sn=!G&&j==-1||G&&j==1,Ea=!oe||G&&j!=1?0:Ze>>(G||!Sn),qs=oe&&Sn?-1:1,ka=()=>{const Q=J.height,ne=Q>>1,se=M?100:L,Ce=M?0:V,Pe=M?20:5,ot=p/(se-Ce),Pt=j!=-1&&(!oe||G==0||j==1),tn=j!=1&&(!oe||G!=j);g.save(),g.fillStyle=qu,g.font=`${ne}px ${ys}`,g.textAlign="right",g.lineWidth=1;for(let nn=se;nn>Ce;nn-=Pe){const Jn=ge+(se-nn)*ot,Ve=nn%2==0|0;if(Ve){const et=Jn+ne*(Jn==ge?.8:.35);Pt&&g.fillText(nn,Q*.85,et),tn&&g.fillText(nn,(oe?Ze:k.width)-Q*.1,et),g.strokeStyle=qu,g.setLineDash([2,4]),g.lineDashOffset=0}else g.strokeStyle=Fy,g.setLineDash([2,8]),g.lineDashOffset=1;g.beginPath(),g.moveTo(T+Q*Ve*Pt,~~Jn+.5),g.lineTo(re-Q*Ve*tn,~~Jn+.5),g.stroke()}g.restore()},zs=(Q,ne)=>{const se=St[Q]+(Q<St.length-1?(St[Q+1]-St[Q])*ne:0);return isNaN(se)?-1/0:se},Cn=(Q,ne=qs)=>ne*Fn*((Q+Ea)/k.width)+this._spinAngle,lt=(Q,ne,se)=>{const Ce=A+ne*wn,Pe=Cn(Q,se);return[m+Ce*Math.cos(Pe),v+Ce*Math.sin(Pe)]},Ia=(Q,ne,se,Ce,Pe)=>{g.beginPath();for(const ot of j&&!oe?[1,-1]:[qs]){const[Pt,tn]=d?[Cn(Q,ot),Cn(Q+se,ot)]:[];g.moveTo(...lt(Q,ne,ot)),g.lineTo(...lt(Q,ne+Ce,ot)),d?g.arc(m,v,A+(ne+Ce)*wn,Pt,tn,ot!=1):g.lineTo(...lt(Q+se,ne+Ce,ot)),g.lineTo(...lt(Q+se,ne,ot)),d&&!Pe&&g.arc(m,v,A+ne*wn,tn,Pt,ot==1)}Ta(Pe),g.fill()},Aa=(Q=0,ne=0)=>{let se;if(_==_s&&!Mt||H==Un)se=E[G];else{const Ce=_==Lu?ne%Wt:en.findLastIndex(Pe=>a?yn(Q)<=yn(Pe.level):Q<=Pe.level);se=en[Ce].color}g.fillStyle=g.strokeStyle=se};if(X){if(oe&&!W){const Q=Ze*(G+Sn),ne=Sn?-1:1;g.setTransform(ne,0,0,1,Q,0)}if((!K||Y)&&(K&&(g.globalAlpha=this.bgAlpha),g.fillStyle=bn,(G==0||!W&&!ve)&&g.fillRect(T,ge-C,Ze,(K&&this.reflexAlpha==1?p:y)+C),g.globalAlpha=1),this.showScaleY&&!l&&!W&&(G==0||!ve)&&ka(),a?(g.setLineDash([Sa,st]),g.lineWidth=N[0].width):g.lineWidth=u?Math.min(O,N[0].width/2):O,g.save(),!W){const Q=new Path2D;Q.rect(0,ge,k.width,p),g.clip(Q)}}let St=this._fftData[G];this._analyzer[G].getFloatFrequencyData(St),te&&(St=St.map((Q,ne)=>Q+PS(this._binToFreq(ne)))),g.beginPath();let $i=[];for(let Q=0;Q<ep;Q++){const ne=N[Q],{posX:se,barCenter:Ce,width:Pe,freq:ot,binLo:Pt,binHi:tn,ratioLo:nn,ratioHi:Jn}=ne;let Ve=Math.max(zs(Pt,nn),zs(tn,Jn));for(let we=Pt+1;we<tn;we++)St[we]>Ve&&(Ve=St[we]);if(Ve=this._normalizedB(Ve),ne.value[G]=Ve,Zf+=Ve,ne.peak[G]>0&&ne.alpha[G]>0&&(ne.hold[G]--,ne.hold[G]<0)){if(I&&!Me){const we=!o||u&&O>0?1:o?ne.peak[G]:P;ne.alpha[G]=we*(1+ne.hold[G]/be)}else ne.peak[G]+=ne.hold[G]*Le/ye/Ht;ne.alpha[G]<=0&&(ne.peak[G]=0)}if(Ve>=ne.peak[G]&&(ne.peak[G]=Ve,ne.hold[G]=de,ne.alpha[G]=!o||u&&O>0?1:o?Ve:P),!X)continue;g.globalAlpha=l||o?Ve:u?P:1,Aa(Ve,Q);const et=l?_e:a?yn(Ve):Ve*_e|0;if(H==Un){const we=Q?0:(this._normalizedB(St[N[1].binLo])*_e+et)/2;if(W){if(Q==0&&(oe&&g.moveTo(...lt(0,0)),g.lineTo(...lt(0,se<0?we:et))),se>=0){const vt=[se,et];g.lineTo(...lt(...vt)),$i.push(vt)}}else{if(Q==0)if(j==-1&&!oe)g.moveTo(T,We-(se<T?we:et));else{const vt=Pt?this._normalizedB(St[Pt-1])*_e:et;g.moveTo(T-O,We-vt)}(oe||j!=-1||se>=T)&&g.lineTo(se,We-et)}}else if(a){if(Y&&!K&&(G==0||!ve)){const we=g.globalAlpha;g.strokeStyle=Ly,g.globalAlpha=1,Ca(Ce,ge,We),g.strokeStyle=g.fillStyle,g.globalAlpha=we}if(Mt){const we=l?0:en.findLastIndex(Tn=>yn(Ve)<=yn(Tn.level));let vt=We;for(let Tn=Wt-1;Tn>=we;Tn--){g.strokeStyle=en[Tn].color;let ip=We-(Tn==we?et:yn(en[Tn].level));Ca(Ce,vt,ip),vt=ip-st}}else Ca(Ce,We,We-et)}else if(se>=T)if(W)Ia(se,0,Pe,et,u);else if(d){const we=Pe/2,vt=We+we;g.beginPath(),g.moveTo(se,vt),g.lineTo(se,vt-et),g.arc(Ce,vt-et,we,Dr,Fn),g.lineTo(se+Pe,vt),Ta(u),g.fill()}else{const we=u?g.lineWidth:0;g.beginPath(),g.rect(se,We+we,Pe,-et-we),Ta(u),g.fill()}const Qn=ne.peak[G],np=ne.alpha[G];if(Qn>0&&np>0&&q&&!Me&&!l&&se>=T&&se<re){if(I?g.globalAlpha=np:u&&O>0?g.globalAlpha=1:o&&(g.globalAlpha=Qn),(_==Mu||Mt)&&Aa(Qn),a){const we=yn(Qn);we>=st&&g.fillRect(se,We-we,Pe,Sa)}else if(!W)g.fillRect(se,We-Qn*_e,Pe,2);else if(H!=Un){const we=Qn*_e;Ia(se,we,Pe,!this._radialInvert||Je||we+A>=2?-2:2)}}}if(X){if(g.globalAlpha=1,H==Un){if(Aa(),W&&!oe){if(j){let Q;for(;Q=$i.pop();)g.lineTo(...lt(...Q,-1))}g.closePath()}if(O>0&&g.stroke(),P>0){if(W){const Q=oe?Cn(Ze>>1):0,ne=oe?Cn(Ze):Fn;g.moveTo(...lt(oe?Ze>>1:0,0)),g.arc(m,v,A,Q,ne,oe?!Sn:!0)}else g.lineTo(re,We),g.lineTo(T,We);g.globalAlpha=P,g.fill(),g.globalAlpha=1}if((Me||W&&q)&&($i=[],g.beginPath(),N.forEach((Q,ne)=>{let se=Q.posX,Ce=Q.peak[G],Pe=ne?"lineTo":"moveTo";if(W&&se<0){const ot=N[ne+1];Ce=zy(se,Ce,ot.posX,ot.peak[G],0),se=0}Ce*=_e,Me?(g[Pe](...W?lt(se,Ce):[se,We-Ce]),W&&j&&!oe&&$i.push([se,Ce])):Ce>0&&Ia(se,Ce,1,-2)}),Me)){let Q;for(;Q=$i.pop();)g.lineTo(...lt(...Q,-1));g.lineWidth=1,g.stroke()}}g.restore(),oe&&!W&&g.setTransform(1,0,0,1,0,0),(!oe&&!ve||G)&&MS(G)}}if(NS(Zf/(ep<<tp-1)),X&&(j&&!W&&!oe&&(g.setTransform(-1,0,0,1,k.width-T,0),g.drawImage(k,T,0,m,k.height,0,0,m,k.height),g.setTransform(1,0,0,1,0,0)),g.setLineDash([]),OS()),this.showFPS){const G=J.height;g.font=`bold ${G}px ${ys}`,g.fillStyle=Dy,g.textAlign="right",g.fillText(Math.round(R),k.width-G,G*2)}this.onCanvasDraw&&(g.save(),g.fillStyle=g.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),g.restore())}_freqScaling(e){switch(this._frequencyScale){case Bn:return Math.log2(e);case Or:return 26.81*e/(1960+e)-.53;case Pr:return Math.log2(1+e/700);case ki:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==At,p=1-s,m=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],y=b.colorStops,C=b.dir=="h";let T;if(i?T=n.createRadialGradient(r,a,u,r,a,c-(u-c)*h):T=n.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,m]),y){const A=h&&!this._splitGradient&&(!C||i);for(let x=0;x<1+A;x++){const N=y.length-1;y.forEach((k,E)=>{let f=k.pos;if(A&&(f/=2),h&&!d&&!i&&!C&&(f*=p,!A&&f>.5*p&&(f+=.5*s)),x==1)if(i||d){const _=N-E;k=y[_],f=1-k.pos/2}else E==0&&f>0&&T.addColorStop(.5,k.color),f+=.5;T.addColorStop(f,k.color),h&&E==N&&f<.5&&T.addColorStop(.5,k.color)})}}this._canvasGradients[v]=T}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==n,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Hu&&n.width==u&&n.height==d)&&(n.width=u,n.height=d,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,u,d)),i.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Wu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new pt(Vy,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(Ii).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Ii,...e});for(const r of Object.keys(e))i.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const Yy={verdant:{colorStops:[{color:"#D3FFA6",pos:0},{color:"#036B5B",pos:.5},{color:"#D3FFA6",pos:1}]},twilight:{colorStops:[{color:"#81B9FF",pos:0},{color:"#371A5E",pos:.5},{color:"#81B9FF",pos:1}]},bloom:{colorStops:[{color:"#FFD4FE",pos:0},{color:"#FD05F9",pos:.5},{color:"#FFD4FE",pos:1}]},mystic:{colorStops:[{color:"#1F023A",pos:0},{color:"#CA76FF",pos:.5},{color:"#1F023A",pos:1}]},flare:{colorStops:[{color:"#FFFFFF",pos:0},{color:"#FC5F00",pos:.5},{color:"#FFFFFF",pos:1}]},glacier:{colorStops:[{color:"#4CE5F2",pos:0},{color:"#005A98",pos:.5},{color:"#4CE5F2",pos:1}]}},Ju=({stream:t,className:e,onClick:n})=>{var o;const i=ue(null),s=hn();return Ie(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Ky(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",Yy[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),D("div",{onClick:n,className:Bt("w-full",e),ref:i})},Qu=Yi(null),Fr=({className:t,debug:e=!1})=>{const n=vo(Qu);return!e||!n||!(n.region||n.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[n.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",n.region]}),n.region&&n.dc&&D("span",{children:" · "}),n.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",n.dc]})]})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Zu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Xy=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),eh=t=>{const e=Xy(t);return e.charAt(0).toUpperCase()+e.slice(1)},Jy=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
21
+ */const Zu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Xy=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),eh=t=>{const e=Xy(t);return e.charAt(0).toUpperCase()+e.slice(1)},Jy=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
@@ -28,12 +28,12 @@ var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,co
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Zy=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>lt("svg",{...Qy,width:String(e),height:e,stroke:t,"stroke-width":n?Number(i)*24/Number(e):i,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>lt(l,c)),...Tt(s)]);/**
31
+ */const Zy=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>ct("svg",{...Qy,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>ct(l,c)),...Tt(s)]);/**
32
32
  * @license lucide-preact v0.515.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const Ye=(t,e)=>{const i=({class:n="",children:s,...o})=>lt(Zy,{...o,iconNode:e,class:Jy(`lucide-${Zu(eh(t))}`,`lucide-${Zu(t)}`,n)},s);return i.displayName=eh(t),i};/**
36
+ */const Ye=(t,e)=>{const n=({class:i="",children:s,...o})=>ct(Zy,{...o,iconNode:e,class:Jy(`lucide-${Zu(eh(t))}`,`lucide-${Zu(t)}`,i)},s);return n.displayName=eh(t),n};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
@@ -48,7 +48,7 @@ var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,co
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const ih=Ye("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
51
+ */const nh=Ye("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
52
52
  * @license lucide-preact v0.515.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
@@ -58,12 +58,12 @@ var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,co
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const i0=Ye("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const n0=Ye("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
62
62
  * @license lucide-preact v0.515.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const n0=Ye("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
66
+ */const i0=Ye("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
67
67
  * @license lucide-preact v0.515.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
@@ -108,12 +108,12 @@ var FS=Object.defineProperty;var US=(vt,J,ni)=>J in vt?FS(vt,J,{enumerable:!0,co
108
108
  *
109
109
  * This source code is licensed under the ISC license.
110
110
  * See the LICENSE file in the root directory of this source tree.
111
- */const In=Ye("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),nh=Yn(!1),h0=()=>Ll(nh),Rt=({children:t,className:e,onClick:i,tooltip:n,disabled:s=!1})=>D("button",{title:n,"aria-label":n,disabled:s,onClick:i,className:Bt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),sh=({call:t,chatMode:e})=>{const[i,n]=h0(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(Rt,{tooltip:i?"Unmute":"Mute",onClick:s,className:Bt(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(n0,{className:"w-5 h-5 text-black dark:text-white"}):D(s0,{className:"w-5 h-5 text-black dark:text-white"})}),D(Rt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(r0,{className:"w-4 h-4 text-black dark:text-white"})})]})},oh=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Xt.div,{layoutId:Cn,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!i&&D(Ju,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Ru,{stream:t.remoteStream,chatMode:i}),D(xr,{size:"small"}),D(sh,{call:t,chatMode:i}),D(Fr,{debug:n})]});function rh(){const[t,e]=ve(!1),i=ui();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(Rt,{tooltip:"More",onClick:()=>e(!t),children:D(ih,{className:"text-black dark:text-white"})}),t&&D("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[D(Rt,{tooltip:"More",onClick:()=>e(!t),children:D(ih,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(d0,{className:"w-4 h-4"})]}),i.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(u0,{className:"w-4 h-4"})]}),i.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D(t0,{className:"w-4 h-4"})]})]})]})]})}function f0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ws={exports:{}},p0=ws.exports,ah;function g0(){return ah||(ah=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(p0,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function E(){var g;if(!(typeof window===i||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===i)try{var S=window.document.cookie,I=encodeURIComponent(x),M=S.indexOf(I+"=");M!==-1&&(g=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function k(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),E()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=E();_!=null&&(A=f(_)),u.call(y)}r=new p,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[b];return y||(y=o[b]=new p(b,r.methodFactory)),y};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(ws)),ws.exports}var m0=g0();const v0=f0(m0),_0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),y0="[ai-agent-widget]",re=v0.getLogger("telnyx-ai-agent-widget"),b0=re.methodFactory;re.methodFactory=(t,e,i)=>{const n=b0(t,e,i);return function(...s){n(_0(),y0,...s)}},re.setLevel("info");function w0({onCapture:t,onClose:e}){const i=ce(null),n=ce(null),s=ce(null),[o,r]=ve(null),[a,l]=ve(!0);Le(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,i.current&&(i.current.srcObject=h,l(!1))}catch(h){re.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,p=h.getContext("2d");if(!p)return;h.width=d.videoWidth,h.height=d.videoHeight,p.drawImage(d,0,0,h.width,h.height);const m=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(m),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[D("div",{className:"absolute top-2 right-2 z-10",children:D(Rt,{tooltip:"Close",onClick:u,children:D(In,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(_t,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:Bt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("button",{onClick:c,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[D(th,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const Ur=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],S0=["audio","lang","mark","p","s","sub","w"],lh=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ch(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function dh(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const uh=Ur.filter(t=>!S0.includes(t)),C0=ch(Ur,"gi"),hh=ch(uh,"gi"),T0=dh(Ur,"i"),k0=dh(uh,"i"),E0=new RegExp(`${hh.source}|${lh.source}`,"i");function I0(t){const e=E0.test(t),i=e?C0:hh,n=e?T0:k0;return t.replace(i,"").replace(n,"").replace(lh,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function A0({item:t,containerRef:e}){const i=ce(null),n=t.role==="assistant"?I0(t.content):t.content;return Le(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:Bt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:Bt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),n&&D("p",{className:Bt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const fh=({transcript:t,onSendMessage:e,allowAttachments:i=!0,awaitAcceptance:n=!1,sendDisabled:s=!1})=>{const o=ce(!1),[r,a]=ve(!1),[l,c]=ve(null),u=ce(null),d=ce(null),h=ce(null),[p,m]=ve([]),[v,b]=ve(!1),[y,C]=ve([]),[,T]=ms();Le(()=>()=>{p.forEach(R=>URL.revokeObjectURL(R.preview))},[p]),Le(()=>{if(y.length===0)return;const R=t.filter(P=>P.role==="user"&&!P.id.startsWith("optimistic-"));if(R.length>0){const P=R[R.length-1];C(O=>O.filter(L=>L.timestamp>P.timestamp))}},[t,y]);const A=R=>new Promise((P,O)=>{const L=new FileReader;L.onload=()=>P(L.result),L.onerror=O,L.readAsDataURL(R)}),x=async R=>{if(i&&R.type.startsWith("image/"))try{const P=await A(R),O=URL.createObjectURL(R),L={id:Date.now().toString(),file:R,base64:P,preview:O};m(V=>[...V,L])}catch(P){re.error("Error processing image:",P)}},N=R=>{m(P=>{const O=P.find(L=>L.id===R);return O&&URL.revokeObjectURL(O.preview),P.filter(L=>L.id!==R)})},E=R=>{const P=R.target,O=P.files;O&&O.length>0&&(Array.from(O).forEach(x),P.value="")},k=R=>{var O;const P=(O=R.clipboardData)==null?void 0:O.items;P&&Array.from(P).forEach(L=>{if(L.type.startsWith("image/")){const V=L.getAsFile();V&&x(V)}})},f=()=>{var R;(R=d.current)==null||R.click()},_=()=>{b(!0)},g=R=>{fetch(R).then(P=>P.blob()).then(P=>{const O=new File([P],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});x(O)}).catch(P=>{re.error("Error processing camera capture:",P)})},S=async()=>{var O;if(s||o.current)return;if(n){const L=u.current;if(!L||!L.value.trim())return;const V=L.value;o.current=!0,a(!0),c(null);try{await e(V,[]),L.value===V&&(L.value="")}catch($){c($ instanceof Error?$.message:"Message was not sent. Please try again.")}finally{o.current=!1,a(!1)}return}const R=u.current&&u.current.value.trim()!=="",P=i&&p.length>0;if(R||P){const L=((O=u.current)==null?void 0:O.value)||"",V=new Date,$={id:`optimistic-${V.getTime()}`,role:"user",content:L,timestamp:V,attachments:p.map(W=>({type:"image",url:W.base64}))};C(W=>[...W,$]),P&&T("processing_image"),e(L,p.map(W=>W.base64)),u.current&&(u.current.value=""),p.forEach(W=>URL.revokeObjectURL(W.preview)),m([])}},I=R=>{R.key==="Enter"&&(R.preventDefault(),S())},M=[...t,...y];return D("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:h,children:M.map((R,P)=>D(A0,{item:R,containerRef:h},R.id+P))}),l&&D("p",{role:"alert",className:"text-sm mb-2",children:l}),p.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:p.map(R=>D("div",{className:"relative",children:[D("img",{src:R.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>N(R.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:D(In,{className:"w-3 h-3"})})]},R.id))}),D("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[D("input",{ref:u,type:"text","aria-label":"Message",readOnly:r,onKeyDown:I,onPaste:k,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),i&&D(_t,{children:[D("input",{ref:d,type:"file",accept:"image/*",multiple:!0,onChange:E,className:"hidden"}),D(Rt,{tooltip:"Attach image",onClick:f,children:D(o0,{className:"text-[#969696] w-4 h-4"})}),D(Rt,{tooltip:"Take photo",onClick:_,children:D(th,{className:"text-[#969696] w-4 h-4"})})]}),D(Rt,{tooltip:"Send",onClick:S,disabled:s||r,children:D(l0,{className:"text-[#969696] w-4 h-4"})})]}),i&&v&&D(w0,{onCapture:g,onClose:()=>b(!1)})]})};function R0({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D(Rt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(In,{className:"text-black dark:text-white"})})]})}const x0=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Gc,{children:D(Xt.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[D("div",{className:"p-4 text-center",children:[D(R0,{onCollapse:e}),!n&&D(Ju,{className:"h-[144px]",stream:t.remoteStream}),D(xr,{size:"large",className:"mb-4"}),D(sh,{call:t,chatMode:n}),D(Fr,{className:"mt-2",debug:s})]}),D(Ru,{stream:t.remoteStream,chatMode:n}),D(fh,{transcript:i,onSendMessage:(o,r)=>t.sendConversationMessage(o,r)})]})});function ph(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function U(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var gh=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),D0=new Uint8Array(16);function L0(){if(!gh)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return gh(D0)}for(var mh=[],Ss=0;Ss<256;++Ss)mh[Ss]=(Ss+256).toString(16).substr(1);function Ui(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||L0)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,a){var l=0,c=mh;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const M0={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},O0={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:P0,SDP_CREATE_ANSWER_FAILED:N0,SDP_SET_LOCAL_DESCRIPTION_FAILED:F0,SDP_SET_REMOTE_DESCRIPTION_FAILED:vh,SDP_SEND_FAILED:_h,MEDIA_MICROPHONE_PERMISSION_DENIED:yh,MEDIA_DEVICE_NOT_FOUND:bh,MEDIA_GET_USER_MEDIA_FAILED:Br,HOLD_FAILED:U0,INVALID_CALL_PARAMETERS:B0,BYE_SEND_FAILED:V0,SUBSCRIBE_FAILED:$0,PEER_CLOSED_DURING_INIT:Vr,WEBSOCKET_CONNECTION_FAILED:j0,WEBSOCKET_ERROR:H0,RECONNECTION_EXHAUSTED:$r,GATEWAY_FAILED:W0,LOGIN_FAILED:wh,INVALID_CREDENTIALS:G0,AUTHENTICATION_REQUIRED:q0,ICE_RESTART_FAILED:z0,NETWORK_OFFLINE:K0,SESSION_NOT_REATTACHED:Sh,UNEXPECTED_ERROR:Ch}=M0,{HIGH_RTT:Y0,HIGH_JITTER:X0,HIGH_PACKET_LOSS:J0,LOW_MOS:Th,LOW_LOCAL_AUDIO:Cs,LOW_INBOUND_AUDIO:Ts,LOW_BYTES_RECEIVED:jr,LOW_BYTES_SENT:kh,RECORDING_UNAVAILABLE:Q0,RECORDING_BUFFER_OVERFLOW:Z0,ICE_CONNECTIVITY_LOST:eb,ICE_GATHERING_TIMEOUT:tb,ICE_GATHERING_EMPTY:ib,PEER_CONNECTION_FAILED:nb,ONLY_HOST_ICE_CANDIDATES:sb,ANSWER_WHILE_PEER_ACTIVE:ob,ICE_CANDIDATE_PAIR_CHANGED:rb,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:ab,MULTIPLE_ACTIVE_CALLS_DETECTED:lb,DUPLICATE_INBOUND_ANSWER:cb,SHARED_REMOTE_ELEMENT_OVERWRITE:db,TOKEN_EXPIRING_SOON:ub,UNKNOWN_REATTACHED_SESSION:hb,SIGNALING_RECOVERY_REQUIRED:fb,MEDIA_RECOVERY_REQUIRED:pb,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:gb}=O0,Eh="wss://rtc.telnyx.com",Ih={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Ah={urls:"stun:stun.l.google.com:19302"},mb={urls:"stun:stun.telnyx.com:3478"},vb={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},_b={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},yb={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},bb={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},wb=[mb,Ah,vb,_b,yb,bb],Sb=[{urls:"stun:stundev.telnyx.com:3478"},Ah,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(F||(F={}));const Cb={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},Tb={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed with host (local network) candidates only. This is diagnostic evidence that no server-reflexive (srflx), peer-reflexive (prflx), or relay (TURN) candidates were found; connectivity may still succeed, but network traversal options can be limited.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function je(t,e){const i=Tb[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Jt extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,Jt.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}}function Bi(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return yh;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return bh}return Br}function ae(t,e,i,n){const s=Cb[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Jt({code:t,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:n??s.fatal})}class kb extends Error{constructor(e,i,n=""){super(`Signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=i,this.method=n}}class Hr extends Error{constructor(e,i,n){super(`Stale request cancelled (id=${e}, gen=${i}, current=${n})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=i,this.currentGeneration=n}}var Eb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Rh(t,e){return t(e={exports:{}},e.exports),e.exports}var Ib=Rh(function(t){var e,i;e=Eb,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,y){var C=b[y];if(typeof C.bind=="function")return C.bind(b);try{return Function.prototype.bind.call(C,b)}catch{return function(){return Function.prototype.apply.apply(C,[b,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(b,y){for(var C=0;C<r.length;C++){var T=r[C];this[T]=C<b?n:this.methodFactory(T,b,y)}this.log=this.debug}function u(b,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[b].apply(this,arguments))}}function d(b,y,C){return function(T){return T==="debug"&&(T="log"),typeof console!==s&&(T==="trace"&&o?l:console[T]!==void 0?a(console,T):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,y,C){var T,A=this;y=y??"WARN";var x="loglevel";function N(){var k;if(typeof window!==s&&x){try{k=window.localStorage[x]}catch{}if(typeof k===s)try{var f=window.document.cookie,_=f.indexOf(encodeURIComponent(x)+"=");_!==-1&&(k=/^([^;]+)/.exec(f.slice(_))[1])}catch{}return A.levels[k]===void 0&&(k=void 0),k}}typeof b=="string"?x+=":"+b:typeof b=="symbol"&&(x=void 0),A.name=b,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return T},A.setLevel=function(k,f){if(typeof k=="string"&&A.levels[k.toUpperCase()]!==void 0&&(k=A.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(T=k,f!==!1&&function(_){var g=(r[_]||"silent").toUpperCase();if(typeof window!==s&&x){try{return void(window.localStorage[x]=g)}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+g+";"}catch{}}}(k),c.call(A,k,b),typeof console===s&&k<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(k){y=k,N()||A.setLevel(k,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&x){try{return void window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(k){A.setLevel(A.levels.TRACE,k)},A.disableAll=function(k){A.setLevel(A.levels.SILENT,k)};var E=N();E==null&&(E=y),A.setLevel(E,!1)}var p=new h,m={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=m[b];return y||(y=m[b]=new h(b,p.getLevel(),p.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return m},p.default=p,p},t.exports?t.exports=i():e.log=i()});const xh={debug:0,info:1,warn:2,error:3};class Ab{constructor(e={}){var i,n,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(i=e.enabled)!==null&&i!==void 0&&i,level:(n=e.level)!==null&&n!==void 0?n:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,i,n){if(!this.isCapturing||!this.options.enabled||xh[e]<xh[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:i},n&&Object.keys(n).length>0?{context:n}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Dh=null;const w=Ib.getLogger("telnyx"),ks={trace:0,debug:1,info:2,warn:3,error:4};let Lh=ks.info;function Mh(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const Rb=w.methodFactory;w.methodFactory=(t,e,i)=>{const n=Rb(t,e,i);return function(...s){if(ks[t]>=Lh){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Dh;if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Mh(a[0]):{args:a.map(Mh)}),o.addEntry(t,l,c)}}},w.setLevel("debug",!1);const Es=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{w.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Oh=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Is=t=>t instanceof Function||typeof t=="function",An=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,xb=/^(ws|wss):\/\//,Ph=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Ph(a,r):{result:s}},As=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),Rn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Wr=t=>{var e,i,n,s,o,r;let a="",l="";return!((i=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||i===void 0)&&i.state&&(a=(s=(n=t==null?void 0:t.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function Nh({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?Db(n,t):n,i=s}),resolve:e,reject:i}}const Db=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Gr="telnyx-voice-sdk-id",Rs="telnyx-voice-sdk-session-id",xs="telnyx-voice-sdk-session-id-stored-at",qr="telnyx-voice-sdk-active-calls",Lb=9e4;function Fh(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(xs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=Lb}function xn(){return sessionStorage.getItem(Gr)}function zr(t,e=Date.now()){sessionStorage.setItem(Rs,t),sessionStorage.setItem(xs,String(e))}function Uh(){sessionStorage.removeItem(Gr),sessionStorage.removeItem(Rs),sessionStorage.removeItem(xs)}function hi(){(function(t){try{sessionStorage.removeItem(t)}catch(e){w.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(qr)}function Bh(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return w.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(qr);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return w.debug("Active-calls recovery marker payload was malformed — discarded."),hi(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(w.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),hi(),null):i.calls.length===0?(w.debug("Active-calls recovery marker had no call records — discarded."),hi(),null):i}catch(i){return w.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),hi(),null}}function Vh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void hi();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){w.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(qr,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var He,xt,ie;(function(t){t.Offer="offer",t.Answer="answer"})(He||(He={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(xt||(xt={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ie||(ie={}));const pt={generic:"event",[ie.Display]:"participantData",[ie.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Mb={invalidCredentialsOptions:"InvalidCredentialsOptions"},$h=8e6,jh={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!1};var z,Kr,ot,Dt,Ue,Vi;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Kr||(Kr={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(ot||(ot={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Dt||(Dt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Ue||(Ue={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Vi||(Vi={}));const $i="GLOBAL",it={},Dn=(t,e)=>`${t}|${e}`,Hh=(t,e=$i)=>Dn(t,e)in it,Qt=(t,e,i=$i)=>{const n=Dn(t,i);n in it||(it[n]=[]),it[n].push(e)},Wh=(t,e,i=$i)=>{const n=function(s){Lt(t,n,i),e(s)};return n.prototype.targetRef=e,Qt(t,n,i)},Lt=(t,e,i=$i)=>{if(!Hh(t,i))return!1;const n=Dn(t,i);if(Is(e))for(let s=it[n].length-1;s>=0;s--){const o=it[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&it[n].splice(s,1)}else it[n]=[];return it[n].length===0&&delete it[n],!0},j=(t,e,i=$i,n=!0)=>{const s=n&&i!==$i;if(!Hh(t,i))return s&&j(t,e),!1;const o=Dn(t,i),r=it[o].length;if(!r)return s&&j(t,e),!1;for(let a=r-1;a>=0;a--)it[o][a](e);return s&&j(t,e),!0},Yr=t=>{const e=Dn(t,"");Object.keys(it).filter(i=>i.indexOf(e)===0).forEach(i=>delete it[i])};let Ob=typeof WebSocket<"u"?WebSocket:null;const Pb=0,Nb=1,Fb=2,Gh=3;class Ds{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Eh,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:i,env:n,region:s,useCanaryRtcServer:o}=e.options;w.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Eh),i&&(this._host=(r=>`${xb.test(r)?"":"wss://"}${r}`)(i)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===Nb}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Pb}get closing(){return!!this._wsClient&&this._wsClient.readyState===Fb}get closed(){return!!this._wsClient&&this._wsClient.readyState===Gh}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){w.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=xn();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&e.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),w.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const n=this.socketGeneration;this._wsClient=new Ob(e.toString()),this.socketGeneration+=1,w.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:n}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(n){w.error("WebSocket connection failed:",n);const s=ae(j0,n);j(F.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var i;(i=this._wsClient)===null||i===void 0||i.send(e)}send(e,i){var n;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=p=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),this.session.onOutboundConfirmed(),u)return;const{result:m,error:v}=Ph(p);return v?c(v):l(m)};Wh(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),i&&i>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),Lt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return w.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Hr(s.id,o,this.socketGeneration));c(new kb(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return w.debug(`SEND:
111
+ */const Ai=Ye("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ih=Yi(!1),h0=()=>Ll(ih),Rt=({children:t,className:e,onClick:n,tooltip:i,disabled:s=!1})=>D("button",{title:i,"aria-label":i,disabled:s,onClick:n,className:Bt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),sh=({call:t,chatMode:e})=>{const[n,i]=h0(),s=()=>{i(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(Rt,{tooltip:n?"Unmute":"Mute",onClick:s,className:Bt(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?D(i0,{className:"w-5 h-5 text-black dark:text-white"}):D(s0,{className:"w-5 h-5 text-black dark:text-white"})}),D(Rt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(r0,{className:"w-4 h-4 text-black dark:text-white"})})]})},oh=({call:t,onExpand:e,chatMode:n,debug:i=!1})=>D(Xt.div,{layoutId:Ti,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!n&&D(Ju,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Ru,{stream:t.remoteStream,chatMode:n}),D(xr,{size:"small"}),D(sh,{call:t,chatMode:n}),D(Fr,{debug:i})]});function rh(){const[t,e]=me(!1),n=hn();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},o=()=>{i(n.report_issue_url)},r=()=>{i(n.view_history_url)};return D("div",{children:[D(Rt,{tooltip:"More",onClick:()=>e(!t),children:D(nh,{className:"text-black dark:text-white"})}),t&&D("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[D(Rt,{tooltip:"More",onClick:()=>e(!t),children:D(nh,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(d0,{className:"w-4 h-4"})]}),n.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(u0,{className:"w-4 h-4"})]}),n.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D(t0,{className:"w-4 h-4"})]})]})]})]})}function f0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ws={exports:{}},p0=ws.exports,ah;function g0(){return ah||(ah=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(p0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==n&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function k(){var g;if(!(typeof window===n||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===n)try{var S=window.document.cookie,I=encodeURIComponent(x),P=S.indexOf(I+"=");P!==-1&&(g=/^([^;]+)/.exec(S.slice(P+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function E(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),k()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=k();_!=null&&(A=f(_)),u.call(y)}r=new p,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[b];return y||(y=o[b]=new p(b,r.methodFactory)),y};var m=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(ws)),ws.exports}var m0=g0();const v0=f0(m0),_0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),y0="[ai-agent-widget]",ae=v0.getLogger("telnyx-ai-agent-widget"),b0=ae.methodFactory;ae.methodFactory=(t,e,n)=>{const i=b0(t,e,n);return function(...s){i(_0(),y0,...s)}},ae.setLevel("info");function w0({onCapture:t,onClose:e}){const n=ue(null),i=ue(null),s=ue(null),[o,r]=me(null),[a,l]=me(!0);Ie(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,n.current&&(n.current.srcObject=h,l(!1))}catch(h){ae.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const d=n.current,h=i.current,p=h.getContext("2d");if(!p)return;h.width=d.videoWidth,h.height=d.videoHeight,p.drawImage(d,0,0,h.width,h.height);const m=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(m),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[D("div",{className:"absolute top-2 right-2 z-10",children:D(Rt,{tooltip:"Close",onClick:u,children:D(Ai,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(yt,{children:[D("video",{ref:n,autoPlay:!0,playsInline:!0,className:Bt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("button",{onClick:c,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[D(th,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const Ur=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],S0=["audio","lang","mark","p","s","sub","w"],lh=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ch(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`</?(?:${n})(?:\\s+[^<>]*)?\\s*/?>`,e)}function dh(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`<\\/?(?:${n})(?:\\s+[^<>]*)?$`,e)}const uh=Ur.filter(t=>!S0.includes(t)),C0=ch(Ur,"gi"),hh=ch(uh,"gi"),T0=dh(Ur,"i"),E0=dh(uh,"i"),k0=new RegExp(`${hh.source}|${lh.source}`,"i");function I0(t){const e=k0.test(t),n=e?C0:hh,i=e?T0:E0;return t.replace(n,"").replace(i,"").replace(lh,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function A0({item:t,containerRef:e}){const n=ue(null),i=t.role==="assistant"?I0(t.content):t.content;return Ie(()=>{var s;n.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:Bt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:Bt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),i&&D("p",{className:Bt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:i})]})]})}const fh=({transcript:t,onSendMessage:e,allowAttachments:n=!0,awaitAcceptance:i=!1,sendDisabled:s=!1})=>{const o=ue(!1),[r,a]=me(!1),[l,c]=me(null),u=ue(null),d=ue(null),h=ue(null),[p,m]=me([]),[v,b]=me(!1),[y,C]=me([]),[,T]=ms();Ie(()=>()=>{p.forEach(R=>URL.revokeObjectURL(R.preview))},[p]),Ie(()=>{if(y.length===0)return;const R=t.filter(M=>M.role==="user"&&!M.id.startsWith("optimistic-"));if(R.length>0){const M=R[R.length-1];C(O=>O.filter(L=>L.timestamp>M.timestamp))}},[t,y]);const A=R=>new Promise((M,O)=>{const L=new FileReader;L.onload=()=>M(L.result),L.onerror=O,L.readAsDataURL(R)}),x=async R=>{if(n&&R.type.startsWith("image/"))try{const M=await A(R),O=URL.createObjectURL(R),L={id:Date.now().toString(),file:R,base64:M,preview:O};m(V=>[...V,L])}catch(M){ae.error("Error processing image:",M)}},N=R=>{m(M=>{const O=M.find(L=>L.id===R);return O&&URL.revokeObjectURL(O.preview),M.filter(L=>L.id!==R)})},k=R=>{const M=R.target,O=M.files;O&&O.length>0&&(Array.from(O).forEach(x),M.value="")},E=R=>{var O;const M=(O=R.clipboardData)==null?void 0:O.items;M&&Array.from(M).forEach(L=>{if(L.type.startsWith("image/")){const V=L.getAsFile();V&&x(V)}})},f=()=>{var R;(R=d.current)==null||R.click()},_=()=>{b(!0)},g=R=>{fetch(R).then(M=>M.blob()).then(M=>{const O=new File([M],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});x(O)}).catch(M=>{ae.error("Error processing camera capture:",M)})},S=async()=>{var O;if(s||o.current)return;if(i){const L=u.current;if(!L||!L.value.trim())return;const V=L.value;o.current=!0,a(!0),c(null);try{await e(V,[]),L.value===V&&(L.value="")}catch(j){c(j instanceof Error?j.message:"Message was not sent. Please try again.")}finally{o.current=!1,a(!1)}return}const R=u.current&&u.current.value.trim()!=="",M=n&&p.length>0;if(R||M){const L=((O=u.current)==null?void 0:O.value)||"",V=new Date,j={id:`optimistic-${V.getTime()}`,role:"user",content:L,timestamp:V,attachments:p.map(H=>({type:"image",url:H.base64}))};C(H=>[...H,j]),M&&T("processing_image"),e(L,p.map(H=>H.base64)),u.current&&(u.current.value=""),p.forEach(H=>URL.revokeObjectURL(H.preview)),m([])}},I=R=>{R.key==="Enter"&&(R.preventDefault(),S())},P=[...t,...y];return D("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:h,children:P.map((R,M)=>D(A0,{item:R,containerRef:h},R.id+M))}),l&&D("p",{role:"alert",className:"text-sm mb-2",children:l}),p.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:p.map(R=>D("div",{className:"relative",children:[D("img",{src:R.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>N(R.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:D(Ai,{className:"w-3 h-3"})})]},R.id))}),D("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[D("input",{ref:u,type:"text","aria-label":"Message",readOnly:r,onKeyDown:I,onPaste:E,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),n&&D(yt,{children:[D("input",{ref:d,type:"file",accept:"image/*",multiple:!0,onChange:k,className:"hidden"}),D(Rt,{tooltip:"Attach image",onClick:f,children:D(o0,{className:"text-[#969696] w-4 h-4"})}),D(Rt,{tooltip:"Take photo",onClick:_,children:D(th,{className:"text-[#969696] w-4 h-4"})})]}),D(Rt,{tooltip:"Send",onClick:S,disabled:s||r,children:D(l0,{className:"text-[#969696] w-4 h-4"})})]}),n&&v&&D(w0,{onCapture:g,onClose:()=>b(!1)})]})};function R0({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D(Rt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(Ai,{className:"text-black dark:text-white"})})]})}const x0=({call:t,onCollapse:e,transcript:n,chatMode:i,debug:s=!1})=>D(Gc,{children:D(Xt.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[D("div",{className:"p-4 text-center",children:[D(R0,{onCollapse:e}),!i&&D(Ju,{className:"h-[144px]",stream:t.remoteStream}),D(xr,{size:"large",className:"mb-4"}),D(sh,{call:t,chatMode:i}),D(Fr,{className:"mt-2",debug:s})]}),D(Ru,{stream:t.remoteStream,chatMode:i}),D(fh,{transcript:n,onSendMessage:(o,r)=>t.sendConversationMessage(o,r)})]})});function ph(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function U(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(u){o(u)}}function a(c){try{l(i.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof n?u:new n(function(d){d(u)})).then(r,a)}l((i=i.apply(t,[])).next())})}var gh=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),D0=new Uint8Array(16);function L0(){if(!gh)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return gh(D0)}for(var mh=[],Ss=0;Ss<256;++Ss)mh[Ss]=(Ss+256).toString(16).substr(1);function Vn(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||L0)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=mh;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const M0={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},O0={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:P0,SDP_CREATE_ANSWER_FAILED:N0,SDP_SET_LOCAL_DESCRIPTION_FAILED:F0,SDP_SET_REMOTE_DESCRIPTION_FAILED:vh,SDP_SEND_FAILED:_h,MEDIA_MICROPHONE_PERMISSION_DENIED:yh,MEDIA_DEVICE_NOT_FOUND:bh,MEDIA_GET_USER_MEDIA_FAILED:Br,HOLD_FAILED:U0,INVALID_CALL_PARAMETERS:B0,BYE_SEND_FAILED:V0,SUBSCRIBE_FAILED:$0,PEER_CLOSED_DURING_INIT:Vr,WEBSOCKET_CONNECTION_FAILED:j0,WEBSOCKET_ERROR:H0,RECONNECTION_EXHAUSTED:$r,GATEWAY_FAILED:W0,LOGIN_FAILED:wh,INVALID_CREDENTIALS:G0,AUTHENTICATION_REQUIRED:q0,ICE_RESTART_FAILED:z0,NETWORK_OFFLINE:K0,SESSION_NOT_REATTACHED:Sh,UNEXPECTED_ERROR:Ch}=M0,{HIGH_RTT:Y0,HIGH_JITTER:X0,HIGH_PACKET_LOSS:J0,LOW_MOS:Th,LOW_LOCAL_AUDIO:Cs,LOW_INBOUND_AUDIO:Ts,LOW_BYTES_RECEIVED:jr,LOW_BYTES_SENT:Eh,RECORDING_UNAVAILABLE:Q0,RECORDING_BUFFER_OVERFLOW:Z0,ICE_CONNECTIVITY_LOST:eb,ICE_GATHERING_TIMEOUT:tb,ICE_GATHERING_EMPTY:nb,PEER_CONNECTION_FAILED:ib,ONLY_HOST_ICE_CANDIDATES:sb,ANSWER_WHILE_PEER_ACTIVE:ob,ICE_CANDIDATE_PAIR_CHANGED:rb,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:ab,MULTIPLE_ACTIVE_CALLS_DETECTED:lb,DUPLICATE_INBOUND_ANSWER:cb,SHARED_REMOTE_ELEMENT_OVERWRITE:db,TOKEN_EXPIRING_SOON:ub,UNKNOWN_REATTACHED_SESSION:hb,SIGNALING_RECOVERY_REQUIRED:fb,MEDIA_RECOVERY_REQUIRED:pb,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:gb}=O0,kh="wss://rtc.telnyx.com",Ih={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Ah={urls:"stun:stun.l.google.com:19302"},mb={urls:"stun:stun.telnyx.com:3478"},vb={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},_b={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},yb={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},bb={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},wb=[mb,Ah,vb,_b,yb,bb],Sb=[{urls:"stun:stundev.telnyx.com:3478"},Ah,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(F||(F={}));const Cb={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},Tb={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed with host (local network) candidates only. This is diagnostic evidence that no server-reflexive (srflx), peer-reflexive (prflx), or relay (TURN) candidates were found; connectivity may still succeed, but network traversal options can be limited.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function je(t,e){const n=Tb[t];return{code:t,name:n.name,message:n.message,description:n.description,causes:[...n.causes],solutions:[...n.solutions]}}class Jt extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,Jt.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}}function $n(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return yh;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return bh}return Br}function le(t,e,n,i){const s=Cb[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Jt({code:t,name:s.name,description:s.description,message:n||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:i??s.fatal})}class Eb extends Error{constructor(e,n,i=""){super(`Signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${n}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=n,this.method=i}}class Hr extends Error{constructor(e,n,i){super(`Stale request cancelled (id=${e}, gen=${n}, current=${i})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=n,this.currentGeneration=i}}var kb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Rh(t,e){return t(e={exports:{}},e.exports),e.exports}var Ib=Rh(function(t){var e,n;e=kb,n=function(){var i=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,y){var C=b[y];if(typeof C.bind=="function")return C.bind(b);try{return Function.prototype.bind.call(C,b)}catch{return function(){return Function.prototype.apply.apply(C,[b,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(b,y){for(var C=0;C<r.length;C++){var T=r[C];this[T]=C<b?i:this.methodFactory(T,b,y)}this.log=this.debug}function u(b,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[b].apply(this,arguments))}}function d(b,y,C){return function(T){return T==="debug"&&(T="log"),typeof console!==s&&(T==="trace"&&o?l:console[T]!==void 0?a(console,T):console.log!==void 0?a(console,"log"):i)}(b)||u.apply(this,arguments)}function h(b,y,C){var T,A=this;y=y??"WARN";var x="loglevel";function N(){var E;if(typeof window!==s&&x){try{E=window.localStorage[x]}catch{}if(typeof E===s)try{var f=window.document.cookie,_=f.indexOf(encodeURIComponent(x)+"=");_!==-1&&(E=/^([^;]+)/.exec(f.slice(_))[1])}catch{}return A.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?x+=":"+b:typeof b=="symbol"&&(x=void 0),A.name=b,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return T},A.setLevel=function(E,f){if(typeof E=="string"&&A.levels[E.toUpperCase()]!==void 0&&(E=A.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(T=E,f!==!1&&function(_){var g=(r[_]||"silent").toUpperCase();if(typeof window!==s&&x){try{return void(window.localStorage[x]=g)}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+g+";"}catch{}}}(E),c.call(A,E,b),typeof console===s&&E<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(E){y=E,N()||A.setLevel(E,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&x){try{return void window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(E){A.setLevel(A.levels.TRACE,E)},A.disableAll=function(E){A.setLevel(A.levels.SILENT,E)};var k=N();k==null&&(k=y),A.setLevel(k,!1)}var p=new h,m={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=m[b];return y||(y=m[b]=new h(b,p.getLevel(),p.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return m},p.default=p,p},t.exports?t.exports=n():e.log=n()});const xh={debug:0,info:1,warn:2,error:3};class Ab{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||xh[e]<xh[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Dh=null;const w=Ib.getLogger("telnyx"),Es={trace:0,debug:1,info:2,warn:3,error:4};let Lh=Es.info;function Mh(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const Rb=w.methodFactory;w.methodFactory=(t,e,n)=>{const i=Rb(t,e,n);return function(...s){if(Es[t]>=Lh){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);i(...r)}const o=Dh;if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Mh(a[0]):{args:a.map(Mh)}),o.addEntry(t,l,c)}}},w.setLevel("debug",!1);const ks=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{w.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Oh=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Is=t=>t instanceof Function||typeof t=="function",Ri=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,xb=/^(ws|wss):\/\//,Ph=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Ph(a,r):{result:s}},As=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),xi=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Wr=t=>{var e,n,i,s,o,r;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function Nh({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?Db(i,t):i,n=s}),resolve:e,reject:n}}const Db=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Gr="telnyx-voice-sdk-id",Rs="telnyx-voice-sdk-session-id",xs="telnyx-voice-sdk-session-id-stored-at",qr="telnyx-voice-sdk-active-calls",Lb=9e4;function Fh(t=Date.now()){const e=function(){const n=Number(sessionStorage.getItem(xs));return Number.isFinite(n)?n:null}();return e!==null&&t-e<=Lb}function Di(){return sessionStorage.getItem(Gr)}function zr(t,e=Date.now()){sessionStorage.setItem(Rs,t),sessionStorage.setItem(xs,String(e))}function Uh(){sessionStorage.removeItem(Gr),sessionStorage.removeItem(Rs),sessionStorage.removeItem(xs)}function fn(){(function(t){try{sessionStorage.removeItem(t)}catch(e){w.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(qr)}function Bh(t=Date.now()){const e=function(n){try{return sessionStorage.getItem(n)}catch(i){return w.debug(`safeGetItem('${n}') failed: ${i instanceof Error?i.message:String(i)}`),null}}(qr);if(!e)return null;try{const n=JSON.parse(e);if(!n||typeof n!="object"||!Array.isArray(n.calls))return w.debug("Active-calls recovery marker payload was malformed — discarded."),fn(),null;const i=Number(n.storedAt);return!Number.isFinite(i)||t-i>9e5?(w.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),fn(),null):n.calls.length===0?(w.debug("Active-calls recovery marker had no call records — discarded."),fn(),null):n}catch(n){return w.debug(`Active-calls recovery marker JSON parse failed — discarded: ${n instanceof Error?n.message:String(n)}`),fn(),null}}function Vh(t,e,n=Date.now()){if(!Array.isArray(t)||t.length===0)return void fn();(function(i,s){try{sessionStorage.setItem(i,s)}catch(o){w.info(`safeSetItem('${i}') failed: ${o instanceof Error?o.message:String(o)}`)}})(qr,JSON.stringify({sessionId:e,calls:t,storedAt:n}))}var He,xt,ie;(function(t){t.Offer="offer",t.Answer="answer"})(He||(He={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(xt||(xt={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ie||(ie={}));const gt={generic:"event",[ie.Display]:"participantData",[ie.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Mb={invalidCredentialsOptions:"InvalidCredentialsOptions"},$h=8e6,jh={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!1};var z,Kr,rt,Dt,Be,jn;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Kr||(Kr={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(rt||(rt={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Dt||(Dt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Be||(Be={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(jn||(jn={}));const Hn="GLOBAL",nt={},Li=(t,e)=>`${t}|${e}`,Hh=(t,e=Hn)=>Li(t,e)in nt,Qt=(t,e,n=Hn)=>{const i=Li(t,n);i in nt||(nt[i]=[]),nt[i].push(e)},Wh=(t,e,n=Hn)=>{const i=function(s){Lt(t,i,n),e(s)};return i.prototype.targetRef=e,Qt(t,i,n)},Lt=(t,e,n=Hn)=>{if(!Hh(t,n))return!1;const i=Li(t,n);if(Is(e))for(let s=nt[i].length-1;s>=0;s--){const o=nt[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&nt[i].splice(s,1)}else nt[i]=[];return nt[i].length===0&&delete nt[i],!0},$=(t,e,n=Hn,i=!0)=>{const s=i&&n!==Hn;if(!Hh(t,n))return s&&$(t,e),!1;const o=Li(t,n),r=nt[o].length;if(!r)return s&&$(t,e),!1;for(let a=r-1;a>=0;a--)nt[o][a](e);return s&&$(t,e),!0},Yr=t=>{const e=Li(t,"");Object.keys(nt).filter(n=>n.indexOf(e)===0).forEach(n=>delete nt[n])};let Ob=typeof WebSocket<"u"?WebSocket:null;const Pb=0,Nb=1,Fb=2,Gh=3;class Ds{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=kh,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:o}=e.options;w.debug("Creating new Connection",{host:this._host,env:i,region:s,useCanaryRtcServer:o}),i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":kh),n&&(this._host=(r=>`${xb.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===Nb}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Pb}get closing(){return!!this._wsClient&&this._wsClient.readyState===Fb}get closed(){return!!this._wsClient&&this._wsClient.readyState===Gh}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){w.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let n=Di();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),w.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const i=this.socketGeneration;this._wsClient=new Ob(e.toString()),this.socketGeneration+=1,w.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:i}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(i){w.error("WebSocket connection failed:",i);const s=le(j0,i);$(F.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e,n){var i;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=p=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),this.session.onOutboundConfirmed(),u)return;const{result:m,error:v}=Ph(p);return v?c(v):l(m)};Wh(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),n&&n>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),Lt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return w.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Hr(s.id,o,this.socketGeneration));c(new Eb(s.id,n,r))},n),this._pendingRequestTimers.set(s.id,d))});return w.debug(`SEND:
112
112
  `,JSON.stringify(s,null,2),`
113
- `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(w.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Is(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const i=this.socketGeneration;e.onopen=n=>(w.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),j(F.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),w.debug("WebSocket onclose",{code:n==null?void 0:n.code,reason:n==null?void 0:n.reason,wasClean:n==null?void 0:n.wasClean,socketGeneration:i,sessionId:this.session.sessionid}),j(F.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),w.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ae(H0);return j(F.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),j(F.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),j(F.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Oh(n.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(Gr,a)),this._unsetTimer(r.id),w.debug(`RECV:
113
+ `),(i=this._wsClient)===null||i===void 0||i.send(JSON.stringify(s)),a}close(){if(w.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Is(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const n=this.socketGeneration;e.onopen=i=>(w.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),$(F.SocketOpen,i,this.session.uuid)),e.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),w.debug("WebSocket onclose",{code:i==null?void 0:i.code,reason:i==null?void 0:i.reason,wasClean:i==null?void 0:i.wasClean,socketGeneration:n,sessionId:this.session.sessionid}),$(F.SocketClose,{event:i,socketGeneration:n},this.session.uuid)),e.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),w.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=le(H0);return $(F.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),$(F.SocketError,{error:i,sessionId:this.session.sessionid,socketGeneration:n},this.session.uuid)},e.onmessage=i=>{var s,o;this.lastInboundAt=Date.now(),$(F.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Oh(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(Gr,a)),this._unsetTimer(r.id),w.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Ue[`${(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=Wr(r);j(F.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Gh?(w.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?w.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(w.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),j(F.SocketClose,{code:Ih.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):w.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(w.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(w.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):w.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{Lt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Hr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),j(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",e)}}Ds.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class ji{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Ui()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const qh={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 qe extends ji{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=ph(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in qh)n&&i.hasOwnProperty(n)&&(i[qh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class zh extends qe{constructor(e){super(),this.method=ie.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ub{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>U(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Wr(i))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const i=new zh(xn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Nh({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Ue.REGISTER,Ue.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Nh({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Xr extends qe{constructor(e){super(),this.method=ie.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Hi{constructor(e){this._session=e,this._lastInboundAt=0,this._lastOutboundConfirmedAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Hi.CRITICAL_METHODS.has(e)}start(){this._intervalId||(w.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),w.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}onOutboundConfirmed(){this._lastOutboundConfirmedAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),w.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void w.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(w.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?w.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(w.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Hi.isCriticalMethod(n)?(w.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):w.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){w.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){w.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(w.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,w.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ae(K0);j(F.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){w.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt,s=i-this._lastOutboundConfirmedAt,o=n>=2e4;if(!o&&!(s>=45e3))return;if(!this._probeInFlight)return w.info(o?`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`:`Signaling health: inbound WS activity is flowing but no outbound request has been answered for ${Math.round(s/1e3)}s, sending health probe`),void this._sendProbe();const r=i-this._lastProbeSentAt;r>=5e3&&(w.warn(`Signaling health: probe timed out after ${r}ms (inbound silent for ${Math.round(n/1e3)}s, no outbound request answered for ${Math.round(s/1e3)}s) — declaring signaling unhealthy`),this._triggerSignalingRecovery(o?"Signaling health probe timed out: no inbound WS activity after probe":"Signaling health probe timed out: inbound WS activity is flowing but no outbound request is being answered","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Xr(xn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{w.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void w.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(w.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(w.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(w.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,w.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=je(fb);j(F.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(w.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):w.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i){w.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void w.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=je(pb);j(F.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Hi.CRITICAL_METHODS=new Set([ie.Modify,ie.Bye,ie.Ping]);var Kh="2.27.10",Jr=Kh;class Bb extends qe{constructor(e,i,n,s,o={},r,a=!1){super(),this.method="login";const l={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{early_sdp_answer:a},"User-Agent":{sdkVersion:Jr,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Vb extends qe{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class Yh extends qe{toString(){return ie.Invite}}class Xh extends qe{toString(){return ie.Answer}}class Jh extends qe{toString(){return ie.Attach}}class $b extends qe{toString(){return ie.Bye}}class jb extends qe{toString(){return ie.Candidate}}class Hb extends qe{toString(){return ie.EndOfCandidates}}class Ls extends qe{toString(){return ie.Modify}}class Qh extends qe{toString(){return ie.Info}}class Wb extends qe{toString(){return ie.Broadcast}}class Gb extends qe{toString(){return ie.Subscribe}}class qb extends qe{toString(){return ie.Unsubscribe}}class zb extends qe{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Jr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class fi{constructor(e){if(this.options=e,this.uuid=Ui(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Hi(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Lh=(n=ks[i])!==null&&n!==void 0?n:ks.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new Ds(this),this.registerAgent=new Ub(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return U(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return w.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),w.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Hi.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?Ds.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>U(this,void 0,void 0,function*(){if(s instanceof Hr)throw w.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=ae(q0,s,void 0,!0);j(F.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return U(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},fi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&w.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return As(this.options)||Rn(this.options)}broadcast(e){}disconnect(){return U(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),w.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Qt(e,i,this.uuid),this}off(e,i){return Lt(e,i,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new Ds(this)),this._attachListeners(),this._autoReconnect||(w.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(w.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),w.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ae(wh,e);j(F.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Uh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=fi.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-fi.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{w.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=je(ub);j(F.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return U(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),As(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(Rn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";w.error(s);const o=ae(G0,void 0,s);return void j(F.Error,{error:o,type:Mb.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r,a;return U(this,void 0,void 0,function*(){let l;const c=!!xn(),u=c&&(this.sessionid&&Fh()?this.sessionid:function(h=Date.now()){const p=sessionStorage.getItem(Rs);return p?Fh(h)?p:(sessionStorage.removeItem(Rs),sessionStorage.removeItem(xs),null):null}())||"";if(e==="login"){const h=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,p=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:h,pn_late_fanout:h}),m=(a=this.options.earlySdpAnswer)!==null&&a!==void 0&&a;l=new Bb(this.options.login,this.options.password||this.options.passwd,this.options.login_token,u,p,c,m)}else l=new zb({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:u,userVariables:this.options.userVariables,reconnection:c});const d=yield this.execute(l).catch(h=>{this._handleLoginError(h),n&&n(h)});d&&(this.sessionid=d.sessid,this.sessionid&&zr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return U(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){w.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(Ih).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)w.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),w.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Yr(this.relayProtocol);for(const l in this.subscriptions)Yr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&zr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){w.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ae($r);return void j(F.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;w.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{w.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(w.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=je(gb);j(F.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else w.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],Lt(e,null,i)):(delete this.subscriptions[e],Yr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Is(i)&&Qt(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),w.debug("Attaching socket event listeners"),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage),this.on(F.SocketActivity,this._onSocketActivity)}_detachListeners(){w.debug("Detaching socket event listeners"),this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.SocketMessage,this._onSocketMessage),this.off(F.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),w.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(w.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Xr(xn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){w.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}onOutboundConfirmed(){this._signalingHealthMonitor.onOutboundConfirmed()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([z.Early,z.Active,z.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){w.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return w.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return w.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||w.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Qt(e,i)}static off(e){Lt(e)}static uuid(){return Ui()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}fi.TOKEN_EXPIRY_WARNING_SECONDS=120,fi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const Ms=t=>navigator.mediaDevices.getUserMedia(t),Ln=t=>t&&t instanceof MediaStream,Os=(t,e,i)=>{const n=An(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(w.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=je(db);j(F.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},Zh=(t,e)=>{const i=An(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},ef=(t,e)=>U(void 0,void 0,void 0,function*(){const i=An(t);if(i===null)return w.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return w.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),Kb=t=>{t&&t.readyState==="live"&&t.stop()},Mn=t=>{Ln(t)&&t.getTracks().forEach(Kb),t=null},Ps=t=>U(void 0,void 0,void 0,function*(){w.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield Ms(t)}catch(n){if(w.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){w.warn("Device not found or not readable, falling back to default device");try{return yield Ms(s)}catch(o){throw w.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),On=(t=null,e=!1)=>U(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Dt.AudioIn||s===Dt.AudioOut,video:!s||s===Dt.Video}))(t)).catch(s=>(w.error(s),null));if(n){if(Mn(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),tf=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Ns=(t,e,i)=>U(void 0,void 0,void 0,function*(){const n=yield On(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),Yb=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Qr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,nf=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Qr(a)):[]},Zr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=ea(t);return i.includes(e)||n.includes(e)},ea=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Wi=(t,e=null,i=null)=>{if(!Ln(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},ta=t=>{Wi(t,"audio",!0)},Fs=t=>{Wi(t,"audio",!1)};function Xb(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,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:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Ps}}catch(t){return t.message}}var Ae;function sf(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function of(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{w.error("playAudio",e),t._playFulfilled=!0}))}function rf(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Ae||(Ae={}));const af=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class Jb extends ji{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Ui(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class Qb extends ji{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ue{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._isHeld=!1,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new Ab(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Dh=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,w.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ue.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return U(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),w.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return w.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],m=new Date;this._lastIntermediateFlushTime=m;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(m.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:m.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return w.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return U(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void w.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void w.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return U(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return U(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;w.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),m=(o||r)&&p.length<=ue.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=ue.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},m?{keepalive:!0}:{}));if(C.ok)return void w.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const T=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),w.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:T})}}catch(C){v=C,w.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const y=ue.RETRY_DELAYS_MS[b];if(y===void 0)break;w.info(`CallReportCollector: Retrying ${d} in ${y}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,y))}throw w.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,m,v,b;if(this.statsBuffer.length<2)return!1;const y=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],T=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((T==null?void 0:T.networkType)==="vpn"&&(T==null?void 0:T.candidateType)!=="relay"))return!1;const A=((i=y.ice)===null||i===void 0?void 0:i.writable)===!1,x=((n=y.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",N=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),E=this._positiveDelta((a=y.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),k=N>0&&E===0,f=this._positiveDelta((u=(c=y.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),_=this._positiveDelta((m=(p=y.audio)===null||p===void 0?void 0:p.inbound)===null||m===void 0?void 0:m.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return A||x||k||f>0&&_===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(Ts,!1),this._trackBreach(jr,!1))}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(ue.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return U(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(f=>{switch(f.type){case"outbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(r=f);break;case"inbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(a=f);break;case"media-playout":f.kind==="audio"&&(l=f);break;case"remote-inbound-rtp":f.kind==="audio"&&(c=f);break;case"remote-outbound-rtp":f.kind==="audio"&&(u=f);break;case"candidate-pair":(f.nominated||f.state==="succeeded")&&h.push(f);break;case"transport":p=f}});const m=p==null?void 0:p.selectedCandidatePairId,v=m?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,m):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),y=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:m?h.find(f=>f.id===m)||h[h.length-1]||null:h[h.length-1]||null,r){const f=this._getOutboundAudioLevel(s,r);if(f!==null&&this.intervalAudioLevels.outbound.push(f),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(r.bytesSent||0)-this.previousStats.outboundBytes,g=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const f=this._getInboundAudioLevel(s,a);if(f!==null&&this.intervalAudioLevels.inbound.push(f),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(a.bytesReceived||0)-this.previousStats.inboundBytes,g=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,T,A,x,N;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),T=this._resolveCandidate(s,d.remoteCandidateId)),d&&(A=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),T?{remote:T}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(rb)),this.previousCandidatePairSnapshot=A),r&&(x=this._getLocalAudioTrackSnapshot(),N=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(x,N),this.previousStats.timestamp=o.getTime();const E=o.getTime()-this.intervalStartTime.getTime(),k=this._collectionIntervalFor();if(e||E>=k){const f=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,T,p,x,N,l,c,u,b,y);this.statsBuffer.push(f),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(f,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){w.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ue.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void w.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=ue.STATS_FLUSH_THRESHOLD||o>=ue.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){w.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){w.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,m,v,b,y;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,T=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(i){const x=(r=i.packetsReceived)!==null&&r!==void 0?r:0,N=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const E=x-this._prevPacketsReceived,k=N-this._prevPacketsLost,f=E+k;f>0&&(A=k/f*100)}this._prevPacketsReceived=x,this._prevPacketsLost=N}if(this._trackBreach(Y0,C!==void 0&&C>ue.THRESHOLD_RTT_MS),this._trackBreach(X0,T!==void 0&&T>ue.THRESHOLD_JITTER_MS),this._trackBreach(J0,A!==void 0&&A>ue.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(Ts,!1):this._trackLowInboundAudio(e),C!==void 0&&T!==void 0&&A!==void 0){const x=93.2-.11*T-2.5*A-.01*(1e3*C),N=Math.max(1,Math.min(4.5,1+.035*x+x*(x-60)*(100-x)*7e-6));this._trackBreach(Th,N<ue.THRESHOLD_MOS)}else this._trackBreach(Th,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const x=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,N=e.audio.inbound.bytesReceived;this._trackBreach(jr,!this._isHeld&&x!==void 0&&N-x==0)}if(((m=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||m===void 0?void 0:m.bytesSent)!==void 0){const x=(y=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||y===void 0?void 0:y.bytesSent,N=e.audio.outbound.bytesSent;this._trackBreach(kh,x!==void 0&&N-x==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=ue.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(Cs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ue.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(Cs)):this._trackBreach(Cs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(Cs,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(Ts,!1);const o=s<=ue.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(Ts,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=ue.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ue.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=je(e);w.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,m,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),m?{codec:this._buildCodecSnapshot(m,n.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamplesEvents:d.synthesizedSamplesEvents,synthesizedSamplesDuration:d.synthesizedSamplesDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSamplesCount:d.totalSamplesCount,totalSamplesDuration:d.totalSamplesDuration})),h||p){const y={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let T;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(T=h.totalRoundTripTime/h.roundTripTimeMeasurements),y.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:T,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(y.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=y}return b}_resolveCandidate(e,i){if(!i)return void w.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void w.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;w.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void w.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,w.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}ue.INITIAL_COLLECTION_INTERVAL_MS=1e3,ue.STATS_FLUSH_THRESHOLD=300,ue.LOGS_FLUSH_THRESHOLD=800,ue.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ue.CONSECUTIVE_BREACHES_REQUIRED=3,ue.THRESHOLD_RTT_MS=.4,ue.THRESHOLD_JITTER_MS=30,ue.THRESHOLD_PACKET_LOSS_PCT=1,ue.THRESHOLD_MOS=3.5,ue.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ue.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ue.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,ue.WARNING_THROTTLE_MS=15e3,ue.RETRY_DELAYS_MS=[500,1e3,2e3],ue.KEEPALIVE_BODY_LIMIT_BYTES=61440;class ze{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow={local:!1,remote:!1},this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return w.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Q0),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return w.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),w.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,w.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return U(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void w.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void w.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=ze.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),U(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||w.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){w.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+ze.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+ze.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,w.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Z0))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*ze.BYTES_PER_SAMPLE+ze.FRAMES_PER_SECOND*ze.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:$h}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{w.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return U(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void w.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{w.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!1}}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return U(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=ze.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=ze.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void w.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),w.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,w.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=ze.RETRY_DELAYS_MS[c];if(u===void 0)break;w.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw w.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=je(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}ze.RETRY_DELAYS_MS=[500,1e3,2e3],ze.KEEPALIVE_BODY_LIMIT_BYTES=61440,ze.PACKET_OVERHEAD_BYTES=160,ze.BYTES_PER_SAMPLE=4,ze.FRAMES_PER_SECOND=100;class Zb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return U(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,w.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){w.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return U(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){w.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return U(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&w.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){w.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var Us,lf=Rh(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,_,g,S){var I,M,R;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if((M=f._events)?(M.newListener&&(f.emit("newListener",_,g.listener?g.listener:g),M=f._events),R=M[_]):(M=f._events=new n,f._eventsCount=0),R){if(typeof R=="function"?R=M[_]=S?[g,R]:[R,g]:S?R.unshift(g):R.push(g),!R.warned&&(I=o(f))&&0<I&&R.length>I){R.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+_+" listeners added. Use emitter.setMaxListeners() to increase limit");P.name="MaxListenersExceededWarning",P.emitter=f,P.type=_,P.count=R.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(P)}}else R=M[_]=g,++f._eventsCount;return f}function a(f,_,g){function S(){f.removeListener(_,S),I||(I=!0,g.apply(f,arguments))}var I=!1;return S.listener=g,S}function l(f){var _=this._events;if(_){var g=_[f];if(typeof g=="function")return 1;if(g)return g.length}return 0}function c(f,_){for(var g=Array(_);_--;)g[_]=f[_];return g}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(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 _,g,S,I,M,R,P,O=f==="error";if(R=this._events)O=O&&R.error==null;else if(!O)return!1;if(P=this.domain,O){if(_=arguments[1],!P){if(_ instanceof Error)throw _;var L=new Error('Uncaught, unspecified "error" event. ('+_+")");throw L.context=_,L}return _||(_=new Error('Uncaught, unspecified "error" event')),_.domainEmitter=this,_.domain=P,_.domainThrown=!1,P.emit("error",_),!1}if(!(g=R[f]))return!1;var V=typeof g=="function";switch(S=arguments.length){case 1:(function($,W,q){if(W)$.call(q);else for(var G=$.length,oe=c($,G),K=0;K<G;++K)oe[K].call(q)})(g,V,this);break;case 2:(function($,W,q,G){if(W)$.call(q,G);else for(var oe=$.length,K=c($,oe),Z=0;Z<oe;++Z)K[Z].call(q,G)})(g,V,this,arguments[1]);break;case 3:(function($,W,q,G,oe){if(W)$.call(q,G,oe);else for(var K=$.length,Z=c($,K),Y=0;Y<K;++Y)Z[Y].call(q,G,oe)})(g,V,this,arguments[1],arguments[2]);break;case 4:(function($,W,q,G,oe,K){if(W)$.call(q,G,oe,K);else for(var Z=$.length,Y=c($,Z),te=0;te<Z;++te)Y[te].call(q,G,oe,K)})(g,V,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),M=1;M<S;M++)I[M-1]=arguments[M];(function($,W,q,G){if(W)$.apply(q,G);else for(var oe=$.length,K=c($,oe),Z=0;Z<oe;++Z)K[Z].apply(q,G)})(g,V,this,I)}return!0},s.prototype.addListener=function(f,_){return r(this,f,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,_){return r(this,f,_,!0)},s.prototype.once=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,_)),this},s.prototype.prependOnceListener=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,_)),this},s.prototype.removeListener=function(f,_){var g,S,I,M,R;if(typeof _!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(g=S[f]))return this;if(g===_||g.listener&&g.listener===_)--this._eventsCount==0?this._events=new n:(delete S[f],S.removeListener&&this.emit("removeListener",f,g.listener||_));else if(typeof g!="function"){for(I=-1,M=g.length;0<M--;)if(g[M]===_||g[M].listener&&g[M].listener===_){R=g[M].listener,I=M;break}if(0>I)return this;if(g.length===1){if(g[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[f]}else(function(P,O){for(var L=O,V=L+1,$=P.length;V<$;L+=1,V+=1)P[L]=P[V];P.pop()})(g,I);S.removeListener&&this.emit("removeListener",f,R||_)}return this},s.prototype.removeAllListeners=function(f){var _,g;if(!(g=this._events))return this;if(!g.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):g[f]&&(--this._eventsCount==0?this._events=new n:delete g[f]),this;if(arguments.length===0){for(var S,I=Object.keys(g),M=0;M<I.length;++M)(S=I[M])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(_=g[f])=="function")this.removeListener(f,_);else if(_)do this.removeListener(f,_[_.length-1]);while(_[0]);return this},s.prototype.listeners=function(f){var _,g,S=this._events;return S?g=(_=S[f])?typeof _=="function"?[_.listener||_]:function(I){for(var M=Array(I.length),R=0;R<M.length;++R)M[R]=I[R].listener||I[R];return M}(_):[]:g=[],g},s.listenerCount=function(f,_){return typeof f.listenerCount=="function"?f.listenerCount(_):l.call(f,_)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=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 u(d)}for(var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,m=[],v=0;256>v;++v)m.push((v+256).toString(16).substr(1));function b(f){var _=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,g=(m[f[_+0]]+m[f[_+1]]+m[f[_+2]]+m[f[_+3]]+"-"+m[f[_+4]]+m[f[_+5]]+"-"+m[f[_+6]]+m[f[_+7]]+"-"+m[f[_+8]]+m[f[_+9]]+"-"+m[f[_+10]]+m[f[_+11]]+m[f[_+12]]+m[f[_+13]]+m[f[_+14]]+m[f[_+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(g))throw TypeError("Stringified UUID is invalid");return g}function y(f,_,g){var S=(f=f||{}).random||(f.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(f,_){if(!f||!_)return{};const g={...f};if(g.localCandidateId){const S=_.get(g.localCandidateId);g.local={...S}}if(g.remoteCandidateId){const S=_.get(g.remoteCandidateId);g.remote={...S}}return g}function T(f,_,g){return 8*function(S,I,M){const R=S[M],P=I?I[M]:null;return R===null||P===null?null:(R-P)/(S.timestamp-I.timestamp)*1e3}(f,_,g)}function A(f){if(!f.entries)return f;const _={};return f.forEach(function(g,S){_[S]=g}),_}function x(f,_,g={}){if(!f)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};g.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of f.values())switch(I.type){case"outbound-rtp":{const M=I.mediaType||I.kind,R={};let P={};if(!["audio","video"].includes(M))continue;if(I.codecId){const O=f.get(I.codecId);O&&(R.clockRate=O.clockRate,R.mimeType=O.mimeType,R.payloadType=O.payloadType)}P=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[M].outbound.push({...I,...R,track:{...P}});break}case"inbound-rtp":{let M=I.mediaType||I.kind,R={};const P={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const O=f.get(I.codecId);O&&(P.clockRate=O.clockRate,P.mimeType=O.mimeType,P.payloadType=O.payloadType)}if(!S.connection.id&&I.transportId){const O=f.get(I.transportId);if(O&&O.selectedCandidatePairId){const L=f.get(O.selectedCandidatePairId);S.connection=C(L,f)}}R=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[M].inbound.push({...I,...P,track:{...R}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!g.remote)break;let M=I.mediaType||I.kind;const R={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const P=f.get(I.codecId);P&&(R.clockRate=P.clockRate,R.mimeType=P.mimeType,R.payloadType=P.payloadType)}if(!S.connection.id&&I.transportId){const P=f.get(I.transportId);if(P&&P.selectedCandidatePairId){const O=f.get(P.selectedCandidatePairId);S.connection=C(O,f)}}S.remote[M].inbound.push({...I,...R});break}case"remote-outbound-rtp":{if(!g.remote)break;const M=I.mediaType||I.kind,R={};if(!["audio","video"].includes(M))continue;if(I.codecId){const P=f.get(I.codecId);P&&(R.clockRate=P.clockRate,R.mimeType=P.mimeType,R.payloadType=P.payloadType)}S.remote[M].outbound.push({...I,...R});break}}if(!S.connection.id)for(const I of f.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,f));return S=function(I,M){return M&&(I.audio.inbound.map(R=>{let P=M.audio.inbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesReceived"),R.packetRate=T(R,P,"packetsReceived")}),I.audio.outbound.map(R=>{let P=M.audio.outbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesSent"),R.packetRate=T(R,P,"packetsSent")}),I.video.inbound.map(R=>{let P=M.video.inbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesReceived"),R.packetRate=T(R,P,"packetsReceived")}),I.video.outbound.map(R=>{let P=M.video.outbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesSent"),R.packetRate=T(R,P,"packetsSent")})),I}(S,_),S}let N,E={},k=[];e.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 _={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=_.getStatsInterval||1e3,this.rawStats=!!_.rawStats,this.statsObject=!!_.statsObject,this.filteredStats=!!_.filteredStats,this.shouldWrapGetUserMedia=!!_.wrapGetUserMedia,typeof _.remote=="boolean"&&(this.remote=_.remote),this.debug=!!_.debug,this.logLevel=_.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,_){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:_})}async addConnection(f){const{pc:_,peerId:g}=f;let{connectionId:S,remote:I}=f;if(I=typeof I=="boolean"?I:this.remote,!(_&&_ instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!g)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[g]){if(S&&S in this.peersToMonitor[g])throw new Error(`We are already monitoring connection with id ${S}.`);for(let R in this.peersToMonitor[g]){const P=this.peersToMonitor[g][R];if(P.pc===_)throw new Error(`We are already monitoring peer with id ${g}.`);P.pc.connectionState==="closed"&&this.removeConnection({pc:P.pc})}}const M=_.getConfiguration();return M.iceServers&&M.iceServers.forEach(function(R){delete R.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:g,connectionId:S,data:{options:f,peerConfiguration:M}}),this.monitorPeer({peerId:g,connectionId:S,pc:_,remote:I}),{connectionId:S}}getTimeline(f){return this.timeline=this.timeline.sort((_,g)=>_.timestamp.getTime()-g.timestamp.getTime()),f?this.timeline.filter(_=>_.tag===f):this.timeline}get logger(){const f=_=>{const g=["none","error","warn","info","debug"];return g.slice(0,g.indexOf(this.logLevel)+1).indexOf(_)>-1};return{error(..._){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",..._)},warn(..._){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",..._)},info(..._){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",..._)},debug(..._){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",..._)}}}removeConnection(f){let _,{connectionId:g,pc:S}=f;if(!S&&!g)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(g){if(typeof g!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)g in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][g].pc,_=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let M in this.peersToMonitor[I])this.peersToMonitor[I][M].pc===S&&(g=M,_=I)}if(!S||!g)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(g,S),delete this.peersToMonitor[_][g],Object.values(this.peersToMonitor[_]).length===0&&delete this.peersToMonitor[_],{connectionId:g}}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 _ in this.peersToMonitor[f]){let g=this.peersToMonitor[f][_].pc;this.removePeerConnectionEventListeners(_,g)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),k.forEach(f=>{this.removeTrackEventListeners(f)}),k=[],this.shouldWrapGetUserMedia&&N&&(navigator.mediaDevices.getUserMedia=N)}monitorPeer(f){let{peerId:_,connectionId:g,pc:S,remote:I}=f;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const M={pc:S,connectionId:g,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[_]){if(g in this.peersToMonitor[_])return void this.logger.warn(`Already watching connection with ID ${g}`);this.peersToMonitor[_][g]=M}else this.peersToMonitor[_]={[g]:M};this.addPeerConnectionEventListeners(_,g,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(_=>{this.emitEvent(_)})})},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 _={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);_[f]=this.peersToMonitor[f]}else _=this.peersToMonitor;let g=[];for(const S in _)for(const I in _[S]){const M=_[S][I],R=M.pc;if(R&&!this.checkIfConnectionIsClosed(S,I,R))try{const P=this.getTimestamp(),O=R.getStats(null);if(O){const L=await O,V=this.getTimestamp(),$=A(L),W={remote:M.options.remote},q=x(L,M.stats.parsed,W),G={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:V-P,data:q};this.rawStats===!0&&(G.rawStats=L),this.statsObject===!0&&(G.statsObject=$),this.filteredStats===!0&&(G.filteredStats=this.filteroutStats($)),g.push(G),M.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(P){this.logger.error(P)}}return g}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const _ in this.peersToMonitor[f]){const g=this.peersToMonitor[f][_].pc;this.checkIfConnectionIsClosed(f,_,g)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,_,g){const S=this.isConnectionClosed(g);if(S){this.removeConnection({pc:g});let I=g.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:f,connectionId:_,tag:"connection",data:"closed"})}return S}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."),N=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),N.apply(navigator.mediaDevices,arguments).then(_=>(f({stream:_}),_),_=>(f({error:_}),Promise.reject(_)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const _={...f};for(const S in _){var g=_[S];this.statsToMonitor.includes(g.type)||delete _[S]}return _}get peerConnectionListeners(){return{icecandidate:(f,_,g,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:_,data:S.candidate})},track:(f,_,g,S)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,S);const I=S.track,M=S.streams[0];f in this.peersToMonitor&&_ in this.peersToMonitor[f]&&(this.peersToMonitor[f][_].stream=M),this.addTrackEventListeners(I,_),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:_,data:{stream:M?this.getStreamDetails(M):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(R){return"stream:"+R.id})}})},signalingstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:_,data:{signalingState:g.signalingState,localDescription:g.localDescription,remoteDescription:g.remoteDescription}})},iceconnectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceConnectionState})},icegatheringstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceGatheringState})},icecandidateerror:(f,_,g,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:_,error:{errorCode:S.errorCode}})},connectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.connectionState})},negotiationneeded:(f,_,g)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:_})},datachannel:(f,_,g,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:_,data:S.channel})}}}addPeerConnectionEventListeners(f,_,g){this.logger.debug(`Adding event listeners for peer ${f} and connection ${_}.`),E[_]={},Object.keys(this.peerConnectionListeners).forEach(S=>{E[_][S]=this.peerConnectionListeners[S].bind(this,f,_,g),g.addEventListener(S,E[_][S],!1)})}parseGetUserMedia(f){try{const _={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(_.data.details=this.parseStream(f.stream),f.stream.getTracks().map(g=>{this.addTrackEventListeners(g),k.push(g)})),this.emitEvent(_)}catch{}}parseStream(f){const _={audio:[],video:[]};return f.getTracks().forEach(g=>{_[g.kind].push(this.getMediaTrackDetails(g))}),_}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:_=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:_}})},unmute:_=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:_}})},overconstrained:_=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:_}})},ended:_=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:_}}),this.removeTrackEventListeners(_.target)}}}addTrackEventListeners(f,_){E[f.id]={};const g=this.getTrackEventObject(_);Object.keys(g).forEach(S=>{E[f.id][S]=g[S].bind(this),f.addEventListener(S,E[f.id][S])}),E[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(S)}},1e3)}removeTrackEventListeners(f){if(f.id in E){const _=this.getTrackEventObject();Object.keys(_).forEach(g=>{f.removeEventListener(g,E[f.id][g])}),clearInterval(E[f.id].readyState),delete E[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const _={...f,timestamp:new Date};this.addToTimeline(_),_.tag&&this.emit(_.tag,_)}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,_){f in E&&(Object.keys(this.peerConnectionListeners).forEach(g=>{_.removeEventListener(g,E[f][g],!1)}),delete E[f]),_.getSenders().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)}),_.getReceivers().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const _=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),g=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),_.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=g.bind(navigator.mediaDevices)}}}});(Us=lf)&&Us.__esModule&&Object.prototype.hasOwnProperty.call(Us,"default")&&Us.default;var ew=lf.WebRTCStats;function tw(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),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 iw(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class nw extends ji{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class sw extends ji{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class ow extends ji{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function rw(t,e){const i=Ui();let n=!1;const s=new ew({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>U(this,void 0,void 0,function*(){r.event==="stats"&&j(F.StatsFrame,function({data:a}){var l,c,u,d,h,p,m,v;const{audio:b,remote:y}=a,{audio:C}=y,T=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,x=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,N=(v=(m=b.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,E=tw({jitter:1e3*T,rtt:1e3*A,packetsLost:N,packetsReceived:x});return{jitter:T,rtt:A,mos:E,quality:iw(E),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new ow(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>U(this,void 0,void 0,function*(){if(n)w.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new nw(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){w.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>U(this,void 0,void 0,function*(){const a=s.getTimeline();j(F.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new sw(i,e)),s.removeAllPeers(),s.destroy(),n=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const cf=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:pt.conferenceUpdate,call:t.calls[s],canvasInfo:aw(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:ot.LayerInfo},a);j(F.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ot.LayoutInfo},a);j(F.Notification,l,t.uuid);break}}},aw=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Oh(e)},df=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],lw={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function le(t,e){return`telnyx:call:${t}:${e}`}function uf(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function hf(t,e,i){const n=uf(le(t,"new-call-start"));if(n===void 0)return{mode:e,direction:i,steps:[]};const s=[];for(const a of df){if(a==="new-call-start")continue;const l=uf(le(t,a));l!==void 0&&s.push({label:lw[a]||a,fromStart:l-n})}s.sort((a,l)=>a.fromStart-l.fromStart);const o=[];let r=0;for(const a of s)o.push({label:a.label,fromStart:a.fromStart,delta:a.fromStart-r}),r=a.fromStart;return{mode:e,direction:i,steps:o}}function ia(t){for(const e of df)try{performance.clearMarks(le(t,e))}catch{w.warn("Clearing performance marks is failed")}}class pi{constructor(e,i,n,s,o){this.type=e,this.options=i,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>U(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void w.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(w.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return U(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,m=p==null?void 0:p.transport;m&&(d.dtlsState=m.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(m=>{m.type==="candidate-pair"&&m.state==="succeeded"&&(d.candidatePairState=m.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===m.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===m.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),m.type==="transport"&&(d.dtlsCipher=m.dtlsCipher,d.srtpCipher=m.srtpCipher,d.tlsVersion=m.tlsVersion,m.dtlsState&&(d.dtlsState=m.dtlsState))})}catch(p){w.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=je(eb);j(F.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=je(nb);j(F.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(le(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(le(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(le(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void w.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;w.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(le(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;w.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},w.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(w.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(w.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},pi.ICE_RESTART_TIMEOUT_MS),w.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(w.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(w.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===He.Offer}get isAnswer(){return this.type===He.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}get callEstablishmentTimings(){return this._callEstablishmentTimings}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(le(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return U(this,void 0,void 0,function*(){performance.mark(le(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Jt&&j(F.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(w.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{w.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),w.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):w.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(w.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":j(F.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(w.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){w.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?w.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(le(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&Os(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(le(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=hf(this.options.id,e,i);this._callEstablishmentTimings=n,function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void w.info(`${l} No timing data collected`);const c=Math.max(...a.map(m=>m.label.length),4)+2,u=(m,v)=>{for(;m.length<v;)m+=" ";return m},d=(m,v)=>{for(;m.length<v;)m=" "+m;return m},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let m=0;m<h.length;m++)p+="-";w.info(`${l} Call establishment timing breakdown:`),w.info(`${l} ${h}`),w.info(`${l} ${p}`),w.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const m of a){const v=m.delta.toFixed(2)+"ms",b=m.fromStart.toFixed(2)+"ms";w.info(`${l} ${u(m.label,c)}${d(v,14)}${d(b,14)}`)}w.info(`${l} ${p}`)}(n),ia(this.options.id)}createPeerConnection(){return U(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:He.Offer}),performance.mark(le(this.options.id,"set-remote-description")),!this.instance))throw ae(Vr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>U(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),j(F.Error,{error:ae(Bi(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>U(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ae(Vr);if(!this.options.localStream&&!i)throw ae(n?Bi(n):Br,n??void 0);performance.mark(le(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Ln(this.options.localStream)&&(w.info("Muting local audio tracks on start"),Fs(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(le(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=je(ib);j(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=je(tb);j(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},pi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return U(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ae(Vr);this.isDebugEnabled&&(this.statsReporter=rw(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:i,localStream:n=null,screenShare:s=!1}=this.options;if(Ln(n)){const o=n.getAudioTracks();let r=[...o];if(w.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{w.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],w.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{w.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=af(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&Os(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});w.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=af(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);w.info("Add transceiver",e,i)}}_createOffer(){return U(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,w.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(le(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createOffer error:",e),e instanceof Jt?e:ae(P0,e)}}})}_setRemoteDescription(e){return U(this,void 0,void 0,function*(){w.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw w.error("Peer _setRemoteDescription error:",i),ae(vh,i)}})}_createAnswer(){return U(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return w.debug("Skipping negotiation, state:",this.instance.signalingState),w.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:He.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(le(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createAnswer error:",e),e instanceof Jt?e:ae(N0,e)}}})}_setLocalDescription(e){return U(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw w.error("Peer _setLocalDescription error:",i),ae(F0,i)}})}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(Ln(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,U(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield Ns(s,a,Dt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield Ns(r,l,Dt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return Ps(e)})}_isOffer(){return this.type===He.Offer}_isAnswer(){return this.type===He.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?1:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return w.info("RTC config",s),s}restartStatsReporter(){return U(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?w.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(w.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):w.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return U(this,void 0,void 0,function*(){ia(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}pi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,pi.ICE_RESTART_TIMEOUT_MS=15e3;const Bs=Jr;class ff{constructor(e,i){var n;this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Kr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const A in T.constraints)if(T.constraints.hasOwnProperty(A)&&T.constraints[A]!==C[A])return}T.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:u,remoteElement:d,options:h,mediaConstraints:{audio:p,video:m},ringtoneFile:v,ringbackFile:b}=e;this.options=Object.assign({},jh,{audio:p,video:m,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:s,localElement:u,remoteElement:d,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:b,debug:h.debug,debugOutput:h.debugOutput,trickleIce:h.trickleIce,prefetchIceCandidates:(n=h.prefetchIceCandidates)!==null&&n!==void 0?n:jh.prefetchIceCandidates,forceRelayCandidate:h.forceRelayCandidate,keepConnectionAliveOnSocketClose:h.keepConnectionAliveOnSocketClose,mutedMicOnStart:h.mutedMicOnStart},i),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=sf(this.options.ringtoneFile,"_ringtone"),this._ringback=sf(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
- `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!!this.options.forceRelayCandidate||!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return U(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=xt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(le(this.id,"new-peer")),this.peer=new pi(He.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){w.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Jt?e:ae(Ch,e instanceof Error?e:void 0);return j(F.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r,a,l,c;return U(this,void 0,void 0,function*(){const u=((s=(n=(i=this.session).getActiveCalls)===null||n===void 0?void 0:n.call(i))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&w.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=je(ob);return j(F.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void w.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(le(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=xt.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(le(this.id,"new-peer")),this.peer=new pi(He.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){w.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Jt?d:ae(Ch,d instanceof Error?d:void 0);return j(F.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){of(this._ringtone)}stopRingtone(){rf(this._ringtone)}playRingback(){of(this._ringback)}stopRingback(){rf(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return U(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),m=c.initiator||"app:call.hangup",v=this._state<z.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],w.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:m,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(z.Recovering),void this._finalize();if(this.setState(z.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new $b({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let y;try{yield Promise.race([this._execute(b),new Promise(C=>{y=setTimeout(()=>{w.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){w.error("telnyx_rtc.bye failed!",C);const T=ae(V0,C);j(F.Error,{error:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{y&&clearTimeout(y)}}w.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)})}hold(){const e=new Ls({sessid:this.session.sessionid,action:Vi.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Ls({sessid:this.session.sessionid,action:Vi.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Ls({sessid:this.session.sessionid,action:Vi.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new Qh({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new Qh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){w.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,Fs(this.options.localStream)}unmuteAudio(){w.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,ta(this.options.localStream)}_applyDesiredAudioMuteState(){w.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?Fs(this.options.localStream):ta(this.options.localStream)}toggleAudioMute(){w.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return U(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return w.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void j(F.Warning,{warning:je(ab),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;w.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Qr(l.track),localTracks:nf(this.options.localStream)});try{c=yield Ms({audio:{deviceId:{exact:e}}})}catch(h){const p=ae(Bi(h),h);return void j(F.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=ae(Bi(h),h);return j(F.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(m=>m.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,w.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Qr(l.track),localTracks:nf(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Wi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Wi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Wi(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield Ms({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Os(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){Fs(this.options.remoteStream)}undeaf(){ta(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Wi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void w.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void w.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),w.info("Parameters: ",r),w.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{w.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>w.error(a))}else w.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[z.Hangup,z.Destroy,z.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n,s,o,r,a,l;switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:pt.callUpdate,call:this}),e){case z.Purge:w.info(`[${this.id}] Entering Purge state.`);break;case z.Active:if(performance.mark(le(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,w.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(w.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(n=this._callReportCollector)===null||n===void 0||n.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&ef(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new Zb,this._mediaDeviceCollector.logDevicesAtStart();break;case z.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case ie.Answer:if(performance.mark(le(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case ie.Media:if(performance.mark(le(this.id,"telnyx-rtc-media")),this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case ie.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===xt.Inbound?xt.Outbound:xt.Inbound,c={type:pt[i],call:this,displayName:o,displayNumber:r,displayDirection:l};j(F.Notification,c,this.id)||j(F.Notification,c,this.session.uuid);break}case ie.Candidate:this._addIceCandidate(n);break;case ie.Info:case ie.Event:{const o=Object.assign(Object.assign({},n),{type:pt.generic,call:this});j(F.Notification,o,this.id)||j(F.Notification,o,this.session.uuid);break}case ie.Ringing:performance.mark(le(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case ie.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return w.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:ot.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const m in s)p.push(Object.assign({callId:s[m][0],index:Number(m)},Es(s[m][1])));this._dispatchConferenceUpdate({action:ot.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ot.Add,callId:o,index:r},Es(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ot.Modify,callId:o,index:r},Es(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ot.Delete,callId:o,index:r},Es(s)));break;case"clear":this._dispatchConferenceUpdate({action:ot.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ot.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfChat subscription error:",s)});Zr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,cf(this.session,o)):w.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfInfo subscription error:",s)});Zr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){w.error(`Failed to ${e.action} on call ${this.id}`);const i=ae(U0,e);return j(F.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Ls(Object.assign(Object.assign({sessid:this.session.sessionid,action:Vi.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));w.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>U(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(w.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,i){var n,s,o;w.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ae(z0,i);j(F.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return U(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:He.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(le(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this._state!==z.Held&&this.setState(z.Active)}).catch(n=>U(this,void 0,void 0,function*(){w.error("Call setRemoteDescription Error: ",n);const s=ae(vh,n);j(F.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){w.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_warnIfOnlyHostIceCandidates(e){if(!(n=>{if(!n)return!1;const s=n.split(/\r?\n/).filter(o=>/^a=candidate:/i.test(o));return s.length>0&&s.every(o=>/\styp\s+host(?:\s|$)/i.test(o))})(e))return;const i=je(sb);w.warn(`[${this.id}] Warning ${i.code}: ${i.message}`),j(F.Warning,{warning:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._isTerminatingOrTerminated())return;if(this.peer&&(this.peer.iceDone=!0),!e)return void w.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;(n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),this._warnIfOnlyHostIceCandidates(o),performance.mark(le(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Bs}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case He.Offer:this.setState(z.Requesting),a=new Yh(l);break;case He.Answer:this._isRecovering||this.setState(z.Answering),a=this.options.attach===!0?new Jh(l):new Xh(l);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(c=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${r} error:`,c);const u=ae(_h,c);j(F.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){w.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(this._isTerminatingOrTerminated())return;if(!e)return w.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Bs}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case He.Offer:this.setState(z.Requesting),o=new Yh(r);break;case He.Answer:this._isRecovering||this.setState(z.Answering),o=this.options.attach===!0?new Jh(r):new Xh(r);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(a=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${s} error:`,a);const l=ae(_h,a);j(F.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){w.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;if(this._isTerminatingOrTerminated())return;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i,n,s,o;this._isTerminatingOrTerminated()||(e.candidate&&e.candidate.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):(e.candidate===null&&this._warnIfOnlyHostIceCandidates((o=(s=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||s===void 0?void 0:s.localDescription)===null||o===void 0?void 0:o.sdp),this._sendEndOfCandidates()))}_sendIceCandidate(e){const i=new jb({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return w.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{w.debug("Successfully added ICE candidate:",e)}).catch(n=>{w.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new Hb({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(le(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(le(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n;this.options.trickleIce?this._onTrickleIce(i):!((n=this.peer)===null||n===void 0)&&n.iceDone||this._onIce(i)},e.onicegatheringstatechange=i=>{w.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(w.debug("Finished gathering candidates"),performance.mark(le(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(w.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&Os(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:pt.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),w.error(`Media error (${i}): ${n}`,e),j(F.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:pt.peerConnectionFailureError,error:e.error}),w.error("Peer connection failure error"),e.warning&&j(F.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:pt.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:pt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(j(F.Notification,e,this.id,!1)||j(F.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=je(cb);return j(F.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),w.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:m,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var y;this.options.id=d?d.toString():Ui(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(y=h,Object.keys(y).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Qt(F.MediaError,this._onMediaError,this.id),Qt(F.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Qt(F.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Is(m)&&Qt(F.Notification,m.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,T=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,x=this.session.options.debugLogLevel||"debug",N=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new ue({enabled:!0,interval:T,intermediateReportInterval:A},{enabled:!0,level:x,maxEntries:N}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=E=>{var k,f,_,g;j(F.Warning,{warning:E,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),E.code===jr&&this._state!==z.Held?(f=(k=this.session).reportNoRtp)===null||f===void 0||f.call(k,this.id,"inbound"):E.code===kh&&this._state!==z.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((g=(_=this.session).reportNoRtp)===null||g===void 0||g.call(_,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const E={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:15e3,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:$h,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},k={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new ze(E,k);const f=(l=this.session.connection)===null||l===void 0?void 0:l.host;f&&this._callRecorder._setHost(f),this._callRecorder.onWarning=_=>{j(F.Warning,{warning:_,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(z.Recovering):this.setState(z.New),w.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}getEstablishmentTimings(){var e,i,n;const s=(e=this.peer)===null||e===void 0?void 0:e.callEstablishmentTimings;if(s)return s;const o=!((i=this.options)===null||i===void 0)&&i.trickleIce&&!(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)?"trickle":"non-trickle";return hf(this.id,o,this.direction)}_finalize(){var e,i,n;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(i=this._callRecorder)===null||i===void 0||i.stop(),ia(this.id),w.debug(`[${this.id}] Closing peer from _finalize`),(n=this.peer)===null||n===void 0||n.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;Mn(s),Mn(o),Zh(r,s),Zh(a,o),Lt(F.MediaError,null,this.id),Lt(F.PeerConnectionFailureError,null,this.id),Lt(F.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{w.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,i,n,s,o,r,a,l,c,u,d,h;const p=this.session.options,m=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},m?{anonymousLogin:{targetType:m.target_type,targetId:m.target_id,targetVersionId:m.target_version_id,targetParams:this._sanitizeClientOption(m.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(i=p.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=p.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)!==null&&c!==void 0&&c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:i,username:n,credential:s})=>({urls:i,hasUsername:!!n,hasCredential:!!s}))}_sanitizeClientOption(e,i=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(i>=4)return"[truncated]";if(Array.isArray(e))return e.map(n=>this._sanitizeClientOption(n,i+1)).filter(n=>n!==void 0);if(typeof e=="object"){const n=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,i+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(n)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void w.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void w.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Bs,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;w.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,n,s,a,l).catch(u=>{w.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return U(this,void 0,void 0,function*(){if(!this._callReportCollector)return void w.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{w.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return w.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Bs,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void w.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw w.error("Failed to post call report",{error:c}),c}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),w.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),w.debug("Stats stopped")}}ff.setStateTelnyx=t=>{if(t){switch(t._state){case z.Recovering:t.state="recovering";break;case z.Requesting:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class gi extends ff{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Jb(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new Qb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return U(this,void 0,void 0,function*(){this.screenShare instanceof gi&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return U(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>U(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new gi(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return U(this,void 0,void 0,function*(){this.screenShare instanceof gi&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&ef(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>U(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
115
+ `),Be[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!$(r.id,r)){const l=Wr(r);$(F.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Gh?(w.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?w.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(w.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),$(F.SocketClose,{code:Ih.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):w.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(w.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(w.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):w.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{Lt(e);const n=this._pendingRequestTimers.get(e),i=this._pendingRequestRejecters.get(e);n&&(clearTimeout(n),this._pendingRequestTimers.delete(e),i&&i.reject(new Hr(e,i.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),$(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",e)}}Ds.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Wn{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Vn()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const qh={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 qe extends Wn{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=ph(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in qh)i&&n.hasOwnProperty(i)&&(n[qh[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class zh extends qe{constructor(e){super(),this.method=ie.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ub{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>U(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Wr(n))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const n=new zh(Di());this.pendingRequestId=n.request.id,this.gatewayStateTask=Nh({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Be.REGISTER,Be.REGED].includes(i)}),this.session=e,this.gatewayStateTask=Nh({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Xr extends qe{constructor(e){super(),this.method=ie.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Gn{constructor(e){this._session=e,this._lastInboundAt=0,this._lastOutboundConfirmedAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Gn.CRITICAL_METHODS.has(e)}start(){this._intervalId||(w.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),w.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}onOutboundConfirmed(){this._lastOutboundConfirmedAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),w.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void w.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(w.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var n;!((n=this._session.connection)===null||n===void 0)&&n.connected&&(this._probeInFlight?w.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(w.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,n,i=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Gn.isCriticalMethod(i)?(w.warn(`Critical signaling request timed out (id=${e}, method=${i}, timeout=${n}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${i}, id=${e}, timeout=${n}ms)`,"request")):w.warn(`Non-critical signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${n}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,n){w.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${n})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${n})`,`Peer failure detected (${n}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,n){w.warn(`Signaling health: no RTP detected (callId=${e}, direction=${n})`),this._recoverMediaOrSignaling(e,`No RTP ${n} while media should be active`,`No RTP ${n} while signaling is unhealthy`,"no_rtp")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(w.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,w.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=le(K0);$(F.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){w.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const n=Date.now(),i=n-this._lastInboundAt,s=n-this._lastOutboundConfirmedAt,o=i>=2e4;if(!o&&!(s>=45e3))return;if(!this._probeInFlight)return w.info(o?`Signaling health: no inbound WS activity for ${Math.round(i/1e3)}s during active call, sending health probe`:`Signaling health: inbound WS activity is flowing but no outbound request has been answered for ${Math.round(s/1e3)}s, sending health probe`),void this._sendProbe();const r=n-this._lastProbeSentAt;r>=5e3&&(w.warn(`Signaling health: probe timed out after ${r}ms (inbound silent for ${Math.round(i/1e3)}s, no outbound request answered for ${Math.round(s/1e3)}s) — declaring signaling unhealthy`),this._triggerSignalingRecovery(o?"Signaling health probe timed out: no inbound WS activity after probe":"Signaling health probe timed out: inbound WS activity is flowing but no outbound request is being answered","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const n=new Xr(Di());(e=this._session.connection)===null||e===void 0||e.send(n).then(()=>this._resolveProbe()).catch(i=>{w.warn("Signaling health: probe Ping failed to send",i)})}_recoverMediaOrSignaling(e,n,i,s){if(!this._session.hasActiveCall())return void w.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(w.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,n)):o==="unknown"?(w.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:n,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(w.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(i,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const n=Date.now(),i=this._lastInboundAt||this._session.connection.lastInboundAt||0;return i===0?"unknown":n-i<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,n="probe"){var i,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,w.debug(`Signaling recovery triggered (source=${n}, reason=${e})`);const r=je(fb);$(F.Warning,{warning:r,reason:e,source:n,sessionId:this._session.sessionid},this._session.uuid),!((i=this._session.connection)===null||i===void 0)&&i.connected?(w.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):w.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,n){w.info(`Signaling health: triggering ICE restart for call ${e}`);const i=this._session.triggerIceRestart(e);if(!i.started)return void w.info(`Signaling health: ICE restart not started for call ${e}: ${i.reason}`);const s=je(pb);$(F.Warning,{warning:s,reason:n,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Gn.CRITICAL_METHODS=new Set([ie.Modify,ie.Bye,ie.Ping]);var Kh="2.27.10",Jr=Kh;class Bb extends qe{constructor(e,n,i,s,o={},r,a=!1){super(),this.method="login";const l={login:e,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{early_sdp_answer:a},"User-Agent":{sdkVersion:Jr,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Vb extends qe{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Yh extends qe{toString(){return ie.Invite}}class Xh extends qe{toString(){return ie.Answer}}class Jh extends qe{toString(){return ie.Attach}}class $b extends qe{toString(){return ie.Bye}}class jb extends qe{toString(){return ie.Candidate}}class Hb extends qe{toString(){return ie.EndOfCandidates}}class Ls extends qe{toString(){return ie.Modify}}class Qh extends qe{toString(){return ie.Info}}class Wb extends qe{toString(){return ie.Broadcast}}class Gb extends qe{toString(){return ie.Subscribe}}class qb extends qe{toString(){return ie.Unsubscribe}}class zb extends qe{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Jr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class pn{constructor(e){if(this.options=e,this.uuid=Vn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Gn(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",Lh=(i=Es[n])!==null&&i!==void 0?i:Es.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new Ds(this),this.registerAgent=new Ub(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return U(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,n=Math.min(1e3*Math.pow(2,e-1),3e4),i=Math.floor(.25*n*(2*Math.random()-1)),s=n+i;return w.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:n,jitterMs:i,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var n;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),w.debug("Calling connect from execute since not currently connected."),this.connect()});const i=Gn.isCriticalMethod(((n=e.request)===null||n===void 0?void 0:n.method)||"")?Ds.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(i!=null?this.connection.send(e,i):this.connection.send(e)).catch(s=>U(this,void 0,void 0,function*(){if(s instanceof Hr)throw w.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=le(q0,s,void 0,!0);$(F.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return U(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let n=!1;yield Promise.race([Promise.all(e.map(i=>i.catch(()=>{}))),new Promise(i=>setTimeout(()=>{n=!0,i()},pn.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),n&&w.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return As(this.options)||xi(this.options)}broadcast(e){}disconnect(){return U(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),w.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Qt(e,n,this.uuid),this}off(e,n){return Lt(e,n,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new Ds(this)),this._attachListeners(),this._autoReconnect||(w.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(w.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),w.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const n=le(wh,e);$(F.Error,{error:n,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Uh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const n=e.split(".");if(n.length!==3)return;const i=JSON.parse(atob(n[1])).exp;if(typeof i!="number")return;const s=i-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=pn.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-pn.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{w.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=je(ub);$(F.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:n,onError:i}={}){return U(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),As(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(xi(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";w.error(s);const o=le(G0,void 0,s);return void $(F.Error,{error:o,type:Mb.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){var s,o,r,a;return U(this,void 0,void 0,function*(){let l;const c=!!Di(),u=c&&(this.sessionid&&Fh()?this.sessionid:function(h=Date.now()){const p=sessionStorage.getItem(Rs);return p?Fh(h)?p:(sessionStorage.removeItem(Rs),sessionStorage.removeItem(xs),null):null}())||"";if(e==="login"){const h=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,p=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:h,pn_late_fanout:h}),m=(a=this.options.earlySdpAnswer)!==null&&a!==void 0&&a;l=new Bb(this.options.login,this.options.password||this.options.passwd,this.options.login_token,u,p,c,m)}else l=new zb({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:u,userVariables:this.options.userVariables,reconnection:c});const d=yield this.execute(l).catch(h=>{this._handleLoginError(h),i&&i(h)});d&&(this.sessionid=d.sessid,this.sessionid&&zr(this.sessionid),this._checkTokenExpiry(),n&&n())})}_onSocketOpen(){return U(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const n=this.calls;n&&Object.values(n).forEach(i=>{if(i!=null&&i.flushIntermediateCallReport)try{i.flushIntermediateCallReport(e)}catch(s){w.error("Failed to flush intermediate call report",{callId:i.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const n=Object.entries(Ih).find(([,i])=>i===e);return n==null?void 0:n[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var n,i,s,o;const r=(i=(n=this.connection)===null||n===void 0?void 0:n.socketGeneration)!==null&&i!==void 0?i:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)w.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),w.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Yr(this.relayProtocol);for(const l in this.subscriptions)Yr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&zr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){w.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=le($r);return void $(F.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;w.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{w.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(w.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=je(gb);$(F.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else w.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Lt(e,null,n)):(delete this.subscriptions[e],Yr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Is(n)&&Qt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),w.debug("Attaching socket event listeners"),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage),this.on(F.SocketActivity,this._onSocketActivity)}_detachListeners(){w.debug("Detaching socket event listeners"),this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.SocketMessage,this._onSocketMessage),this.off(F.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){var e,n;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),w.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(n=this.connection)===null||n===void 0?void 0:n.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(w.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Xr(Di()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){w.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}onOutboundConfirmed(){this._signalingHealthMonitor.onOutboundConfirmed()}hasActiveCall(){const e=this.calls;if(!e)return!1;const n=new Set([z.Early,z.Active,z.Held]);return Object.values(e).some(i=>i&&i._state!=null&&n.has(i._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const n=Object.keys(e);if(n.length!==0){w.debug(`Reconnection exhausted — locally terminating ${n.length} active call(s) (no BYE): ${n.join(", ")}`);for(const i of n){const s=e[i];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const n=this.calls,i=n==null?void 0:n[e];if(!i)return w.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=i.peer;if(!(s!=null&&s.restartIce))return w.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||w.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,n,i=""){this._signalingHealthMonitor.onRequestTimeout(e,n,i)}reportPeerFailure(e,n){this._signalingHealthMonitor.onPeerFailure(e,n)}reportNoRtp(e,n){this._signalingHealthMonitor.onNoRtp(e,n)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,n){Qt(e,n)}static off(e){Lt(e)}static uuid(){return Vn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}pn.TOKEN_EXPIRY_WARNING_SECONDS=120,pn.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const Ms=t=>navigator.mediaDevices.getUserMedia(t),Mi=t=>t&&t instanceof MediaStream,Os=(t,e,n)=>{const i=Ri(t);if(i!==null){if(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject&&i.srcObject!==e&&(w.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),n)){const s=je(db);$(F.Warning,{warning:s,callId:n.callId,sessionId:n.sessionId},n.eventTarget)}i.srcObject=e}},Zh=(t,e)=>{const n=Ri(t);if(n){if(e&&n.srcObject!==e)return;n.srcObject=null}},ef=(t,e)=>U(void 0,void 0,void 0,function*(){const n=Ri(t);if(n===null)return w.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return w.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Kb=t=>{t&&t.readyState==="live"&&t.stop()},Oi=t=>{Mi(t)&&t.getTracks().forEach(Kb),t=null},Ps=t=>U(void 0,void 0,void 0,function*(){w.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Ms(t)}catch(i){if(w.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){w.warn("Device not found or not readable, falling back to default device");try{return yield Ms(s)}catch(o){throw w.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),Pi=(t=null,e=!1)=>U(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Dt.AudioIn||s===Dt.AudioOut,video:!s||s===Dt.Video}))(t)).catch(s=>(w.error(s),null));if(i){if(Oi(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(o=>o.kind===t)),e===!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}),tf=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Ns=(t,e,n)=>U(void 0,void 0,void 0,function*(){const i=yield Pi(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(t===o||e===r)return o}return null}),Yb=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},Qr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,nf=t=>{var e,n,i,s,o,r;return t?((n=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&n!==void 0?n:[...(s=(i=t.getAudioTracks)===null||i===void 0?void 0:i.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Qr(a)):[]},Zr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=ea(t);return n.includes(e)||i.includes(e)},ea=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},qn=(t,e=null,n=null)=>{if(!Mi(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.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}})},ta=t=>{qn(t,"audio",!0)},Fs=t=>{qn(t,"audio",!1)};function Xb(){try{const{browserInfo:t,name:e,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 u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,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:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Ps}}catch(t){return t.message}}var Re;function sf(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function of(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{w.error("playAudio",e),t._playFulfilled=!0}))}function rf(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Re||(Re={}));const af=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class Jb extends Wn{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Vn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class Qb extends Wn{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class fe{constructor(e,n){var i;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._isHeld=!1,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new Ab(s)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,Dh=i)}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,w.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:fe.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this._scheduleNextCollection())}stop(){var e,n;return U(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),w.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,n){var i,s,o,r;const a=this.statsBuffer.length,l=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0,c=(n==null?void 0:n.type)==="socket-close"||(n==null?void 0:n.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return w.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:n,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],m=new Date;this._lastIntermediateFlushTime=m;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(m.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:m.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),n?{flushReason:n}:{});return w.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:n}),v}finally{this._flushing=!1}}postReport(e,n,i,s){var o,r;return U(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void w.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void w.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,n,i,s,!0)})}sendPayload(e,n,i,s,o=!1){return U(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s,!1,o)})}_sendPayload(e,n,i,s,o=!0,r=!1){var a,l;return U(this,void 0,void 0,function*(){const c=new URL(i),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;w.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),m=(o||r)&&p.length<=fe.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=fe.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},m?{keepalive:!0}:{}));if(C.ok)return void w.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const T=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),w.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:T})}}catch(C){v=C,w.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const y=fe.RETRY_DELAYS_MS[b];if(y===void 0)break;w.info(`CallReportCollector: Retrying ${d} in ${y}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,y))}throw w.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,n,i,s,o,r,a,l,c,u,d,h,p,m,v,b;if(this.statsBuffer.length<2)return!1;const y=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],T=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((T==null?void 0:T.networkType)==="vpn"&&(T==null?void 0:T.candidateType)!=="relay"))return!1;const A=((n=y.ice)===null||n===void 0?void 0:n.writable)===!1,x=((i=y.transport)===null||i===void 0?void 0:i.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",N=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),k=this._positiveDelta((a=y.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=N>0&&k===0,f=this._positiveDelta((u=(c=y.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),_=this._positiveDelta((m=(p=y.audio)===null||p===void 0?void 0:p.inbound)===null||m===void 0?void 0:m.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return A||x||E||f>0&&_===0}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}_positiveDelta(e,n){return e===void 0||n===void 0?0:Math.max(0,e-n)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(Ts,!1),this._trackBreach(jr,!1))}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(fe.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:n}_collectStats(e=!1){var n,i;return U(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(f=>{switch(f.type){case"outbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(r=f);break;case"inbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(a=f);break;case"media-playout":f.kind==="audio"&&(l=f);break;case"remote-inbound-rtp":f.kind==="audio"&&(c=f);break;case"remote-outbound-rtp":f.kind==="audio"&&(u=f);break;case"candidate-pair":(f.nominated||f.state==="succeeded")&&h.push(f);break;case"transport":p=f}});const m=p==null?void 0:p.selectedCandidatePairId,v=m?(i=(n=s).get)===null||i===void 0?void 0:i.call(n,m):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),y=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:m?h.find(f=>f.id===m)||h[h.length-1]||null:h[h.length-1]||null,r){const f=this._getOutboundAudioLevel(s,r);if(f!==null&&this.intervalAudioLevels.outbound.push(f),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(r.bytesSent||0)-this.previousStats.outboundBytes,g=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const f=this._getInboundAudioLevel(s,a);if(f!==null&&this.intervalAudioLevels.inbound.push(f),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(a.bytesReceived||0)-this.previousStats.inboundBytes,g=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,T,A,x,N;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),T=this._resolveCandidate(s,d.remoteCandidateId)),d&&(A=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),T?{remote:T}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(rb)),this.previousCandidatePairSnapshot=A),r&&(x=this._getLocalAudioTrackSnapshot(),N=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(x,N),this.previousStats.timestamp=o.getTime();const k=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||k>=E){const f=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,T,p,x,N,l,c,u,b,y);this.statsBuffer.push(f),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(f,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){w.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:fe.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var n,i;const s=this.statsBuffer.length,o=(i=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&i!==void 0?i:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void w.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=fe.STATS_FLUSH_THRESHOLD||o>=fe.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){w.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){w.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,n){var i,s,o,r,a,l,c,u,d,h,p,m,v,b,y;if(!this.onWarning)return;const C=(i=e.connection)===null||i===void 0?void 0:i.roundTripTimeAvg,T=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(n){const x=(r=n.packetsReceived)!==null&&r!==void 0?r:0,N=(a=n.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const k=x-this._prevPacketsReceived,E=N-this._prevPacketsLost,f=k+E;f>0&&(A=E/f*100)}this._prevPacketsReceived=x,this._prevPacketsLost=N}if(this._trackBreach(Y0,C!==void 0&&C>fe.THRESHOLD_RTT_MS),this._trackBreach(X0,T!==void 0&&T>fe.THRESHOLD_JITTER_MS),this._trackBreach(J0,A!==void 0&&A>fe.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(Ts,!1):this._trackLowInboundAudio(e),C!==void 0&&T!==void 0&&A!==void 0){const x=93.2-.11*T-2.5*A-.01*(1e3*C),N=Math.max(1,Math.min(4.5,1+.035*x+x*(x-60)*(100-x)*7e-6));this._trackBreach(Th,N<fe.THRESHOLD_MOS)}else this._trackBreach(Th,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const x=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,N=e.audio.inbound.bytesReceived;this._trackBreach(jr,!this._isHeld&&x!==void 0&&N-x==0)}if(((m=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||m===void 0?void 0:m.bytesSent)!==void 0){const x=(y=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||y===void 0?void 0:y.bytesSent,N=e.audio.outbound.bytesSent;this._trackBreach(Eh,x!==void 0&&N-x==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var n;const i=(n=e.audio)===null||n===void 0?void 0:n.outbound,s=i==null?void 0:i.audioLevelAvg,o=i==null?void 0:i.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=fe.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(Cs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=fe.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(Cs)):this._trackBreach(Cs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(Cs,!1)}_getStatsIntervalDurationMs(e){const n=new Date(e.intervalStartUtc).getTime(),i=new Date(e.intervalEndUtc).getTime()-n;return Number.isFinite(i)&&i>0?i:this.options.interval}_trackLowInboundAudio(e){var n;const i=(n=e.audio)===null||n===void 0?void 0:n.inbound,s=i==null?void 0:i.audioLevelAvg;if(s===void 0)return void this._trackBreach(Ts,!1);const o=s<=fe.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(Ts,o)}_trackBreach(e,n){var i,s;if(n){if(this._breachCounters[e]=((i=this._breachCounters[e])!==null&&i!==void 0?i:0)+1,this._breachCounters[e]>=fe.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=fe.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var n;try{const i=je(e);w.warn(`CallReportCollector: warning ${i.code}: ${i.message}`),(n=this.onWarning)===null||n===void 0||n.call(this,i)}catch(i){w.error(`CallReportCollector: Failed to emit warning ${e}`,{error:i})}}_createStatsEntry(e,n,i,s,o,r,a,l,c,u,d,h,p,m,v){const b={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};if(i&&(b.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),i.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:i.retransmittedPacketsSent}:{}),i.retransmittedBytesSent!==void 0?{retransmittedBytesSent:i.retransmittedBytesSent}:{}),i.headerBytesSent!==void 0?{headerBytesSent:i.headerBytesSent}:{}),i.nackCount!==void 0?{nackCount:i.nackCount}:{}),i.targetBitrate!==void 0?{targetBitrate:i.targetBitrate}:{}),i.totalPacketSendDelay!==void 0?{totalPacketSendDelay:i.totalPacketSendDelay}:{}),i.active!==void 0?{active:i.active}:{}),m?{codec:this._buildCodecSnapshot(m,i.codecId)}:{})),s&&(b.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(b.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),b.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(b.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamplesEvents:d.synthesizedSamplesEvents,synthesizedSamplesDuration:d.synthesizedSamplesDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSamplesCount:d.totalSamplesCount,totalSamplesDuration:d.totalSamplesDuration})),h||p){const y={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let T;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(T=h.totalRoundTripTime/h.roundTripTimeMeasurements),y.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:T,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(y.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=y}return b}_resolveCandidate(e,n){if(!n)return void w.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void w.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.id!==void 0&&(s.id=i.id),i.address!==void 0?s.address=i.address:i.ip!==void 0&&(s.address=i.ip),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),i.url!==void 0&&(s.url=i.url),i.relayProtocol!==void 0&&(s.relayProtocol=i.relayProtocol),Object.keys(s).length!==0)return s;w.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getCodec(e,n){if(!n)return;const i=e.get(n);return i&&i.type==="codec"?i:void 0}_buildCodecSnapshot(e,n){const i=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},n!==void 0?{codecId:n}:{}));return Object.keys(i).length>0?i:void 0}_getOutboundMediaSource(e,n){let i;return n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),i}_getLocalAudioTrackSnapshot(){var e,n;try{const i=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=i==null?void 0:i.track;if(!s)return;const o=(n=s.getSettings)===null||n===void 0?void 0:n.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(i){return void w.debug("CallReportCollector: unable to snapshot local audio track",{error:i})}}_getOutboundAudioSourceStats(e,n){const i=this._getOutboundMediaSource(e,n);if(!i)return;const s=this._withoutUndefined({id:i.id,trackIdentifier:i.trackIdentifier,audioLevel:i.audioLevel,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration,echoReturnLoss:i.echoReturnLoss,echoReturnLossEnhancement:i.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,n){if(!e||Object.keys(e).length===0)return;const i=this._stableStringify(e);i!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=i,w.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:n}))}_withoutUndefined(e){return Object.keys(e).reduce((n,i)=>{const s=e[i];return s!==void 0&&(n[i]=s),n},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(n=>this._sortObjectKeys(n)):e&&typeof e=="object"?Object.keys(e).sort().reduce((n,i)=>(n[i]=this._sortObjectKeys(e[i]),n),{}):e}_getOutboundAudioLevel(e,n){const i=this._getOutboundMediaSource(e,n);if((i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=n,r===void 0||a===void 0)return null;const l=e-r,c=n-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}fe.INITIAL_COLLECTION_INTERVAL_MS=1e3,fe.STATS_FLUSH_THRESHOLD=300,fe.LOGS_FLUSH_THRESHOLD=800,fe.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,fe.CONSECUTIVE_BREACHES_REQUIRED=3,fe.THRESHOLD_RTT_MS=.4,fe.THRESHOLD_JITTER_MS=30,fe.THRESHOLD_PACKET_LOSS_PCT=1,fe.THRESHOLD_MOS=3.5,fe.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,fe.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,fe.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,fe.WARNING_THROTTLE_MS=15e3,fe.RETRY_DELAYS_MS=[500,1e3,2e3],fe.KEEPALIVE_BODY_LIMIT_BYTES=61440;class ze{constructor(e,n){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow={local:!1,remote:!1},this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=n,this.recordingId=n.recordingId||`${n.callId}-${Date.now().toString(36)}`}start(e,n){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return w.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Q0),void(this._started=!0);const i=this.options.tracks||["local","remote"];let s=0;if(i.includes("local")&&e&&(this._attach(e,"local"),s++),i.includes("remote")&&n&&(this._attach(n,"remote"),s++),s===0)return w.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),w.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,w.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return U(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void w.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void w.debug("CallRecorder: postFinalReport skipped — no host available");const n=this.options.tracks||["local","remote"],i=this._startedAt,s=this._endedAt||new Date,o=n.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",i,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=ze.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,n){this._trackStates[n]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const i=new MediaStreamTrackProcessor({track:e});this._processors.push(i);const s=i.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),U(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(n,l)}}catch(a){this._stopped||w.warn("CallRecorder: reader loop error",{track:n,error:a})}})}catch(i){w.warn("CallRecorder: failed to attach track",{track:n,error:i}),this._trackStates[n]=null}}_onFrame(e,n){var i;const s=this._trackStates[e];if(!s||this._stopped)return;const o=n.numberOfFrames,r=new Float32Array(o);n.copyTo(r,{planeIndex:0}),(i=n.close)===null||i===void 0||i.call(n);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,n){const i=e.payloadBytes.length+ze.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[n];if(o.push(e),this._bufferBytes[n]+=i,this._bufferBytes[n]>s){for(;o.length>1&&this._bufferBytes[n]>s;){const r=o.shift();r&&(this._bufferBytes[n]-=r.payloadBytes.length+ze.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[n]||(this._overflowWarnedThisWindow[n]=!0,w.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:n}),this._emitWarning(Z0))}}_flushIntervalMs(){var e;const n=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return n<=0?n:Math.min(n,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*ze.BYTES_PER_SAMPLE+ze.FRAMES_PER_SECOND*ze.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:$h}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(n=>{w.error("CallRecorder: periodic flush error",{error:n})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return U(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void w.debug("CallRecorder: periodic flush skipped — no host available");const n=this.options.tracks||["local","remote"],i=this._startedAt||new Date,s=new Date;yield Promise.allSettled(n.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",i,s);return this._postRecording(e,a,!1).catch(l=>{w.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!1}}finally{this._flushing=!1}}})}_drain(e){const n=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,n}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const n=this.options.endpoint||"/call_recording";try{const i=new URL(e);return`${`${i.protocol.replace(/^ws/,"http")}//${i.host}`}${n}`}catch{return/^https?:\/\//.test(e)?`${e}${n}`:`https://${e}${n}`}}_buildEnvelope(e,n,i,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:i,track:n,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,n,i){return U(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":n.call_report_id,"x-call-id":n.call_id};n.voice_sdk_id&&(s["x-voice-sdk-id"]=n.voice_sdk_id);const o=JSON.stringify(n),r=i&&o.length<=ze.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=ze.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void w.info("CallRecorder: posted",{track:n.track,segment:n.segment,attempt:c+1,status:d.status,packets:n.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),w.error("CallRecorder: failed to post",{track:n.track,segment:n.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,w.warn("CallRecorder: network error posting",{track:n.track,segment:n.segment,attempt:c+1,error:d})}const u=ze.RETRY_DELAYS_MS[c];if(u===void 0)break;w.info("CallRecorder: retrying",{track:n.track,segment:n.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw w.error("CallRecorder: exhausted retries",{track:n.track,segment:n.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var n;try{const i=je(e);(n=this.onWarning)===null||n===void 0||n.call(this,i)}catch(i){w.warn("CallRecorder: failed to emit warning",{code:e,error:i})}}_toBase64(e){let n="";for(let i=0;i<e.length;i+=32768){const s=e.subarray(i,i+32768);n+=String.fromCharCode.apply(null,Array.from(s))}return btoa(n)}}ze.RETRY_DELAYS_MS=[500,1e3,2e3],ze.KEEPALIVE_BODY_LIMIT_BYTES=61440,ze.PACKET_OVERHEAD_BYTES=160,ze.BYTES_PER_SAMPLE=4,ze.FRAMES_PER_SECOND=100;class Zb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return U(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,w.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){w.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return U(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){w.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return U(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),n=new Set(this._rawDeviceCache.map(r=>r.deviceId)),i=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!n.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!i.has(r.deviceId));(s.length>0||o.length>0)&&w.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){w.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var Us,lf=Rh(function(t,e){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,_,g,S){var I,P,R;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if((P=f._events)?(P.newListener&&(f.emit("newListener",_,g.listener?g.listener:g),P=f._events),R=P[_]):(P=f._events=new i,f._eventsCount=0),R){if(typeof R=="function"?R=P[_]=S?[g,R]:[R,g]:S?R.unshift(g):R.push(g),!R.warned&&(I=o(f))&&0<I&&R.length>I){R.warned=!0;var M=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+_+" listeners added. Use emitter.setMaxListeners() to increase limit");M.name="MaxListenersExceededWarning",M.emitter=f,M.type=_,M.count=R.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(M)}}else R=P[_]=g,++f._eventsCount;return f}function a(f,_,g){function S(){f.removeListener(_,S),I||(I=!0,g.apply(f,arguments))}var I=!1;return S.listener=g,S}function l(f){var _=this._events;if(_){var g=_[f];if(typeof g=="function")return 1;if(g)return g.length}return 0}function c(f,_){for(var g=Array(_);_--;)g[_]=f[_];return g}Object.defineProperty(e,"__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 _,g,S,I,P,R,M,O=f==="error";if(R=this._events)O=O&&R.error==null;else if(!O)return!1;if(M=this.domain,O){if(_=arguments[1],!M){if(_ instanceof Error)throw _;var L=new Error('Uncaught, unspecified "error" event. ('+_+")");throw L.context=_,L}return _||(_=new Error('Uncaught, unspecified "error" event')),_.domainEmitter=this,_.domain=M,_.domainThrown=!1,M.emit("error",_),!1}if(!(g=R[f]))return!1;var V=typeof g=="function";switch(S=arguments.length){case 1:(function(j,H,K){if(H)j.call(K);else for(var W=j.length,Y=c(j,W),q=0;q<W;++q)Y[q].call(K)})(g,V,this);break;case 2:(function(j,H,K,W){if(H)j.call(K,W);else for(var Y=j.length,q=c(j,Y),X=0;X<Y;++X)q[X].call(K,W)})(g,V,this,arguments[1]);break;case 3:(function(j,H,K,W,Y){if(H)j.call(K,W,Y);else for(var q=j.length,X=c(j,q),te=0;te<q;++te)X[te].call(K,W,Y)})(g,V,this,arguments[1],arguments[2]);break;case 4:(function(j,H,K,W,Y,q){if(H)j.call(K,W,Y,q);else for(var X=j.length,te=c(j,X),J=0;J<X;++J)te[J].call(K,W,Y,q)})(g,V,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),P=1;P<S;P++)I[P-1]=arguments[P];(function(j,H,K,W){if(H)j.apply(K,W);else for(var Y=j.length,q=c(j,Y),X=0;X<Y;++X)q[X].apply(K,W)})(g,V,this,I)}return!0},s.prototype.addListener=function(f,_){return r(this,f,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,_){return r(this,f,_,!0)},s.prototype.once=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,_)),this},s.prototype.prependOnceListener=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,_)),this},s.prototype.removeListener=function(f,_){var g,S,I,P,R;if(typeof _!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(g=S[f]))return this;if(g===_||g.listener&&g.listener===_)--this._eventsCount==0?this._events=new i:(delete S[f],S.removeListener&&this.emit("removeListener",f,g.listener||_));else if(typeof g!="function"){for(I=-1,P=g.length;0<P--;)if(g[P]===_||g[P].listener&&g[P].listener===_){R=g[P].listener,I=P;break}if(0>I)return this;if(g.length===1){if(g[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete S[f]}else(function(M,O){for(var L=O,V=L+1,j=M.length;V<j;L+=1,V+=1)M[L]=M[V];M.pop()})(g,I);S.removeListener&&this.emit("removeListener",f,R||_)}return this},s.prototype.removeAllListeners=function(f){var _,g;if(!(g=this._events))return this;if(!g.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):g[f]&&(--this._eventsCount==0?this._events=new i:delete g[f]),this;if(arguments.length===0){for(var S,I=Object.keys(g),P=0;P<I.length;++P)(S=I[P])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(_=g[f])=="function")this.removeListener(f,_);else if(_)do this.removeListener(f,_[_.length-1]);while(_[0]);return this},s.prototype.listeners=function(f){var _,g,S=this._events;return S?g=(_=S[f])?typeof _=="function"?[_.listener||_]:function(I){for(var P=Array(I.length),R=0;R<P.length;++R)P[R]=I[R].listener||I[R];return P}(_):[]:g=[],g},s.listenerCount=function(f,_){return typeof f.listenerCount=="function"?f.listenerCount(_):l.call(f,_)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=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 u(d)}for(var p=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,m=[],v=0;256>v;++v)m.push((v+256).toString(16).substr(1));function b(f){var _=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,g=(m[f[_+0]]+m[f[_+1]]+m[f[_+2]]+m[f[_+3]]+"-"+m[f[_+4]]+m[f[_+5]]+"-"+m[f[_+6]]+m[f[_+7]]+"-"+m[f[_+8]]+m[f[_+9]]+"-"+m[f[_+10]]+m[f[_+11]]+m[f[_+12]]+m[f[_+13]]+m[f[_+14]]+m[f[_+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(g))throw TypeError("Stringified UUID is invalid");return g}function y(f,_,g){var S=(f=f||{}).random||(f.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(f,_){if(!f||!_)return{};const g={...f};if(g.localCandidateId){const S=_.get(g.localCandidateId);g.local={...S}}if(g.remoteCandidateId){const S=_.get(g.remoteCandidateId);g.remote={...S}}return g}function T(f,_,g){return 8*function(S,I,P){const R=S[P],M=I?I[P]:null;return R===null||M===null?null:(R-M)/(S.timestamp-I.timestamp)*1e3}(f,_,g)}function A(f){if(!f.entries)return f;const _={};return f.forEach(function(g,S){_[S]=g}),_}function x(f,_,g={}){if(!f)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};g.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of f.values())switch(I.type){case"outbound-rtp":{const P=I.mediaType||I.kind,R={};let M={};if(!["audio","video"].includes(P))continue;if(I.codecId){const O=f.get(I.codecId);O&&(R.clockRate=O.clockRate,R.mimeType=O.mimeType,R.payloadType=O.payloadType)}M=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[P].outbound.push({...I,...R,track:{...M}});break}case"inbound-rtp":{let P=I.mediaType||I.kind,R={};const M={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const O=f.get(I.codecId);O&&(M.clockRate=O.clockRate,M.mimeType=O.mimeType,M.payloadType=O.payloadType)}if(!S.connection.id&&I.transportId){const O=f.get(I.transportId);if(O&&O.selectedCandidatePairId){const L=f.get(O.selectedCandidatePairId);S.connection=C(L,f)}}R=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[P].inbound.push({...I,...M,track:{...R}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!g.remote)break;let P=I.mediaType||I.kind;const R={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const M=f.get(I.codecId);M&&(R.clockRate=M.clockRate,R.mimeType=M.mimeType,R.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=f.get(I.transportId);if(M&&M.selectedCandidatePairId){const O=f.get(M.selectedCandidatePairId);S.connection=C(O,f)}}S.remote[P].inbound.push({...I,...R});break}case"remote-outbound-rtp":{if(!g.remote)break;const P=I.mediaType||I.kind,R={};if(!["audio","video"].includes(P))continue;if(I.codecId){const M=f.get(I.codecId);M&&(R.clockRate=M.clockRate,R.mimeType=M.mimeType,R.payloadType=M.payloadType)}S.remote[P].outbound.push({...I,...R});break}}if(!S.connection.id)for(const I of f.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,f));return S=function(I,P){return P&&(I.audio.inbound.map(R=>{let M=P.audio.inbound.find(O=>O.id===R.id);R.bitrate=T(R,M,"bytesReceived"),R.packetRate=T(R,M,"packetsReceived")}),I.audio.outbound.map(R=>{let M=P.audio.outbound.find(O=>O.id===R.id);R.bitrate=T(R,M,"bytesSent"),R.packetRate=T(R,M,"packetsSent")}),I.video.inbound.map(R=>{let M=P.video.inbound.find(O=>O.id===R.id);R.bitrate=T(R,M,"bytesReceived"),R.packetRate=T(R,M,"packetsReceived")}),I.video.outbound.map(R=>{let M=P.video.outbound.find(O=>O.id===R.id);R.bitrate=T(R,M,"bytesSent"),R.packetRate=T(R,M,"packetsSent")})),I}(S,_),S}let N,k={},E=[];e.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 _={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=_.getStatsInterval||1e3,this.rawStats=!!_.rawStats,this.statsObject=!!_.statsObject,this.filteredStats=!!_.filteredStats,this.shouldWrapGetUserMedia=!!_.wrapGetUserMedia,typeof _.remote=="boolean"&&(this.remote=_.remote),this.debug=!!_.debug,this.logLevel=_.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,_){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:_})}async addConnection(f){const{pc:_,peerId:g}=f;let{connectionId:S,remote:I}=f;if(I=typeof I=="boolean"?I:this.remote,!(_&&_ instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!g)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[g]){if(S&&S in this.peersToMonitor[g])throw new Error(`We are already monitoring connection with id ${S}.`);for(let R in this.peersToMonitor[g]){const M=this.peersToMonitor[g][R];if(M.pc===_)throw new Error(`We are already monitoring peer with id ${g}.`);M.pc.connectionState==="closed"&&this.removeConnection({pc:M.pc})}}const P=_.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(R){delete R.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:g,connectionId:S,data:{options:f,peerConfiguration:P}}),this.monitorPeer({peerId:g,connectionId:S,pc:_,remote:I}),{connectionId:S}}getTimeline(f){return this.timeline=this.timeline.sort((_,g)=>_.timestamp.getTime()-g.timestamp.getTime()),f?this.timeline.filter(_=>_.tag===f):this.timeline}get logger(){const f=_=>{const g=["none","error","warn","info","debug"];return g.slice(0,g.indexOf(this.logLevel)+1).indexOf(_)>-1};return{error(..._){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",..._)},warn(..._){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",..._)},info(..._){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",..._)},debug(..._){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",..._)}}}removeConnection(f){let _,{connectionId:g,pc:S}=f;if(!S&&!g)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(g){if(typeof g!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)g in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][g].pc,_=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let P in this.peersToMonitor[I])this.peersToMonitor[I][P].pc===S&&(g=P,_=I)}if(!S||!g)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(g,S),delete this.peersToMonitor[_][g],Object.values(this.peersToMonitor[_]).length===0&&delete this.peersToMonitor[_],{connectionId:g}}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 _ in this.peersToMonitor[f]){let g=this.peersToMonitor[f][_].pc;this.removePeerConnectionEventListeners(_,g)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),E.forEach(f=>{this.removeTrackEventListeners(f)}),E=[],this.shouldWrapGetUserMedia&&N&&(navigator.mediaDevices.getUserMedia=N)}monitorPeer(f){let{peerId:_,connectionId:g,pc:S,remote:I}=f;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:S,connectionId:g,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[_]){if(g in this.peersToMonitor[_])return void this.logger.warn(`Already watching connection with ID ${g}`);this.peersToMonitor[_][g]=P}else this.peersToMonitor[_]={[g]:P};this.addPeerConnectionEventListeners(_,g,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(_=>{this.emitEvent(_)})})},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 _={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);_[f]=this.peersToMonitor[f]}else _=this.peersToMonitor;let g=[];for(const S in _)for(const I in _[S]){const P=_[S][I],R=P.pc;if(R&&!this.checkIfConnectionIsClosed(S,I,R))try{const M=this.getTimestamp(),O=R.getStats(null);if(O){const L=await O,V=this.getTimestamp(),j=A(L),H={remote:P.options.remote},K=x(L,P.stats.parsed,H),W={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:V-M,data:K};this.rawStats===!0&&(W.rawStats=L),this.statsObject===!0&&(W.statsObject=j),this.filteredStats===!0&&(W.filteredStats=this.filteroutStats(j)),g.push(W),P.stats.parsed=K}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(M){this.logger.error(M)}}return g}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const _ in this.peersToMonitor[f]){const g=this.peersToMonitor[f][_].pc;this.checkIfConnectionIsClosed(f,_,g)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,_,g){const S=this.isConnectionClosed(g);if(S){this.removeConnection({pc:g});let I=g.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:f,connectionId:_,tag:"connection",data:"closed"})}return S}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."),N=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),N.apply(navigator.mediaDevices,arguments).then(_=>(f({stream:_}),_),_=>(f({error:_}),Promise.reject(_)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const _={...f};for(const S in _){var g=_[S];this.statsToMonitor.includes(g.type)||delete _[S]}return _}get peerConnectionListeners(){return{icecandidate:(f,_,g,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:_,data:S.candidate})},track:(f,_,g,S)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,S);const I=S.track,P=S.streams[0];f in this.peersToMonitor&&_ in this.peersToMonitor[f]&&(this.peersToMonitor[f][_].stream=P),this.addTrackEventListeners(I,_),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:_,data:{stream:P?this.getStreamDetails(P):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(R){return"stream:"+R.id})}})},signalingstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:_,data:{signalingState:g.signalingState,localDescription:g.localDescription,remoteDescription:g.remoteDescription}})},iceconnectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceConnectionState})},icegatheringstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceGatheringState})},icecandidateerror:(f,_,g,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:_,error:{errorCode:S.errorCode}})},connectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.connectionState})},negotiationneeded:(f,_,g)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:_})},datachannel:(f,_,g,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:_,data:S.channel})}}}addPeerConnectionEventListeners(f,_,g){this.logger.debug(`Adding event listeners for peer ${f} and connection ${_}.`),k[_]={},Object.keys(this.peerConnectionListeners).forEach(S=>{k[_][S]=this.peerConnectionListeners[S].bind(this,f,_,g),g.addEventListener(S,k[_][S],!1)})}parseGetUserMedia(f){try{const _={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(_.data.details=this.parseStream(f.stream),f.stream.getTracks().map(g=>{this.addTrackEventListeners(g),E.push(g)})),this.emitEvent(_)}catch{}}parseStream(f){const _={audio:[],video:[]};return f.getTracks().forEach(g=>{_[g.kind].push(this.getMediaTrackDetails(g))}),_}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:_=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:_}})},unmute:_=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:_}})},overconstrained:_=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:_}})},ended:_=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:_}}),this.removeTrackEventListeners(_.target)}}}addTrackEventListeners(f,_){k[f.id]={};const g=this.getTrackEventObject(_);Object.keys(g).forEach(S=>{k[f.id][S]=g[S].bind(this),f.addEventListener(S,k[f.id][S])}),k[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(S)}},1e3)}removeTrackEventListeners(f){if(f.id in k){const _=this.getTrackEventObject();Object.keys(_).forEach(g=>{f.removeEventListener(g,k[f.id][g])}),clearInterval(k[f.id].readyState),delete k[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const _={...f,timestamp:new Date};this.addToTimeline(_),_.tag&&this.emit(_.tag,_)}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,_){f in k&&(Object.keys(this.peerConnectionListeners).forEach(g=>{_.removeEventListener(g,k[f][g],!1)}),delete k[f]),_.getSenders().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)}),_.getReceivers().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const _=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),g=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),_.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=g.bind(navigator.mediaDevices)}}}});(Us=lf)&&Us.__esModule&&Object.prototype.hasOwnProperty.call(Us,"default")&&Us.default;var ew=lf.WebRTCStats;function tw(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,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 nw(t){return isNaN(t)?null:t>4.2?"excellent":t>=4.1&&t<=4.2?"good":t>=3.7&&t<=4?"fair":t>=3.1&&t<=3.6?"poor":"bad"}class iw extends Wn{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class sw extends Wn{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class ow extends Wn{constructor(e,n,i){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:n,debug_report_data:i})}}function rw(t,e){const n=Vn();let i=!1;const s=new ew({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>U(this,void 0,void 0,function*(){r.event==="stats"&&$(F.StatsFrame,function({data:a}){var l,c,u,d,h,p,m,v;const{audio:b,remote:y}=a,{audio:C}=y,T=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,x=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,N=(v=(m=b.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,k=tw({jitter:1e3*T,rtt:1e3*A,packetsLost:N,packetsReceived:x});return{jitter:T,rtt:A,mos:k,quality:nw(k),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new ow(n,e,r))});return{get isRunning(){return i},start:(r,a,l)=>U(this,void 0,void 0,function*(){if(i)w.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new iw(n,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0}catch(c){w.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>U(this,void 0,void 0,function*(){const a=s.getTimeline();$(F.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new sw(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const cf=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:gt.conferenceUpdate,call:t.calls[s],canvasInfo:aw(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:rt.LayerInfo},a);$(F.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:rt.LayoutInfo},a);$(F.Notification,l,t.uuid);break}}},aw=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Oh(e)},df=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],lw={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function ce(t,e){return`telnyx:call:${t}:${e}`}function uf(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function hf(t,e,n){const i=uf(ce(t,"new-call-start"));if(i===void 0)return{mode:e,direction:n,steps:[]};const s=[];for(const a of df){if(a==="new-call-start")continue;const l=uf(ce(t,a));l!==void 0&&s.push({label:lw[a]||a,fromStart:l-i})}s.sort((a,l)=>a.fromStart-l.fromStart);const o=[];let r=0;for(const a of s)o.push({label:a.label,fromStart:a.fromStart,delta:a.fromStart-r}),r=a.fromStart;return{mode:e,direction:n,steps:o}}function na(t){for(const e of df)try{performance.clearMarks(ce(t,e))}catch{w.warn("Clearing performance marks is failed")}}class gn{constructor(e,n,i,s,o){this.type=e,this.options=n,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>U(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void w.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(w.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return U(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,m=p==null?void 0:p.transport;m&&(d.dtlsState=m.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(m=>{m.type==="candidate-pair"&&m.state==="succeeded"&&(d.candidatePairState=m.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===m.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===m.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),m.type==="transport"&&(d.dtlsCipher=m.dtlsCipher,d.srtpCipher=m.srtpCipher,d.tlsVersion=m.tlsVersion,m.dtlsState&&(d.dtlsState=m.dtlsState))})}catch(p){w.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=je(eb);$(F.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=je(ib);$(F.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(ce(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(ce(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(ce(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void w.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;w.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(ce(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;w.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},w.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},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._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(w.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(w.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},gn.ICE_RESTART_TIMEOUT_MS),w.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(w.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(w.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===He.Offer}get isAnswer(){return this.type===He.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}get callEstablishmentTimings(){return this._callEstablishmentTimings}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(ce(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return U(this,void 0,void 0,function*(){performance.mark(ce(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Jt&&$(F.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(w.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{w.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),w.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):w.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(w.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":$(F.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(w.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){w.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?w.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(ce(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&Os(i,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(ce(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",n=this.isOffer?"outbound":"inbound",i=hf(this.options.id,e,n);this._callEstablishmentTimings=i,function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void w.info(`${l} No timing data collected`);const c=Math.max(...a.map(m=>m.label.length),4)+2,u=(m,v)=>{for(;m.length<v;)m+=" ";return m},d=(m,v)=>{for(;m.length<v;)m=" "+m;return m},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let m=0;m<h.length;m++)p+="-";w.info(`${l} Call establishment timing breakdown:`),w.info(`${l} ${h}`),w.info(`${l} ${p}`),w.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const m of a){const v=m.delta.toFixed(2)+"ms",b=m.fromStart.toFixed(2)+"ms";w.info(`${l} ${u(m.label,c)}${d(v,14)}${d(b,14)}`)}w.info(`${l} ${p}`)}(i),na(this.options.id)}createPeerConnection(){return U(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:He.Offer}),performance.mark(ce(this.options.id,"set-remote-description")),!this.instance))throw le(Vr);const n=!!this.options.receiveOnlyAudio&&!this.options.audio;let i=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>U(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),$(F.Error,{error:le($n(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>U(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),i=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return i=s,null})),!this.instance)throw le(Vr);if(!this.options.localStream&&!n)throw le(i?$n(i):Br,i??void 0);performance.mark(ce(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Mi(this.options.localStream)&&(w.info("Muting local audio tracks on start"),Fs(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(ce(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=je(nb);$(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=je(tb);$(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},gn.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return U(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw le(Vr);this.isDebugEnabled&&(this.statsReporter=rw(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Mi(i)){const o=i.getAudioTracks();let r=[...o];if(w.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{w.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],w.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{w.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=af(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&Os(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});w.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=af(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);w.info("Add transceiver",e,n)}}_createOffer(){return U(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,w.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(ce(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(ce(this.options.id,"set-local-description")),performance.mark(ce(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createOffer error:",e),e instanceof Jt?e:le(P0,e)}}})}_setRemoteDescription(e){return U(this,void 0,void 0,function*(){w.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(n){throw w.error("Peer _setRemoteDescription error:",n),le(vh,n)}})}_createAnswer(){return U(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return w.debug("Skipping negotiation, state:",this.instance.signalingState),w.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:He.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(ce(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(ce(this.options.id,"set-local-description")),performance.mark(ce(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createAnswer error:",e),e instanceof Jt?e:le(N0,e)}}})}_setLocalDescription(e){return U(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(n){throw w.error("Peer _setLocalDescription error:",n),le(F0,n)}})}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(Mi(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,U(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield Ns(s,a,Dt.AudioIn).catch(()=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield Ns(r,l,Dt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Ps(e)})}_isOffer(){return this.type===He.Offer}_isAnswer(){return this.type===He.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?1:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return w.info("RTC config",s),s}restartStatsReporter(){return U(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?w.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(w.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):w.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return U(this,void 0,void 0,function*(){na(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}gn.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,gn.ICE_RESTART_TIMEOUT_MS=15e3;const Bs=Jr;class ff{constructor(e,n){var i;this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Kr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const A in T.constraints)if(T.constraints.hasOwnProperty(A)&&T.constraints[A]!==C[A])return}T.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:u,remoteElement:d,options:h,mediaConstraints:{audio:p,video:m},ringtoneFile:v,ringbackFile:b}=e;this.options=Object.assign({},jh,{audio:p,video:m,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:s,localElement:u,remoteElement:d,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:b,debug:h.debug,debugOutput:h.debugOutput,trickleIce:h.trickleIce,prefetchIceCandidates:(i=h.prefetchIceCandidates)!==null&&i!==void 0?i:jh.prefetchIceCandidates,forceRelayCandidate:h.forceRelayCandidate,keepConnectionAliveOnSocketClose:h.keepConnectionAliveOnSocketClose,mutedMicOnStart:h.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=sf(this.options.ringtoneFile,"_ringtone"),this._ringback=sf(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
+ `).map(n=>n.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,n;return(n=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||n===void 0?void 0:n.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(n=>n.enabled===!0&&n.muted!==!0&&n.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,n;return!!this.options.forceRelayCandidate||!!this.recoveredCallId&&(n=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&n!==void 0&&n}invite(){return U(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=xt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(ce(this.id,"new-peer")),this.peer=new gn(He.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){w.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const n=e instanceof Jt?e:le(Ch,e instanceof Error?e:void 0);return $(F.Error,{error:n,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var n,i,s,o,r,a,l,c;return U(this,void 0,void 0,function*(){const u=((s=(i=(n=this.session).getActiveCalls)===null||i===void 0?void 0:i.call(n))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&w.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=je(ob);return $(F.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void w.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(ce(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=xt.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(ce(this.id,"new-peer")),this.peer=new gn(He.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){w.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Jt?d:le(Ch,d instanceof Error?d:void 0);return $(F.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){of(this._ringtone)}stopRingtone(){rf(this._ringtone)}playRingback(){of(this._ringback)}stopRingback(){rf(this._ringback)}hangup(e,n){var i,s,o,r,a,l;return U(this,void 0,void 0,function*(){const c=e||{},u=n!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),m=c.initiator||"app:call.hangup",v=this._state<z.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],w.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:m,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(z.Recovering),void this._finalize();if(this.setState(z.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new $b({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let y;try{yield Promise.race([this._execute(b),new Promise(C=>{y=setTimeout(()=>{w.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){w.error("telnyx_rtc.bye failed!",C);const T=le(V0,C);$(F.Error,{error:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{y&&clearTimeout(y)}}w.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)})}hold(){const e=new Ls({sessid:this.session.sessionid,action:jn.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Ls({sessid:this.session.sessionid,action:jn.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Ls({sessid:this.session.sessionid,action:jn.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new Qh({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},s=new Qh({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){w.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,Fs(this.options.localStream)}unmuteAudio(){w.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,ta(this.options.localStream)}_applyDesiredAudioMuteState(){w.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?Fs(this.options.localStream):ta(this.options.localStream)}toggleAudioMute(){w.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,n=this._desiredAudioMuted){var i,s,o;return U(this,void 0,void 0,function*(){const r=!!n,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return w.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void $(F.Warning,{warning:je(ab),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((i=this.options)===null||i===void 0?void 0:i.id)||this.id);let c;w.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Qr(l.track),localTracks:nf(this.options.localStream)});try{c=yield Ms({audio:{deviceId:{exact:e}}})}catch(h){const p=le($n(h),h);return void $(F.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=le($n(h),h);return $(F.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(m=>m.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,w.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Qr(l.track),localTracks:nf(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,qn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,qn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,qn(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield Ms({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Os(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){Fs(this.options.remoteStream)}undeaf(){ta(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,qn(e,"audio",null)}setBandwidthEncodingsMaxBps(e,n){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void w.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,s=i.getSenders();if(!s)return void w.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===n);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),w.info("Parameters: ",r),w.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{w.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>w.error(a))}else w.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[z.Hangup,z.Destroy,z.Purge].includes(this._state)}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n,i,s,o,r,a,l;switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:gt.callUpdate,call:this}),e){case z.Purge:w.info(`[${this.id}] Entering Purge state.`);break;case z.Active:if(performance.mark(ce(this.id,"call-active")),(n=this.peer)===null||n===void 0||n.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,w.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(w.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(i=this._callReportCollector)===null||i===void 0||i.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&ef(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new Zb,this._mediaDeviceCollector.logDevicesAtStart();break;case z.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case ie.Answer:if(performance.mark(ce(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case ie.Media:if(performance.mark(ce(this.id,"telnyx-rtc-media")),this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case ie.Display:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===xt.Inbound?xt.Outbound:xt.Inbound,c={type:gt[n],call:this,displayName:o,displayNumber:r,displayDirection:l};$(F.Notification,c,this.id)||$(F.Notification,c,this.session.uuid);break}case ie.Candidate:this._addIceCandidate(i);break;case ie.Info:case ie.Event:{const o=Object.assign(Object.assign({},i),{type:gt.generic,call:this});$(F.Notification,o,this.id)||$(F.Notification,o,this.session.uuid);break}case ie.Ringing:performance.mark(ce(this.id,"ringing")),this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case ie.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},i),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,n){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return w.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=n;this._dispatchConferenceUpdate({action:rt.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const m in s)p.push(Object.assign({callId:s[m][0],index:Number(m)},ks(s[m][1])));this._dispatchConferenceUpdate({action:rt.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:rt.Add,callId:o,index:r},ks(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:rt.Modify,callId:o,index:r},ks(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:rt.Delete,callId:o,index:r},ks(s)));break;case"clear":this._dispatchConferenceUpdate({action:rt.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:rt.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{w.error("ConfChat subscription error:",s)});Zr(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,cf(this.session,o)):w.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{w.error("ConfInfo subscription error:",s)});Zr(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){w.error(`Failed to ${e.action} on call ${this.id}`);const n=le(U0,e);return $(F.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,n={}){const i=new Ls(Object.assign(Object.assign({sessid:this.session.sessionid,action:jn.UpdateMedia,callID:this.options.id,sdp:e},n.trickle?{trickle:!0}:{}),{dialogParams:this.options}));w.info(`ICE restart: sending ${n.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(i).then(s=>U(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(w.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,n){var i,s,o;w.error(e,n),(i=this.peer)===null||i===void 0||i.finishIceRestart();const r=le(z0,n);$(F.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return U(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:He.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{performance.mark(ce(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this._state!==z.Held&&this.setState(z.Active)}).catch(i=>U(this,void 0,void 0,function*(){w.error("Call setRemoteDescription Error: ",i);const s=le(vh,i);$(F.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){w.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_warnIfOnlyHostIceCandidates(e){if(!(i=>{if(!i)return!1;const s=i.split(/\r?\n/).filter(o=>/^a=candidate:/i.test(o));return s.length>0&&s.every(o=>/\styp\s+host(?:\s|$)/i.test(o))})(e))return;const n=je(sb);w.warn(`[${this.id}] Warning ${n.code}: ${n.message}`),$(F.Warning,{warning:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onIceSdp(e){var n,i,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._isTerminatingOrTerminated())return;if(this.peer&&(this.peer.iceDone=!0),!e)return void w.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),this._warnIfOnlyHostIceCandidates(o),performance.mark(ce(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Bs}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case He.Offer:this.setState(z.Requesting),a=new Yh(l);break;case He.Answer:this._isRecovering||this.setState(z.Answering),a=this.options.attach===!0?new Jh(l):new Xh(l);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ce(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(c=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${r} error:`,c);const u=le(_h,c);$(F.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){w.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var n;if(this._isTerminatingOrTerminated())return;if(!e)return w.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:i,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${Bs}`};if(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)this._sendIceRestartModify(i,{trickle:!0});else{switch(s){case He.Offer:this.setState(z.Requesting),o=new Yh(r);break;case He.Answer:this._isRecovering||this.setState(z.Answering),o=this.options.attach===!0?new Jh(r):new Xh(r);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ce(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(a=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${s} error:`,a);const l=le(_h,a);$(F.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){w.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var n;if(this._isTerminatingOrTerminated())return;const{instance:i}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(i.localDescription),s)}e.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var n,i,s,o;this._isTerminatingOrTerminated()||(e.candidate&&e.candidate.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):(e.candidate===null&&this._warnIfOnlyHostIceCandidates((o=(s=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||s===void 0?void 0:s.localDescription)===null||o===void 0?void 0:o.sdp),this._sendEndOfCandidates()))}_sendIceCandidate(e){const n=new jb({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return w.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{w.debug("Successfully added ICE candidate:",e)}).catch(i=>{w.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Hb({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark(ce(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark(ce(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){e.onicecandidate=n=>{var i;this.options.trickleIce?this._onTrickleIce(n):!((i=this.peer)===null||i===void 0)&&i.iceDone||this._onIce(n)},e.onicegatheringstatechange=n=>{w.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(w.debug("Finished gathering candidates"),performance.mark(ce(this.id,"ice-gathering-completed")))},e.onicecandidateerror=n=>{var i;if(w.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&Os(i,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:gt.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),w.error(`Media error (${n}): ${i}`,e),$(F.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:gt.peerConnectionFailureError,error:e.error}),w.error("Peer connection failure error"),e.warning&&$(F.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:gt.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:gt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&($(F.Notification,e,this.id,!1)||$(F.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const n=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(n&&n!==this){const i=je(cb);return $(F.Warning,{warning:i,callId:this.id,activeCallId:n.id,sessionId:this.session.sessionid},this.session.uuid),w.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${n.id})`),!1}return!0}_init(){var e,n,i,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:m,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var y;this.options.id=d?d.toString():Vn(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(y=h,Object.keys(y).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Qt(F.MediaError,this._onMediaError,this.id),Qt(F.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Qt(F.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Is(m)&&Qt(F.Notification,m.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,T=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,x=this.session.options.debugLogLevel||"debug",N=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new fe({enabled:!0,interval:T,intermediateReportInterval:A},{enabled:!0,level:x,maxEntries:N}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=k=>{var E,f,_,g;$(F.Warning,{warning:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),k.code===jr&&this._state!==z.Held?(f=(E=this.session).reportNoRtp)===null||f===void 0||f.call(E,this.id,"inbound"):k.code===Eh&&this._state!==z.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((g=(_=this.session).reportNoRtp)===null||g===void 0||g.call(_,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const k={enabled:!0,flushIntervalMs:(n=this.session.options.callRecordingFlushIntervalMs)!==null&&n!==void 0?n:15e3,maxBufferBytes:(i=this.session.options.callRecordingMaxBufferBytes)!==null&&i!==void 0?i:$h,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},E={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new ze(k,E);const f=(l=this.session.connection)===null||l===void 0?void 0:l.host;f&&this._callRecorder._setHost(f),this._callRecorder.onWarning=_=>{$(F.Warning,{warning:_,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(z.Recovering):this.setState(z.New),w.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}getEstablishmentTimings(){var e,n,i;const s=(e=this.peer)===null||e===void 0?void 0:e.callEstablishmentTimings;if(s)return s;const o=!((n=this.options)===null||n===void 0)&&n.trickleIce&&!(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)?"trickle":"non-trickle";return hf(this.id,o,this.direction)}_finalize(){var e,n,i;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(n=this._callRecorder)===null||n===void 0||n.stop(),na(this.id),w.debug(`[${this.id}] Closing peer from _finalize`),(i=this.peer)===null||i===void 0||i.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;Oi(s),Oi(o),Zh(r,s),Zh(a,o),Lt(F.MediaError,null,this.id),Lt(F.PeerConnectionFailureError,null,this.id),Lt(F.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{w.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,n,i,s,o,r,a,l,c,u,d,h;const p=this.session.options,m=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},m?{anonymousLogin:{targetType:m.target_type,targetId:m.target_id,targetVersionId:m.target_version_id,targetParams:this._sanitizeClientOption(m.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(n=p.autoReconnect)===null||n===void 0||n,maxReconnectAttempts:(i=p.maxReconnectAttempts)!==null&&i!==void 0?i:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)!==null&&c!==void 0&&c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:n,username:i,credential:s})=>({urls:n,hasUsername:!!i,hasCredential:!!s}))}_sanitizeClientOption(e,n=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(n>=4)return"[truncated]";if(Array.isArray(e))return e.map(i=>this._sanitizeClientOption(i,n+1)).filter(i=>i!==void 0);if(typeof e=="object"){const i=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,n+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(i)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var n;if(!this._callReportCollector)return;const i=this.session.callReportId;if(!i)return void w.debug("Cannot flush intermediate report: call_report_id not available");const s=(n=this.session.connection)===null||n===void 0?void 0:n.host;if(!s)return void w.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Bs,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;w.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,i,s,a,l).catch(u=>{w.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,n,i,s;return U(this,void 0,void 0,function*(){if(!this._callReportCollector)return void w.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{w.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return w.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===xt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Bs,clientSummary:this._getClientSummary()},a=(n=this.session.connection)===null||n===void 0?void 0:n.host;if(!a)return void w.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw w.error("Failed to post call report",{error:c}),c}finally{(i=this._callReportCollector)===null||i===void 0||i.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),w.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),w.debug("Stats stopped")}}ff.setStateTelnyx=t=>{if(t){switch(t._state){case z.Recovering:t.state="recovering";break;case z.Requesting:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class mn extends ff{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new Jb(e,n)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const n=new Qb(e);this.session.connection.sendRawText(JSON.stringify(n.request))}}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return U(this,void 0,void 0,function*(){this.screenShare instanceof mn&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return U(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",()=>U(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});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)`},e);return this.screenShare=new mn(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return U(this,void 0,void 0,function*(){this.screenShare instanceof mn&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&ef(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>U(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+=`
117
117
  ${r.type}
118
- `,Object.keys(r).forEach(a=>{o.includes(a)||(n+=` ${a}: ${r[a]}
119
- `)}))}),w.info(n)}),2e3)}}class Vs extends fi{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>Vs.ACTIVE_CALL_STATE_NAMES.has(e.state))}_extractSafeCallIdentifiers(e){var i,n;const s={callId:e.id,state:e.state,direction:e.direction};!((i=e.options)===null||i===void 0)&&i.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),!((n=e.options)===null||n===void 0)&&n.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const i=this.getActiveCalls().filter(r=>r.id!==e);if(i.length===0)return;const n=je(lb),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};j(F.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),w.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${i.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return U(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return U(this,void 0,void 0,function*(){w.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return U(this,void 0,void 0,function*(){try{const n=yield Ps({audio:e,video:i});return Mn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){w.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(z.Purge),w.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){w.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(z.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(Wh(F.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return On().catch(e=>{const i=ae(Bi(e),e);return j(F.MediaError,i,this.uuid),[]})}getVideoDevices(){return On(Dt.Video).catch(e=>(j(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return On(Dt.AudioIn).catch(e=>{const i=ae(Bi(e),e);return j(F.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return On(Dt.AudioOut).catch(e=>(w.error("getAudioOutDevices",e),j(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return Ns(e,i,n)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(i=>U(void 0,void 0,void 0,function*(){const n=[],s=yield Ps({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<tf.length;r++){const[a,l]=tf[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return Mn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=ph(e,["micId","micLabel"]);return Yb(s),this._audioConstraints=yield((o,r,a,l)=>U(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield Ns(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const i=this.options.env==="development";this._iceServers=i?Sb:wb}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=An(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=An(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new Wb({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Gb({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=ea(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new qb({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=ea(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return gi.setStateTelnyx(e)}}Vs.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class pf{constructor(e,i){this.code=i,this.message=e}}class cw{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new Vb(e,i);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*(e=2,i=6,Math.floor(Math.random()*(i-e+1)+e));var e,i}handleMessage(e){var i,n,s,o,r,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:h,method:p,params:m={},voice_sdk_id:v}=e,b=m==null?void 0:m.callID,y=m==null?void 0:m.eventChannel,C=m==null?void 0:m.eventType,T=d.calls[b],A=(i=T==null?void 0:T.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),x=new Set(Object.keys(d.calls));if(Array.isArray(m==null?void 0:m.reattached_sessions)&&x.size){w.debug(`Reattach: active call IDs before cleanup check: [${Array.from(x).join(", ")}].`);const f=m.reattached_sessions.length===0,_=m.reattached_sessions.some(g=>x.has(g));if(f||!_)for(const g of Object.keys(d.calls)){const S=d.calls[g];w.debug(`Session not reattached — terminating active call ${g} `);const I=ae(Sh);j(F.Error,{error:I,callId:g,sessionId:d.sessionid},d.uuid),S.hangup({},!1)}}if(Array.isArray(m==null?void 0:m.reattached_sessions)&&d.sessionid){const f=Bh();if(f&&f.calls.length>0)if(f.sessionId!==d.sessionid)w.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${d.sessionid}) — ignoring all.`),hi();else{const _=new Set(m.reattached_sessions),g=[];for(const S of f.calls)try{if(_.has(S.id)){w.debug(`Recovery marker for call ${S.id} was reattached — keeping for Attach element restore.`),g.push(S);continue}w.info(`Recovery marker for call ${S.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=ae(Sh);j(F.Error,{error:I,callId:S.id,sessionId:d.sessionid,customHeaders:S.customHeaders},d.uuid)}catch(I){w.debug(`Recovery marker for a saved call failed to process (callId=${S==null?void 0:S.id}) — skipping: ${I instanceof Error?I.message:String(I)}`),g.push(S)}Vh(g,f.sessionId,f.storedAt)}}if(C==="channelPvtData")return this._handlePvtEvent(m.pvtData);const N=({recoveredCallId:f,forceRelayCandidateForRecovery:_,mutedMicOnStart:g,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M}={})=>{var R,P,O,L,V,$;const W={audio:!0,video:d.options.video,remoteSdp:m.sdp,destinationNumber:m.callee_id_number,remoteCallerName:m.caller_id_name,remoteCallerNumber:m.caller_id_number,callerName:m.callee_id_name,callerNumber:m.callee_id_number,attach:p===ie.Attach,mediaSettings:m.mediaSettings,debug:(R=d.options.debug)!==null&&R!==void 0&&R,debugOutput:(P=d.options.debugOutput)!==null&&P!==void 0?P:"socket",trickleIce:(O=d.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(L=d.options.prefetchIceCandidates)!==null&&L!==void 0&&L,forceRelayCandidate:typeof _=="boolean"?_:(V=d.options.forceRelayCandidate)!==null&&V!==void 0&&V,keepConnectionAliveOnSocketClose:($=d.options.keepConnectionAliveOnSocketClose)!==null&&$!==void 0&&$,mutedMicOnStart:g??d.options.mutedMicOnStart};b&&(W.id=b),m.telnyx_call_control_id&&(W.telnyxCallControlId=m.telnyx_call_control_id),m.telnyx_session_id&&(W.telnyxSessionId=m.telnyx_session_id),m.telnyx_leg_id&&(W.telnyxLegId=m.telnyx_leg_id),m.client_state&&(W.clientState=m.client_state),m.dialogParams&&m.dialogParams.custom_headers&&m.dialogParams.custom_headers.length&&(W.customHeaders=m.dialogParams.custom_headers),f&&(W.recoveredCallId=f),M&&(W.wasHeldBeforeRecovery=M),S!==void 0&&(W.remoteElement=S),I!==void 0&&(W.localElement=I),performance.mark(le(W.id,"new-call-start"));const q=new gi(d,W);return q.nodeId=this.nodeId,q},E=new zh(v),k=new Xr(v);switch(p){case ie.Answer:case ie.Display:case ie.Candidate:case ie.Ringing:case ie.Bye:case ie.Media:if(!b||!T)return void w.error(`Received ${p} for non existing call:`,m);T.handleMessage(e),this._ack(h,p);break;case ie.Ping:this.session.setPingReceived(),this.session.execute(k);break;case ie.Punt:d.options.keepConnectionAliveOnSocketClose&&A?(w.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(h,p)):(w.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case ie.Invite:{const g=N();g.direction=xt.Inbound,g.playRingtone(),g.setState(z.Ringing),this.session.emitMultipleActiveCallsWarning(g.id),this._ack(h,p);break}case ie.Attach:{const g=T||null;if(Object.keys(d.calls).length===0){let S,I;w.warn(`[${new Date().toISOString()}][${b}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${b}`);let M=!1,R=!1;const P=Bh();if(P&&P.sessionId===d.sessionid){const L=P.calls.find(V=>V!==null&&typeof V=="object"&&V.id===b);L&&(S=L.remoteElement,I=L.localElement,M=L.wasHeld===!0,typeof L.forceRelayCandidate=="boolean"&&(R=L.forceRelayCandidate),(S||I)&&w.info(`[${b}] Attach: restoring per-call media elements from recovery marker (remoteElement=${S??"<none>"}, localElement=${I??"<none>"}).`),typeof L.forceRelayCandidate=="boolean"&&w.info(`[${b}] Attach: restoring forceRelayCandidate=${L.forceRelayCandidate} from recovery marker.`))}const O=N({recoveredCallId:b,forceRelayCandidateForRecovery:R,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,p);break}if(g){const S=g.id,I=g.state==="held",M=g.shouldForceRelayCandidateForRecovery();M&&w.warn(`[${new Date().toISOString()}][${b}] Attach: forcing relay candidate for recovery`),w.info(`[${new Date().toISOString()}][${b}] Attach: recovering active call ${S}.`),g.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const R=N({recoveredCallId:S,forceRelayCandidateForRecovery:M,mutedMicOnStart:g.isAudioMuted,remoteElement:g.options.remoteElement,localElement:g.options.localElement,wasHeldBeforeRecovery:I});R.answer(),this.session.emitMultipleActiveCallsWarning(R.id),this._ack(h,p);break}w.warn(`Attach: callID ${b} does not match any active calls. `),j(F.Warning,{warning:je(hb),callId:b,params:m,sessionId:d.sessionid},d.uuid),this._ack(h,p);break}case ie.Event:case"webrtc.event":if(!y)return void w.error("Verto received an unknown event:",m);const f=d.relayProtocol,_=y.split(".")[0];d._existsSubscription(f,y)?j(f,m,y):y===d.sessionid?this._handleSessionEvent(m.eventData):d._existsSubscription(f,_)?j(f,m,_):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):j(F.Notification,m,d.uuid);break;case ie.Info:m.type=pt.generic,j(F.Notification,m,d.uuid);break;case ie.ClientReady:this.session.execute(E);break;case"ai_conversation":j(F.AIConversationMessage,{method:"ai_conversation",params:m,voice_sdk_id:v},d.uuid);break;default:{const g=Wr(e);if(g){switch(g){case Ue.REGISTER:case Ue.REGED:if(!this.isDuplicateGatewayState(g,[Ue.REGED,Ue.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,g===Ue.REGED&&this.session.resetReconnectAttempts();const S=(s=(n=e==null?void 0:e.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.call_report_id;S&&(d.callReportId=S,w.debug("Captured call_report_id from REGED:",S));const I=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.dc;I&&(d.dc=I);const M=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;M&&(d.region=M),w.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),m.type=pt.vertoClientReady,j(F.Ready,m,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const S=new pf("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=ae(wh,S);j(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(E)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:case Ue.TIMEOUT:if(!this.isDuplicateGatewayState(g,[Ue.FAILED,Ue.FAIL_WAIT,Ue.TIMEOUT])){const S=ae(W0,new Error(`Gateway state: ${g}`));if(j(F.Error,{error:S,sessionId:d.sessionid},d.uuid),d.options.skipLastVoiceSdkId=!0,w.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${d.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const I=new pf("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const M=ae($r,I);j(F.Error,{error:M,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const I=ae($r,new Error("Connection Retry Failed"));j(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(w.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(I=>{var M;return((M=I.peer)===null||M===void 0?void 0:M.instance)&&!I.signalingStateClosed}))return w.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();w.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:w.warn("GatewayState message unknown method:",e)}break}w.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&w.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},m={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=h||this._retrieveCallId(b,o);if(y&&i.calls.hasOwnProperty(y)){const C=i.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(T=>{T==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(m).catch(b=>{w.error("liveArray subscription error:",b);const y=ae($0,b);j(F.Error,{error:y,sessionId:i.sessionid},i.uuid)});Zr(v,o)&&p();break}case"conference-liveArray-part":{let p=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(p=i.calls[v]||null,v!==null){const b={type:pt.conferenceUpdate,action:ot.Leave,conferenceName:r,participantId:Number(u),role:d};j(F.Notification,b,v,!1)||j(F.Notification,b,i.uuid),p===null&&Lt(F.Notification,null,v)}}const m=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:m}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{w.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":cf(this.session,e);break;case"logo-info":{const i={type:pt.conferenceUpdate,action:ot.LogoInfo,logo:e.logoURL};j(F.Notification,i,this.session.uuid);break}}}}class dw extends Vs{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new cw(this),window.addEventListener("beforeunload",i=>{if(w.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return Uh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(w.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));try{const n=this.getActiveCalls().map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders,forceRelayCandidate:s.shouldForceRelayCandidateForRecovery()};return s.state==="held"&&(o.wasHeld=!0),typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(this.getActiveCalls().forEach(s=>{if(s.flushIntermediateCallReport)try{w.debug(`beforeunload: flushing call report for ${s.id}.`),s.flushIntermediateCallReport({type:"page-unload"})}catch(o){w.debug(`beforeunload: failed to flush call report for ${s.id}: ${o instanceof Error?o.message:String(o)}`)}}),!this.sessionid||n.length===0)return w.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void hi();w.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),Vh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];w.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${s.join(", ")}]): ${n instanceof Error?n.message:String(n)}`)}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(w.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),zr(this.sessionid))})}validateOptions(){return As(this.options)||Rn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(B0,void 0,"Error: destinationNumber is required");const i=new gi(this,e);return e.id||w.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(le(i.id,"new-call-start")),i.invite(),i}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!Rn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return U(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),As(this.options)?this.handleLoginOnSocketOpen():Rn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}function gf(t){return{options:t,statsSamples:[]}}function uw(t){var e,i;const n=(i=(e=t.call)===null||e===void 0?void 0:e.peer)===null||i===void 0?void 0:i.instance,s=t.statsSamples[t.statsSamples.length-1];if(!n||!s)return;const o=function(a,l){var c;const u=[],d=new Set,h=new Map,p=new Map,m={host:0,srflx:0,prflx:0,relay:0};a.forEach(k=>{switch(k.type){case"local-candidate":{const f=k;m[f.candidateType]++,p.set(f.id,f);break}case"remote-candidate":{const f=k;h.set(f.id,f);break}case"candidate-pair":{const f=k;u.push(f);break}case"transport":{const f=k;typeof f.selectedCandidatePairId=="string"&&d.add(f.selectedCandidatePairId);break}}});const v=function(k,f,_,g){var S,I;const M=k.find(V=>f.has(V.id)),R=k.find(V=>V.selected===!0),P=k.find(V=>V.nominated===!0&&V.state==="succeeded"),O=k.filter(V=>V.state==="succeeded"),L=(I=(S=M??R)!==null&&S!==void 0?S:P)!==null&&I!==void 0?I:O.length===1?O[0]:void 0;return L?Object.assign(Object.assign({},L),{localCandidate:_.get(L.localCandidateId),remoteCandidate:g.get(L.remoteCandidateId)}):null}(u,d,p,h),b=m.relay>0,y=m.srflx===0&&m.relay===0&&m.prflx===0,C=l.iceGatheringState,T=l.iceConnectionState,A=C==="complete",x=((c=v==null?void 0:v.localCandidate)===null||c===void 0?void 0:c.candidateType)==="relay",{hasMultipleNetworkInterfaces:N,vpnDetected:E}=function(k){if(k.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const f=Array.from(k.values());return{hasMultipleNetworkInterfaces:new Set(f.filter(_=>_.candidateType==="host").map(_=>_.address)).size>=2,vpnDetected:f.some(_=>_.networkType==="vpn")}}(p);return{candidateGatheringCompleted:A,gatheringComplete:A,candidateCounts:m,candidates:Array.from(p.values()),hasRelayCandidate:b,onlyHostCandidates:y,isTurnRequired:x,hasMultipleNetworkInterfaces:N,vpnDetected:E,hasSelectedPair:!!v,selectedPair:v??void 0,iceGatheringState:C,iceConnectionState:T}}(s,n),r=n.getConfiguration().iceServers;return r&&(o.serverCandidateComparison=function(a,l){var c,u;if(!a||a.length===0)return;const d=[];for(const h of a){const p=Array.isArray(h.urls)?h.urls:[h.urls],m=l.filter(y=>p.some(C=>hw(y.url,C,y.protocol))),v=(u=(c=m[0])===null||c===void 0?void 0:c.candidateType)!==null&&u!==void 0?u:null,b=m.length>0;d.push({urls:h.urls,hasCandidates:b,candidateType:v,candidates:m,candidateCount:m.length})}return d}(r,o.candidates)),o}function mf(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(e=>/^turns?:/i.test(e))}function vf(t){var e;let i=t;const n=i.match(/^([a-z]+:)(\/\/)?([^@]*@)(.+)$/i);n&&(i=n[1]+((e=n[2])!==null&&e!==void 0?e:"")+n[4]);const s=i.indexOf("?transport=");return s!==-1&&(i=i.substring(0,s)),i}function _f(t){const e=t.indexOf("?transport=");if(e===-1)return;const i=t.substring(e+11).toLowerCase(),n=i.indexOf("&");return n===-1?i:i.substring(0,n)}function hw(t,e,i){var n;if(!t||!e||vf(t)!==vf(e))return!1;const s=_f(e);if(s===void 0)return!0;const o=(n=_f(t))!==null&&n!==void 0?n:i==null?void 0:i.toLowerCase();return o===void 0||o===s}const na=2e3,fw=100,yf=.01,pw="To check your microphone, we will be recorded your voice for a few seconds and played back to you so you can hear how it sounds.";function gw(){var t;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((t=navigator.mediaDevices)===null||t===void 0?void 0:t.getUserMedia)!="function")return{report:{activeCapturePerformed:!1,captureError:"not_supported",captureErrorMessage:"getUserMedia is not available in this environment"},stream:void 0};try{return{report:{deviceAvailable:!0},stream:yield navigator.mediaDevices.getUserMedia({audio:!0})}}catch(e){const{captureError:i,captureErrorMessage:n}=function(s){const o=s&&typeof s=="object"&&"name"in s?String(s.name):"",r=s instanceof Error?s.message:String(s);return o==="NotAllowedError"||o==="PermissionDeniedError"||o==="SecurityError"?{captureError:"permission_denied",captureErrorMessage:`Microphone permission denied: ${r}`}:o==="NotFoundError"||o==="DevicesNotFoundError"||o==="OverconstrainedError"||o==="ConstraintNotSatisfiedError"?{captureError:"no_device",captureErrorMessage:`No microphone device found: ${r}`}:o==="TypeError"?{captureError:"not_supported",captureErrorMessage:`Microphone capture is not supported: ${r}`}:{captureError:"unknown",captureErrorMessage:r}}(e);return{report:{activeCapturePerformed:!1,captureError:i,captureErrorMessage:n,deviceAvailable:!1},stream:void 0}}})}function mw(t,e,i){return U(this,void 0,void 0,function*(){if(typeof AudioContext>"u")return null;let n,s,o;try{n=new AudioContext,s=n.createAnalyser(),o=n.createMediaStreamSource(t),s.fftSize=2048,o.connect(s);const r=new Float32Array(s.fftSize),a=Date.now()+e;let l=0,c=0,u=0;for(;Date.now()<a;){s.getFloatTimeDomainData(r);let d=0;for(const m of r)d+=m*m;const h=Math.sqrt(d/r.length);l=Math.max(l,h),c+=h,u+=1;const p=a-Date.now();p>0&&(yield new Promise(m=>setTimeout(m,Math.min(fw,p))))}return{audioLevel:l,audioDetected:l>=i,audioLevelStats:{peak:l,average:u>0?c/u:0,samples:u}}}catch{return null}finally{try{o==null||o.disconnect(),s==null||s.disconnect(),yield n==null?void 0:n.close()}catch{}}})}function vw(t,e){return U(this,void 0,void 0,function*(){if(typeof MediaRecorder<"u")try{const i=["audio/webm;codecs=opus","audio/webm"].find(r=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(r)),n=i?new MediaRecorder(t,{mimeType:i}):new MediaRecorder(t),s=[],o=Date.now();return yield new Promise(r=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(c),clearTimeout(u),r(d))};n.ondataavailable=({data:d})=>{d.size>0&&s.push(d)},n.onerror=()=>l(),n.onstop=()=>U(this,void 0,void 0,function*(){const d=n.mimeType||i||"audio/webm",h=yield(p=new Blob(s,{type:d}),new Promise(m=>{try{const v=new FileReader;v.onloadend=()=>m(typeof v.result=="string"?v.result:void 0),v.onerror=()=>m(void 0),v.readAsDataURL(p)}catch{m(void 0)}}));var p;l(h?{recordingDataUrl:h,recordingMimeType:d,recordingDurationMs:Date.now()-o}:void 0)});const c=setTimeout(()=>{try{n.state!=="inactive"&&n.stop()}catch{l()}},e),u=setTimeout(()=>l(),e+1e3);n.start()})}catch{return}})}function bf(t){var e,i;return U(this,void 0,void 0,function*(){const n=function(p){var m,v;const b=p&&typeof p=="object"?p:void 0;return{sampleDurationMs:Math.max(0,(m=b==null?void 0:b.sampleDurationMs)!==null&&m!==void 0?m:na),silenceThreshold:Math.min(1,Math.max(0,(v=b==null?void 0:b.silenceThreshold)!==null&&v!==void 0?v:yf)),record:(b==null?void 0:b.record)===!0,warnOnRecording:b==null?void 0:b.warnOnRecording}}(t.options.microphone),s=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((p=navigator.permissions)===null||p===void 0?void 0:p.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}})}(),{report:o,stream:r}=yield gw(),a=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator<"u"&&typeof((p=navigator.mediaDevices)===null||p===void 0?void 0:p.enumerateDevices)=="function")try{const m=(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:v})=>v==="audioinput").map(({deviceId:v,label:b})=>({deviceId:v||"",label:b||"",kind:"audioinput"}));return{devices:m,deviceCount:m.length,deviceAvailable:m.length>0,labelsAccessible:m.some(({label:v})=>v.length>0)}}catch{return}})}(),l=r?"granted":o.captureError==="permission_denied"?"denied":s,c={currentPermissionState:l,isPermissionGrantedCurrently:l==="granted",isGetUserMediaFailed:!r,deviceAvailable:(a==null?void 0:a.deviceAvailable)||o.deviceAvailable||!1,deviceCount:(e=a==null?void 0:a.deviceCount)!==null&&e!==void 0?e:0,devices:(i=a==null?void 0:a.devices)!==null&&i!==void 0?i:[],labelsAccessible:a==null?void 0:a.labelsAccessible,captureError:o.captureError,captureErrorMessage:o.captureErrorMessage,activeCapturePerformed:o.activeCapturePerformed};if(r)try{const p=yield function(m,v,b){var y,C,T;return U(this,void 0,void 0,function*(){m.activeCapturePerformed=!0,m.recordingPerformed=b.record,b.record&&b.warnOnRecording&&b.warnOnRecording(pw);const[A,x]=yield Promise.all([mw(v,(y=b.sampleDurationMs)!==null&&y!==void 0?y:na,(C=b.silenceThreshold)!==null&&C!==void 0?C:yf),b.record?vw(v,(T=b.sampleDurationMs)!==null&&T!==void 0?T:na):Promise.resolve(void 0)]);return A&&(m.audioLevel=A.audioLevel,m.audioDetected=A.audioDetected,m.audioLevelStats=A.audioLevelStats),x&&(m.recordingDataUrl=x.recordingDataUrl,m.recordingMimeType=x.recordingMimeType,m.recordingDurationMs=x.recordingDurationMs,m.recordingPerformed=!0),x})}(c,r,n);p&&(c.playbackPerformed=yield(u=p.recordingDataUrl,d=p.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise(m=>{let v,b=!1;const y=setTimeout(()=>C(!1),d),C=T=>{b||(b=!0,clearTimeout(y),v&&(v.onended=null,v.onerror=null,v.paused||v.pause(),v.src=""),m(T))};try{v=new Audio(u),v.onended=()=>C(!0),v.onerror=()=>C(!1),v.play().catch(()=>C(!1))}catch{C(!1)}})))}finally{try{r.getTracks().forEach(p=>p.stop())}catch{}}var u,d;const h=function(p){const m=[],v=(y,C)=>m.push({code:y,message:C,source:"microphone"});p.currentPermissionState==="denied"&&v("microphone_permission_denied","Microphone permission has been denied by the user."),p.deviceAvailable===!1&&v("microphone_no_device","No audio input device is available.");const b=p.captureError?{permission_denied:["microphone_capture_permission_denied","Active microphone capture was denied permission."],no_device:["microphone_capture_no_device","No microphone device was found for active capture."],not_supported:["microphone_capture_not_supported","Active microphone capture is not supported."],unknown:["microphone_capture_failed","Active microphone capture failed."]}[p.captureError]:void 0;return b&&v(...b),p.activeCapturePerformed&&p.audioDetected===!1&&v("microphone_silent","No audio was detected above the silence threshold during active capture."),m}(c);return h.length>0&&(c.reasons=h),Object.keys(c).length>0?c:void 0})}const sa=300,oa=500,ra=30,aa=100,la=.02,ca=.05,$s=8e3;function gt(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function da(t){const e=t.filter(o=>gt(o)!==void 0);if(e.length===0)return;let i=1/0,n=-1/0,s=0;for(const o of e)o<i&&(i=o),o>n&&(n=o),s+=o;return{min:i,max:n,average:s/e.length}}function ua(t){var e,i;const n=[],s=new Set;t.forEach(r=>{const a=r;n.push(a),a.type==="transport"&&typeof a.selectedCandidatePairId=="string"&&s.add(a.selectedCandidatePairId)});const o=n.filter(r=>r.type==="candidate-pair");return(i=(e=o.find(r=>s.has(r.id)))!==null&&e!==void 0?e:o.find(r=>r.selected===!0||r.nominated===!0&&r.state==="succeeded"))!==null&&i!==void 0?i:o.find(r=>r.state==="succeeded")}function Gi(t,e){let i=0,n=!1;for(const s of t){const o=gt(s[e]);o!==void 0&&(i+=o,n=!0)}return n?i:void 0}function qi(t,e,i=!1){const n=[];return t.forEach(s=>{const o=s;o.type!==e||i&&!function(r){var a;const l=(a=r.kind)!==null&&a!==void 0?a:r.mediaType;return l===void 0||l==="audio"}(o)||n.push(o)}),n}function _w(t,e){const i=t.packets===void 0?e.packets!==void 0:e.packets!==void 0&&e.packets>t.packets,n=t.bytes===void 0?e.bytes!==void 0:e.bytes!==void 0&&e.bytes>t.bytes;return i||n}function wf(t,e){if(t!==void 0&&e!==void 0)return gt(e-t)}function Sf(t,e){var i,n;if(!t.some(c=>qi(c,`${e}-rtp`,!0).length>0))return;const s=t.map(c=>function(u,d){const h=qi(u,`${d}-rtp`,!0);return d==="outbound"?{packets:Gi(h,"packetsSent"),bytes:Gi(h,"bytesSent")}:{packets:Gi(h,"packetsReceived"),bytes:Gi(h,"bytesReceived")}}(c,e)).filter(({packets:c,bytes:u})=>c!==void 0||u!==void 0),o=(i=s[0])!==null&&i!==void 0?i:{},r=(n=s[s.length-1])!==null&&n!==void 0?n:{},a=wf(o.packets,r.packets),l=wf(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&_w(o,r)},r.packets!==void 0?{packets:r.packets}:{}),r.bytes!==void 0?{bytes:r.bytes}:{}),a!==void 0?{packetsDelta:a}:{}),l!==void 0?{bytesDelta:l}:{})}function Cf(t,e){const i=[];for(const n of t)for(const s of qi(n,e,!0)){const o=gt(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&i.push(r)}}return i}function Tf(t){const e=Gi(t,"packetsReceived"),i=Gi(t,"packetsLost"),n=t.map(r=>gt(r.fractionLost)).filter(r=>r!==void 0&&r>=0&&r<=1),s=n.length>0?Math.max(...n):void 0,o=e!==void 0&&i!==void 0?e+i:void 0;return{packetsReceived:e,packetsLost:i,packetLossFraction:s??(i!==void 0&&o!==void 0&&o>0?i/o:void 0)}}function kf(t){let e;return t.forEach(i=>{e===void 0&&(e=gt(i.timestamp))}),e}function yw(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,i=Sf(e,"inbound"),n=Sf(e,"outbound"),s=da(function(p){var m;const v=[];for(const b of p){let y=!1;const C=qi(b,"remote-inbound-rtp",!0);for(const T of C){const A=gt(T.roundTripTime);if(A!==void 0){const x=1e3*A;x>=0&&(v.push(x),y=!0)}}if(!y){const T=gt((m=ua(b))===null||m===void 0?void 0:m.currentRoundTripTime);if(T!==void 0){const A=1e3*T;A>=0&&v.push(A)}}}return v}(e)),o=(r=da(Cf(e,"inbound-rtp")),a=da(Cf(e,"remote-inbound-rtp")),(r==null?void 0:r.average)===void 0?a:(a==null?void 0:a.average)===void 0?r:a.average>r.average?a:r);var r,a;const l=function(p,m,v){var b;if(p.length===0)return;const y=p[p.length-1],C=qi(y,"inbound-rtp",!0),T=qi(y,"remote-inbound-rtp",!0),A=function(_,g){return _.packetLossFraction===void 0?g:g.packetLossFraction===void 0?_:g.packetLossFraction>_.packetLossFraction?g:_}(Tf(C),Tf(T));let x=v==null?void 0:v.packets,N=(b=A.packetsReceived)!==null&&b!==void 0?b:m==null?void 0:m.packets;const E=A.packetsLost,k=A.packetLossFraction,f=ua(y);return x===void 0&&(x=gt(f==null?void 0:f.packetsSent)),N===void 0&&(N=gt(f==null?void 0:f.packetsReceived)),x!==void 0||N!==void 0||E!==void 0?{packetsSent:x,packetsReceived:N,packetsLost:E,packetLossFraction:k}:void 0}(e,i,n),c=function(p,m,v){if(p.length===0)return;const b=p[p.length-1];let y=v==null?void 0:v.bytes,C=m==null?void 0:m.bytes;const T=ua(b);return y===void 0&&(y=gt(T==null?void 0:T.bytesSent)),C===void 0&&(C=gt(T==null?void 0:T.bytesReceived)),y!==void 0||C!==void 0?{bytesSent:y,bytesReceived:C}:void 0}(e,i,n),u=function(p,m,v){if(p.length<2)return;const b=p[0],y=p[p.length-1],C=kf(b),T=kf(y);if(C===void 0||T===void 0)return;const A=(T-C)/1e3;if(A<=0)return;const x=(v==null?void 0:v.bytesDelta)!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/A:void 0,N=(m==null?void 0:m.bytesDelta)!==void 0&&m.bytesDelta>=0?8*m.bytesDelta/A:void 0;return x!==void 0||N!==void 0?{outbound:x,inbound:N}:void 0}(e,i,n),d=function(p,m,v){let b=!1,y="good";return(p==null?void 0:p.average)!==void 0&&(b=!0,p.average>=oa?y="poor":p.average>=sa&&y==="good"&&(y="fair")),(m==null?void 0:m.average)!==void 0&&(b=!0,m.average>=aa?y="poor":m.average>=ra&&y==="good"&&(y="fair")),(v==null?void 0:v.packetLossFraction)!==void 0&&(b=!0,v.packetLossFraction>=ca?y="poor":v.packetLossFraction>=la&&y==="good"&&(y="fair")),b?y:"unknown"}(s,o,l),h=function(p,m,v,b){const y=[];return(p==null?void 0:p.average)!==void 0&&(p.average>=oa?y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (poor: ≥${oa}ms threshold)`,source:"network"}):p.average>=sa&&y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (degraded: ≥${sa}ms threshold)`,source:"network"})),(m==null?void 0:m.average)!==void 0&&(m.average>=aa?y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (poor: ≥${aa}ms threshold)`,source:"network"}):m.average>=ra&&y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (degraded: ≥${ra}ms threshold)`,source:"network"})),(v==null?void 0:v.packetLossFraction)!==void 0&&(v.packetLossFraction>=ca?y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (poor: ≥${100*ca}% threshold)`,source:"network"}):v.packetLossFraction>=la&&y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (degraded: ≥${100*la}% threshold)`,source:"network"})),b&&(b.outbound!==void 0&&b.outbound<$s&&y.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(b.outbound)} bps (<${$s} bps threshold)`,source:"network"}),b.inbound!==void 0&&b.inbound<$s&&y.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(b.inbound)} bps (<${$s} bps threshold)`,source:"network"})),y}(s,o,l,t.options.mode==="network-only"?void 0:u);return{quality:d,rtt:s,jitter:o,packets:l,bytes:c,bitrate:u,inbound:i,outbound:n,reasons:h.length>0?h:void 0}}function Ef(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ha(t,e){return t.find(i=>i.label===e)}class bw{constructor(){this.startedAtMonoMs=If()}build(e={}){var i,n;const s={};try{const o=(n=(i=e.call)===null||i===void 0?void 0:i.getEstablishmentTimings)===null||n===void 0?void 0:n.call(i);if(o){s.callEstablishment={mode:o.mode,direction:o.direction,steps:o.steps.map(d=>Object.assign({},d))};const r=ha(o.steps,"ICE candidate gathering started"),a=ha(o.steps,"All ICE candidates gathered"),l=Ef(r&&a?a.fromStart-r.fromStart:void 0);l!==void 0&&(s.iceGatheringMs=l);const c=ha(o.steps,"First server-reflexive/relay candidate found"),u=Ef(r&&c?c.fromStart-r.fromStart:void 0);u!==void 0&&(s.firstNonHostCandidateMs=u)}}catch{}return s}complete(e){const i=If()-this.startedAtMonoMs;Number.isFinite(i)&&i>=0&&(e.totalMs=i)}}function If(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function fa(){return new bw}const $t={NoCandidates:"ice_no_candidates",OnlyHostCandidates:"ice_only_host_candidates",GatheringTimeout:"ice_gathering_timeout",NoSelectedPair:"ice_no_selected_pair",TurnRequired:"ice_turn_required",ServerNoCandidates:"ice_server_no_candidates",MultipleInterfaces:"ice_multiple_interfaces",VpnDetected:"ice_vpn_detected"},Pn={LowBitrate:"network_low_bitrate",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},pa={CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureFailed:"microphone_capture_failed"},mi=()=>({reasons:[],warnings:[]}),Af={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function Xe(t,e){return t?e?Af[t]>=Af[e]?t:e:t:e}function rt(t,e,i){return{code:t,message:e,source:i}}function Nn(t,e,i){return{code:t,message:e,source:i}}function Rf(t,e=!1){var i;if(!t)return mi();const n=mi(),{reasons:s,warnings:o}=n,r=t.candidates.length>0;r||(s.push(rt($t.NoCandidates,"No ICE candidates were gathered.","ice")),n.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(Nn($t.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(rt($t.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),n.verdict=Xe(n.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(rt($t.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),n.verdict=Xe(n.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(rt($t.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),n.verdict=Xe(n.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(rt($t.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),n.verdict=Xe(n.verdict,"degraded"));const l=((i=t.serverCandidateComparison)!==null&&i!==void 0?i:[]).filter(({hasCandidates:c})=>!c);return l.length>0&&o.push(Nn($t.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(Nn($t.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(Nn($t.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!n.verdict&&r&&(n.verdict="ready"),n}function ww(t){if(t.established&&!t.error)return mi();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[rt("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function xf(t,e=!0){var i;if(!t)return mi();const n=mi(),{reasons:s,warnings:o}=n,r=e?t.reasons:(i=t.reasons)===null||i===void 0?void 0:i.filter(({code:l})=>l!==Pn.LowBitrate);switch(r!=null&&r.length&&(s.push(...r),n.verdict="degraded"),t.quality){case"poor":s.push(rt(Pn.PoorQuality,"Network quality is poor.","network")),n.verdict=Xe(n.verdict,"blocked");break;case"fair":o.push(Nn(Pn.FairQuality,"Network quality is fair.","network")),n.verdict=Xe(n.verdict,"degraded");break;case"good":n.verdict=Xe(n.verdict,"ready")}const a=[t.inbound,t.outbound].filter(l=>!!l);if(e&&a.length>0){const l=a.filter(({flowing:c})=>c).length;a.length===2&&l===2?n.verdict=Xe(n.verdict,"ready"):l>0?(s.push(rt(Pn.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),n.verdict=Xe(n.verdict,"blocked")):(s.push(rt(Pn.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),n.verdict=Xe(n.verdict,"blocked"))}return n}function Sw(t){var e;if(!t)return mi();const i=mi();!((e=t.reasons)===null||e===void 0)&&e.length&&i.reasons.push(...t.reasons);const n=t.currentPermissionState==="denied"||t.isPermissionGrantedCurrently===!1||t.captureError==="permission_denied",s=t.deviceAvailable===!1||t.captureError!==void 0,o=t.activeCapturePerformed===!0&&t.audioDetected===!1;return n?i.verdict="permission_denied":s?i.verdict="blocked":o?i.verdict="degraded":(t.activeCapturePerformed===!0&&t.audioDetected===!0||t.activeCapturePerformed!==!0&&t.isPermissionGrantedCurrently===!0&&t.deviceAvailable!==!1)&&(i.verdict="ready"),i}class ga{constructor(e){this.options=e}run(){return U(this,void 0,void 0,function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(gf(this.options));default:return this.runFull()}})}runFull(){return U(this,void 0,void 0,function*(){const e=yield this.runTest({diagnosticOptions:this.options,modules:{ice:!!this.options.ice,network:!!this.options.network,microphone:!!this.options.microphone},autoHangup:this.options.autoHangup!==!1});return e.setupFailed?e.error?zi({callId:e.callId,timings:e.timings},e.error):{version:1,verdict:"inconclusive",reasons:[{code:"call_setup_timeout",message:"The diagnostic call did not reach the established state",source:"diagnostic"}],callId:e.callId,timings:e.timings}:zi({ice:e.ice,network:e.network,microphone:e.microphone,timings:e.timings,callId:e.callId,raw:e.raw},e.error)})}runNetworkOnly(){var e,i,n;return U(this,void 0,void 0,function*(){const s=this.options.client.iceServers,o=function(c){const u=[];for(const d of c)(Array.isArray(d.urls)?d.urls:[d.urls]).forEach(h=>{u.push(Object.assign(Object.assign({},d),{urls:h}))});return u}((n=(i=(e=this.options.rtcConfig)===null||e===void 0?void 0:e.iceServers)!==null&&i!==void 0?i:s)!==null&&n!==void 0?n:[]);let r=[];const a=fa();let l;try{return r=yield Promise.all(o.map(c=>U(this,void 0,void 0,function*(){const u=yield this.runTest({diagnosticOptions:Object.assign(Object.assign({},this.options),{durationMs:3e3,statsSampleIntervalMs:500,rtcConfig:Object.assign(Object.assign({},this.options.rtcConfig),{iceServers:[c]})}),iceServers:[c],forceRelayCandidate:mf(c),modules:{ice:!0,network:!!this.options.network,microphone:!1},autoHangup:!0}),d=function(h){if(h.error)return h.error.message;if(h.setupFailed)return"The diagnostic call did not reach the established state";if(!h.ice)return"No ICE report was produced";if(h.ice.candidates.length===0)return"No ICE candidates were gathered";if(!h.ice.hasSelectedPair)return"No ICE candidate pair was selected"}(u);return{server:c,established:d===void 0,callId:u.callId,ice:u.ice,network:u.network,timings:u.timings,error:d}}))),l=zi({serverTests:r,timings:a.build()},void 0,{networkOnly:!0}),l}catch(c){return l=zi({timings:a.build()},js(c),{networkOnly:!0}),l}finally{l!=null&&l.timings&&a.complete(l.timings)}})}runTest(e){return U(this,void 0,void 0,function*(){const i=gf(e.diagnosticOptions),n=fa();let s,o,r,a=!1;const l=c=>{c.callId===(s==null?void 0:s.id)&&(o=js(c.error))};e.diagnosticOptions.client.on("telnyx.error",l);try{if(s=this.createDiagnosticCall(e.diagnosticOptions,e.iceServers,e.forceRelayCandidate),i.call=s,a=yield this.waitForCallEstablishment(s),!a)return r={established:!1,setupFailed:!0,callId:s.id,timings:n.build({call:s}),error:o},r;yield this.collectSamples(s,i);const c=e.modules.ice?uw(i):void 0,u=e.modules.network?yw(i):void 0,d=e.modules.microphone?yield bf(i):void 0;return r={established:!0,setupFailed:!1,callId:s.id,ice:c,network:u,microphone:d,timings:n.build({call:s}),raw:{samples:i.statsSamples.length?i.statsSamples:void 0}},r}catch(c){return i.error=js(c),r={established:a,setupFailed:!1,callId:s==null?void 0:s.id,timings:n.build({call:s}),error:i.error},r}finally{if(e.diagnosticOptions.client.off("telnyx.error",l),s&&e.autoHangup)try{yield s.hangup()}catch{}r!=null&&r.timings&&n.complete(r.timings)}})}runMicrophoneOnly(e){return U(this,void 0,void 0,function*(){const i=fa();let n;try{return n=zi({microphone:this.options.microphone?yield bf(e):void 0,timings:i.build()},e.error),n}catch(s){return e.error=js(s),n=zi({timings:i.build()},e.error),n}finally{n!=null&&n.timings&&i.complete(n.timings)}})}waitForCallEstablishment(e){return U(this,void 0,void 0,function*(){const i=Date.now()+3e4,n=()=>{var s,o;return e.state==="active"&&((o=(s=e.peer)===null||s===void 0?void 0:s.instance)===null||o===void 0?void 0:o.connectionState)==="connected"};for(;Date.now()<i;){if(n())return!0;if(["done","hangup","destroy"].includes(e.state))return!1;yield Df(500)}return n()})}createDiagnosticCall(e,i,n=!1){const{client:s,destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c,rtcConfig:u}=e;return s.newCall({destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c===!0,iceServers:i??(u==null?void 0:u.iceServers),forceRelayCandidate:n})}collectSamples(e,i){var n,s,o;return U(this,void 0,void 0,function*(){const r=(n=i.options.durationMs)!==null&&n!==void 0?n:5e3,a=(s=i.options.statsSampleIntervalMs)!==null&&s!==void 0?s:1e3,l=Date.now()+r;for(;Date.now()<l;){try{const c=yield(o=e.peer.instance)===null||o===void 0?void 0:o.getStats();c&&i.statsSamples.push(c)}catch{}yield Df(Math.min(a,Math.max(0,l-Date.now())))}})}}function zi(t,e,i){const{verdict:n,reasons:s,warnings:o}=function(r,a,l={}){var c,u;const d=[Rf(r.ice),xf(r.network),Sw(r.microphone),...((c=r.serverTests)!==null&&c!==void 0?c:[]).flatMap(v=>[Rf(v.ice,l.networkOnly&&mf(v.server)),xf(v.network,!l.networkOnly),ww(v)])],h=d.flatMap(v=>v.reasons),p=d.flatMap(v=>v.warnings);let m=d.reduce((v,b)=>Xe(v,b.verdict),void 0);if(l.networkOnly&&!((u=r.serverTests)===null||u===void 0)&&u.length){const v=r.serverTests.filter(b=>b.established&&!b.error).length;v===0?m="blocked":v<r.serverTests.length&&(m="degraded")}if(a)switch(a.code){case yh:h.push(rt(pa.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),m=Xe(m,"permission_denied");break;case bh:h.push(rt(pa.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;case Br:h.push(rt(pa.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;default:h.push(rt("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),m=Xe(m,"blocked")}return{verdict:m??"inconclusive",reasons:h,warnings:p}}(t,e,i);return Object.assign(Object.assign({},t),{version:1,verdict:n??"inconclusive",reasons:s.length?s:void 0,warnings:o.length?o:void 0})}function js(t){return t instanceof Error?t:new Error(String(t))}function Df(t){return new Promise(e=>setTimeout(e,t))}const Lf="+1-872-231-5806";class Cw extends dw{constructor(e){super(e),w.info(`SDK version: ${Kh}`)}newCall(e){return super.newCall(e)}runPreCall(e={}){var i,n;return U(this,void 0,void 0,function*(){const s={client:this,destinationNumber:(i=e.destinationNumber)!==null&&i!==void 0?i:Lf,durationMs:e.durationMs,ice:!0,network:!0,microphone:!0,mode:"full",rtcConfig:{iceServers:(n=e.iceServers)!==null&&n!==void 0?n:this.iceServers}};return new ga(s).run()})}runNetworkCheck(e={}){var i;return U(this,void 0,void 0,function*(){const n={client:this,destinationNumber:Lf,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(i=e.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new ga(n).run()})}runMicrophoneCheck(e={}){var i;return U(this,void 0,void 0,function*(){const n={client:this,ice:!1,network:!1,microphone:{sampleDurationMs:e.durationMs,silenceThreshold:e.silenceThreshold,record:(i=e.record)!==null&&i!==void 0&&i,warnOnRecording:e.warnOnRecording},mode:"microphone-only"};return new ga(n).run()})}static webRTCInfo(){return Xb()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ae.not_supported},{browserName:"Firefox",supported:Ae.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",features:["audio"],supported:Ae.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",features:["audio"],supported:Ae.partial}]}]}}function Tw(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const i=e;return i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"&&typeof i.arguments=="string"}function Mf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Of={exports:{}},Pf;function kw(){return Pf||(Pf=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||l,h),m=i?i+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,p=new Array(h);d<h;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,p){var m=i?i+l:l;if(!this._events[m])return!1;var v=this._events[m],b=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,p),!0}for(C=1,y=new Array(b-1);C<b;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var T=v.length,A;for(C=0;C<T;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!y)for(A=1,y=new Array(b-1);A<b;A++)y[A-1]=arguments[A];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var m=0,v=[],b=p.length;m<b;m++)(p[m].fn!==c||d&&!p[m].once||u&&p[m].context!==u)&&v.push(p[m]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=i?i+l:l,this._events[c]&&r(this,c)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Of)),Of.exports}var Ew=kw();const Fn=Mf(Ew),ma=new Fn;var va={exports:{}},Iw=va.exports,Nf;function Aw(){return Nf||(Nf=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(Iw,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function E(){var g;if(!(typeof window===i||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===i)try{var S=window.document.cookie,I=encodeURIComponent(x),M=S.indexOf(I+"=");M!==-1&&(g=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function k(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),E()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=E();_!=null&&(A=f(_)),u.call(y)}r=new p,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(va)),va.exports}var Rw=Aw();const xw=Mf(Rw),Dw=()=>new Date().toISOString().replace("T"," ").replace("Z",""),pe=xw.getLogger("telnyx-ai-agent"),Lw=pe.methodFactory;pe.methodFactory=(t,e,i)=>{const n=Lw(t,e,i);return function(...s){n(Dw(),"-",...s)}},pe.setLevel("info");function Mw(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Ow=10,Pw=500,Nw=100,Fw=300,Ff=20;class Uw{constructor(e){B(this,"remoteIntervalId",null);B(this,"localIntervalId",null);B(this,"remoteStream",null);B(this,"localStream",null);B(this,"remoteAudioContext",null);B(this,"remoteSource",null);B(this,"remoteAnalyser",null);B(this,"localAudioContext",null);B(this,"localSource",null);B(this,"localAnalyser",null);B(this,"thinkingStartTime",null);B(this,"lastState",null);B(this,"userIsSpeaking",!1);B(this,"lastUserAudioTime",null);B(this,"userSpeechStartTime",null);B(this,"remoteSilenceStartTime",null);B(this,"remoteSilenceThresholdMs");B(this,"userSilenceStartTime",null);B(this,"isFirstAgentSpeech",!0);B(this,"monitorStartTime",null);B(this,"volumeThreshold");B(this,"silenceDurationMs");B(this,"minSpeechDurationMs");B(this,"maxLatencyMs");B(this,"updateAgentState",Mw(e=>{pe.debug("AudioStreamMonitor updateAgentState",e),pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ma.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Ow,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Pw,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Nw,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??Fw}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,i;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(i=this.remoteAudioContext)==null||i.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,i;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(i=this.localAudioContext)==null||i.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null,this.remoteSilenceStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;pe.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let n=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(i);const o=i.reduce((l,c)=>l+c,0)/i.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&pe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(this.remoteSilenceStartTime=null,n)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&(this.remoteSilenceStartTime===null&&(this.remoteSilenceStartTime=performance.now()),performance.now()-this.remoteSilenceStartTime>=this.remoteSilenceThresholdMs&&this.updateAgentState({state:"listening"}));n=r};this.remoteIntervalId=window.setInterval(s,Ff)}startLocalMonitor(){if(!this.localStream){pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(pe.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),i=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const n=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&pe.debug("Local audio volume:",n),n>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(i,Ff)}destroy(){this.stopAudioStreamMonitor()}}function Bw(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Vw(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function $w(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Un(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function jw(t){if(!Un(t))return null;const e=t.params;return Tw(e)?e.item:null}function Hw(t){if(!Un(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const n of e.client_side_tools)if(n&&typeof n=="object"&&typeof n.name=="string"){const s=n;i.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return i}function Ww(t){if(!Un(t))return null;const e=t.params;if(!e||typeof e!="object")return null;const i=e;if(i.type==="response.audio.delta"){const n=i.format;if(!n||typeof n!="object")return null;const s=n;return typeof i.response_id!="string"||typeof i.delta!="string"||typeof i.sequence!="number"||!Number.isInteger(i.sequence)||typeof s.encoding!="string"||typeof s.sample_rate!="number"||typeof s.channels!="number"?null:{type:"response.audio.delta",response_id:i.response_id,item_id:typeof i.item_id=="string"?i.item_id:void 0,sequence:i.sequence,delta:i.delta,format:{encoding:s.encoding,sample_rate:s.sample_rate,channels:s.channels}}}return i.type==="response.audio.done"&&typeof i.response_id=="string"?{type:"response.audio.done",response_id:i.response_id}:i.type==="response.audio.interrupted"?{type:"response.audio.interrupted",response_id:typeof i.response_id=="string"?i.response_id:void 0}:null}function Gw(t){var e;return Un(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function qw(t){var i;if(!t||typeof t!="object")return!1;const e=t;return((i=e.params)==null?void 0:i.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const zw=3e4;function Kw(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function _a(t){return JSON.stringify({error:t})}class Yw{constructor(e){B(this,"registry",new Map);B(this,"toolTimeouts",new Map);B(this,"inFlight",new Set);B(this,"completed",new Set);B(this,"generation",0);B(this,"getActiveCall");B(this,"timeoutMs");B(this,"events");B(this,"handleEvent",e=>{const i=Hw(e);if(i){this.ingestToolSettings(i);return}const n=jw(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:zw,this.events={onInvoked:i=>this.safeEmit(()=>e.events.onInvoked(i)),onCompleted:i=>this.safeEmit(()=>e.events.onCompleted(i)),onError:i=>this.safeEmit(()=>e.events.onError(i))}}safeEmit(e){try{e()}catch(i){pe.warn(`[client-tools] lifecycle listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}register(e,i){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,i)}registerAll(e){for(const[i,n]of Object.entries(e))this.register(i,n)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:i,timeout_ms:n}of e)typeof n=="number"&&n>0&&this.toolTimeouts.set(i,n)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,i){this.generation===i&&this.completed.add(e)}async execute(e){const{call_id:i,name:n}=e;if(this.inFlight.has(i)||this.completed.has(i)){pe.debug(`[client-tools] duplicate function_call ignored (call_id=${i})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(n);if(!r){pe.warn(`[client-tools] no handler registered for tool "${n}"`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"unknown_tool"}),this.sendOutput(i,n,_a("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{pe.warn(`[client-tools] invalid JSON arguments for tool "${n}" (call_id=${i})`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"invalid_arguments"}),this.sendOutput(i,n,_a("invalid_arguments"),!0,s,o);return}this.inFlight.add(i),this.events.onInvoked({callId:i,toolName:n});const l={callId:i,toolName:n,rawArguments:e.arguments},c=this.toolTimeouts.get(n)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n,c);this.sendOutput(i,n,Kw(u),!1,s,o)}catch(u){const d=u instanceof Uf?"timeout":"handler_error";pe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,_a(d),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Uf(n,i,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){pe.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){pe.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}if(!r||a!==r){pe.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:n}),this.events.onCompleted({callId:e,toolName:i,isError:s})}catch(l){pe.warn(`[client-tools] failed to send output for "${i}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:i,reason:"shutdown"})}}}class Uf extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Ws=class Ws{constructor(e){B(this,"enabled");B(this,"getActiveCall");B(this,"events");B(this,"subscriptionConfirmed",!1);B(this,"subscribeAttempts",0);B(this,"handleEvent",e=>{if(!this.enabled)return;if(Gw(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Ww(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Xw(i.delta)}catch(s){pe.warn(`[streaming-audio] invalid base64 delta for response ${i.response_id}: ${s instanceof Error?s.message:"unknown error"}`);return}this.emitSafely(()=>this.events.onDelta({responseId:i.response_id,itemId:i.item_id,sequence:i.sequence,audio:n,format:{encoding:i.format.encoding,sampleRate:i.format.sample_rate,channels:i.format.channels}}));return}if(i.type==="response.audio.done"){this.emitSafely(()=>this.events.onDone({responseId:i.response_id}));return}this.emitSafely(()=>this.events.onInterrupted({responseId:i.response_id}))}});this.enabled=e.enabled,this.getActiveCall=e.getActiveCall,this.events=e.events}onCallActive(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0,this.sendSubscription()}reset(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0}sendSubscription(){if(!this.enabled||this.subscribeAttempts>=Ws.MAX_SUBSCRIBE_ATTEMPTS)return;const e=this.getActiveCall();if(e)try{const i={type:"response.audio_stream.subscribe"};e.sendAIConversationMessage(i),this.subscribeAttempts+=1}catch(i){pe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){pe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}};B(Ws,"MAX_SUBSCRIBE_ATTEMPTS",10);let ya=Ws;function Xw(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Bf(t){if(!Un(t))return null;const e=t.params;if(e.type==="response.error"){if(!e.error||typeof e.error!="object")return null;const n=e.error.reason;return typeof n=="string"&&n.length>0?{type:"response.error",reason:n}:null}if(e.type!=="response.text.delta"&&e.type!=="response.text.done"||typeof e.item_id!="string"||!e.item_id||typeof e.response_id!="string"||!e.response_id)return null;const i=e.type==="response.text.delta"?e.delta:e.text;return typeof i!="string"||e.type==="response.text.delta"&&!i?null:{type:e.type,itemId:e.item_id,text:i}}function Vf(t){return Vw(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Jw(t){if(!$w(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",i=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((n,s)=>(s.type==="text"&&(n+=s.text),n),""),i=t.params.item.content.reduce((n,s)=>(s.type==="image_url"&&s.image_url.url&&n.push({type:"image",url:s.image_url.url}),n),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:i}}class $f extends Fn{constructor(i,n={}){super();B(this,"source");B(this,"assembleAssistantMessages");B(this,"completedItemIds",new Set);B(this,"transcript",[]);B(this,"onSocketMessage",i=>{if(!(!Bw(i)||!i.params))switch(i.params.type){case"response.text.delta":{if(this.assembleAssistantMessages){this.handleAssistantText(i);return}const n=Vf(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"response.text.done":{this.assembleAssistantMessages&&this.handleAssistantText(i);return}case"conversation.item.deleted":{if(qw(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&(this.transcript.splice(s,1),this.emitTranscriptUpdated())}return}case"conversation.item.created":{const n=Jw(i);if(n){const s=this.transcript.findIndex(o=>o.id===n.id);s!==-1?this.transcript[s]=n:this.transcript.push(n),this.emit("transcript.item",n),this.emitTranscriptUpdated()}return}}});this.source=i,this.assembleAssistantMessages=n.assembleAssistantMessages??!1,this.source.on(F.SocketMessage,this.onSocketMessage)}detach(){this.source.off(F.SocketMessage,this.onSocketMessage)}emitTranscriptUpdated(){this.assembleAssistantMessages&&this.emit("transcript.updated",[...this.transcript])}handleAssistantText(i){const n=Bf(i);if(!n||n.type==="response.error"||this.completedItemIds.has(n.itemId))return;const s=this.transcript.findIndex(a=>a.role==="assistant"&&a.id===n.itemId),o=this.transcript[s],r={id:n.itemId,role:"assistant",content:n.type==="response.text.delta"?((o==null?void 0:o.content)??"")+n.text:n.text,timestamp:(o==null?void 0:o.timestamp)??new Date};if(o?this.transcript[s]=r:r.content&&this.transcript.push(r),n.type==="response.text.done")this.completedItemIds.add(n.itemId),this.emit("response.done"),!o&&r.content&&this.emit("transcript.item",r);else{const a=Vf(i);a&&this.emit("transcript.item",a)}this.emitTranscriptUpdated()}}const jt=t=>typeof t=="object"&&t!==null,jf=t=>{const e=jt(t)&&jt(t.result)?t.result:t;if(!(!jt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Qw=t=>jt(t)&&jt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Zw=(t,e)=>{if(!e||!jt(t)||!jt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!jt(i.params))return;const n=i.params;jt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class eS extends Fn{constructor(i){super();B(this,"telnyxRTC");B(this,"transcription");B(this,"removeLoginSuccessHook",null);B(this,"authenticated",!1);B(this,"authenticating",!1);B(this,"agentId");B(this,"versionId");B(this,"widgetVersion");B(this,"conversationId");B(this,"debug");B(this,"audioStreamMonitor");B(this,"clientTools");B(this,"streamingAudio");B(this,"activeCall");B(this,"chatMode");B(this,"dc",null);B(this,"region",null);B(this,"callReportId",null);B(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});B(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});B(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});B(this,"onSocketMessage",i=>{const n=jf(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});B(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,this.streamingAudio.onCallActive(),i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.streamingAudio.reset(),this.audioStreamMonitor.stopAudioStreamMonitor()))});B(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});B(this,"onAgentStateChange",i=>{this.emit("conversation.agent.state",i)});this.agentId=i.agentId,this.versionId=i.versionId||"main",this.widgetVersion=i.widgetVersion,this.conversationId=i.conversationId,this.debug=i.debug||!1,this.chatMode=i.chatMode||!1,this.activeCall=null,pe.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId},s={};i.conversationId&&(s.conversation_id=i.conversationId),i.streamingAudio&&(s.streamingAudio=!0),Object.keys(s).length>0&&(n.target_params=s),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new Cw({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,prefetchIceCandidates:i.prefetchIceCandidates,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0,rtcIp:i.rtcIp,rtcPort:i.rtcPort}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(F.Ready,this.onClientReady),this.telnyxRTC.on(F.Error,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketClose,this.onSocketClose),this.telnyxRTC.on(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(F.Notification,this.onNotification),this.transcription=new $f(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ma.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Uw(i.vad),this.clientTools=new Yw({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:o=>this.emit("client.tool.invoked",o),onCompleted:o=>this.emit("client.tool.completed",o),onError:o=>this.emit("client.tool.error",o)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(F.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new ya({enabled:i.streamingAudio??!1,getActiveCall:()=>this.activeCall,events:{onDelta:o=>this.emit("assistant.audio.delta",o),onDone:o=>this.emit("assistant.audio.done",o),onInterrupted:o=>this.emit("assistant.audio.interrupted",o)}}),this.telnyxRTC.on(F.AIConversationMessage,this.streamingAudio.handleEvent)}registerClientTool(i,n){this.clientTools.register(i,n)}unregisterClientTool(i){return this.clientTools.unregister(i)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var i;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(F.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(F.AIConversationMessage,this.streamingAudio.handleEvent),this.clientTools.reset(),this.streamingAudio.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(F.Ready,this.onClientReady),this.telnyxRTC.off(F.Error,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketClose,this.onSocketClose),this.telnyxRTC.off(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(F.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ma.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(i,n)}get transcript(){return this.transcription.transcript}async startConversation(i){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw pe.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw pe.warn(d.message),this.emit("agent.error",d),d}const n=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=i||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[n],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var i;return(i=this.activeCall)==null?void 0:i.hangup()}setRemoteStream(i){this.audioStreamMonitor.setRemoteStream(i)}installLoginSuccessHook(){const i=this.telnyxRTC,n=i.execute,s=i.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=p=>{c===p&&(this.authenticating=!1)},d=function(p){const m=Qw(p),v=c;return m&&Zw(p,a),n.call(this,p).then(b=>{const y=m?jf(b):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),b})},h=function(p){const m=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&i.login===h&&u(m)})};return i.execute=d,i.login=h,()=>{l=!1,i.execute===d&&(i.execute=n),i.login===h&&(i.login=s)}}emitLoginStarted(i){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",i)}emitLoginSuccess(i){const n=this.telnyxRTC,s=n.sessionid||null;i.sessionId&&(n.sessionid=i.sessionId);const o=i.sessionId||n.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}const tS={production:"rtc.telnyx.com",development:"rtcdev.telnyx.com"};function iS(t){if(t.url)return t.url;const e=tS[t.environment??"production"];return`wss://${t.region?`${t.region}.`:""}${e}`}let nS=0;const sS=()=>`text-chat-${Date.now()}-${++nS}`;class oS extends Fn{constructor(i){super();B(this,"socket",null);B(this,"pending",new Map);B(this,"options");B(this,"closedByUs",!1);B(this,"conversationId",null);B(this,"assistantVersionId",null);B(this,"onMessage",i=>{let n;try{n=JSON.parse(i.data)}catch{pe.warn("[TextChat] dropping non-JSON frame");return}const s=n,o=s.id?this.pending.get(s.id):void 0;if(o){this.pending.delete(s.id),s.error?o.reject(new Error(s.error.message??"Text chat error")):o.resolve(s.result??{});return}this.emit(F.SocketMessage,n)});B(this,"onClose",i=>{this.closedByUs||this.teardown("Text chat socket closed"),this.emit(F.SocketClose,i)});B(this,"onError",()=>{this.emit(F.SocketError,new Error("Text chat socket error"))});this.options=i,this.conversationId=i.conversationId??null}get isConnected(){var i;return((i=this.socket)==null?void 0:i.readyState)===WebSocket.OPEN}async connect(){if(this.socket)throw new Error("Text chat transport is already connected");const i=iS(this.options);pe.debug("[TextChat] connecting to",i);const n=new WebSocket(i);this.socket=n,this.closedByUs=!1;try{if(await new Promise((o,r)=>{const a=()=>{u(),o()},l=()=>{u(),r(new Error(`Failed to connect to ${i}`))},c=()=>{u(),r(new Error(`Connection to ${i} closed before it opened`))},u=()=>{n.removeEventListener("open",a),n.removeEventListener("error",l),n.removeEventListener("close",c)};n.addEventListener("open",a),n.addEventListener("error",l),n.addEventListener("close",c)}),this.socket!==n)throw new Error("Text chat transport is not connected");n.addEventListener("message",this.onMessage),n.addEventListener("close",this.onClose),n.addEventListener("error",this.onError);const s=await this.request("text_chat_login",{target_type:"ai_assistant",target_id:this.options.assistantId,target_version_id:this.options.versionId,conversation_id:this.conversationId??void 0});return this.conversationId=s.conversation_id??null,this.assistantVersionId=s.ai_assistant_version_id??null,{conversationId:this.conversationId,assistantVersionId:this.assistantVersionId}}catch(s){throw this.socket===n&&this.teardown("Text chat transport failed to connect"),s}}async sendMessage(i){await this.request("text_chat_message",{content:i})}disconnect(){this.closedByUs=!0,this.teardown("Text chat transport disconnected")}teardown(i){var n,s,o,r;this.rejectPending(i),(n=this.socket)==null||n.removeEventListener("message",this.onMessage),(s=this.socket)==null||s.removeEventListener("close",this.onClose),(o=this.socket)==null||o.removeEventListener("error",this.onError),(r=this.socket)==null||r.close(),this.socket=null}rejectPending(i){for(const[,n]of this.pending)n.reject(new Error(i));this.pending.clear()}request(i,n){const s=this.socket;if(!s||s.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Text chat transport is not connected"));const o=sS();return new Promise((r,a)=>{this.pending.set(o,{resolve:r,reject:a}),s.send(JSON.stringify({jsonrpc:"2.0",id:o,method:i,params:n}))})}}class rS extends Error{constructor(i){const n={stream_truncated:"The assistant response ended before it was complete.",stream_failed:"The assistant response stream failed.",assistant_error:"The assistant could not complete its response."};super(Object.hasOwn(n,i)?n[i]:`Assistant response failed: ${i}`);B(this,"reason");this.name="TextChatResponseError",this.reason=i}}class aS extends Fn{constructor(i){super();B(this,"agentId");B(this,"transport");B(this,"transcription");B(this,"connected",!1);B(this,"agentState","listening");B(this,"onSocketClose",()=>{this.connected&&(this.connected=!1,this.setAgentState("listening"),this.emit("agent.disconnected"))});B(this,"onSocketMessage",i=>{const n=Bf(i);(n==null?void 0:n.type)==="response.error"&&(this.setAgentState("listening"),this.emit("agent.error",new rS(n.reason)))});B(this,"onResponseDone",()=>{this.setAgentState("listening")});B(this,"onTranscriptUpdated",i=>{this.emit("transcript.updated",i)});B(this,"onTranscriptItem",i=>{i.role==="assistant"&&this.setAgentState("listening"),this.emit("transcript.item",i)});this.agentId=i.agentId,pe.setLevel(i.debug?"debug":"info"),this.transport=new oS({assistantId:i.agentId,versionId:i.versionId,conversationId:i.conversationId,environment:i.environment,region:i.region,url:i.url}),this.transcription=new $f(this.transport,{assembleAssistantMessages:!0}),this.transcription.addListener("transcript.item",this.onTranscriptItem),this.transcription.on("transcript.updated",this.onTranscriptUpdated),this.transcription.on("response.done",this.onResponseDone),this.transport.on(F.SocketMessage,this.onSocketMessage),this.transport.on(F.SocketClose,this.onSocketClose)}get socketEvents(){return this.transport}get conversationId(){return this.transport.conversationId}get isConnected(){return this.connected}get transcript(){return this.transcription.transcript}async connect(){try{const{conversationId:i}=await this.transport.connect();this.connected=!0,this.emit("agent.connected",{conversationId:i})}catch(i){const n=i instanceof Error?i:new Error(String(i));throw this.emit("agent.error",n),n}}async sendMessage(i){if(!this.connected)throw new Error("Not connected. Call connect() first.");this.setAgentState("thinking");try{await this.transport.sendMessage(i)}catch(n){const s=n instanceof Error?n:new Error(String(n));throw this.setAgentState("listening"),this.emit("agent.error",s),s}}disconnect(){this.transport.disconnect();const i=this.connected;this.connected=!1,this.setAgentState("listening"),i&&this.emit("agent.disconnected")}setAgentState(i){this.agentState!==i&&(this.agentState=i,this.emit("conversation.agent.state",{state:i}))}}var Hf={exports:{}},Bn={},Wf;function lS(){if(Wf)return Bn;Wf=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(n,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:n,key:r,ref:s!==void 0?s:null,props:o}}return Bn.Fragment=e,Bn.jsx=i,Bn.jsxs=i,Bn}var Gf;function cS(){return Gf||(Gf=1,Hf.exports=lS()),Hf.exports}cS(),Nt(void 0),Nt(null);const dS=(t,e,i,n,s,o,r,a,l,c,u,d,h,p)=>new eS({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,prefetchIceCandidates:o,vad:r,conversationId:a,chatMode:l,region:c,skipLastVoiceSdkId:u??!0,streamingAudio:d,rtcIp:h,rtcPort:p}),Hs=10,qf=5e3,uS=[46001,46003],hS=["login incorrect","authentication required","authentication failed"];function zf(t){var n;const e=t.code;if(e&&uS.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return hS.some(s=>i.includes(s))}const fS=(t,e,i,n,s,o,r,a,l,c,u,d,h,p)=>{const m=u??!0,[v,b]=ve(null),[y,C]=ve(!1),[T,A]=ve(null),[x,N]=ve(!1),E=ce(0),k=ce(null),f=ce(null),_=ce(!1),g=ce(!1),S=ce(0),I=ce(0),M=Ne(()=>{k.current&&(clearTimeout(k.current),k.current=null)},[]),R=Ne(()=>{M(),E.current=0,g.current=!0,N(!1),A(null)},[M]),P=Ne(()=>{M(),N(!1)},[M]),O=Ne(L=>{if(M(),E.current>=Hs){re.error(`Max login retry attempts (${Hs}) exceeded`),N(!1);return}E.current+=1;const V=S.current,$=I.current;re.info(`Scheduling login retry attempt ${E.current}/${Hs} in ${qf}ms due to: ${L}`),N(!0),k.current=window.setTimeout(()=>{var G;k.current=null;const W=f.current,q=W==null?void 0:W.telnyxRTC;if(S.current!==V||I.current!==$||W!=null&&W.isAuthenticating){re.info("Skipping login retry because a newer socket/login is already in progress"),P();return}if(_.current||g.current||W!=null&&W.isAuthenticated){re.info("Skipping login retry because login already succeeded before retry timeout fired"),R();return}f.current&&(re.info(`Executing reconnect attempt ${E.current} (socket disconnect)`),(G=q==null?void 0:q.socketDisconnect)==null||G.call(q))},qf)},[M,P,R]);return Le(()=>{if(!t)return;const L=dS(t,e,i,n,s,o,r,a,l,c,m,d,h,p);_.current=!1,g.current=!1,C(!1),A(null),N(!1),f.current=L;const V=()=>{re.info("Agent connected successfully"),_.current=!0,C(!0),R()},$=()=>{re.info("Agent disconnected"),_.current=!1,g.current=!1,C(!1)},W=Y=>{if(re.error("AI Agent error:",Y),zf(Y)){if(_.current||g.current){re.debug("Ignoring retryable error — login already succeeded");return}E.current<Hs?(A(null),O(Y.message)):(A(Y),N(!1))}else A(Y),N(!1)},q=L.telnyxRTC??null,G=()=>{I.current+=1,g.current=!1},oe=()=>{re.info("Login succeeded; clearing pending login retry flow"),R()},K=()=>{S.current+=1,g.current=!1},Z=()=>{g.current=!1};return L.on("agent.connected",V),L.on("agent.disconnected",$),L.on("agent.error",W),L.on("agent.login.started",G),L.on("agent.login.success",oe),q&&typeof q=="object"&&(q.on(F.SocketOpen,K),q.on(F.SocketClose,Z)),L.connect(),b(L),()=>{M(),L.off("agent.connected",V),L.off("agent.disconnected",$),L.off("agent.error",W),L.off("agent.login.started",G),L.off("agent.login.success",oe),q&&typeof q=="object"&&(q.off(F.SocketOpen,K),q.off(F.SocketClose,Z)),L.disconnect(),_.current=!1,f.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,d,h,p,M,R,O]),{client:v,isConnected:y,error:T,isReconnecting:x}},pS="telnyx-ai-agent",Re={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",TRANSCRIPT_UPDATED:"transcript.updated",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error",CLIENT_TOOLS_CONFIGURED:"client.tools.configured",ASSISTANT_AUDIO_DELTA:"assistant.audio.delta",ASSISTANT_AUDIO_DONE:"assistant.audio.done",ASSISTANT_AUDIO_INTERRUPTED:"assistant.audio.interrupted"};function gS(t){var n,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;i.push({name:r.name,description:(n=r.client_side_tool)==null?void 0:n.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return i}function Kf(){const t=document.querySelector(pS);return t instanceof HTMLElement?t:null}function nt(t,e,i){const n=i||Kf();if(!n){re.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),re.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const mS=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ce(null),l=Jn(Qu);Le(()=>{const c=i==null?void 0:i.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??Kf()},[i]),Le(()=>{if(!t)return;const c=a.current,u=()=>{n();const f=t.telnyxRTC,_={dc:(f==null?void 0:f.dc)??null,region:(f==null?void 0:f.region)??null,callReportId:(f==null?void 0:f.callReportId)??null};l(_),nt(Re.AGENT_CONNECTED,_,c)},d=()=>{l(null),nt(Re.AGENT_DISCONNECTED,void 0,c)},h=k=>{const f={message:k.message,name:k.name};if(zf(k)){re.debug("Ignoring retryable agent.error in widget event layer"),nt(Re.AGENT_ERROR,f,c);return}o(k),nt(Re.AGENT_ERROR,f,c)},p=k=>{var f;s(k),nt(Re.CONVERSATION_UPDATE,{type:k.type,callState:(f=k.call)==null?void 0:f.state},c)},m=k=>{nt(Re.TRANSCRIPT_ITEM,k,c)},v=k=>{nt(Re.CONVERSATION_AGENT_STATE,k,c)},b=k=>{nt(Re.AGENT_AUDIO_MUTE,{muted:k},c)},C=t.telnyxRTC,T=k=>{r(k);const f=gS(k);f&&nt(Re.CLIENT_TOOLS_CONFIGURED,{tools:f},c)},A=k=>{const f=k,_={code:f==null?void 0:f.code,reason:f==null?void 0:f.reason,wasClean:f==null?void 0:f.wasClean,timestamp:new Date().toISOString()};re.info("[socket.close]",_),nt(Re.SOCKET_CLOSE,_,c)};C&&typeof C=="object"&&(C.on(F.SocketMessage,T),C.on(F.SocketClose,A));const x=k=>{var _;const f={responseId:k.responseId,itemId:k.itemId,sequence:k.sequence,byteLength:((_=k.audio)==null?void 0:_.byteLength)??0,format:{encoding:k.format.encoding,sampleRate:k.format.sampleRate,channels:k.format.channels}};nt(Re.ASSISTANT_AUDIO_DELTA,f,c)},N=k=>{nt(Re.ASSISTANT_AUDIO_DONE,{responseId:k.responseId},c)},E=k=>{nt(Re.ASSISTANT_AUDIO_INTERRUPTED,{responseId:k.responseId},c)};return t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),t.on("assistant.audio.delta",x),t.on("assistant.audio.done",N),t.on("assistant.audio.interrupted",E),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),t.off("assistant.audio.delta",x),t.off("assistant.audio.done",N),t.off("assistant.audio.interrupted",E),C&&typeof C=="object"&&(C.off(F.SocketMessage,T),C.off(F.SocketClose,A))}},[t,n,s,o,r,l])},vS=(t,e,i,n,s,o,r,a)=>{const[l,c]=ve(null),[u,d]=ve([]),[h,p]=ve(!1),[m,v]=ve(!1),[b,y]=ve(!1),[C,T]=ve(null),[A,x]=ve(null),[,N]=ms(),E=Au(),k=ce(null),f=ce(!1),[_,g]=ve(!1),[S,I]=ve(0);Le(()=>{var Ze;if(c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),!t||f.current)return;N("listening"),console.log(e);const L=new aS({agentId:t,environment:e,versionId:i,conversationId:n,region:s,debug:o,url:a});let V=!1,$=!1,W=!1,q=!1,G=null,oe=null;const K=new Set,Z=(Ze=r==null?void 0:r.current)==null?void 0:Ze.getRootNode(),Y=Z instanceof ShadowRoot?Z.host:null,te=(ne,ye)=>{V||nt(ne,ye,Y)},me=()=>{oe=null,y(!1)},Oe=ne=>{te(Re.TRANSCRIPT_ITEM,ne)},_e=ne=>{V||(d([...ne]),te(Re.TRANSCRIPT_UPDATED,[...ne]))},xe=ne=>{if(V||$)return;const ye="reason"in ne&&typeof ne.reason=="string"?ne.reason:void 0,Be=ne.name==="TextChatResponseError"?"response":q||L.isConnected?"send":"connection";Be==="connection"?T(ne):Be==="response"&&x(ne),te(Re.AGENT_ERROR,{message:ne.message,name:ne.name,reason:ye,scope:Be})},he=()=>{V||(p(!1),me(),W&&(W=!1,te(Re.AGENT_DISCONNECTED)),$||T(new Error("Connection to the assistant was lost. Reconnect to continue.")))},de=ne=>{if(V||(Eu(ne)&&E(ne.params.widget_settings),!ne||typeof ne!="object"))return;const ye=ne;if(ye.method!=="ai_conversation"||!ye.params)return;const{type:Be,response_id:Ee,item_id:Ht,text:Vn,error:wt}=ye.params;if(Be==="response.error"&&wt&&typeof wt=="object"&&"reason"in wt&&typeof wt.reason=="string"&&wt.reason)me();else if(typeof Ee=="string"&&Ee&&typeof Ht=="string"&&Ht){if(K.has(Ee))return;oe&&!oe.responseId&&(oe.responseId=Ee),Be==="response.text.done"&&typeof Vn=="string"&&(K.add(Ee),(oe==null?void 0:oe.responseId)===Ee&&me())}},fe=ne=>{V||(N(ne.state==="thinking"?"thinking":"listening"),te(Re.CONVERSATION_AGENT_STATE,ne))};L.on("transcript.item",Oe),L.on("transcript.updated",_e),L.on("agent.error",xe),L.on("agent.disconnected",he),L.on("conversation.agent.state",fe),L.socketEvents.on(F.SocketMessage,de);const Je=()=>V?Promise.resolve():G||($=!0,L.disconnect(),$=!1,me(),v(!0),p(!1),T(null),x(null),G=L.connect().then(()=>{V||(p(L.isConnected),L.isConnected&&(W=!0,te(Re.AGENT_CONNECTED,{conversationId:L.conversationId})))}).catch(ne=>{V||T(ne instanceof Error?ne:new Error(String(ne)))}).finally(()=>{G=null,V||v(!1)}),G),Qe=async ne=>{if(V||!L.isConnected||G)throw new Error("Reconnect before sending.");if(oe)throw new Error("Wait for the current reply to finish.");const ye={};oe=ye,y(!0),x(null),q=!0;try{await L.sendMessage(ne)}catch(Be){throw!V&&oe===ye&&me(),Be}finally{q=!1}},Mt=()=>{var ne;V||($=!0,L.disconnect(),V=!0,((ne=k.current)==null?void 0:ne.agent)===L&&(k.current=null),L.off("transcript.item",Oe),L.off("transcript.updated",_e),L.off("agent.error",xe),L.off("agent.disconnected",he),L.off("conversation.agent.state",fe),L.socketEvents.off(F.SocketMessage,de),N("listening"))};return k.current={agent:L,send:Qe,connect:Je,end:Mt},c(L),Je(),Mt},[t,e,i,n,s,o,a,r,S,N,E]);const M=Ne(async L=>{if(!k.current)throw new Error("Connect before sending.");await k.current.send(L)},[]),R=Ne(()=>{var L;(L=k.current)==null||L.connect()},[]),P=Ne(()=>{var L;f.current||(f.current=!0,(L=k.current)==null||L.end(),g(!0),c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),N("listening"))},[N]),O=Ne(()=>{f.current&&(f.current=!1,g(!1),I(L=>L+1))},[]);return{isEnded:_,sessionKey:S,endChat:P,startChat:O,client:l,transcript:u,isConnected:h,isConnecting:m,isResponding:b,error:C,responseError:A,sendMessage:M,retry:R}},_S=2e3;async function yS(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Yf(t){const e=t.split("-"),i=e[e.length-1];return i&&i.length===13&&/^\d+$/.test(i)?e.slice(0,-1).join("-"):t}const bS=(t,e)=>{const[i,n]=ve([]),[,s]=ms(),o=ce(e);Le(()=>{o.current=e},[e]);const r=ce(void 0),a=ce(void 0);return Le(()=>{if(!t)return;const c=h=>{n(p=>{const m=p[p.length-1];if(h.role==="assistant"&&m&&Yf(m.id)===Yf(h.id)&&m.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&m.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&m.greetingLatencyMs===void 0,y={...m,content:m.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...p.slice(0,-1),y]}if(h.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...p];return y[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(m&&m.role==="user"&&h.timestamp.getTime()-m.timestamp.getTime()<_S){const C={...m,id:h.id,content:m.content+" "+h.content,timestamp:h.timestamp,attachments:[...m.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...p,h]})},u=({state:h,userPerceivedLatencyMs:p,greetingLatencyMs:m,thinkingStartedAt:v})=>{(p!==void 0||m!==void 0)&&re.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${m} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),m!==void 0&&(a.current=m)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var m;const p=(m=h.call)==null?void 0:m.state;(p==="destroy"||p==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const p=await yS(h);d.push(p)}catch(p){throw re.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Ki={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class wS{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,i){var n;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,i),re.debug(`[client-tools] registered handler "${e}"`),(n=this.agent)==null||n.registerClientTool(e,i)}unregister(e){var n;const i=this.handlers.delete(e);return i&&(re.debug(`[client-tools] unregistered handler "${e}"`),(n=this.agent)==null||n.unregisterClientTool(e)),i}list(){return Array.from(this.handlers.keys())}attach(e,i){this.detach(),this.agent=e,this.listeners=i;for(const[n,s]of this.handlers)e.registerClientTool(n,s);this.boundInvoked=n=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(n)},this.boundCompleted=n=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(n)},this.boundError=n=>{var s;return(s=this.listeners)==null?void 0:s.onError(n)},e.on(Ki.INVOKED,this.boundInvoked),e.on(Ki.COMPLETED,this.boundCompleted),e.on(Ki.ERROR,this.boundError),this.handlers.size>0&&re.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Ki.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Ki.COMPLETED,this.boundCompleted),this.boundError&&e.off(Ki.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function ba(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const SS=(t,e)=>{const i=ce(null);i.current===null&&(i.current=new wS),so(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){re.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=i.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),Le(()=>{const n=i.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return n.attach(t,{onInvoked:o=>{ba(s(),Re.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{ba(s(),Re.CLIENT_TOOL_COMPLETED,o)},onError:o=>{ba(s(),Re.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},CS=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=ui(),[r,a]=ve(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=bS(e,i),d=ce(!1);switch(Le(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,re.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[n,t]),r){case"collapsed":return D(oh,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(x0,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(oh,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},wa=({message:t})=>D(Xt.div,{layoutId:Cn,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:[D("div",{className:"rounded-full animate-spin",children:D(i0,{})}),t&&D("p",{role:"status",children:t})]}),TS=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(wa,{});case"done":case"purged":case"destroy":return null;case"active":return D(CS,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(wa,{})}},Xf=({className:t})=>D("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Jf(){const t=ui();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(Xf,{className:"w-8 h-8 mr-2"})}const kS=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=ui(),o=ce(!1),r=Ne(async()=>{if(!t){re.error("Client is not initialized.");return}if(!n){re.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){re.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return Le(()=>{i&&t&&n&&!o.current&&(o.current=!0,re.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(Xt.div,{layoutId:Cn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[D(Jf,{}),"Connecting..."]}):D(Xt.button,{layoutId:Cn,onClick:r,disabled:!n,"aria-busy":!n,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D(Jf,{}),s.start_call_text]})},ES=({transcript:t,onSendMessage:e,isConnected:i,isConnecting:n,isResponding:s,connectionError:o,responseError:r,onRetry:a,isEnded:l,onEndChat:c,onStartChat:u,startLabel:d="Start new chat",onClose:h,debug:p=!1})=>l?D(Xt.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{duration:.15,ease:"easeOut"},onClick:u,className:"inline-flex w-fit max-w-full items-center justify-center gap-2.5 rounded-full bg-[#FEFDF5] px-4 py-3 text-base font-medium leading-6 text-black shadow-lg shadow-[#38383840] cursor-pointer transition-colors hover:bg-[#F3F2EA] focus-visible:outline-2 focus-visible:outline-offset-4 dark:bg-black dark:text-white dark:hover:bg-[#1C1C1E]",children:[D(Xf,{className:"h-6 w-6 shrink-0"}),D("span",{children:d})]}):D(Gc,{children:D(Xt.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[D("div",{className:"p-4 text-center",children:[D("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D("button",{type:"button",onClick:c,className:"ml-auto flex items-center gap-1.5 rounded-full border border-[#969696] dark:border-[#3D3D46] px-3 py-1.5 text-sm cursor-pointer focus-visible:outline focus-visible:outline-offset-2",children:[D(In,{className:"w-4 h-4","aria-hidden":"true"}),"End chat"]}),h&&D(Rt,{tooltip:"Close",className:"ml-auto",onClick:h,children:D(In,{className:"text-black dark:text-white"})})]}),D(xr,{size:"large",className:"mb-4"}),D(Fr,{className:"mt-2",debug:p})]}),D("div",{className:"px-4 pb-2 text-sm",children:[o&&D("p",{role:"alert",children:o.message}),!i&&(n?D("p",{role:"status",children:"Connecting…"}):D("button",{className:"underline",onClick:a,children:"Reconnect"})),r&&D("p",{role:"alert",children:r.message}),s&&D("p",{role:"status",children:"Receiving reply…"})]}),D(fh,{transcript:t,onSendMessage:e,allowAttachments:!1,awaitAcceptance:!0,sendDisabled:!i||s||n})]})}),IS='@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-leading:initial;--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;--tw-outline-style:solid}}}@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-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--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-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-fit{width:fit-content}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.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-1\\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-2\\.5{gap:calc(var(--spacing)*2.5)}.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-lg{border-radius:var(--radius-lg)}.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-t{border-top-style:var(--tw-border-style);border-top-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}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.pb-2{padding-bottom:calc(var(--spacing)*2)}.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-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--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))}.leading-6{--tw-leading:calc(var(--spacing)*6);line-height:calc(var(--spacing)*6)}.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}.opacity-0{opacity:0}.opacity-60{opacity:.6}.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-\\[\\#38383840\\]{--tw-shadow-color:#38383840}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383840\\]{--tw-shadow-color:color-mix(in oklab,#38383840 var(--tw-shadow-alpha),transparent)}}.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-lg{--tw-backdrop-blur:blur(var(--blur-lg));-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,)}.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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;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 (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-\\[\\#F3F2EA\\]:hover{background-color:#f3f2ea}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.focus-visible\\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\\:outline-offset-4:focus-visible{outline-offset:4px}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@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)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#1C1C1E\\]:where(.dark,.dark *):hover{background-color:#1c1c1e}.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-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-leading{syntax:"*";inherits:false}@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}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@keyframes spin{to{transform:rotate(360deg)}}',AS=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),RS={duration:.1,ease:"circOut"},xS=({children:t,position:e="fixed",rootRef:i})=>{const n=ui(),o=(e??n.position??"fixed")==="fixed"?D(AS,{children:t}):t;return D("div",{ref:i,className:Bt(n.theme==="dark"&&"dark"),children:D(Ym,{transition:RS,children:[D("style",{children:IS}),o]})})},DS=t=>D(Xt.div,{layoutId:Cn,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:[D(e0,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.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"," ",D(c0,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(a0,{className:"w-4 h-4"}),"Retry"]})]});function Zt(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Qf(t,e){return t===void 0?e:Zt(t)}function LS({"agent-id":t,debug:e,"trickle-ice":i,"prefetch-ice-candidates":n,"call-destination-number":s,"call-caller-number":o,"call-caller-name":r,"call-custom-headers":a,"call-audio":l,vad:c,"show-user-perceived-latency":u,"show-greeting-latency":d,"conversation-id":h,"chat-mode":p,"text-only":m,"text-chat-url":v,region:b,"rtc-ip":y,"rtc-port":C,"skip-last-voice-sdk-id":T,"streaming-audio":A,environment:x,position:N="fixed","version-id":E}){const k=Zt(e),f=C!=null&&C.trim()?Number(C):void 0,_=Qf(i,!0),g=Qf(n,!0),S=Zt(p),I=Zt(m),M=Zt(A),R=T===void 0?!0:Zt(T),P=ct(()=>{if(c)try{return JSON.parse(c)}catch(Ee){re.error("Invalid JSON for vad attribute:",c,Ee);return}},[c]),O=ct(()=>({showUserPerceivedLatency:Zt(u),showGreetingLatency:Zt(d)}),[u,d]),{client:L,error:V,isConnected:$,isReconnecting:W}=fS(I?void 0:t,x,E,k,_,g,P,h,S,b,R,M,y,f),[q,G]=ve(null),[oe,K]=ve(!1),[Z,Y]=ve(!1),[te,me]=ve(!1),[Oe,_e]=ve(!1),xe=Jn(nh),he=Au(),de={};if(s&&(de.destinationNumber=s),o&&(de.callerNumber=o),r&&(de.callerName=r),a)try{de.customHeaders=JSON.parse(a)}catch(Ee){re.error("Invalid JSON for call-custom-headers attribute:",a,Ee)}if(l)try{de.audio=JSON.parse(l);const Ee=de.audio;if(typeof Ee=="object"){const Ht=navigator.mediaDevices.getSupportedConstraints();Object.keys(Ee).forEach(Vn=>{Ht[Vn]||re.warn(`Audio constraint not supported by browser: ${Vn}`)})}}catch(Ee){re.error("Invalid JSON for call-audio attribute:",l,Ee)}const fe=Ne(()=>{K(!1)},[]),Je=Ne(Ee=>{var Ht;if(((Ht=Ee.call)==null?void 0:Ht.state)==="destroy")return xe(!1),_e(!0),G(null);G(Ee)},[xe]),Qe=Ne(()=>{K(!1),W||Y(!0)},[W]),Mt=Ne(()=>{re.info("User triggered retry"),Y(!1),K(!0),L&&L.connect()},[L]),Ze=Ne(Ee=>{Eu(Ee)&&(he(Ee.params.widget_settings),me(!0))},[he]),ne=ce(null),ye=vS(I?t:void 0,x,E,h,b,k,ne,v);return mS(L,{onReady:fe,onConversationUpdate:Je,onError:Qe,onConfigMessage:Ze},ne),SS(L,ne),D(xS,{position:N,rootRef:ne,children:t?I?D(ES,{isConnected:ye.isConnected,isConnecting:ye.isConnecting,isResponding:ye.isResponding,connectionError:ye.error,responseError:ye.responseError,onRetry:ye.retry,isEnded:ye.isEnded,onEndChat:ye.endChat,onStartChat:ye.startChat,startLabel:h?"Start chat":"Start new chat",transcript:ye.transcript,onSendMessage:ye.sendMessage,debug:k},JSON.stringify([t,x,E,h,b,k,v,ye.sessionKey])):Z||V?D(DS,{agentId:t,onRetry:Mt}):oe||W?D(wa,{message:W?"Retrying...":void 0}):q!=null&&q.call?D(TS,{call:q.call,client:L,latencySettings:O,chatMode:S,debug:k}):te?D(kS,{client:L,callProps:de,chatMode:S&&!Oe,isReady:$&&!!L}):null:D("div",{children:"Please provide an assistant ID."})})}gp(LS,"telnyx-ai-agent",Ey,{shadow:!0})})();
118
+ `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
119
+ `)}))}),w.info(i)}),2e3)}}class Vs extends pn{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>Vs.ACTIVE_CALL_STATE_NAMES.has(e.state))}_extractSafeCallIdentifiers(e){var n,i;const s={callId:e.id,state:e.state,direction:e.direction};!((n=e.options)===null||n===void 0)&&n.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),!((i=e.options)===null||i===void 0)&&i.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const n=this.getActiveCalls().filter(r=>r.id!==e);if(n.length===0)return;const i=je(lb),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};$(F.Warning,{warning:i,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:n.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),w.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${n.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return U(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return U(this,void 0,void 0,function*(){w.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,n=!0){return U(this,void 0,void 0,function*(){try{const i=yield Ps({audio:e,video:n});return Oi(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){w.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(z.Purge),w.info("Start hangup for ",i),yield i.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){w.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(z.Purge),i.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Wh(F.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return Pi().catch(e=>{const n=le($n(e),e);return $(F.MediaError,n,this.uuid),[]})}getVideoDevices(){return Pi(Dt.Video).catch(e=>($(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Pi(Dt.AudioIn).catch(e=>{const n=le($n(e),e);return $(F.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return Pi(Dt.AudioOut).catch(e=>(w.error("getAudioOutDevices",e),$(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Ns(e,n,i)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(n=>U(void 0,void 0,void 0,function*(){const i=[],s=yield Ps({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<tf.length;r++){const[a,l]=tf[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 Oi(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=ph(e,["micId","micLabel"]);return Yb(s),this._audioConstraints=yield((o,r,a,l)=>U(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield Ns(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?Sb:wb}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=Ri(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=Ri(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new Wb({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return U(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Gb({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=ea(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return U(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new qb({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=ea(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return mn.setStateTelnyx(e)}}Vs.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class pf{constructor(e,n){this.code=n,this.message=e}}class cw{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new Vb(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*(e=2,n=6,Math.floor(Math.random()*(n-e+1)+e));var e,n}handleMessage(e){var n,i,s,o,r,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:h,method:p,params:m={},voice_sdk_id:v}=e,b=m==null?void 0:m.callID,y=m==null?void 0:m.eventChannel,C=m==null?void 0:m.eventType,T=d.calls[b],A=(n=T==null?void 0:T.peer)===null||n===void 0?void 0:n.isConnectionHealthy(),x=new Set(Object.keys(d.calls));if(Array.isArray(m==null?void 0:m.reattached_sessions)&&x.size){w.debug(`Reattach: active call IDs before cleanup check: [${Array.from(x).join(", ")}].`);const f=m.reattached_sessions.length===0,_=m.reattached_sessions.some(g=>x.has(g));if(f||!_)for(const g of Object.keys(d.calls)){const S=d.calls[g];w.debug(`Session not reattached — terminating active call ${g} `);const I=le(Sh);$(F.Error,{error:I,callId:g,sessionId:d.sessionid},d.uuid),S.hangup({},!1)}}if(Array.isArray(m==null?void 0:m.reattached_sessions)&&d.sessionid){const f=Bh();if(f&&f.calls.length>0)if(f.sessionId!==d.sessionid)w.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${d.sessionid}) — ignoring all.`),fn();else{const _=new Set(m.reattached_sessions),g=[];for(const S of f.calls)try{if(_.has(S.id)){w.debug(`Recovery marker for call ${S.id} was reattached — keeping for Attach element restore.`),g.push(S);continue}w.info(`Recovery marker for call ${S.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=le(Sh);$(F.Error,{error:I,callId:S.id,sessionId:d.sessionid,customHeaders:S.customHeaders},d.uuid)}catch(I){w.debug(`Recovery marker for a saved call failed to process (callId=${S==null?void 0:S.id}) — skipping: ${I instanceof Error?I.message:String(I)}`),g.push(S)}Vh(g,f.sessionId,f.storedAt)}}if(C==="channelPvtData")return this._handlePvtEvent(m.pvtData);const N=({recoveredCallId:f,forceRelayCandidateForRecovery:_,mutedMicOnStart:g,remoteElement:S,localElement:I,wasHeldBeforeRecovery:P}={})=>{var R,M,O,L,V,j;const H={audio:!0,video:d.options.video,remoteSdp:m.sdp,destinationNumber:m.callee_id_number,remoteCallerName:m.caller_id_name,remoteCallerNumber:m.caller_id_number,callerName:m.callee_id_name,callerNumber:m.callee_id_number,attach:p===ie.Attach,mediaSettings:m.mediaSettings,debug:(R=d.options.debug)!==null&&R!==void 0&&R,debugOutput:(M=d.options.debugOutput)!==null&&M!==void 0?M:"socket",trickleIce:(O=d.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(L=d.options.prefetchIceCandidates)!==null&&L!==void 0&&L,forceRelayCandidate:typeof _=="boolean"?_:(V=d.options.forceRelayCandidate)!==null&&V!==void 0&&V,keepConnectionAliveOnSocketClose:(j=d.options.keepConnectionAliveOnSocketClose)!==null&&j!==void 0&&j,mutedMicOnStart:g??d.options.mutedMicOnStart};b&&(H.id=b),m.telnyx_call_control_id&&(H.telnyxCallControlId=m.telnyx_call_control_id),m.telnyx_session_id&&(H.telnyxSessionId=m.telnyx_session_id),m.telnyx_leg_id&&(H.telnyxLegId=m.telnyx_leg_id),m.client_state&&(H.clientState=m.client_state),m.dialogParams&&m.dialogParams.custom_headers&&m.dialogParams.custom_headers.length&&(H.customHeaders=m.dialogParams.custom_headers),f&&(H.recoveredCallId=f),P&&(H.wasHeldBeforeRecovery=P),S!==void 0&&(H.remoteElement=S),I!==void 0&&(H.localElement=I),performance.mark(ce(H.id,"new-call-start"));const K=new mn(d,H);return K.nodeId=this.nodeId,K},k=new zh(v),E=new Xr(v);switch(p){case ie.Answer:case ie.Display:case ie.Candidate:case ie.Ringing:case ie.Bye:case ie.Media:if(!b||!T)return void w.error(`Received ${p} for non existing call:`,m);T.handleMessage(e),this._ack(h,p);break;case ie.Ping:this.session.setPingReceived(),this.session.execute(E);break;case ie.Punt:d.options.keepConnectionAliveOnSocketClose&&A?(w.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(h,p)):(w.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case ie.Invite:{const g=N();g.direction=xt.Inbound,g.playRingtone(),g.setState(z.Ringing),this.session.emitMultipleActiveCallsWarning(g.id),this._ack(h,p);break}case ie.Attach:{const g=T||null;if(Object.keys(d.calls).length===0){let S,I;w.warn(`[${new Date().toISOString()}][${b}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${b}`);let P=!1,R=!1;const M=Bh();if(M&&M.sessionId===d.sessionid){const L=M.calls.find(V=>V!==null&&typeof V=="object"&&V.id===b);L&&(S=L.remoteElement,I=L.localElement,P=L.wasHeld===!0,typeof L.forceRelayCandidate=="boolean"&&(R=L.forceRelayCandidate),(S||I)&&w.info(`[${b}] Attach: restoring per-call media elements from recovery marker (remoteElement=${S??"<none>"}, localElement=${I??"<none>"}).`),typeof L.forceRelayCandidate=="boolean"&&w.info(`[${b}] Attach: restoring forceRelayCandidate=${L.forceRelayCandidate} from recovery marker.`))}const O=N({recoveredCallId:b,forceRelayCandidateForRecovery:R,remoteElement:S,localElement:I,wasHeldBeforeRecovery:P});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,p);break}if(g){const S=g.id,I=g.state==="held",P=g.shouldForceRelayCandidateForRecovery();P&&w.warn(`[${new Date().toISOString()}][${b}] Attach: forcing relay candidate for recovery`),w.info(`[${new Date().toISOString()}][${b}] Attach: recovering active call ${S}.`),g.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const R=N({recoveredCallId:S,forceRelayCandidateForRecovery:P,mutedMicOnStart:g.isAudioMuted,remoteElement:g.options.remoteElement,localElement:g.options.localElement,wasHeldBeforeRecovery:I});R.answer(),this.session.emitMultipleActiveCallsWarning(R.id),this._ack(h,p);break}w.warn(`Attach: callID ${b} does not match any active calls. `),$(F.Warning,{warning:je(hb),callId:b,params:m,sessionId:d.sessionid},d.uuid),this._ack(h,p);break}case ie.Event:case"webrtc.event":if(!y)return void w.error("Verto received an unknown event:",m);const f=d.relayProtocol,_=y.split(".")[0];d._existsSubscription(f,y)?$(f,m,y):y===d.sessionid?this._handleSessionEvent(m.eventData):d._existsSubscription(f,_)?$(f,m,_):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):$(F.Notification,m,d.uuid);break;case ie.Info:m.type=gt.generic,$(F.Notification,m,d.uuid);break;case ie.ClientReady:this.session.execute(k);break;case"ai_conversation":$(F.AIConversationMessage,{method:"ai_conversation",params:m,voice_sdk_id:v},d.uuid);break;default:{const g=Wr(e);if(g){switch(g){case Be.REGISTER:case Be.REGED:if(!this.isDuplicateGatewayState(g,[Be.REGED,Be.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,g===Be.REGED&&this.session.resetReconnectAttempts();const S=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;S&&(d.callReportId=S,w.debug("Captured call_report_id from REGED:",S));const I=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.dc;I&&(d.dc=I);const P=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;P&&(d.region=P),w.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),m.type=gt.vertoClientReady,$(F.Ready,m,d.uuid)}break;case Be.UNREGED:case Be.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const S=new pf("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=le(wh,S);$(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(k)},this.reconnectDelay());break;case Be.FAILED:case Be.FAIL_WAIT:case Be.TIMEOUT:if(!this.isDuplicateGatewayState(g,[Be.FAILED,Be.FAIL_WAIT,Be.TIMEOUT])){const S=le(W0,new Error(`Gateway state: ${g}`));if($(F.Error,{error:S,sessionId:d.sessionid},d.uuid),d.options.skipLastVoiceSdkId=!0,w.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${d.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const I=new pf("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const P=le($r,I);$(F.Error,{error:P,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const I=le($r,new Error("Connection Retry Failed"));$(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(w.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(I=>{var P;return((P=I.peer)===null||P===void 0?void 0:P.instance)&&!I.signalingStateClosed}))return w.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();w.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:w.warn("GatewayState message unknown method:",e)}break}w.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,n){const{previousGatewayState:i}=this.session.connection,s=n.includes(i);return s&&w.debug(`Gateway state '${e}' received but previous state was '${i}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(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:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},m={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=h||this._retrieveCallId(b,o);if(y&&n.calls.hasOwnProperty(y)){const C=n.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(T=>{T==="INVALID_PACKET"&&p()})}}},v=yield n.vertoSubscribe(m).catch(b=>{w.error("liveArray subscription error:",b);const y=le($0,b);$(F.Error,{error:y,sessionId:n.sessionid},n.uuid)});Zr(v,o)&&p();break}case"conference-liveArray-part":{let p=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(p=n.calls[v]||null,v!==null){const b={type:gt.conferenceUpdate,action:rt.Leave,conferenceName:r,participantId:Number(u),role:d};$(F.Notification,b,v,!1)||$(F.Notification,b,n.uuid),p===null&&Lt(F.Notification,null,v)}}const m=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:m}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{w.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":cf(this.session,e);break;case"logo-info":{const n={type:gt.conferenceUpdate,action:rt.LogoInfo,logo:e.logoURL};$(F.Notification,n,this.session.uuid);break}}}}class dw extends Vs{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new cw(this),window.addEventListener("beforeunload",n=>{if(w.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return Uh(),void(this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(w.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({initiator:"sdk:beforeunload"},!0))}));try{const i=this.getActiveCalls().map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders,forceRelayCandidate:s.shouldForceRelayCandidateForRecovery()};return s.state==="held"&&(o.wasHeld=!0),typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(this.getActiveCalls().forEach(s=>{if(s.flushIntermediateCallReport)try{w.debug(`beforeunload: flushing call report for ${s.id}.`),s.flushIntermediateCallReport({type:"page-unload"})}catch(o){w.debug(`beforeunload: failed to flush call report for ${s.id}: ${o instanceof Error?o.message:String(o)}`)}}),!this.sessionid||i.length===0)return w.debug(`No sessionID ${this.sessionid} or activeCalls ${i.length} during saving calls recover marker!`),void fn();w.info(`Saving recovery marker for ${i.length} active call(s) before unload (sessid=${this.sessionid}): [${i.map(s=>s.id).join(", ")}].`),Vh(i,this.sessionid)}catch(i){const s=this.calls?Object.keys(this.calls):[];w.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${s.join(", ")}]): ${i instanceof Error?i.message:String(i)}`)}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(w.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),zr(this.sessionid))})}validateOptions(){return As(this.options)||xi(this.options)}newCall(e){if(!this.validateCallOptions(e))throw le(B0,void 0,"Error: destinationNumber is required");const n=new mn(this,e);return e.id||w.debug(`newCall: callId was not provided in options, SDK-generated ID: ${n.id}`),this.emitMultipleActiveCallsWarning(n.id),performance.mark(ce(n.id,"new-call-start")),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!xi(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return U(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),As(this.options)?this.handleLoginOnSocketOpen():xi(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}function gf(t){return{options:t,statsSamples:[]}}function uw(t){var e,n;const i=(n=(e=t.call)===null||e===void 0?void 0:e.peer)===null||n===void 0?void 0:n.instance,s=t.statsSamples[t.statsSamples.length-1];if(!i||!s)return;const o=function(a,l){var c;const u=[],d=new Set,h=new Map,p=new Map,m={host:0,srflx:0,prflx:0,relay:0};a.forEach(E=>{switch(E.type){case"local-candidate":{const f=E;m[f.candidateType]++,p.set(f.id,f);break}case"remote-candidate":{const f=E;h.set(f.id,f);break}case"candidate-pair":{const f=E;u.push(f);break}case"transport":{const f=E;typeof f.selectedCandidatePairId=="string"&&d.add(f.selectedCandidatePairId);break}}});const v=function(E,f,_,g){var S,I;const P=E.find(V=>f.has(V.id)),R=E.find(V=>V.selected===!0),M=E.find(V=>V.nominated===!0&&V.state==="succeeded"),O=E.filter(V=>V.state==="succeeded"),L=(I=(S=P??R)!==null&&S!==void 0?S:M)!==null&&I!==void 0?I:O.length===1?O[0]:void 0;return L?Object.assign(Object.assign({},L),{localCandidate:_.get(L.localCandidateId),remoteCandidate:g.get(L.remoteCandidateId)}):null}(u,d,p,h),b=m.relay>0,y=m.srflx===0&&m.relay===0&&m.prflx===0,C=l.iceGatheringState,T=l.iceConnectionState,A=C==="complete",x=((c=v==null?void 0:v.localCandidate)===null||c===void 0?void 0:c.candidateType)==="relay",{hasMultipleNetworkInterfaces:N,vpnDetected:k}=function(E){if(E.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const f=Array.from(E.values());return{hasMultipleNetworkInterfaces:new Set(f.filter(_=>_.candidateType==="host").map(_=>_.address)).size>=2,vpnDetected:f.some(_=>_.networkType==="vpn")}}(p);return{candidateGatheringCompleted:A,gatheringComplete:A,candidateCounts:m,candidates:Array.from(p.values()),hasRelayCandidate:b,onlyHostCandidates:y,isTurnRequired:x,hasMultipleNetworkInterfaces:N,vpnDetected:k,hasSelectedPair:!!v,selectedPair:v??void 0,iceGatheringState:C,iceConnectionState:T}}(s,i),r=i.getConfiguration().iceServers;return r&&(o.serverCandidateComparison=function(a,l){var c,u;if(!a||a.length===0)return;const d=[];for(const h of a){const p=Array.isArray(h.urls)?h.urls:[h.urls],m=l.filter(y=>p.some(C=>hw(y.url,C,y.protocol))),v=(u=(c=m[0])===null||c===void 0?void 0:c.candidateType)!==null&&u!==void 0?u:null,b=m.length>0;d.push({urls:h.urls,hasCandidates:b,candidateType:v,candidates:m,candidateCount:m.length})}return d}(r,o.candidates)),o}function mf(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(e=>/^turns?:/i.test(e))}function vf(t){var e;let n=t;const i=n.match(/^([a-z]+:)(\/\/)?([^@]*@)(.+)$/i);i&&(n=i[1]+((e=i[2])!==null&&e!==void 0?e:"")+i[4]);const s=n.indexOf("?transport=");return s!==-1&&(n=n.substring(0,s)),n}function _f(t){const e=t.indexOf("?transport=");if(e===-1)return;const n=t.substring(e+11).toLowerCase(),i=n.indexOf("&");return i===-1?n:n.substring(0,i)}function hw(t,e,n){var i;if(!t||!e||vf(t)!==vf(e))return!1;const s=_f(e);if(s===void 0)return!0;const o=(i=_f(t))!==null&&i!==void 0?i:n==null?void 0:n.toLowerCase();return o===void 0||o===s}const ia=2e3,fw=100,yf=.01,pw="To check your microphone, we will be recorded your voice for a few seconds and played back to you so you can hear how it sounds.";function gw(){var t;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((t=navigator.mediaDevices)===null||t===void 0?void 0:t.getUserMedia)!="function")return{report:{activeCapturePerformed:!1,captureError:"not_supported",captureErrorMessage:"getUserMedia is not available in this environment"},stream:void 0};try{return{report:{deviceAvailable:!0},stream:yield navigator.mediaDevices.getUserMedia({audio:!0})}}catch(e){const{captureError:n,captureErrorMessage:i}=function(s){const o=s&&typeof s=="object"&&"name"in s?String(s.name):"",r=s instanceof Error?s.message:String(s);return o==="NotAllowedError"||o==="PermissionDeniedError"||o==="SecurityError"?{captureError:"permission_denied",captureErrorMessage:`Microphone permission denied: ${r}`}:o==="NotFoundError"||o==="DevicesNotFoundError"||o==="OverconstrainedError"||o==="ConstraintNotSatisfiedError"?{captureError:"no_device",captureErrorMessage:`No microphone device found: ${r}`}:o==="TypeError"?{captureError:"not_supported",captureErrorMessage:`Microphone capture is not supported: ${r}`}:{captureError:"unknown",captureErrorMessage:r}}(e);return{report:{activeCapturePerformed:!1,captureError:n,captureErrorMessage:i,deviceAvailable:!1},stream:void 0}}})}function mw(t,e,n){return U(this,void 0,void 0,function*(){if(typeof AudioContext>"u")return null;let i,s,o;try{i=new AudioContext,s=i.createAnalyser(),o=i.createMediaStreamSource(t),s.fftSize=2048,o.connect(s);const r=new Float32Array(s.fftSize),a=Date.now()+e;let l=0,c=0,u=0;for(;Date.now()<a;){s.getFloatTimeDomainData(r);let d=0;for(const m of r)d+=m*m;const h=Math.sqrt(d/r.length);l=Math.max(l,h),c+=h,u+=1;const p=a-Date.now();p>0&&(yield new Promise(m=>setTimeout(m,Math.min(fw,p))))}return{audioLevel:l,audioDetected:l>=n,audioLevelStats:{peak:l,average:u>0?c/u:0,samples:u}}}catch{return null}finally{try{o==null||o.disconnect(),s==null||s.disconnect(),yield i==null?void 0:i.close()}catch{}}})}function vw(t,e){return U(this,void 0,void 0,function*(){if(typeof MediaRecorder<"u")try{const n=["audio/webm;codecs=opus","audio/webm"].find(r=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(r)),i=n?new MediaRecorder(t,{mimeType:n}):new MediaRecorder(t),s=[],o=Date.now();return yield new Promise(r=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(c),clearTimeout(u),r(d))};i.ondataavailable=({data:d})=>{d.size>0&&s.push(d)},i.onerror=()=>l(),i.onstop=()=>U(this,void 0,void 0,function*(){const d=i.mimeType||n||"audio/webm",h=yield(p=new Blob(s,{type:d}),new Promise(m=>{try{const v=new FileReader;v.onloadend=()=>m(typeof v.result=="string"?v.result:void 0),v.onerror=()=>m(void 0),v.readAsDataURL(p)}catch{m(void 0)}}));var p;l(h?{recordingDataUrl:h,recordingMimeType:d,recordingDurationMs:Date.now()-o}:void 0)});const c=setTimeout(()=>{try{i.state!=="inactive"&&i.stop()}catch{l()}},e),u=setTimeout(()=>l(),e+1e3);i.start()})}catch{return}})}function bf(t){var e,n;return U(this,void 0,void 0,function*(){const i=function(p){var m,v;const b=p&&typeof p=="object"?p:void 0;return{sampleDurationMs:Math.max(0,(m=b==null?void 0:b.sampleDurationMs)!==null&&m!==void 0?m:ia),silenceThreshold:Math.min(1,Math.max(0,(v=b==null?void 0:b.silenceThreshold)!==null&&v!==void 0?v:yf)),record:(b==null?void 0:b.record)===!0,warnOnRecording:b==null?void 0:b.warnOnRecording}}(t.options.microphone),s=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((p=navigator.permissions)===null||p===void 0?void 0:p.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}})}(),{report:o,stream:r}=yield gw(),a=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator<"u"&&typeof((p=navigator.mediaDevices)===null||p===void 0?void 0:p.enumerateDevices)=="function")try{const m=(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:v})=>v==="audioinput").map(({deviceId:v,label:b})=>({deviceId:v||"",label:b||"",kind:"audioinput"}));return{devices:m,deviceCount:m.length,deviceAvailable:m.length>0,labelsAccessible:m.some(({label:v})=>v.length>0)}}catch{return}})}(),l=r?"granted":o.captureError==="permission_denied"?"denied":s,c={currentPermissionState:l,isPermissionGrantedCurrently:l==="granted",isGetUserMediaFailed:!r,deviceAvailable:(a==null?void 0:a.deviceAvailable)||o.deviceAvailable||!1,deviceCount:(e=a==null?void 0:a.deviceCount)!==null&&e!==void 0?e:0,devices:(n=a==null?void 0:a.devices)!==null&&n!==void 0?n:[],labelsAccessible:a==null?void 0:a.labelsAccessible,captureError:o.captureError,captureErrorMessage:o.captureErrorMessage,activeCapturePerformed:o.activeCapturePerformed};if(r)try{const p=yield function(m,v,b){var y,C,T;return U(this,void 0,void 0,function*(){m.activeCapturePerformed=!0,m.recordingPerformed=b.record,b.record&&b.warnOnRecording&&b.warnOnRecording(pw);const[A,x]=yield Promise.all([mw(v,(y=b.sampleDurationMs)!==null&&y!==void 0?y:ia,(C=b.silenceThreshold)!==null&&C!==void 0?C:yf),b.record?vw(v,(T=b.sampleDurationMs)!==null&&T!==void 0?T:ia):Promise.resolve(void 0)]);return A&&(m.audioLevel=A.audioLevel,m.audioDetected=A.audioDetected,m.audioLevelStats=A.audioLevelStats),x&&(m.recordingDataUrl=x.recordingDataUrl,m.recordingMimeType=x.recordingMimeType,m.recordingDurationMs=x.recordingDurationMs,m.recordingPerformed=!0),x})}(c,r,i);p&&(c.playbackPerformed=yield(u=p.recordingDataUrl,d=p.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise(m=>{let v,b=!1;const y=setTimeout(()=>C(!1),d),C=T=>{b||(b=!0,clearTimeout(y),v&&(v.onended=null,v.onerror=null,v.paused||v.pause(),v.src=""),m(T))};try{v=new Audio(u),v.onended=()=>C(!0),v.onerror=()=>C(!1),v.play().catch(()=>C(!1))}catch{C(!1)}})))}finally{try{r.getTracks().forEach(p=>p.stop())}catch{}}var u,d;const h=function(p){const m=[],v=(y,C)=>m.push({code:y,message:C,source:"microphone"});p.currentPermissionState==="denied"&&v("microphone_permission_denied","Microphone permission has been denied by the user."),p.deviceAvailable===!1&&v("microphone_no_device","No audio input device is available.");const b=p.captureError?{permission_denied:["microphone_capture_permission_denied","Active microphone capture was denied permission."],no_device:["microphone_capture_no_device","No microphone device was found for active capture."],not_supported:["microphone_capture_not_supported","Active microphone capture is not supported."],unknown:["microphone_capture_failed","Active microphone capture failed."]}[p.captureError]:void 0;return b&&v(...b),p.activeCapturePerformed&&p.audioDetected===!1&&v("microphone_silent","No audio was detected above the silence threshold during active capture."),m}(c);return h.length>0&&(c.reasons=h),Object.keys(c).length>0?c:void 0})}const sa=300,oa=500,ra=30,aa=100,la=.02,ca=.05,$s=8e3;function mt(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function da(t){const e=t.filter(o=>mt(o)!==void 0);if(e.length===0)return;let n=1/0,i=-1/0,s=0;for(const o of e)o<n&&(n=o),o>i&&(i=o),s+=o;return{min:n,max:i,average:s/e.length}}function ua(t){var e,n;const i=[],s=new Set;t.forEach(r=>{const a=r;i.push(a),a.type==="transport"&&typeof a.selectedCandidatePairId=="string"&&s.add(a.selectedCandidatePairId)});const o=i.filter(r=>r.type==="candidate-pair");return(n=(e=o.find(r=>s.has(r.id)))!==null&&e!==void 0?e:o.find(r=>r.selected===!0||r.nominated===!0&&r.state==="succeeded"))!==null&&n!==void 0?n:o.find(r=>r.state==="succeeded")}function zn(t,e){let n=0,i=!1;for(const s of t){const o=mt(s[e]);o!==void 0&&(n+=o,i=!0)}return i?n:void 0}function Kn(t,e,n=!1){const i=[];return t.forEach(s=>{const o=s;o.type!==e||n&&!function(r){var a;const l=(a=r.kind)!==null&&a!==void 0?a:r.mediaType;return l===void 0||l==="audio"}(o)||i.push(o)}),i}function _w(t,e){const n=t.packets===void 0?e.packets!==void 0:e.packets!==void 0&&e.packets>t.packets,i=t.bytes===void 0?e.bytes!==void 0:e.bytes!==void 0&&e.bytes>t.bytes;return n||i}function wf(t,e){if(t!==void 0&&e!==void 0)return mt(e-t)}function Sf(t,e){var n,i;if(!t.some(c=>Kn(c,`${e}-rtp`,!0).length>0))return;const s=t.map(c=>function(u,d){const h=Kn(u,`${d}-rtp`,!0);return d==="outbound"?{packets:zn(h,"packetsSent"),bytes:zn(h,"bytesSent")}:{packets:zn(h,"packetsReceived"),bytes:zn(h,"bytesReceived")}}(c,e)).filter(({packets:c,bytes:u})=>c!==void 0||u!==void 0),o=(n=s[0])!==null&&n!==void 0?n:{},r=(i=s[s.length-1])!==null&&i!==void 0?i:{},a=wf(o.packets,r.packets),l=wf(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&_w(o,r)},r.packets!==void 0?{packets:r.packets}:{}),r.bytes!==void 0?{bytes:r.bytes}:{}),a!==void 0?{packetsDelta:a}:{}),l!==void 0?{bytesDelta:l}:{})}function Cf(t,e){const n=[];for(const i of t)for(const s of Kn(i,e,!0)){const o=mt(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&n.push(r)}}return n}function Tf(t){const e=zn(t,"packetsReceived"),n=zn(t,"packetsLost"),i=t.map(r=>mt(r.fractionLost)).filter(r=>r!==void 0&&r>=0&&r<=1),s=i.length>0?Math.max(...i):void 0,o=e!==void 0&&n!==void 0?e+n:void 0;return{packetsReceived:e,packetsLost:n,packetLossFraction:s??(n!==void 0&&o!==void 0&&o>0?n/o:void 0)}}function Ef(t){let e;return t.forEach(n=>{e===void 0&&(e=mt(n.timestamp))}),e}function yw(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,n=Sf(e,"inbound"),i=Sf(e,"outbound"),s=da(function(p){var m;const v=[];for(const b of p){let y=!1;const C=Kn(b,"remote-inbound-rtp",!0);for(const T of C){const A=mt(T.roundTripTime);if(A!==void 0){const x=1e3*A;x>=0&&(v.push(x),y=!0)}}if(!y){const T=mt((m=ua(b))===null||m===void 0?void 0:m.currentRoundTripTime);if(T!==void 0){const A=1e3*T;A>=0&&v.push(A)}}}return v}(e)),o=(r=da(Cf(e,"inbound-rtp")),a=da(Cf(e,"remote-inbound-rtp")),(r==null?void 0:r.average)===void 0?a:(a==null?void 0:a.average)===void 0?r:a.average>r.average?a:r);var r,a;const l=function(p,m,v){var b;if(p.length===0)return;const y=p[p.length-1],C=Kn(y,"inbound-rtp",!0),T=Kn(y,"remote-inbound-rtp",!0),A=function(_,g){return _.packetLossFraction===void 0?g:g.packetLossFraction===void 0?_:g.packetLossFraction>_.packetLossFraction?g:_}(Tf(C),Tf(T));let x=v==null?void 0:v.packets,N=(b=A.packetsReceived)!==null&&b!==void 0?b:m==null?void 0:m.packets;const k=A.packetsLost,E=A.packetLossFraction,f=ua(y);return x===void 0&&(x=mt(f==null?void 0:f.packetsSent)),N===void 0&&(N=mt(f==null?void 0:f.packetsReceived)),x!==void 0||N!==void 0||k!==void 0?{packetsSent:x,packetsReceived:N,packetsLost:k,packetLossFraction:E}:void 0}(e,n,i),c=function(p,m,v){if(p.length===0)return;const b=p[p.length-1];let y=v==null?void 0:v.bytes,C=m==null?void 0:m.bytes;const T=ua(b);return y===void 0&&(y=mt(T==null?void 0:T.bytesSent)),C===void 0&&(C=mt(T==null?void 0:T.bytesReceived)),y!==void 0||C!==void 0?{bytesSent:y,bytesReceived:C}:void 0}(e,n,i),u=function(p,m,v){if(p.length<2)return;const b=p[0],y=p[p.length-1],C=Ef(b),T=Ef(y);if(C===void 0||T===void 0)return;const A=(T-C)/1e3;if(A<=0)return;const x=(v==null?void 0:v.bytesDelta)!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/A:void 0,N=(m==null?void 0:m.bytesDelta)!==void 0&&m.bytesDelta>=0?8*m.bytesDelta/A:void 0;return x!==void 0||N!==void 0?{outbound:x,inbound:N}:void 0}(e,n,i),d=function(p,m,v){let b=!1,y="good";return(p==null?void 0:p.average)!==void 0&&(b=!0,p.average>=oa?y="poor":p.average>=sa&&y==="good"&&(y="fair")),(m==null?void 0:m.average)!==void 0&&(b=!0,m.average>=aa?y="poor":m.average>=ra&&y==="good"&&(y="fair")),(v==null?void 0:v.packetLossFraction)!==void 0&&(b=!0,v.packetLossFraction>=ca?y="poor":v.packetLossFraction>=la&&y==="good"&&(y="fair")),b?y:"unknown"}(s,o,l),h=function(p,m,v,b){const y=[];return(p==null?void 0:p.average)!==void 0&&(p.average>=oa?y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (poor: ≥${oa}ms threshold)`,source:"network"}):p.average>=sa&&y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (degraded: ≥${sa}ms threshold)`,source:"network"})),(m==null?void 0:m.average)!==void 0&&(m.average>=aa?y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (poor: ≥${aa}ms threshold)`,source:"network"}):m.average>=ra&&y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (degraded: ≥${ra}ms threshold)`,source:"network"})),(v==null?void 0:v.packetLossFraction)!==void 0&&(v.packetLossFraction>=ca?y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (poor: ≥${100*ca}% threshold)`,source:"network"}):v.packetLossFraction>=la&&y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (degraded: ≥${100*la}% threshold)`,source:"network"})),b&&(b.outbound!==void 0&&b.outbound<$s&&y.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(b.outbound)} bps (<${$s} bps threshold)`,source:"network"}),b.inbound!==void 0&&b.inbound<$s&&y.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(b.inbound)} bps (<${$s} bps threshold)`,source:"network"})),y}(s,o,l,t.options.mode==="network-only"?void 0:u);return{quality:d,rtt:s,jitter:o,packets:l,bytes:c,bitrate:u,inbound:n,outbound:i,reasons:h.length>0?h:void 0}}function kf(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ha(t,e){return t.find(n=>n.label===e)}class bw{constructor(){this.startedAtMonoMs=If()}build(e={}){var n,i;const s={};try{const o=(i=(n=e.call)===null||n===void 0?void 0:n.getEstablishmentTimings)===null||i===void 0?void 0:i.call(n);if(o){s.callEstablishment={mode:o.mode,direction:o.direction,steps:o.steps.map(d=>Object.assign({},d))};const r=ha(o.steps,"ICE candidate gathering started"),a=ha(o.steps,"All ICE candidates gathered"),l=kf(r&&a?a.fromStart-r.fromStart:void 0);l!==void 0&&(s.iceGatheringMs=l);const c=ha(o.steps,"First server-reflexive/relay candidate found"),u=kf(r&&c?c.fromStart-r.fromStart:void 0);u!==void 0&&(s.firstNonHostCandidateMs=u)}}catch{}return s}complete(e){const n=If()-this.startedAtMonoMs;Number.isFinite(n)&&n>=0&&(e.totalMs=n)}}function If(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function fa(){return new bw}const $t={NoCandidates:"ice_no_candidates",OnlyHostCandidates:"ice_only_host_candidates",GatheringTimeout:"ice_gathering_timeout",NoSelectedPair:"ice_no_selected_pair",TurnRequired:"ice_turn_required",ServerNoCandidates:"ice_server_no_candidates",MultipleInterfaces:"ice_multiple_interfaces",VpnDetected:"ice_vpn_detected"},Ni={LowBitrate:"network_low_bitrate",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},pa={CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureFailed:"microphone_capture_failed"},vn=()=>({reasons:[],warnings:[]}),Af={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function Xe(t,e){return t?e?Af[t]>=Af[e]?t:e:t:e}function at(t,e,n){return{code:t,message:e,source:n}}function Fi(t,e,n){return{code:t,message:e,source:n}}function Rf(t,e=!1){var n;if(!t)return vn();const i=vn(),{reasons:s,warnings:o}=i,r=t.candidates.length>0;r||(s.push(at($t.NoCandidates,"No ICE candidates were gathered.","ice")),i.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(Fi($t.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(at($t.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),i.verdict=Xe(i.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(at($t.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),i.verdict=Xe(i.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(at($t.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),i.verdict=Xe(i.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(at($t.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),i.verdict=Xe(i.verdict,"degraded"));const l=((n=t.serverCandidateComparison)!==null&&n!==void 0?n:[]).filter(({hasCandidates:c})=>!c);return l.length>0&&o.push(Fi($t.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(Fi($t.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(Fi($t.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!i.verdict&&r&&(i.verdict="ready"),i}function ww(t){if(t.established&&!t.error)return vn();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[at("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function xf(t,e=!0){var n;if(!t)return vn();const i=vn(),{reasons:s,warnings:o}=i,r=e?t.reasons:(n=t.reasons)===null||n===void 0?void 0:n.filter(({code:l})=>l!==Ni.LowBitrate);switch(r!=null&&r.length&&(s.push(...r),i.verdict="degraded"),t.quality){case"poor":s.push(at(Ni.PoorQuality,"Network quality is poor.","network")),i.verdict=Xe(i.verdict,"blocked");break;case"fair":o.push(Fi(Ni.FairQuality,"Network quality is fair.","network")),i.verdict=Xe(i.verdict,"degraded");break;case"good":i.verdict=Xe(i.verdict,"ready")}const a=[t.inbound,t.outbound].filter(l=>!!l);if(e&&a.length>0){const l=a.filter(({flowing:c})=>c).length;a.length===2&&l===2?i.verdict=Xe(i.verdict,"ready"):l>0?(s.push(at(Ni.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),i.verdict=Xe(i.verdict,"blocked")):(s.push(at(Ni.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),i.verdict=Xe(i.verdict,"blocked"))}return i}function Sw(t){var e;if(!t)return vn();const n=vn();!((e=t.reasons)===null||e===void 0)&&e.length&&n.reasons.push(...t.reasons);const i=t.currentPermissionState==="denied"||t.isPermissionGrantedCurrently===!1||t.captureError==="permission_denied",s=t.deviceAvailable===!1||t.captureError!==void 0,o=t.activeCapturePerformed===!0&&t.audioDetected===!1;return i?n.verdict="permission_denied":s?n.verdict="blocked":o?n.verdict="degraded":(t.activeCapturePerformed===!0&&t.audioDetected===!0||t.activeCapturePerformed!==!0&&t.isPermissionGrantedCurrently===!0&&t.deviceAvailable!==!1)&&(n.verdict="ready"),n}class ga{constructor(e){this.options=e}run(){return U(this,void 0,void 0,function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(gf(this.options));default:return this.runFull()}})}runFull(){return U(this,void 0,void 0,function*(){const e=yield this.runTest({diagnosticOptions:this.options,modules:{ice:!!this.options.ice,network:!!this.options.network,microphone:!!this.options.microphone},autoHangup:this.options.autoHangup!==!1});return e.setupFailed?e.error?Yn({callId:e.callId,timings:e.timings},e.error):{version:1,verdict:"inconclusive",reasons:[{code:"call_setup_timeout",message:"The diagnostic call did not reach the established state",source:"diagnostic"}],callId:e.callId,timings:e.timings}:Yn({ice:e.ice,network:e.network,microphone:e.microphone,timings:e.timings,callId:e.callId,raw:e.raw},e.error)})}runNetworkOnly(){var e,n,i;return U(this,void 0,void 0,function*(){const s=this.options.client.iceServers,o=function(c){const u=[];for(const d of c)(Array.isArray(d.urls)?d.urls:[d.urls]).forEach(h=>{u.push(Object.assign(Object.assign({},d),{urls:h}))});return u}((i=(n=(e=this.options.rtcConfig)===null||e===void 0?void 0:e.iceServers)!==null&&n!==void 0?n:s)!==null&&i!==void 0?i:[]);let r=[];const a=fa();let l;try{return r=yield Promise.all(o.map(c=>U(this,void 0,void 0,function*(){const u=yield this.runTest({diagnosticOptions:Object.assign(Object.assign({},this.options),{durationMs:3e3,statsSampleIntervalMs:500,rtcConfig:Object.assign(Object.assign({},this.options.rtcConfig),{iceServers:[c]})}),iceServers:[c],forceRelayCandidate:mf(c),modules:{ice:!0,network:!!this.options.network,microphone:!1},autoHangup:!0}),d=function(h){if(h.error)return h.error.message;if(h.setupFailed)return"The diagnostic call did not reach the established state";if(!h.ice)return"No ICE report was produced";if(h.ice.candidates.length===0)return"No ICE candidates were gathered";if(!h.ice.hasSelectedPair)return"No ICE candidate pair was selected"}(u);return{server:c,established:d===void 0,callId:u.callId,ice:u.ice,network:u.network,timings:u.timings,error:d}}))),l=Yn({serverTests:r,timings:a.build()},void 0,{networkOnly:!0}),l}catch(c){return l=Yn({timings:a.build()},js(c),{networkOnly:!0}),l}finally{l!=null&&l.timings&&a.complete(l.timings)}})}runTest(e){return U(this,void 0,void 0,function*(){const n=gf(e.diagnosticOptions),i=fa();let s,o,r,a=!1;const l=c=>{c.callId===(s==null?void 0:s.id)&&(o=js(c.error))};e.diagnosticOptions.client.on("telnyx.error",l);try{if(s=this.createDiagnosticCall(e.diagnosticOptions,e.iceServers,e.forceRelayCandidate),n.call=s,a=yield this.waitForCallEstablishment(s),!a)return r={established:!1,setupFailed:!0,callId:s.id,timings:i.build({call:s}),error:o},r;yield this.collectSamples(s,n);const c=e.modules.ice?uw(n):void 0,u=e.modules.network?yw(n):void 0,d=e.modules.microphone?yield bf(n):void 0;return r={established:!0,setupFailed:!1,callId:s.id,ice:c,network:u,microphone:d,timings:i.build({call:s}),raw:{samples:n.statsSamples.length?n.statsSamples:void 0}},r}catch(c){return n.error=js(c),r={established:a,setupFailed:!1,callId:s==null?void 0:s.id,timings:i.build({call:s}),error:n.error},r}finally{if(e.diagnosticOptions.client.off("telnyx.error",l),s&&e.autoHangup)try{yield s.hangup()}catch{}r!=null&&r.timings&&i.complete(r.timings)}})}runMicrophoneOnly(e){return U(this,void 0,void 0,function*(){const n=fa();let i;try{return i=Yn({microphone:this.options.microphone?yield bf(e):void 0,timings:n.build()},e.error),i}catch(s){return e.error=js(s),i=Yn({timings:n.build()},e.error),i}finally{i!=null&&i.timings&&n.complete(i.timings)}})}waitForCallEstablishment(e){return U(this,void 0,void 0,function*(){const n=Date.now()+3e4,i=()=>{var s,o;return e.state==="active"&&((o=(s=e.peer)===null||s===void 0?void 0:s.instance)===null||o===void 0?void 0:o.connectionState)==="connected"};for(;Date.now()<n;){if(i())return!0;if(["done","hangup","destroy"].includes(e.state))return!1;yield Df(500)}return i()})}createDiagnosticCall(e,n,i=!1){const{client:s,destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c,rtcConfig:u}=e;return s.newCall({destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c===!0,iceServers:n??(u==null?void 0:u.iceServers),forceRelayCandidate:i})}collectSamples(e,n){var i,s,o;return U(this,void 0,void 0,function*(){const r=(i=n.options.durationMs)!==null&&i!==void 0?i:5e3,a=(s=n.options.statsSampleIntervalMs)!==null&&s!==void 0?s:1e3,l=Date.now()+r;for(;Date.now()<l;){try{const c=yield(o=e.peer.instance)===null||o===void 0?void 0:o.getStats();c&&n.statsSamples.push(c)}catch{}yield Df(Math.min(a,Math.max(0,l-Date.now())))}})}}function Yn(t,e,n){const{verdict:i,reasons:s,warnings:o}=function(r,a,l={}){var c,u;const d=[Rf(r.ice),xf(r.network),Sw(r.microphone),...((c=r.serverTests)!==null&&c!==void 0?c:[]).flatMap(v=>[Rf(v.ice,l.networkOnly&&mf(v.server)),xf(v.network,!l.networkOnly),ww(v)])],h=d.flatMap(v=>v.reasons),p=d.flatMap(v=>v.warnings);let m=d.reduce((v,b)=>Xe(v,b.verdict),void 0);if(l.networkOnly&&!((u=r.serverTests)===null||u===void 0)&&u.length){const v=r.serverTests.filter(b=>b.established&&!b.error).length;v===0?m="blocked":v<r.serverTests.length&&(m="degraded")}if(a)switch(a.code){case yh:h.push(at(pa.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),m=Xe(m,"permission_denied");break;case bh:h.push(at(pa.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;case Br:h.push(at(pa.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;default:h.push(at("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),m=Xe(m,"blocked")}return{verdict:m??"inconclusive",reasons:h,warnings:p}}(t,e,n);return Object.assign(Object.assign({},t),{version:1,verdict:i??"inconclusive",reasons:s.length?s:void 0,warnings:o.length?o:void 0})}function js(t){return t instanceof Error?t:new Error(String(t))}function Df(t){return new Promise(e=>setTimeout(e,t))}const Lf="+1-872-231-5806";class Cw extends dw{constructor(e){super(e),w.info(`SDK version: ${Kh}`)}newCall(e){return super.newCall(e)}runPreCall(e={}){var n,i;return U(this,void 0,void 0,function*(){const s={client:this,destinationNumber:(n=e.destinationNumber)!==null&&n!==void 0?n:Lf,durationMs:e.durationMs,ice:!0,network:!0,microphone:!0,mode:"full",rtcConfig:{iceServers:(i=e.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new ga(s).run()})}runNetworkCheck(e={}){var n;return U(this,void 0,void 0,function*(){const i={client:this,destinationNumber:Lf,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(n=e.iceServers)!==null&&n!==void 0?n:this.iceServers}};return new ga(i).run()})}runMicrophoneCheck(e={}){var n;return U(this,void 0,void 0,function*(){const i={client:this,ice:!1,network:!1,microphone:{sampleDurationMs:e.durationMs,silenceThreshold:e.silenceThreshold,record:(n=e.record)!==null&&n!==void 0&&n,warnOnRecording:e.warnOnRecording},mode:"microphone-only"};return new ga(i).run()})}static webRTCInfo(){return Xb()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Re.not_supported},{browserName:"Firefox",supported:Re.not_supported},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",supported:Re.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",features:["video","audio"],supported:Re.full},{browserName:"Edge",features:["audio"],supported:Re.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Re.full},{browserName:"Firefox",features:["audio"],supported:Re.partial},{browserName:"Safari",supported:Re.not_supported},{browserName:"Edge",features:["audio"],supported:Re.partial}]}]}}function Tw(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const n=e;return n.type==="function_call"&&typeof n.call_id=="string"&&typeof n.name=="string"&&typeof n.arguments=="string"}function Mf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Of={exports:{}},Pf;function Ew(){return Pf||(Pf=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||l,h),m=n?n+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=p,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,p=new Array(h);d<h;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,p){var m=n?n+l:l;if(!this._events[m])return!1;var v=this._events[m],b=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,p),!0}for(C=1,y=new Array(b-1);C<b;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var T=v.length,A;for(C=0;C<T;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!y)for(A=1,y=new Array(b-1);A<b;A++)y[A-1]=arguments[A];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var m=0,v=[],b=p.length;m<b;m++)(p[m].fn!==c||d&&!p[m].once||u&&p[m].context!==u)&&v.push(p[m]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Of)),Of.exports}var kw=Ew();const Ui=Mf(kw),ma=new Ui;var va={exports:{}},Iw=va.exports,Nf;function Aw(){return Nf||(Nf=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(Iw,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==n&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===n||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function k(){var g;if(!(typeof window===n||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===n)try{var S=window.document.cookie,I=encodeURIComponent(x),P=S.indexOf(I+"=");P!==-1&&(g=/^([^;]+)/.exec(S.slice(P+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function E(){if(!(typeof window===n||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),k()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=k();_!=null&&(A=f(_)),u.call(y)}r=new p,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};var m=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(va)),va.exports}var Rw=Aw();const xw=Mf(Rw),Dw=()=>new Date().toISOString().replace("T"," ").replace("Z",""),pe=xw.getLogger("telnyx-ai-agent"),Lw=pe.methodFactory;pe.methodFactory=(t,e,n)=>{const i=Lw(t,e,n);return function(...s){i(Dw(),"-",...s)}},pe.setLevel("info");function Mw(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const Ow=10,Pw=500,Nw=100,Fw=300,Ff=20;class Uw{constructor(e){B(this,"remoteIntervalId",null);B(this,"localIntervalId",null);B(this,"remoteStream",null);B(this,"localStream",null);B(this,"remoteAudioContext",null);B(this,"remoteSource",null);B(this,"remoteAnalyser",null);B(this,"localAudioContext",null);B(this,"localSource",null);B(this,"localAnalyser",null);B(this,"thinkingStartTime",null);B(this,"lastState",null);B(this,"userIsSpeaking",!1);B(this,"lastUserAudioTime",null);B(this,"userSpeechStartTime",null);B(this,"remoteSilenceStartTime",null);B(this,"remoteSilenceThresholdMs");B(this,"userSilenceStartTime",null);B(this,"isFirstAgentSpeech",!0);B(this,"monitorStartTime",null);B(this,"volumeThreshold");B(this,"silenceDurationMs");B(this,"minSpeechDurationMs");B(this,"maxLatencyMs");B(this,"updateAgentState",Mw(e=>{pe.debug("AudioStreamMonitor updateAgentState",e),pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ma.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Ow,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Pw,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Nw,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??Fw}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null,this.remoteSilenceStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;pe.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&pe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(this.remoteSilenceStartTime=null,i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&(this.remoteSilenceStartTime===null&&(this.remoteSilenceStartTime=performance.now()),performance.now()-this.remoteSilenceStartTime>=this.remoteSilenceThresholdMs&&this.updateAgentState({state:"listening"}));i=r};this.remoteIntervalId=window.setInterval(s,Ff)}startLocalMonitor(){if(!this.localStream){pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(pe.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&pe.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Ff)}destroy(){this.stopAudioStreamMonitor()}}function Bw(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Vw(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function $w(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Bi(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function jw(t){if(!Bi(t))return null;const e=t.params;return Tw(e)?e.item:null}function Hw(t){if(!Bi(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const n=[];for(const i of e.client_side_tools)if(i&&typeof i=="object"&&typeof i.name=="string"){const s=i;n.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return n}function Ww(t){if(!Bi(t))return null;const e=t.params;if(!e||typeof e!="object")return null;const n=e;if(n.type==="response.audio.delta"){const i=n.format;if(!i||typeof i!="object")return null;const s=i;return typeof n.response_id!="string"||typeof n.delta!="string"||typeof n.sequence!="number"||!Number.isInteger(n.sequence)||typeof s.encoding!="string"||typeof s.sample_rate!="number"||typeof s.channels!="number"?null:{type:"response.audio.delta",response_id:n.response_id,item_id:typeof n.item_id=="string"?n.item_id:void 0,sequence:n.sequence,delta:n.delta,format:{encoding:s.encoding,sample_rate:s.sample_rate,channels:s.channels}}}return n.type==="response.audio.done"&&typeof n.response_id=="string"?{type:"response.audio.done",response_id:n.response_id}:n.type==="response.audio.interrupted"?{type:"response.audio.interrupted",response_id:typeof n.response_id=="string"?n.response_id:void 0}:null}function Gw(t){var e;return Bi(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function qw(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const zw=3e4;function Kw(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function _a(t){return JSON.stringify({error:t})}class Yw{constructor(e){B(this,"registry",new Map);B(this,"toolTimeouts",new Map);B(this,"inFlight",new Set);B(this,"completed",new Set);B(this,"generation",0);B(this,"getActiveCall");B(this,"timeoutMs");B(this,"events");B(this,"handleEvent",e=>{const n=Hw(e);if(n){this.ingestToolSettings(n);return}const i=jw(e);i&&this.execute(i)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:zw,this.events={onInvoked:n=>this.safeEmit(()=>e.events.onInvoked(n)),onCompleted:n=>this.safeEmit(()=>e.events.onCompleted(n)),onError:n=>this.safeEmit(()=>e.events.onError(n))}}safeEmit(e){try{e()}catch(n){pe.warn(`[client-tools] lifecycle listener threw: ${n instanceof Error?n.message:"unknown error"}`)}}register(e,n){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof n!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,n)}registerAll(e){for(const[n,i]of Object.entries(e))this.register(n,i)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:n,timeout_ms:i}of e)typeof i=="number"&&i>0&&this.toolTimeouts.set(n,i)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,n){this.generation===n&&this.completed.add(e)}async execute(e){const{call_id:n,name:i}=e;if(this.inFlight.has(n)||this.completed.has(n)){pe.debug(`[client-tools] duplicate function_call ignored (call_id=${n})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(i);if(!r){pe.warn(`[client-tools] no handler registered for tool "${i}"`),this.markCompleted(n,s),this.events.onError({callId:n,toolName:i,reason:"unknown_tool"}),this.sendOutput(n,i,_a("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{pe.warn(`[client-tools] invalid JSON arguments for tool "${i}" (call_id=${n})`),this.markCompleted(n,s),this.events.onError({callId:n,toolName:i,reason:"invalid_arguments"}),this.sendOutput(n,i,_a("invalid_arguments"),!0,s,o);return}this.inFlight.add(n),this.events.onInvoked({callId:n,toolName:i});const l={callId:n,toolName:i,rawArguments:e.arguments},c=this.toolTimeouts.get(i)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),n,i,c);this.sendOutput(n,i,Kw(u),!1,s,o)}catch(u){const d=u instanceof Uf?"timeout":"handler_error";pe.warn(`[client-tools] tool "${i}" failed (call_id=${n}, reason=${d})`),this.events.onError({callId:n,toolName:i,reason:d}),this.sendOutput(n,i,_a(d),!0,s,o)}finally{this.inFlight.delete(n),this.markCompleted(n,s)}}withTimeout(e,n,i,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Uf(i,n,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,n,i,s,o,r){if(this.generation!==o){pe.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:n,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){pe.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:n,reason:"shutdown"});return}if(!r||a!==r){pe.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:n,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:i}),this.events.onCompleted({callId:e,toolName:n,isError:s})}catch(l){pe.warn(`[client-tools] failed to send output for "${n}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:n,reason:"shutdown"})}}}class Uf extends Error{constructor(e,n,i){super(`Client tool "${e}" timed out after ${i}ms (call_id=${n})`),this.name="ToolTimeoutError"}}const Ws=class Ws{constructor(e){B(this,"enabled");B(this,"getActiveCall");B(this,"events");B(this,"subscriptionConfirmed",!1);B(this,"subscribeAttempts",0);B(this,"handleEvent",e=>{if(!this.enabled)return;if(Gw(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const n=Ww(e);if(n){if(this.subscriptionConfirmed=!0,n.type==="response.audio.delta"){let i;try{i=Xw(n.delta)}catch(s){pe.warn(`[streaming-audio] invalid base64 delta for response ${n.response_id}: ${s instanceof Error?s.message:"unknown error"}`);return}this.emitSafely(()=>this.events.onDelta({responseId:n.response_id,itemId:n.item_id,sequence:n.sequence,audio:i,format:{encoding:n.format.encoding,sampleRate:n.format.sample_rate,channels:n.format.channels}}));return}if(n.type==="response.audio.done"){this.emitSafely(()=>this.events.onDone({responseId:n.response_id}));return}this.emitSafely(()=>this.events.onInterrupted({responseId:n.response_id}))}});this.enabled=e.enabled,this.getActiveCall=e.getActiveCall,this.events=e.events}onCallActive(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0,this.sendSubscription()}reset(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0}sendSubscription(){if(!this.enabled||this.subscribeAttempts>=Ws.MAX_SUBSCRIBE_ATTEMPTS)return;const e=this.getActiveCall();if(e)try{const n={type:"response.audio_stream.subscribe"};e.sendAIConversationMessage(n),this.subscribeAttempts+=1}catch(n){pe.warn(`[streaming-audio] failed to subscribe: ${n instanceof Error?n.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(n){pe.warn(`[streaming-audio] event listener threw: ${n instanceof Error?n.message:"unknown error"}`)}}};B(Ws,"MAX_SUBSCRIBE_ATTEMPTS",10);let ya=Ws;function Xw(t){const e=globalThis.atob(t);return Uint8Array.from(e,n=>n.charCodeAt(0))}function Bf(t){if(!Bi(t))return null;const e=t.params;if(e.type==="response.error"){if(!e.error||typeof e.error!="object")return null;const i=e.error.reason;return typeof i=="string"&&i.length>0?{type:"response.error",reason:i}:null}if(e.type!=="response.text.delta"&&e.type!=="response.text.done"||typeof e.item_id!="string"||!e.item_id||typeof e.response_id!="string"||!e.response_id)return null;const n=e.type==="response.text.delta"?e.delta:e.text;return typeof n!="string"||e.type==="response.text.delta"&&!n?null:{type:e.type,itemId:e.item_id,text:n}}function Vf(t){return Vw(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Jw(t){if(!$w(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class $f extends Ui{constructor(n,i={}){super();B(this,"source");B(this,"assembleAssistantMessages");B(this,"completedItemIds",new Set);B(this,"transcript",[]);B(this,"onSocketMessage",n=>{if(!(!Bw(n)||!n.params))switch(n.params.type){case"response.text.delta":{if(this.assembleAssistantMessages){this.handleAssistantText(n);return}const i=Vf(n);i&&(this.transcript.push(i),this.emit("transcript.item",i));return}case"response.text.done":{this.assembleAssistantMessages&&this.handleAssistantText(n);return}case"conversation.item.deleted":{if(qw(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&(this.transcript.splice(s,1),this.emitTranscriptUpdated())}return}case"conversation.item.created":{const i=Jw(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i),this.emitTranscriptUpdated()}return}}});this.source=n,this.assembleAssistantMessages=i.assembleAssistantMessages??!1,this.source.on(F.SocketMessage,this.onSocketMessage)}detach(){this.source.off(F.SocketMessage,this.onSocketMessage)}emitTranscriptUpdated(){this.assembleAssistantMessages&&this.emit("transcript.updated",[...this.transcript])}handleAssistantText(n){const i=Bf(n);if(!i||i.type==="response.error"||this.completedItemIds.has(i.itemId))return;const s=this.transcript.findIndex(a=>a.role==="assistant"&&a.id===i.itemId),o=this.transcript[s],r={id:i.itemId,role:"assistant",content:i.type==="response.text.delta"?((o==null?void 0:o.content)??"")+i.text:i.text,timestamp:(o==null?void 0:o.timestamp)??new Date};if(o?this.transcript[s]=r:r.content&&this.transcript.push(r),i.type==="response.text.done")this.completedItemIds.add(i.itemId),this.emit("response.done"),!o&&r.content&&this.emit("transcript.item",r);else{const a=Vf(n);a&&this.emit("transcript.item",a)}this.emitTranscriptUpdated()}}const jt=t=>typeof t=="object"&&t!==null,jf=t=>{const e=jt(t)&&jt(t.result)?t.result:t;if(!(!jt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Qw=t=>jt(t)&&jt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Zw=(t,e)=>{if(!e||!jt(t)||!jt(t.request))return;const{request:n}=t;if(n.method!=="login"&&n.method!=="anonymous_login"||!jt(n.params))return;const i=n.params;jt(i["User-Agent"])&&(i["User-Agent"].widgetVersion=e),n.method==="anonymous_login"&&(i.widget_version=e)};class eS extends Ui{constructor(n){super();B(this,"telnyxRTC");B(this,"transcription");B(this,"removeLoginSuccessHook",null);B(this,"authenticated",!1);B(this,"authenticating",!1);B(this,"agentId");B(this,"versionId");B(this,"widgetVersion");B(this,"conversationId");B(this,"debug");B(this,"audioStreamMonitor");B(this,"clientTools");B(this,"streamingAudio");B(this,"activeCall");B(this,"chatMode");B(this,"dc",null);B(this,"region",null);B(this,"callReportId",null);B(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const n={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",n)});B(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});B(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});B(this,"onSocketMessage",n=>{const i=jf(n);i!==void 0&&this.emitLoginSuccess({sessionId:i})});B(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,this.streamingAudio.onCallActive(),n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.streamingAudio.reset(),this.audioStreamMonitor.stopAudioStreamMonitor()))});B(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});B(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.widgetVersion=n.widgetVersion,this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,pe.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId},s={};n.conversationId&&(s.conversation_id=n.conversationId),n.streamingAudio&&(s.streamingAudio=!0),Object.keys(s).length>0&&(i.target_params=s),n.widgetVersion&&(i.widget_version=n.widgetVersion),this.telnyxRTC=new Cw({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,prefetchIceCandidates:n.prefetchIceCandidates,region:n.region,skipLastVoiceSdkId:n.skipLastVoiceSdkId??!0,rtcIp:n.rtcIp,rtcPort:n.rtcPort}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(F.Ready,this.onClientReady),this.telnyxRTC.on(F.Error,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketClose,this.onSocketClose),this.telnyxRTC.on(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(F.Notification,this.onNotification),this.transcription=new $f(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ma.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Uw(n.vad),this.clientTools=new Yw({getActiveCall:()=>this.activeCall,timeoutMs:n.clientToolTimeoutMs,events:{onInvoked:o=>this.emit("client.tool.invoked",o),onCompleted:o=>this.emit("client.tool.completed",o),onError:o=>this.emit("client.tool.error",o)}}),n.clientTools&&this.clientTools.registerAll(n.clientTools),this.telnyxRTC.on(F.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new ya({enabled:n.streamingAudio??!1,getActiveCall:()=>this.activeCall,events:{onDelta:o=>this.emit("assistant.audio.delta",o),onDone:o=>this.emit("assistant.audio.done",o),onInterrupted:o=>this.emit("assistant.audio.interrupted",o)}}),this.telnyxRTC.on(F.AIConversationMessage,this.streamingAudio.handleEvent)}registerClientTool(n,i){this.clientTools.register(n,i)}unregisterClientTool(n){return this.clientTools.unregister(n)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var n;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(F.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(F.AIConversationMessage,this.streamingAudio.handleEvent),this.clientTools.reset(),this.streamingAudio.reset(),(n=this.removeLoginSuccessHook)==null||n.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(F.Ready,this.onClientReady),this.telnyxRTC.off(F.Error,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketClose,this.onSocketClose),this.telnyxRTC.off(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(F.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ma.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){pe.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw pe.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw pe.warn(d.message),this.emit("agent.error",d),d}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}installLoginSuccessHook(){const n=this.telnyxRTC,i=n.execute,s=n.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=p=>{c===p&&(this.authenticating=!1)},d=function(p){const m=Qw(p),v=c;return m&&Zw(p,a),i.call(this,p).then(b=>{const y=m?jf(b):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),b})},h=function(p){const m=++c;if(l){const v={sessionId:n.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&n.login===h&&u(m)})};return n.execute=d,n.login=h,()=>{l=!1,n.execute===d&&(n.execute=i),n.login===h&&(n.login=s)}}emitLoginStarted(n){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",n)}emitLoginSuccess(n){const i=this.telnyxRTC,s=i.sessionid||null;n.sessionId&&(i.sessionid=n.sessionId);const o=n.sessionId||i.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}const tS={production:"rtc.telnyx.com",development:"rtcdev.telnyx.com"};function nS(t){if(t.url)return t.url;const e=tS[t.environment??"production"];return`wss://${t.region?`${t.region}.`:""}${e}`}let iS=0;const sS=()=>`text-chat-${Date.now()}-${++iS}`;class oS extends Ui{constructor(n){super();B(this,"socket",null);B(this,"pending",new Map);B(this,"options");B(this,"closedByUs",!1);B(this,"conversationId",null);B(this,"assistantVersionId",null);B(this,"onMessage",n=>{let i;try{i=JSON.parse(n.data)}catch{pe.warn("[TextChat] dropping non-JSON frame");return}const s=i,o=s.id?this.pending.get(s.id):void 0;if(o){this.pending.delete(s.id),s.error?o.reject(new Error(s.error.message??"Text chat error")):o.resolve(s.result??{});return}this.emit(F.SocketMessage,i)});B(this,"onClose",n=>{this.closedByUs||this.teardown("Text chat socket closed"),this.emit(F.SocketClose,n)});B(this,"onError",()=>{this.emit(F.SocketError,new Error("Text chat socket error"))});this.options=n,this.conversationId=n.conversationId??null}get isConnected(){var n;return((n=this.socket)==null?void 0:n.readyState)===WebSocket.OPEN}async connect(){if(this.socket)throw new Error("Text chat transport is already connected");const n=nS(this.options);pe.debug("[TextChat] connecting to",n);const i=new WebSocket(n);this.socket=i,this.closedByUs=!1;try{if(await new Promise((o,r)=>{const a=()=>{u(),o()},l=()=>{u(),r(new Error(`Failed to connect to ${n}`))},c=()=>{u(),r(new Error(`Connection to ${n} closed before it opened`))},u=()=>{i.removeEventListener("open",a),i.removeEventListener("error",l),i.removeEventListener("close",c)};i.addEventListener("open",a),i.addEventListener("error",l),i.addEventListener("close",c)}),this.socket!==i)throw new Error("Text chat transport is not connected");i.addEventListener("message",this.onMessage),i.addEventListener("close",this.onClose),i.addEventListener("error",this.onError);const s=await this.request("text_chat_login",{target_type:"ai_assistant",target_id:this.options.assistantId,target_version_id:this.options.versionId,conversation_id:this.conversationId??void 0});return this.conversationId=s.conversation_id??null,this.assistantVersionId=s.ai_assistant_version_id??null,{conversationId:this.conversationId,assistantVersionId:this.assistantVersionId}}catch(s){throw this.socket===i&&this.teardown("Text chat transport failed to connect"),s}}async sendMessage(n){await this.request("text_chat_message",{content:n})}disconnect(){this.closedByUs=!0,this.teardown("Text chat transport disconnected")}teardown(n){var i,s,o,r;this.rejectPending(n),(i=this.socket)==null||i.removeEventListener("message",this.onMessage),(s=this.socket)==null||s.removeEventListener("close",this.onClose),(o=this.socket)==null||o.removeEventListener("error",this.onError),(r=this.socket)==null||r.close(),this.socket=null}rejectPending(n){for(const[,i]of this.pending)i.reject(new Error(n));this.pending.clear()}request(n,i){const s=this.socket;if(!s||s.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Text chat transport is not connected"));const o=sS();return new Promise((r,a)=>{this.pending.set(o,{resolve:r,reject:a}),s.send(JSON.stringify({jsonrpc:"2.0",id:o,method:n,params:i}))})}}class rS extends Error{constructor(n){const i={stream_truncated:"The assistant response ended before it was complete.",stream_failed:"The assistant response stream failed.",assistant_error:"The assistant could not complete its response."};super(Object.hasOwn(i,n)?i[n]:`Assistant response failed: ${n}`);B(this,"reason");this.name="TextChatResponseError",this.reason=n}}class aS extends Ui{constructor(n){super();B(this,"agentId");B(this,"transport");B(this,"transcription");B(this,"connected",!1);B(this,"agentState","listening");B(this,"onSocketClose",()=>{this.connected&&(this.connected=!1,this.setAgentState("listening"),this.emit("agent.disconnected"))});B(this,"onSocketMessage",n=>{const i=Bf(n);(i==null?void 0:i.type)==="response.error"&&(this.setAgentState("listening"),this.emit("agent.error",new rS(i.reason)))});B(this,"onResponseDone",()=>{this.setAgentState("listening")});B(this,"onTranscriptUpdated",n=>{this.emit("transcript.updated",n)});B(this,"onTranscriptItem",n=>{n.role==="assistant"&&this.setAgentState("listening"),this.emit("transcript.item",n)});this.agentId=n.agentId,pe.setLevel(n.debug?"debug":"info"),this.transport=new oS({assistantId:n.agentId,versionId:n.versionId,conversationId:n.conversationId,environment:n.environment,region:n.region,url:n.url}),this.transcription=new $f(this.transport,{assembleAssistantMessages:!0}),this.transcription.addListener("transcript.item",this.onTranscriptItem),this.transcription.on("transcript.updated",this.onTranscriptUpdated),this.transcription.on("response.done",this.onResponseDone),this.transport.on(F.SocketMessage,this.onSocketMessage),this.transport.on(F.SocketClose,this.onSocketClose)}get socketEvents(){return this.transport}get conversationId(){return this.transport.conversationId}get isConnected(){return this.connected}get transcript(){return this.transcription.transcript}async connect(){try{const{conversationId:n}=await this.transport.connect();this.connected=!0,this.emit("agent.connected",{conversationId:n})}catch(n){const i=n instanceof Error?n:new Error(String(n));throw this.emit("agent.error",i),i}}async sendMessage(n){if(!this.connected)throw new Error("Not connected. Call connect() first.");this.setAgentState("thinking");try{await this.transport.sendMessage(n)}catch(i){const s=i instanceof Error?i:new Error(String(i));throw this.setAgentState("listening"),this.emit("agent.error",s),s}}disconnect(){this.transport.disconnect();const n=this.connected;this.connected=!1,this.setAgentState("listening"),n&&this.emit("agent.disconnected")}setAgentState(n){this.agentState!==n&&(this.agentState=n,this.emit("conversation.agent.state",{state:n}))}}var Hf={exports:{}},Vi={},Wf;function lS(){if(Wf)return Vi;Wf=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return Vi.Fragment=e,Vi.jsx=n,Vi.jsxs=n,Vi}var Gf;function cS(){return Gf||(Gf=1,Hf.exports=lS()),Hf.exports}cS(),Nt(void 0),Nt(null);const dS=(t,e,n,i,s,o,r,a,l,c,u,d,h,p)=>new eS({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,prefetchIceCandidates:o,vad:r,conversationId:a,chatMode:l,region:c,skipLastVoiceSdkId:u??!0,streamingAudio:d,rtcIp:h,rtcPort:p}),Hs=10,qf=5e3,uS=[46001,46003],hS=["login incorrect","authentication required","authentication failed"];function zf(t){var i;const e=t.code;if(e&&uS.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return hS.some(s=>n.includes(s))}const fS=(t,e,n,i,s,o,r,a,l,c,u,d,h,p)=>{const m=u??!0,[v,b]=me(null),[y,C]=me(!1),[T,A]=me(null),[x,N]=me(!1),[k,E]=me(0),f=ue(0),_=ue(null),g=ue(null),S=ue(!1),I=ue(!1),P=ue(0),R=ue(0),M=Ne(()=>{_.current&&(clearTimeout(_.current),_.current=null)},[]),O=Ne(()=>{M(),f.current=0,I.current=!0,N(!1),A(null)},[M]),L=Ne(()=>{M(),N(!1)},[M]),V=Ne(H=>{ae.info(`Rebuilding AI Agent client: ${H}`),M(),f.current=0,I.current=!1,S.current=!1,N(!1),A(null),E(K=>K+1)},[M]),j=Ne(H=>{if(M(),f.current>=Hs){ae.error(`Max login retry attempts (${Hs}) exceeded`),N(!1);return}f.current+=1;const K=P.current,W=R.current;ae.info(`Scheduling login retry attempt ${f.current}/${Hs} in ${qf}ms due to: ${H}`),N(!0),_.current=window.setTimeout(()=>{var X;_.current=null;const Y=g.current,q=Y==null?void 0:Y.telnyxRTC;if(P.current!==K||R.current!==W||Y!=null&&Y.isAuthenticating){ae.info("Skipping login retry because a newer socket/login is already in progress"),L();return}if(S.current||I.current||Y!=null&&Y.isAuthenticated){ae.info("Skipping login retry because login already succeeded before retry timeout fired"),O();return}g.current&&(ae.info(`Executing reconnect attempt ${f.current} (socket disconnect)`),(X=q==null?void 0:q.socketDisconnect)==null||X.call(q))},qf)},[M,L,O]);return Ie(()=>{if(!t)return;const H=dS(t,e,n,i,s,o,r,a,l,c,m,d,h,p);S.current=!1,I.current=!1,f.current=0,C(!1),A(null),N(!1),g.current=H;const K=()=>{ae.info("Agent connected successfully"),S.current=!0,C(!0),O()},W=()=>{ae.info("Agent disconnected"),S.current=!1,I.current=!1,C(!1)},Y=be=>{if(ae.error("AI Agent error:",be),zf(be)){if(S.current||I.current){ae.debug("Ignoring retryable error — login already succeeded");return}f.current<Hs?(A(null),j(be.message)):(A(be),N(!1))}else A(be),N(!1)},q=H.telnyxRTC??null,X=()=>{R.current+=1,I.current=!1},te=()=>{ae.info("Login succeeded; clearing pending login retry flow"),O()},J=()=>{P.current+=1,I.current=!1},he=()=>{I.current=!1};return H.on("agent.connected",K),H.on("agent.disconnected",W),H.on("agent.error",Y),H.on("agent.login.started",X),H.on("agent.login.success",te),q&&typeof q=="object"&&(q.on(F.SocketOpen,J),q.on(F.SocketClose,he)),H.connect(),b(H),()=>{M(),H.off("agent.connected",K),H.off("agent.disconnected",W),H.off("agent.error",Y),H.off("agent.login.started",X),H.off("agent.login.success",te),q&&typeof q=="object"&&(q.off(F.SocketOpen,J),q.off(F.SocketClose,he)),H.disconnect(),S.current=!1,g.current=null}},[t,e,n,i,s,o,r,a,l,c,u,m,d,h,p,k,M,O,j]),Ie(()=>{if(!t)return;const H=W=>{var q,X;if(!W.persisted)return;ae.info("Page entering bfcache; closing agent socket"),M();const Y=g.current;(X=(q=Y==null?void 0:Y.telnyxRTC)==null?void 0:q.socketDisconnect)==null||X.call(q)},K=W=>{W.persisted&&V("bfcache restore (pageshow persisted)")};return window.addEventListener("pagehide",H),window.addEventListener("pageshow",K),()=>{window.removeEventListener("pagehide",H),window.removeEventListener("pageshow",K)}},[t,M,V]),{client:v,isConnected:y,error:T,isReconnecting:x,reconnect:V}},pS="telnyx-ai-agent",xe={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",TRANSCRIPT_UPDATED:"transcript.updated",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error",CLIENT_TOOLS_CONFIGURED:"client.tools.configured",ASSISTANT_AUDIO_DELTA:"assistant.audio.delta",ASSISTANT_AUDIO_DONE:"assistant.audio.done",ASSISTANT_AUDIO_INTERRUPTED:"assistant.audio.interrupted"};function gS(t){var i,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const n=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;n.push({name:r.name,description:(i=r.client_side_tool)==null?void 0:i.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return n}function Kf(){const t=document.querySelector(pS);return t instanceof HTMLElement?t:null}function it(t,e,n){const i=n||Kf();if(!i){ae.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ae.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const mS=(t,e,n)=>{const{onReady:i,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=Ji(Qu);Ie(()=>{const c=n==null?void 0:n.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??Kf()},[n]),Ie(()=>{if(!t)return;const c=a.current,u=()=>{i();const f=t.telnyxRTC,_={dc:(f==null?void 0:f.dc)??null,region:(f==null?void 0:f.region)??null,callReportId:(f==null?void 0:f.callReportId)??null};l(_),it(xe.AGENT_CONNECTED,_,c)},d=()=>{l(null),it(xe.AGENT_DISCONNECTED,void 0,c)},h=E=>{const f={message:E.message,name:E.name};if(zf(E)){ae.debug("Ignoring retryable agent.error in widget event layer"),it(xe.AGENT_ERROR,f,c);return}o(E),it(xe.AGENT_ERROR,f,c)},p=E=>{var f;s(E),it(xe.CONVERSATION_UPDATE,{type:E.type,callState:(f=E.call)==null?void 0:f.state},c)},m=E=>{it(xe.TRANSCRIPT_ITEM,E,c)},v=E=>{it(xe.CONVERSATION_AGENT_STATE,E,c)},b=E=>{it(xe.AGENT_AUDIO_MUTE,{muted:E},c)},C=t.telnyxRTC,T=E=>{r(E);const f=gS(E);f&&it(xe.CLIENT_TOOLS_CONFIGURED,{tools:f},c)},A=E=>{const f=E,_={code:f==null?void 0:f.code,reason:f==null?void 0:f.reason,wasClean:f==null?void 0:f.wasClean,timestamp:new Date().toISOString()};ae.info("[socket.close]",_),it(xe.SOCKET_CLOSE,_,c)};C&&typeof C=="object"&&(C.on(F.SocketMessage,T),C.on(F.SocketClose,A));const x=E=>{var _;const f={responseId:E.responseId,itemId:E.itemId,sequence:E.sequence,byteLength:((_=E.audio)==null?void 0:_.byteLength)??0,format:{encoding:E.format.encoding,sampleRate:E.format.sampleRate,channels:E.format.channels}};it(xe.ASSISTANT_AUDIO_DELTA,f,c)},N=E=>{it(xe.ASSISTANT_AUDIO_DONE,{responseId:E.responseId},c)},k=E=>{it(xe.ASSISTANT_AUDIO_INTERRUPTED,{responseId:E.responseId},c)};return t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),t.on("assistant.audio.delta",x),t.on("assistant.audio.done",N),t.on("assistant.audio.interrupted",k),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),t.off("assistant.audio.delta",x),t.off("assistant.audio.done",N),t.off("assistant.audio.interrupted",k),C&&typeof C=="object"&&(C.off(F.SocketMessage,T),C.off(F.SocketClose,A))}},[t,i,s,o,r,l])},vS=(t,e,n,i,s,o,r,a)=>{const[l,c]=me(null),[u,d]=me([]),[h,p]=me(!1),[m,v]=me(!1),[b,y]=me(!1),[C,T]=me(null),[A,x]=me(null),[,N]=ms(),k=Au(),E=ue(null),f=ue(!1),[_,g]=me(!1),[S,I]=me(0);Ie(()=>{var Ze;if(c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),!t||f.current)return;N("listening"),console.log(e);const L=new aS({agentId:t,environment:e,versionId:n,conversationId:i,region:s,debug:o,url:a});let V=!1,j=!1,H=!1,K=!1,W=null,Y=null;const q=new Set,X=(Ze=r==null?void 0:r.current)==null?void 0:Ze.getRootNode(),te=X instanceof ShadowRoot?X.host:null,J=(re,Me)=>{V||it(re,Me,te)},he=()=>{Y=null,y(!1)},be=re=>{J(xe.TRANSCRIPT_ITEM,re)},ye=re=>{V||(d([...re]),J(xe.TRANSCRIPT_UPDATED,[...re]))},Le=re=>{if(V||j)return;const Me="reason"in re&&typeof re.reason=="string"?re.reason:void 0,_e=re.name==="TextChatResponseError"?"response":K||L.isConnected?"send":"connection";_e==="connection"?T(re):_e==="response"&&x(re),J(xe.AGENT_ERROR,{message:re.message,name:re.name,reason:Me,scope:_e})},de=()=>{V||(p(!1),he(),H&&(H=!1,J(xe.AGENT_DISCONNECTED)),j||T(new Error("Connection to the assistant was lost. Reconnect to continue.")))},ve=re=>{if(V||(ku(re)&&k(re.params.widget_settings),!re||typeof re!="object"))return;const Me=re;if(Me.method!=="ai_conversation"||!Me.params)return;const{type:_e,response_id:Ht,item_id:Fe,text:_n,error:st}=Me.params;if(_e==="response.error"&&st&&typeof st=="object"&&"reason"in st&&typeof st.reason=="string"&&st.reason)he();else if(typeof Ht=="string"&&Ht&&typeof Fe=="string"&&Fe){if(q.has(Ht))return;Y&&!Y.responseId&&(Y.responseId=Ht),_e==="response.text.done"&&typeof _n=="string"&&(q.add(Ht),(Y==null?void 0:Y.responseId)===Ht&&he())}},oe=re=>{V||(N(re.state==="thinking"?"thinking":"listening"),J(xe.CONVERSATION_AGENT_STATE,re))};L.on("transcript.item",be),L.on("transcript.updated",ye),L.on("agent.error",Le),L.on("agent.disconnected",de),L.on("conversation.agent.state",oe),L.socketEvents.on(F.SocketMessage,ve);const Je=()=>V?Promise.resolve():W||(j=!0,L.disconnect(),j=!1,he(),v(!0),p(!1),T(null),x(null),W=L.connect().then(()=>{V||(p(L.isConnected),L.isConnected&&(H=!0,J(xe.AGENT_CONNECTED,{conversationId:L.conversationId})))}).catch(re=>{V||T(re instanceof Error?re:new Error(String(re)))}).finally(()=>{W=null,V||v(!1)}),W),Qe=async re=>{if(V||!L.isConnected||W)throw new Error("Reconnect before sending.");if(Y)throw new Error("Wait for the current reply to finish.");const Me={};Y=Me,y(!0),x(null),K=!0;try{await L.sendMessage(re)}catch(_e){throw!V&&Y===Me&&he(),_e}finally{K=!1}},Mt=()=>{var re;V||(j=!0,L.disconnect(),V=!0,((re=E.current)==null?void 0:re.agent)===L&&(E.current=null),L.off("transcript.item",be),L.off("transcript.updated",ye),L.off("agent.error",Le),L.off("agent.disconnected",de),L.off("conversation.agent.state",oe),L.socketEvents.off(F.SocketMessage,ve),N("listening"))};return E.current={agent:L,send:Qe,connect:Je,end:Mt},c(L),Je(),Mt},[t,e,n,i,s,o,a,r,S,N,k]);const P=Ne(async L=>{if(!E.current)throw new Error("Connect before sending.");await E.current.send(L)},[]),R=Ne(()=>{var L;(L=E.current)==null||L.connect()},[]),M=Ne(()=>{var L;f.current||(f.current=!0,(L=E.current)==null||L.end(),g(!0),c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),N("listening"))},[N]),O=Ne(()=>{f.current&&(f.current=!1,g(!1),I(L=>L+1))},[]);return{isEnded:_,sessionKey:S,endChat:M,startChat:O,client:l,transcript:u,isConnected:h,isConnecting:m,isResponding:b,error:C,responseError:A,sendMessage:P,retry:R}},_S=2e3;async function yS(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Yf(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const bS=(t,e)=>{const[n,i]=me([]),[,s]=ms(),o=ue(e);Ie(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return Ie(()=>{if(!t)return;const c=h=>{i(p=>{const m=p[p.length-1];if(h.role==="assistant"&&m&&Yf(m.id)===Yf(h.id)&&m.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&m.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&m.greetingLatencyMs===void 0,y={...m,content:m.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...p.slice(0,-1),y]}if(h.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...p];return y[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(m&&m.role==="user"&&h.timestamp.getTime()-m.timestamp.getTime()<_S){const C={...m,id:h.id,content:m.content+" "+h.content,timestamp:h.timestamp,attachments:[...m.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...p,h]})},u=({state:h,userPerceivedLatencyMs:p,greetingLatencyMs:m,thinkingStartedAt:v})=>{(p!==void 0||m!==void 0)&&ae.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${m} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),m!==void 0&&(a.current=m)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var m;const p=(m=h.call)==null?void 0:m.state;(p==="destroy"||p==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const p=await yS(h);d.push(p)}catch(p){throw ae.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Xn={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class wS{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,n){var i;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof n!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,n),ae.debug(`[client-tools] registered handler "${e}"`),(i=this.agent)==null||i.registerClientTool(e,n)}unregister(e){var i;const n=this.handlers.delete(e);return n&&(ae.debug(`[client-tools] unregistered handler "${e}"`),(i=this.agent)==null||i.unregisterClientTool(e)),n}list(){return Array.from(this.handlers.keys())}attach(e,n){this.detach(),this.agent=e,this.listeners=n;for(const[i,s]of this.handlers)e.registerClientTool(i,s);this.boundInvoked=i=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(i)},this.boundCompleted=i=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(i)},this.boundError=i=>{var s;return(s=this.listeners)==null?void 0:s.onError(i)},e.on(Xn.INVOKED,this.boundInvoked),e.on(Xn.COMPLETED,this.boundCompleted),e.on(Xn.ERROR,this.boundError),this.handlers.size>0&&ae.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Xn.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Xn.COMPLETED,this.boundCompleted),this.boundError&&e.off(Xn.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function ba(t,e,n){t&&t.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}const SS=(t,e)=>{const n=ue(null);n.current===null&&(n.current=new wS),so(()=>{const i=e.current;if(!i)return;const s=i.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){ae.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=n.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),Ie(()=>{const i=n.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return i.attach(t,{onInvoked:o=>{ba(s(),xe.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{ba(s(),xe.CLIENT_TOOL_COMPLETED,o)},onError:o=>{ba(s(),xe.CLIENT_TOOL_ERROR,o)}}),()=>{i.detach()}},[t,e])},CS=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const o=hn(),[r,a]=me(i?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=bS(e,n),d=ue(!1);switch(Ie(()=>{if(i&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,ae.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[i,t]),r){case"collapsed":return D(oh,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return D(x0,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return D(oh,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},wa=({message:t})=>D(Xt.div,{layoutId:Ti,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:[D("div",{className:"rounded-full animate-spin",children:D(n0,{})}),t&&D("p",{role:"status",children:t})]}),TS=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(wa,{});case"done":case"purged":case"destroy":return null;case"active":return D(CS,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return D(wa,{})}},Xf=({className:t})=>D("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Jf(){const t=hn();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(Xf,{className:"w-8 h-8 mr-2"})}const ES=({client:t,callProps:e,chatMode:n,isReady:i})=>{const s=hn(),o=ue(!1),r=Ne(async()=>{if(!t){ae.error("Client is not initialized.");return}if(!i){ae.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){ae.error("Failed to start AI Agent conversation:",a)}},[t,e,i]);return Ie(()=>{n&&t&&i&&!o.current&&(o.current=!0,ae.info("[ChatMode] Auto-starting conversation"),r())},[n,t,i,r]),n?D(Xt.div,{layoutId:Ti,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[D(Jf,{}),"Connecting..."]}):D(Xt.button,{layoutId:Ti,onClick:r,disabled:!i,"aria-busy":!i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D(Jf,{}),s.start_call_text]})},kS=({transcript:t,onSendMessage:e,isConnected:n,isConnecting:i,isResponding:s,connectionError:o,responseError:r,onRetry:a,isEnded:l,onEndChat:c,onStartChat:u,startLabel:d="Start new chat",onClose:h,debug:p=!1})=>l?D(Xt.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{duration:.15,ease:"easeOut"},onClick:u,className:"inline-flex w-fit max-w-full items-center justify-center gap-2.5 rounded-full bg-[#FEFDF5] px-4 py-3 text-base font-medium leading-6 text-black shadow-lg shadow-[#38383840] cursor-pointer transition-colors hover:bg-[#F3F2EA] focus-visible:outline-2 focus-visible:outline-offset-4 dark:bg-black dark:text-white dark:hover:bg-[#1C1C1E]",children:[D(Xf,{className:"h-6 w-6 shrink-0"}),D("span",{children:d})]}):D(Gc,{children:D(Xt.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[D("div",{className:"p-4 text-center",children:[D("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D("button",{type:"button",onClick:c,className:"ml-auto flex items-center gap-1.5 rounded-full border border-[#969696] dark:border-[#3D3D46] px-3 py-1.5 text-sm cursor-pointer focus-visible:outline focus-visible:outline-offset-2",children:[D(Ai,{className:"w-4 h-4","aria-hidden":"true"}),"End chat"]}),h&&D(Rt,{tooltip:"Close",className:"ml-auto",onClick:h,children:D(Ai,{className:"text-black dark:text-white"})})]}),D(xr,{size:"large",className:"mb-4"}),D(Fr,{className:"mt-2",debug:p})]}),D("div",{className:"px-4 pb-2 text-sm",children:[o&&D("p",{role:"alert",children:o.message}),!n&&(i?D("p",{role:"status",children:"Connecting…"}):D("button",{className:"underline",onClick:a,children:"Reconnect"})),r&&D("p",{role:"alert",children:r.message}),s&&D("p",{role:"status",children:"Receiving reply…"})]}),D(fh,{transcript:t,onSendMessage:e,allowAttachments:!1,awaitAcceptance:!0,sendDisabled:!n||s||i})]})}),IS='@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-leading:initial;--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;--tw-outline-style:solid}}}@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-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--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-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--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}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-6{width:calc(var(--spacing)*6)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-fit{width:fit-content}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.shrink-0{flex-shrink:0}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.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-1\\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-2\\.5{gap:calc(var(--spacing)*2.5)}.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-lg{border-radius:var(--radius-lg)}.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-t{border-top-style:var(--tw-border-style);border-top-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}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.pb-2{padding-bottom:calc(var(--spacing)*2)}.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-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--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))}.leading-6{--tw-leading:calc(var(--spacing)*6);line-height:calc(var(--spacing)*6)}.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}.opacity-0{opacity:0}.opacity-60{opacity:.6}.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-\\[\\#38383840\\]{--tw-shadow-color:#38383840}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383840\\]{--tw-shadow-color:color-mix(in oklab,#38383840 var(--tw-shadow-alpha),transparent)}}.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-lg{--tw-backdrop-blur:blur(var(--blur-lg));-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,)}.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))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;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 (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-\\[\\#F3F2EA\\]:hover{background-color:#f3f2ea}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.focus-visible\\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\\:outline-offset-4:focus-visible{outline-offset:4px}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@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)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#1C1C1E\\]:where(.dark,.dark *):hover{background-color:#1c1c1e}.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-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-leading{syntax:"*";inherits:false}@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}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@keyframes spin{to{transform:rotate(360deg)}}',AS=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),RS={duration:.1,ease:"circOut"},xS=({children:t,position:e="fixed",rootRef:n})=>{const i=hn(),o=(e??i.position??"fixed")==="fixed"?D(AS,{children:t}):t;return D("div",{ref:n,className:Bt(i.theme==="dark"&&"dark"),children:D(Ym,{transition:RS,children:[D("style",{children:IS}),o]})})},DS=t=>D(Xt.div,{layoutId:Ti,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:[D(e0,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.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"," ",D(c0,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(a0,{className:"w-4 h-4"}),"Retry"]})]});function Zt(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Qf(t,e){return t===void 0?e:Zt(t)}function LS({"agent-id":t,debug:e,"trickle-ice":n,"prefetch-ice-candidates":i,"call-destination-number":s,"call-caller-number":o,"call-caller-name":r,"call-custom-headers":a,"call-audio":l,vad:c,"show-user-perceived-latency":u,"show-greeting-latency":d,"conversation-id":h,"chat-mode":p,"text-only":m,"text-chat-url":v,region:b,"rtc-ip":y,"rtc-port":C,"skip-last-voice-sdk-id":T,"streaming-audio":A,environment:x,position:N="fixed","version-id":k}){const E=Zt(e),f=C!=null&&C.trim()?Number(C):void 0,_=Qf(n,!0),g=Qf(i,!0),S=Zt(p),I=Zt(m),P=Zt(A),R=T===void 0?!0:Zt(T),M=dt(()=>{if(c)try{return JSON.parse(c)}catch(Fe){ae.error("Invalid JSON for vad attribute:",c,Fe);return}},[c]),O=dt(()=>({showUserPerceivedLatency:Zt(u),showGreetingLatency:Zt(d)}),[u,d]),{client:L,error:V,isConnected:j,isReconnecting:H,reconnect:K}=fS(I?void 0:t,x,k,E,_,g,M,h,S,b,R,P,y,f),[W,Y]=me(null),[q,X]=me(!1),[te,J]=me(!1),[he,be]=me(!1),[ye,Le]=me(!1),de=Ji(ih),ve=Au(),oe={};if(s&&(oe.destinationNumber=s),o&&(oe.callerNumber=o),r&&(oe.callerName=r),a)try{oe.customHeaders=JSON.parse(a)}catch(Fe){ae.error("Invalid JSON for call-custom-headers attribute:",a,Fe)}if(l)try{oe.audio=JSON.parse(l);const Fe=oe.audio;if(typeof Fe=="object"){const _n=navigator.mediaDevices.getSupportedConstraints();Object.keys(Fe).forEach(st=>{_n[st]||ae.warn(`Audio constraint not supported by browser: ${st}`)})}}catch(Fe){ae.error("Invalid JSON for call-audio attribute:",l,Fe)}const Je=Ne(()=>{X(!1)},[]),Qe=Ne(Fe=>{var _n;if(((_n=Fe.call)==null?void 0:_n.state)==="destroy")return de(!1),Le(!0),Y(null);Y(Fe)},[de]),Mt=Ne(()=>{X(!1),H||J(!0)},[H]),Ze=Ne(()=>{ae.info("User triggered retry"),J(!1),X(!0),K("user retry")},[K]);Ie(()=>{L&&(J(!1),Y(null),de(!1))},[L,de]);const re=Ne(Fe=>{ku(Fe)&&(ve(Fe.params.widget_settings),be(!0))},[ve]),Me=ue(null),_e=vS(I?t:void 0,x,k,h,b,E,Me,v);return mS(L,{onReady:Je,onConversationUpdate:Qe,onError:Mt,onConfigMessage:re},Me),SS(L,Me),D(xS,{position:N,rootRef:Me,children:t?I?D(kS,{isConnected:_e.isConnected,isConnecting:_e.isConnecting,isResponding:_e.isResponding,connectionError:_e.error,responseError:_e.responseError,onRetry:_e.retry,isEnded:_e.isEnded,onEndChat:_e.endChat,onStartChat:_e.startChat,startLabel:h?"Start chat":"Start new chat",transcript:_e.transcript,onSendMessage:_e.sendMessage,debug:E},JSON.stringify([t,x,k,h,b,E,v,_e.sessionKey])):te||V?D(DS,{agentId:t,onRetry:Ze}):q||H?D(wa,{message:H?"Retrying...":void 0}):W!=null&&W.call?D(TS,{call:W.call,client:L,latencySettings:O,chatMode:S,debug:E}):he?D(ES,{client:L,callProps:oe,chatMode:S&&!ye,isReady:j&&!!L}):null:D("div",{children:"Please provide an assistant ID."})})}gp(LS,"telnyx-ai-agent",ky,{shadow:!0})})();