@telnyx/ai-agent-widget 0.34.2 → 0.35.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.
@@ -1,4 +1,4 @@
1
- var Cw=Object.defineProperty;var Tw=(rt,z,Gt)=>z in rt?Cw(rt,z,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):rt[z]=Gt;var $=(rt,z,Gt)=>Tw(rt,typeof z!="symbol"?z+"":z,Gt);(function(){"use strict";var rt,z,Gt,qt,Zr,Qr,ea,ta,As,xs,Ls,ia,Fi={},na=[],Jh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Bi=Array.isArray;function ut(t,e){for(var i in e)t[i]=e[i];return t}function Ds(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ze(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?rt.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 Vi(t,r,n,s,null)}function Vi(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??++Gt,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function ht(t){return t.children}function at(t,e){this.props=t,this.context=e}function di(t,e){if(e==null)return t.__?di(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"?di(t):null}function sa(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 sa(t)}}function Os(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!Tn.__r++||Zr!=z.debounceRendering)&&((Zr=z.debounceRendering)||Qr)(Tn)}function Tn(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(ea),t=qt.shift(),a=qt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=ut({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),Ms(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??di(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,ca(o,i,r),i.__e!=s&&sa(i)));Tn.__r=0}function oa(t,e,i,n,s,o,r,a,l,c,u){var d,h,g,v,_,S,b=n&&n.__k||na,T=e.length;for(l=Zh(i,e,b,l,T),d=0;d<T;d++)(g=i.__k[d])!=null&&(h=g.__i==-1?Fi:b[g.__i]||Fi,g.__i=d,S=Ms(t,g,h,s,o,r,a,l,c,u),v=g.__e,g.ref&&h.ref!=g.ref&&(h.ref&&Ps(h.ref,null,g),u.push(g.ref,g.__c||v,g)),_==null&&v!=null&&(_=v),4&g.__u||h.__k===g.__k?l=ra(g,l,t):typeof g.type=="function"&&S!==void 0?l=S:v&&(l=v.nextSibling),g.__u&=-7);return i.__e=_,l}function Zh(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?Vi(null,r,null,null,null):Bi(r)?Vi(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Vi(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=Qh(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=di(a)),ua(a,a));return n}function ra(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=ra(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=di(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ft(t,e){return e=e||[],t==null||typeof t=="boolean"||(Bi(t)?t.some(function(i){ft(i,e)}):e.push(t)),e}function Qh(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 aa(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Jh.test(e)?i:i+"px"}function En(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||aa(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||aa(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(ta,"$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=As,t.addEventListener(e,o?Ls:xs,o)):t.removeEventListener(e,o?Ls:xs,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 la(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=As++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function Ms(t,e,i,n,s,o,r,a,l,c){var u,d,h,g,v,_,S,b,T,k,A,R,D,C,E,p,m,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(b=e.props,T="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],A=u?k?k.props.value:u.__:n,i.__c?S=(d=e.__c=i.__c).__=d.__E:(T?e.__c=d=new f(b,A):(e.__c=d=new at(b,A),d.constructor=f,d.render=tf),k&&k.sub(d),d.props=b,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),T&&d.__s==null&&(d.__s=d.state),T&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ut({},d.__s)),ut(d.__s,f.getDerivedStateFromProps(b,d.__s))),g=d.props,v=d.state,d.__v=e,h)T&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),T&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(T&&f.getDerivedStateFromProps==null&&b!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(w){w&&(w.__=e)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,A),T&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,v,_)})}if(d.context=A,d.props=b,d.__P=t,d.__e=!1,D=z.__r,C=0,T){for(d.state=d.__s,d.__d=!1,D&&D(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,D&&D(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++C<25);d.state=d.__s,d.getChildContext!=null&&(n=ut(ut({},n),d.getChildContext())),T&&!h&&d.getSnapshotBeforeUpdate!=null&&(_=d.getSnapshotBeforeUpdate(g,v)),p=u,u!=null&&u.type===ht&&u.key==null&&(p=da(u.props.children)),a=oa(t,Bi(p)?p:[p],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),S&&(d.__E=d.__=null)}catch(w){if(e.__v=null,l||o!=null)if(w.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(m=o.length;m--;)Ds(o[m]);else e.__e=i.__e,e.__k=i.__k;z.__e(w,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=ef(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function ca(t,e,i){for(var n=0;n<i.length;n++)Ps(i[n],i[++n],i[++n]);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 da(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Bi(t)?t.map(da):ut({},t)}function ef(t,e,i,n,s,o,r,a,l){var c,u,d,h,g,v,_,S=i.props,b=e.props,T=e.type;if(T=="svg"?s="http://www.w3.org/2000/svg":T=="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((g=o[c])&&"setAttribute"in g==!!T&&(T?g.localName==T:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(T==null)return document.createTextNode(b);t=document.createElementNS(s,T,b.is&&b),a&&(z.__m&&z.__m(e,o),a=!1),o=null}if(T==null)S===b||a&&t.data==b||(t.data=b);else{if(o=o&&rt.call(t.childNodes),S=i.props||Fi,!a&&o!=null)for(S={},c=0;c<t.attributes.length;c++)S[(g=t.attributes[c]).name]=g.value;for(c in S)if(g=S[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in b)){if(c=="value"&&"defaultValue"in b||c=="checked"&&"defaultChecked"in b)continue;En(t,c,null,g,s)}}for(c in b)g=b[c],c=="children"?h=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?v=g:c=="checked"?_=g:a&&typeof g!="function"||S[c]===g||En(t,c,g,S[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=""),oa(e.type=="template"?t.content:t,Bi(h)?h:[h],e,i,n,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&di(i,0),a,l),o!=null)for(c=o.length;c--;)Ds(o[c]);a||(c="value",T=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[c]||T=="progress"&&!v||T=="option"&&v!=S[c])&&En(t,c,v,S[c],s),c="checked",_!=null&&_!=t[c]&&En(t,c,_,S[c],s))}return t}function Ps(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){z.__e(s,i)}}function ua(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Ps(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&ua(n[s],e,i||typeof t.type!="function");i||Ds(t.__e),t.__c=t.__=t.__e=void 0}function tf(t,e,i){return this.constructor(t,i)}function kn(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ms(e,t=(!n&&i||e).__k=Ze(ht,null,[t]),s||Fi,Fi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?rt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),ca(o,t,r)}function ha(t,e){kn(t,e,ha)}function Ns(t,e,i){var n,s,o,r,a=ut({},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?rt.call(arguments,2):i),Vi(t.type,a,n||t.key,s||t.ref,null)}function kt(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,Os(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"+ia++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}rt=na.slice,z={__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}},Gt=0,at.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ut({},this.state),typeof t=="function"&&(t=t(ut({},i),this.props)),t&&ut(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Os(this))},at.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Os(this))},at.prototype.render=ht,qt=[],Qr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ea=function(t,e){return t.__v.__b-e.__v.__b},Tn.__r=0,ta=/(PointerCapture)$|Capture$/i,As=0,xs=la(!1),Ls=la(!0),ia=0;var nf=0;function L(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:--nf,__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 Fs(){return(Fs=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 sf=["context","children"];function of(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,sf);return Ns(e,i)}function rf(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ze(of,Fs({},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[fa(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Ze(pa,{name:u},c):s[r]=c}var d=n?Ze(pa,null,s):s;return Ze(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?ha:kn)(this._vdom,this._root)}function fa(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function af(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[fa(t)]=i,this._vdom=Ns(this._vdom,n),kn(this._vdom,this._root)}}function lf(){kn(this._vdom=null,this._root)}function pa(t,e){var i=this;return Ze("slot",Fs({},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 cf(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=rf,s.prototype.attributeChangedCallback=af,s.prototype.disconnectedCallback=lf,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 Mt,_e,Bs,ga,Ui=0,ma=[],Se=z,va=Se.__b,_a=Se.__r,ya=Se.diffed,ba=Se.__c,wa=Se.unmount,Sa=Se.__;function ui(t,e){Se.__h&&Se.__h(_e,t,Ui||e),Ui=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return Ui=1,Ca(Ea,t)}function Ca(t,e,i){var n=ui(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):Ea(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=_e,!_e.__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 g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.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)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=ui(Mt++,3);!Se.__s&&js(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Vs(t,e){var i=ui(Mt++,4);!Se.__s&&js(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function ue(t){return Ui=5,Qe(function(){return{current:t}},[])}function Qe(t,e){var i=ui(Mt++,7);return js(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ge(t,e){return Ui=8,Qe(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=ui(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function df(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Us(){var t=ui(Mt++,11);if(!t.__){for(var e=_e.__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 uf(){for(var t;t=ma.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(In),t.__H.__h.forEach($s),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,va&&va(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Sa&&Sa(t,e)},Se.__r=function(t){_a&&_a(t),Mt=0;var e=(_e=t.__c).__H;e&&(Bs===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(In),e.__h.forEach($s),e.__h=[],Mt=0)),Bs=_e},Se.diffed=function(t){ya&&ya(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ma.push(e)!==1&&ga===Se.requestAnimationFrame||((ga=Se.requestAnimationFrame)||hf)(uf)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Bs=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(In),i.__h=i.__h.filter(function(n){return!n.__||$s(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),ba&&ba(t,e)},Se.unmount=function(t){wa&&wa(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{In(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var Ta=typeof requestAnimationFrame=="function";function hf(t){var e,i=function(){clearTimeout(n),Ta&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Ta&&(e=requestAnimationFrame(i))}function In(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function $s(t){var e=_e;t.__c=t.__(),_e=e}function js(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ea(t,e){return typeof e=="function"?e(t):e}const $i={},ka=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ia=t=>"init"in t,Hs=t=>!!t.write,Ra=t=>"v"in t||"e"in t,Rn=t=>{if("e"in t)throw t.e;if(($i?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},An=new WeakMap,Aa=t=>{var e;return xn(t)&&!!((e=An.get(t))!=null&&e[0])},ff=t=>{const e=An.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},xa=(t,e)=>{let i=An.get(t);if(!i){i=[!0,new Set],An.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},xn=t=>typeof(t==null?void 0:t.then)=="function",La=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},Ws=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(xn(e))for(const r of n.d.keys())La(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,xn(o)&&ff(o))},Da=(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},pf=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Gs=()=>{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},gf=t=>(t.c||(t.c=Gs()),t.m||(t.m=Gs()),t.u||(t.u=Gs()),t.f||(t.f=pf()),t),mf=Symbol(),Oa=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...g)=>h.read(...g),l=(h,...g)=>h.write(...g),c=(h,g)=>{var v;return(v=h.unstable_onInit)==null?void 0:v.call(h,g)},u=(h,g)=>{var v;return(v=h.onMount)==null?void 0:v.call(h,g)},...d)=>{const h=d[0]||(C=>{if(($i?"production":void 0)!=="production"&&!C)throw new Error("Atom is undefined or null");let E=t.get(C);return E||(E={d:new Map,p:new Set,n:0},t.set(C,E),c==null||c(C,D)),E}),g=d[1]||(()=>{const C=[],E=p=>{try{p()}catch(m){C.push(m)}};do{r.f&&E(r.f);const p=new Set,m=p.add.bind(p);n.forEach(f=>{var w;return(w=e.get(f))==null?void 0:w.l.forEach(m)}),n.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),p.forEach(E),n.size&&v()}while(n.size||o.size||s.size);if(C.length)throw new AggregateError(C)}),v=d[2]||(()=>{const C=[],E=new WeakSet,p=new WeakSet,m=Array.from(n);for(;m.length;){const f=m[m.length-1],w=h(f);if(p.has(f)){m.pop();continue}if(E.has(f)){if(i.get(f)===w.n)C.push([f,w]);else if(($i?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");p.add(f),m.pop();continue}E.add(f);for(const I of Da(f,w,e))E.has(I)||m.push(I)}for(let f=C.length-1;f>=0;--f){const[w,I]=C[f];let x=!1;for(const O of I.d.keys())if(O!==w&&n.has(O)){x=!0;break}x&&(_(w),T(w)),i.delete(w)}}),_=d[3]||(C=>{var E;const p=h(C);if(Ra(p)&&(e.has(C)&&i.get(C)!==p.n||Array.from(p.d).every(([M,F])=>_(M).n===F)))return p;p.d.clear();let m=!0;const f=()=>{e.has(C)&&(T(C),v(),g())},w=M=>{var F;if(ka(C,M)){const j=h(M);if(!Ra(j))if(Ia(M))Ws(M,M.init,h);else throw new Error("no atom init");return Rn(j)}const G=_(M);try{return Rn(G)}finally{p.d.set(M,G.n),Aa(p.v)&&La(C,p.v,G),(F=e.get(M))==null||F.t.add(C),m||f()}};let I,x;const O={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return($i?"production":void 0)!=="production"&&!Hs(C)&&console.warn("setSelf function cannot be used with read-only atom"),!x&&Hs(C)&&(x=(...M)=>{if(($i?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return b(C,...M)}finally{v(),g()}}),x}},N=p.n;try{const M=a(C,w,O);return Ws(C,M,h),xn(M)&&(xa(M,()=>I==null?void 0:I.abort()),M.then(f,f)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{m=!1,N!==p.n&&i.get(C)===N&&(i.set(C,p.n),n.add(C),(E=r.c)==null||E.call(r,C))}}),S=d[4]||(C=>{const E=[C];for(;E.length;){const p=E.pop(),m=h(p);for(const f of Da(p,m,e)){const w=h(f);i.set(f,w.n),E.push(f)}}}),b=d[5]||((C,...E)=>{let p=!0;const m=w=>Rn(_(w)),f=(w,...I)=>{var x;const O=h(w);try{if(ka(C,w)){if(!Ia(w))throw new Error("atom not writable");const N=O.n,M=I[0];Ws(w,M,h),T(w),N!==O.n&&(n.add(w),(x=r.c)==null||x.call(r,w),S(w));return}else return b(w,...I)}finally{p||(v(),g())}};try{return l(C,m,f,...E)}finally{p=!1}}),T=d[6]||(C=>{var E;const p=h(C),m=e.get(C);if(m&&!Aa(p.v)){for(const[f,w]of p.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(C),m.d.add(f),w!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),S(f))}for(const f of m.d||[])if(!p.d.has(f)){m.d.delete(f);const w=A(f);w==null||w.t.delete(C)}}}),k=d[7]||(C=>{var E;const p=h(C);let m=e.get(C);if(!m){_(C);for(const f of p.d.keys())k(f).t.add(C);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(C,m),(E=r.m)==null||E.call(r,C),Hs(C)){const f=()=>{let w=!0;const I=(...x)=>{try{return b(C,...x)}finally{w||(v(),g())}};try{const x=u(C,I);x&&(m.u=()=>{w=!0;try{x()}finally{w=!1}})}finally{w=!1}};s.add(f)}}return m}),A=d[8]||(C=>{var E;const p=h(C);let m=e.get(C);if(m&&!m.l.size&&!Array.from(m.t).some(f=>{var w;return(w=e.get(f))==null?void 0:w.d.has(C)})){m.u&&o.add(m.u),m=void 0,e.delete(C),(E=r.u)==null||E.call(r,C);for(const f of p.d.keys()){const w=A(f);w==null||w.t.delete(C)}return}return m}),R=[t,e,i,n,s,o,r,a,l,c,u,h,g,v,_,S,b,T,k,A],D={get:C=>Rn(_(C)),set:(C,...E)=>{try{return b(C,...E)}finally{v(),g()}},sub:(C,E)=>{const m=k(C).l;return m.add(E),g(),()=>{m.delete(E),A(C),g()}}};return Object.defineProperty(D,mf,{value:R}),D},vf=gf,Ma=xa,qs={};let _f=0;function Ln(t,e){const i=`atom${++_f}`,n={toString(){return(qs?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=yf,n.write=bf),n}function yf(t){return t(this)}function bf(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const wf=()=>{let t=0;const e=vf({}),i=new WeakMap,n=new WeakMap,s=Oa(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 Sf(){return(qs?"production":void 0)!=="production"?wf():Oa()}let ji;function Cf(){return ji||(ji=Sf(),(qs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=ji),globalThis.__JOTAI_DEFAULT_STORE__!==ji&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),ji}function Pa(t,e){for(var i in e)t[i]=e[i];return t}function Na(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 Fa=Vs;function Ba(t,e){this.props=t,this.context=e}(Ba.prototype=new at).isPureReactComponent=!0,Ba.prototype.shouldComponentUpdate=function(t,e){return Na(this.props,t)||Na(this.state,e)};var Va=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Va&&Va(t)};var Tf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Ef(t){function e(i){var n=Pa({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=Tf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Ua=function(t,e){return t==null?null:ft(ft(t).map(e))},kf={map:Ua,forEach:Ua,count:function(t){return t?ft(t).length:0},only:function(t){var e=ft(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ft},If=z.__e;z.__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)}If(t,e,i,n)};var $a=z.unmount;function ja(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=Pa({},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 ja(n,e,i)})),t}function Ha(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Ha(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 zs(){this.__u=0,this.o=null,this.__b=null}function Wa(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Dn(){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),$a&&$a(t)},(zs.prototype=new at).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Wa(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]=Ha(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)},zs.prototype.componentWillUnmount=function(){this.o=[]},zs.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]=ja(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Ze(ht,null,t.fallback);return s&&(s.__u&=-33),[Ze(ht,null,e.__a?null:t.children),s]};var Ga=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]}};(Dn.prototype=new at).__a=function(t){var e=this,i=Wa(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Ga(e,t,n)):s()};i?i(o):o()}},Dn.prototype.render=function(t){this.i=null,this.l=new Map;var e=ft(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},Dn.prototype.componentDidUpdate=Dn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Ga(t,i,e)})};var qa=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Rf=/^(?: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]/,Af=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,xf=/[A-Z0-9]/g,Lf=typeof document<"u",Df=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};at.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(at.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var za=z.event;function Of(){}function Mf(){return this.cancelBubble}function Pf(){return this.defaultPrevented}z.event=function(t){return za&&(t=za(t)),t.persist=Of,t.isPropagationStopped=Mf,t.isDefaultPrevented=Pf,t.nativeEvent=t};var Nf={enumerable:!1,configurable:!0,get:function(){return this.class}},Ka=z.vnode;z.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||Lf&&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"||Df(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Af.test(r)&&(r=l):l=r="oninput":o&&Rf.test(r)?r=r.replace(xf,"-$&").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=ft(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=ft(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",Nf)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=qa,Ka&&Ka(t)};var Ya=z.__r;z.__r=function(t){Ya&&Ya(t),t.__c};var Xa=z.diffed;z.diffed=function(t){Xa&&Xa(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 Ja(t){return!!t&&t.$$typeof===qa}function Ff(t){return Ja(t)?Ns.apply(null,arguments):t}var Za={};const Bf={},Vf=kt(void 0);function Qa(t){return De(Vf)||Cf()}const Ks=t=>typeof(t==null?void 0:t.then)=="function",Ys=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Uf=Za.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ys(t),t)}),Xs=new WeakMap,el=(t,e)=>{let i=Xs.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();Ks(c)?(Xs.set(c,i),o=c,c.then(r(c),a(c)),Ma(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),Ma(t,l)}),Xs.set(t,i)),i};function Js(t,e){const{delay:i,unstable_promiseStatus:n=!Za.use}={},s=Qa(),[[o,r,a],l]=Ca(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)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);Ks(d)&&Ys(el(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),df(c),Ks(c)){const u=el(c,()=>s.get(t));return n&&Ys(u),Uf(u)}return c}function On(t,e){const i=Qa();return Ge((...s)=>{if((Bf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function tl(t,e){return[Js(t),On(t)]}const Zs=kt({});function Mn(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const Qs=typeof window<"u",il=Qs?Vs:xe,Pn=kt(null);function eo(t,e){t.indexOf(e)===-1&&t.push(e)}function to(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const It=(t,e,i)=>i>e?e:i<t?t:i;let io=()=>{};const Rt={},nl=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function sl(t){return typeof t=="object"&&t!==null}const ol=t=>/^0[^.\s]+$/u.test(t);function no(t){let e;return()=>(e===void 0&&(e=t()),e)}const et=t=>t,$f=(t,e)=>i=>e(t(i)),Hi=(...t)=>t.reduce($f),Wi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class so{constructor(){this.subscriptions=[]}add(e){return eo(this.subscriptions,e),()=>to(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 pt=t=>t*1e3,gt=t=>t/1e3;function rl(t,e){return e?t*(1e3/e):0}const al=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,jf=1e-7,Hf=12;function Wf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=al(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>jf&&++a<Hf);return r}function Gi(t,e,i,n){if(t===e&&i===n)return et;const s=o=>Wf(o,0,1,t,i);return o=>o===0||o===1?o:al(s(o),e,n)}const ll=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,cl=t=>e=>1-t(1-e),dl=Gi(.33,1.53,.69,.99),oo=cl(dl),ul=ll(oo),hl=t=>(t*=2)<1?.5*oo(t):.5*(2-Math.pow(2,-10*(t-1))),ro=t=>1-Math.sin(Math.acos(t)),fl=cl(ro),pl=ll(ro),Gf=Gi(.42,0,1,1),qf=Gi(0,0,.58,1),gl=Gi(.42,0,.58,1),zf=t=>Array.isArray(t)&&typeof t[0]!="number",ml=t=>Array.isArray(t)&&typeof t[0]=="number",Kf={linear:et,easeIn:Gf,easeInOut:gl,easeOut:qf,circIn:ro,circInOut:pl,circOut:fl,backIn:oo,backInOut:ul,backOut:dl,anticipate:hl},Yf=t=>typeof t=="string",vl=t=>{if(ml(t)){io(t.length===4);const[e,i,n,s]=t;return Gi(e,i,n,s)}else if(Yf(t))return Kf[t];return t},Nn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],_l={value:null};function Xf(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,g=!1)=>{const _=g&&s?i:n;return h&&r.add(d),_.has(d)||_.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&&_l.value&&_l.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Jf=40;function yl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Nn.reduce((k,A)=>(k[A]=Xf(o,e?A:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:g,postRender:v}=r,_=()=>{const k=Rt.useManualTiming?s.timestamp:performance.now();i=!1,Rt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Jf),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),g.process(s),v.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(_))},S=()=>{i=!0,n=!0,s.isProcessing||t(_)};return{schedule:Nn.reduce((k,A)=>{const R=r[A];return k[A]=(D,C=!1,E=!1)=>(i||S(),R.schedule(D,C,E)),k},{}),cancel:k=>{for(let A=0;A<Nn.length;A++)r[Nn[A]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:ao}=yl(typeof requestAnimationFrame<"u"?requestAnimationFrame:et,!0);let Fn;function Zf(){Fn=void 0}const qe={now:()=>(Fn===void 0&&qe.set(Pe.isProcessing||Rt.useManualTiming?Pe.timestamp:performance.now()),Fn),set:t=>{Fn=t,queueMicrotask(Zf)}},bl=t=>e=>typeof e=="string"&&e.startsWith(t),lo=bl("--"),Qf=bl("var(--"),co=t=>Qf(t)?ep.test(t.split("/*")[0].trim()):!1,ep=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,hi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},qi={...hi,transform:t=>It(0,1,t)},Bn={...hi,default:1},zi=t=>Math.round(t*1e5)/1e5,uo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tp(t){return t==null}const ip=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ho=(t,e)=>i=>!!(typeof i=="string"&&ip.test(i)&&i.startsWith(t)||e&&!tp(i)&&Object.prototype.hasOwnProperty.call(i,e)),wl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(uo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},np=t=>It(0,255,t),fo={...hi,transform:t=>Math.round(np(t))},zt={test:ho("rgb","red"),parse:wl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+fo.transform(t)+", "+fo.transform(e)+", "+fo.transform(i)+", "+zi(qi.transform(n))+")"};function sp(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 po={test:ho("#"),parse:sp,transform:zt.transform},Ki=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Ki("deg"),mt=Ki("%"),K=Ki("px"),op=Ki("vh"),rp=Ki("vw"),Sl={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},fi={test:ho("hsl","hue"),parse:wl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(zi(e))+", "+mt.transform(zi(i))+", "+zi(qi.transform(n))+")"},Ie={test:t=>zt.test(t)||po.test(t)||fi.test(t),parse:t=>zt.test(t)?zt.parse(t):fi.test(t)?fi.parse(t):po.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):fi.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},ap=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function lp(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(uo))==null?void 0:e.length)||0)+(((i=t.match(ap))==null?void 0:i.length)||0)>0}const Cl="number",Tl="color",cp="var",dp="var(",El="${}",up=/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 Yi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(up,l=>(Ie.test(l)?(n.color.push(o),s.push(Tl),i.push(Ie.parse(l))):l.startsWith(dp)?(n.var.push(o),s.push(cp),i.push(l)):(n.number.push(o),s.push(Cl),i.push(parseFloat(l))),++o,El)).split(El);return{values:i,split:a,indexes:n,types:s}}function kl(t){return Yi(t).values}function Il(t){const{split:e,types:i}=Yi(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===Cl?o+=zi(s[r]):a===Tl?o+=Ie.transform(s[r]):o+=s[r]}return o}}const hp=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function fp(t){const e=kl(t);return Il(t)(e.map(hp))}const Ft={test:lp,parse:kl,createTransformer:Il,getAnimatableNone:fp};function go(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 pp({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=go(l,a,t+1/3),o=go(l,a,t),r=go(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Vn(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,mo=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},gp=[po,zt,fi],mp=t=>gp.find(e=>e.test(t));function Rl(t){const e=mp(t);if(!e)return!1;let i=e.parse(t);return e===fi&&(i=pp(i)),i}const Al=(t,e)=>{const i=Rl(t),n=Rl(e);if(!i||!n)return Vn(t,e);const s={...i};return o=>(s.red=mo(i.red,n.red,o),s.green=mo(i.green,n.green,o),s.blue=mo(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},vo=new Set(["none","hidden"]);function vp(t,e){return vo.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function _p(t,e){return i=>Ce(t,e,i)}function _o(t){return typeof t=="number"?_p:typeof t=="string"?co(t)?Vn:Ie.test(t)?Al:wp:Array.isArray(t)?xl:typeof t=="object"?Ie.test(t)?Al:yp:Vn}function xl(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>_o(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function yp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=_o(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function bp(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 wp=(t,e)=>{const i=Ft.createTransformer(e),n=Yi(t),s=Yi(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?vo.has(t)&&!s.values.length||vo.has(e)&&!n.values.length?vp(t,e):Hi(xl(bp(n,s),s.values),i):Vn(t,e)};function Ll(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):_o(t)(t,e)}const Sp=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:qe.now()}},Dl=(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)})`},Un=2e4;function yo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<Un;)e+=i,n=t.next(e);return e>=Un?1/0:e}function Cp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(yo(n),Un);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const Tp=5;function Ol(t,e,i){const n=Math.max(e-Tp,0);return rl(i-t(n),e-n)}const Te={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 Ep({duration:t=Te.duration,bounce:e=Te.bounce,velocity:i=Te.velocity,mass:n=Te.mass}){let s,o,r=1-e;r=It(Te.minDamping,Te.maxDamping,r),t=It(Te.minDuration,Te.maxDuration,gt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,g=wo(c,r),v=Math.exp(-d);return bo-h/g*v},o=c=>{const d=c*r*t,h=d*i+i,g=Math.pow(r,2)*Math.pow(c,2)*t,v=Math.exp(-d),_=wo(Math.pow(c,2),r);return(-s(c)+bo>0?-1:1)*((h-g)*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=Ip(s,o,a);if(t=pt(t),isNaN(l))return{stiffness:Te.stiffness,damping:Te.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const kp=12;function Ip(t,e,i){let n=i;for(let s=1;s<kp;s++)n=n-t(n)/e(n);return n}function wo(t,e){return t*Math.sqrt(1-e*e)}const Rp=["duration","bounce"],Ap=["stiffness","damping","mass"];function Ml(t,e){return e.some(i=>t[i]!==void 0)}function xp(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!Ml(t,Ap)&&Ml(t,Rp))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*It(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Te.mass,stiffness:s,damping:o}}else{const i=Ep(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function $n(t=Te.visualDuration,e=Te.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:g}=xp({...i,velocity:-gt(i.velocity||0)}),v=h||0,_=c/(2*Math.sqrt(l*u)),S=r-o,b=gt(Math.sqrt(l/u)),T=Math.abs(S)<5;n||(n=T?Te.restSpeed.granular:Te.restSpeed.default),s||(s=T?Te.restDelta.granular:Te.restDelta.default);let k;if(_<1){const R=wo(b,_);k=D=>{const C=Math.exp(-_*b*D);return r-C*((v+_*b*S)/R*Math.sin(R*D)+S*Math.cos(R*D))}}else if(_===1)k=R=>r-Math.exp(-b*R)*(S+(v+b*S)*R);else{const R=b*Math.sqrt(_*_-1);k=D=>{const C=Math.exp(-_*b*D),E=Math.min(R*D,300);return r-C*((v+_*b*S)*Math.sinh(E)+R*S*Math.cosh(E))/R}}const A={calculatedDuration:g&&d||null,next:R=>{const D=k(R);if(g)a.done=R>=d;else{let C=R===0?v:0;_<1&&(C=R===0?pt(v):Ol(k,R,D));const E=Math.abs(C)<=n,p=Math.abs(r-D)<=s;a.done=E&&p}return a.value=a.done?r:D,a},toString:()=>{const R=Math.min(yo(A),Un),D=Dl(C=>A.next(R*C).value,R,30);return R+"ms "+D},toTransition:()=>{}};return A}$n.applyToOptions=t=>{const e=Cp(t,100,$n);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function So({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},g=E=>a!==void 0&&E<a||l!==void 0&&E>l,v=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let _=i*e;const S=d+_,b=r===void 0?S:r(S);b!==S&&(_=b-d);const T=E=>-_*Math.exp(-E/n),k=E=>b+T(E),A=E=>{const p=T(E),m=k(E);h.done=Math.abs(p)<=c,h.value=h.done?b:m};let R,D;const C=E=>{g(h.value)&&(R=E,D=$n({keyframes:[h.value,v(h.value)],velocity:Ol(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return C(0),{calculatedDuration:null,next:E=>{let p=!1;return!D&&R===void 0&&(p=!0,A(E),C(E)),R!==void 0&&E>=R?D.next(E-R):(!p&&A(E),h)}}}function Lp(t,e,i){const n=[],s=i||Rt.mix||Ll,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]||et:e;a=Hi(l,a)}n.push(a)}return n}function Dp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(io(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=Lp(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=Wi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Op(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Wi(0,e,n);t.push(Ce(i,1,s))}}function Mp(t){const e=[0];return Op(e,t.length-1),e}function Pp(t,e){return t.map(i=>i*e)}function Np(t,e){return t.map(()=>e||gl).splice(0,t.length-1)}function Xi({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=zf(n)?n.map(vl):vl(n),o={done:!1,value:e[0]},r=Pp(i&&i.length===e.length?i:Mp(e),t),a=Dp(r,e,{ease:Array.isArray(s)?s:Np(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Fp=t=>t!==null;function Co(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Fp),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Bp={decay:So,inertia:So,tween:Xi,keyframes:Xi,spring:$n};function Pl(t){typeof t.type=="string"&&(t.type=Bp[t.type])}class To{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 Vp=t=>t/100;class Eo extends To{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!==qe.now()&&this.tick(qe.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;Pl(e);const{type:i=Xi,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Xi;l!==Xi&&typeof a[0]!="number"&&(this.mixKeyframes=Hi(Vp,Ll(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=yo(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:g,type:v,onUpdate:_,finalKeyframe:S}=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 b=this.currentTime-c*(this.playbackSpeed>=0?1:-1),T=this.playbackSpeed>=0?b<0:b>s;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,A=n;if(d){const E=Math.min(this.currentTime,s)/a;let p=Math.floor(E),m=E%1;!m&&E>=1&&(m=1),m===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(h==="reverse"?(m=1-m,g&&(m-=g/a)):h==="mirror"&&(A=r)),k=It(0,1,m)*a}const R=T?{done:!1,value:u[0]}:A.next(k);o&&(R.value=o(R.value));let{done:D}=R;!T&&l!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const C=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return C&&v!==So&&(R.value=Co(u,this.options,S,this.speed)),_&&_(R.value),C&&this.finish(),R}then(e,i){return this.finished.then(e,i)}get duration(){return gt(this.calculatedDuration)}get time(){return gt(this.currentTime)}set time(e){var i;e=pt(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(qe.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=gt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Sp,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(qe.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 Up(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,ko=t=>{const e=Kt(Math.atan2(t[1],t[0]));return Io(e)},$p={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:ko,rotateZ:ko,skewX:t=>Kt(Math.atan(t[1])),skewY:t=>Kt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Io=t=>(t=t%360,t<0&&(t+=360),t),Nl=ko,Fl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Bl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),jp={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Fl,scaleY:Bl,scale:t=>(Fl(t)+Bl(t))/2,rotateX:t=>Io(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>Io(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Nl,rotate:Nl,skewX:t=>Kt(Math.atan(t[4])),skewY:t=>Kt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Ro(t){return t.includes("scale")?1:0}function Ao(t,e){if(!t||t==="none")return Ro(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=jp,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=$p,s=a}if(!s)return Ro(e);const o=n[e],r=s[1].split(",").map(Wp);return typeof o=="function"?o(r):r[o]}const Hp=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Ao(i,e)};function Wp(t){return parseFloat(t.trim())}const pi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],gi=new Set(pi),Vl=t=>t===hi||t===K,Gp=new Set(["x","y","z"]),qp=pi.filter(t=>!Gp.has(t));function zp(t){const e=[];return qp.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Yt={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})=>Ao(e,"x"),y:(t,{transform:e})=>Ao(e,"y")};Yt.translateX=Yt.x,Yt.translateY=Yt.y;const Xt=new Set;let xo=!1,Lo=!1,Do=!1;function Ul(){if(Lo){const t=Array.from(Xt).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=zp(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)})}Lo=!1,xo=!1,Xt.forEach(t=>t.complete(Do)),Xt.clear()}function $l(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Lo=!0)})}function Kp(){Do=!0,$l(),Ul(),Do=!1}class Oo{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?(Xt.add(this),xo||(xo=!0,we.read($l),we.resolveKeyframes(Ul))):(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])}Up(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Xt.delete(this)}cancel(){this.state==="scheduled"&&(Xt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Yp=t=>t.startsWith("--");function Xp(t,e,i){Yp(e)?t.style.setProperty(e,i):t.style[e]=i}const Jp=no(()=>window.ScrollTimeline!==void 0),Zp={};function Qp(t,e){const i=no(t);return()=>Zp[e]??i()}const jl=Qp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ji=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,Hl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ji([0,.65,.55,1]),circOut:Ji([.55,0,1,.45]),backIn:Ji([.31,.01,.66,-.59]),backOut:Ji([.33,1.53,.69,.99])};function Wl(t,e){if(t)return typeof t=="function"?jl()?Dl(t,e):"ease-out":ml(t)?Ji(t):Array.isArray(t)?t.map(i=>Wl(i,e)||Hl.easeOut):Hl[t]}function eg(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=Wl(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 Gl(t){return typeof t=="function"&&"applyToOptions"in t}function tg({type:t,...e}){return Gl(t)&&jl()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class ig extends To{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,io(typeof e.type!="string");const c=tg(e);this.animation=eg(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Co(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Xp(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 gt(Number(e))}get time(){return gt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=pt(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&&Jp()?(this.animation.timeline=e,et):i(this)}}const ql={anticipate:hl,backInOut:ul,circInOut:pl};function ng(t){return t in ql}function sg(t){typeof t.ease=="string"&&ng(t.ease)&&(t.ease=ql[t.ease])}const zl=10;class og extends ig{constructor(e){sg(e),Pl(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 Eo({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-zl).value,a.sample(l).value,zl),a.stop()}}const Kl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function rg(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 ag(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=Kl(s,e),a=Kl(o,e);return!r||!a?!1:rg(t)||(i==="spring"||Gl(i))&&n}function Mo(t){return sl(t)&&"offsetHeight"in t}const lg=new Set(["opacity","clipPath","filter","transform"]),cg=no(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function dg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Mo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return cg()&&i&&lg.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const ug=40;class hg extends To{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 v;super(),this.stop=()=>{var _,S;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(S=this.keyframeResolver)==null||S.cancel()},this.createdAt=qe.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Oo;this.keyframeResolver=new g(a,(_,S,b)=>this.onKeyframesResolved(_,S,h,!b),l,c,u),(v=this.keyframeResolver)==null||v.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=qe.now(),ag(e,o,r,a)||((Rt.instantAnimations||!l)&&(u==null||u(Co(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>ug?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},g=!c&&dg(h)?new og({...h,element:h.motionValue.owner.current}):new Eo(h);g.finished.then(()=>this.notifyFinished()).catch(et),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}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(),Kp()),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 fg=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pg(t){const e=fg.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Yl(t,e,i=1){const[n,s]=pg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return nl(r)?parseFloat(r):r}return co(s)?Yl(s,e,i+1):s}function Po(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Xl=new Set(["width","height","top","left","right","bottom",...pi]),gg={test:t=>t==="auto",parse:t=>t},Jl=t=>e=>e.test(t),Zl=[hi,K,mt,Nt,rp,op,gg],Ql=t=>Zl.find(Jl(t));function mg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||ol(t):!0}const vg=new Set(["brightness","contrast","saturate","opacity"]);function _g(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(uo)||[];if(!n)return t;const s=i.replace(n,"");let o=vg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const yg=/\b([a-z-]*)\(.*?\)/gu,No={...Ft,getAnimatableNone:t=>{const e=t.match(yg);return e?e.map(_g).join(" "):t}},ec={...hi,transform:Math.round},Fo={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Bn,scaleX:Bn,scaleY:Bn,scaleZ:Bn,skew:Nt,skewX:Nt,skewY:Nt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:qi,originX:Sl,originY:Sl,originZ:K},zIndex:ec,fillOpacity:qi,strokeOpacity:qi,numOctaves:ec},bg={...Fo,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:No,WebkitFilter:No},tc=t=>bg[t];function ic(t,e){let i=tc(t);return i!==No&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const wg=new Set(["auto","none","0"]);function Sg(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!wg.has(o)&&Yi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=ic(i,s)}class Cg extends Oo{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(),co(c))){const u=Yl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Xl.has(n)||e.length!==2)return;const[s,o]=e,r=Ql(s),a=Ql(o);if(r!==a)if(Vl(r)&&Vl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Yt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||mg(e[s]))&&n.push(s);n.length&&Sg(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=Yt[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]=Yt[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 Tg(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 nc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,sc=30,Eg=t=>!isNaN(parseFloat(t));class kg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=qe.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=qe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Eg(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 so);const n=this.events[e].add(i);return e==="change"?()=>{n(),we.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=qe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>sc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,sc);return rl(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 mi(t,e){return new kg(t,e)}const{schedule:Bo}=yl(queueMicrotask,!1),lt={x:!1,y:!1};function oc(){return lt.x||lt.y}function Ig(t){return t==="x"||t==="y"?lt[t]?null:(lt[t]=!0,()=>{lt[t]=!1}):lt.x||lt.y?null:(lt.x=lt.y=!0,()=>{lt.x=lt.y=!1})}function rc(t,e){const i=Tg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function ac(t){return!(t.pointerType==="touch"||oc())}function Rg(t,e,i={}){const[n,s,o]=rc(t,i),r=a=>{if(!ac(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{ac(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const lc=(t,e)=>e?t===e?!0:lc(t,e.parentElement):!1,Vo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ag=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function xg(t){return Ag.has(t.tagName)||t.tabIndex!==-1}const jn=new WeakSet;function cc(t){return e=>{e.key==="Enter"&&t(e)}}function Uo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Lg=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=cc(()=>{if(jn.has(i))return;Uo(i,"down");const s=cc(()=>{Uo(i,"up")}),o=()=>Uo(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 dc(t){return Vo(t)&&!oc()}function Dg(t,e,i={}){const[n,s,o]=rc(t,i),r=a=>{const l=a.currentTarget;if(!dc(a))return;jn.add(l);const c=e(l,a),u=(g,v)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),jn.has(l)&&jn.delete(l),dc(g)&&typeof c=="function"&&c(g,{success:v})},d=g=>{u(g,l===window||l===document||i.useGlobalTarget||lc(l,g.target))},h=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Mo(a)&&(a.addEventListener("focus",c=>Lg(c,s)),!xg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function uc(t){return sl(t)&&"ownerSVGElement"in t}function Og(t){return uc(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),Mg=[...Zl,Ie,Ft],Pg=t=>Mg.find(Jl(t)),Zi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Ng extends at{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Mo(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 Fg({children:t,isPresent:e,anchorX:i,root:n}){const s=Us(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(Zi);return Fa(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const g=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const _=n??document.head;return _.appendChild(v),v.sheet&&v.sheet.insertRule(`
1
+ var ES=Object.defineProperty;var IS=(dt,z,Yt)=>z in dt?ES(dt,z,{enumerable:!0,configurable:!0,writable:!0,value:Yt}):dt[z]=Yt;var H=(dt,z,Yt)=>IS(dt,typeof z!="symbol"?z+"":z,Yt);(function(){"use strict";var dt,z,Yt,Xt,Ta,ka,Ea,Ia,$s,js,Hs,Ra,Gi={},Aa=[],qf=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qi=Array.isArray;function gt(t,e){for(var i in e)t[i]=e[i];return t}function Ws(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function tt(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?dt.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??++Yt,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function mt(t){return t.children}function ut(t,e){this.props=t,this.context=e}function gi(t,e){if(e==null)return t.__?gi(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"?gi(t):null}function xa(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 xa(t)}}function Gs(t){(!t.__d&&(t.__d=!0)&&Xt.push(t)&&!On.__r++||Ta!=z.debounceRendering)&&((Ta=z.debounceRendering)||ka)(On)}function On(){for(var t,e,i,n,s,o,r,a=1;Xt.length;)Xt.length>a&&Xt.sort(Ea),t=Xt.shift(),a=Xt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=gt({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),qs(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??gi(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,Pa(o,i,r),i.__e!=s&&xa(i)));On.__r=0}function Da(t,e,i,n,s,o,r,a,l,c,u){var d,h,g,m,v,b,y=n&&n.__k||Aa,C=e.length;for(l=zf(i,e,y,l,C),d=0;d<C;d++)(g=i.__k[d])!=null&&(h=g.__i==-1?Gi:y[g.__i]||Gi,g.__i=d,b=qs(t,g,h,s,o,r,a,l,c,u),m=g.__e,g.ref&&h.ref!=g.ref&&(h.ref&&zs(h.ref,null,g),u.push(g.ref,g.__c||m,g)),v==null&&m!=null&&(v=m),4&g.__u||h.__k===g.__k?l=La(g,l,t):typeof g.type=="function"&&b!==void 0?l=b:m&&(l=m.nextSibling),g.__u&=-7);return i.__e=v,l}function zf(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(mt,{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=Kf(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=gi(a)),Fa(a,a));return n}function La(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=La(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=gi(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function vt(t,e){return e=e||[],t==null||typeof t=="boolean"||(qi(t)?t.some(function(i){vt(i,e)}):e.push(t)),e}function Kf(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 Ma(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||qf.test(e)?i:i+"px"}function Pn(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||Ma(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||Ma(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Ia,"$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=$s,t.addEventListener(e,o?Hs:js,o)):t.removeEventListener(e,o?Hs:js,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 Oa(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=$s++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function qs(t,e,i,n,s,o,r,a,l,c){var u,d,h,g,m,v,b,y,C,k,A,R,D,T,E,p,_,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(y=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],A=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(y,A):(e.__c=d=new ut(y,A),d.constructor=f,d.render=Xf),k&&k.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&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=gt({},d.__s)),gt(d.__s,f.getDerivedStateFromProps(y,d.__s))),g=d.props,m=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&y!==g&&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)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);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(g,m,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,D=z.__r,T=0,C){for(d.state=d.__s,d.__d=!1,D&&D(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,D&&D(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++T<25);d.state=d.__s,d.getChildContext!=null&&(n=gt(gt({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(g,m)),p=u,u!=null&&u.type===mt&&u.key==null&&(p=Na(u.props.children)),a=Da(t,qi(p)?p:[p],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;_--;)Ws(o[_]);else e.__e=i.__e,e.__k=i.__k;z.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Yf(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function Pa(t,e,i){for(var n=0;n<i.length;n++)zs(i[n],i[++n],i[++n]);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 Na(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:qi(t)?t.map(Na):gt({},t)}function Yf(t,e,i,n,s,o,r,a,l){var c,u,d,h,g,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((g=o[c])&&"setAttribute"in g==!!C&&(C?g.localName==C:g.nodeType==3)){t=g,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&&dt.call(t.childNodes),b=i.props||Gi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(g=t.attributes[c]).name]=g.value;for(c in b)if(g=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Pn(t,c,null,g,s)}}for(c in y)g=y[c],c=="children"?h=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?m=g:c=="checked"?v=g:a&&typeof g!="function"||b[c]===g||Pn(t,c,g,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=""),Da(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&&gi(i,0),a,l),o!=null)for(c=o.length;c--;)Ws(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])&&Pn(t,c,m,b[c],s),c="checked",v!=null&&v!=t[c]&&Pn(t,c,v,b[c],s))}return t}function zs(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){z.__e(s,i)}}function Fa(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||zs(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&Fa(n[s],e,i||typeof t.type!="function");i||Ws(t.__e),t.__c=t.__=t.__e=void 0}function Xf(t,e,i){return this.constructor(t,i)}function Nn(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],qs(e,t=(!n&&i||e).__k=tt(mt,null,[t]),s||Gi,Gi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?dt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),Pa(o,t,r)}function Ba(t,e){Nn(t,e,Ba)}function Ks(t,e,i){var n,s,o,r,a=gt({},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?dt.call(arguments,2):i),zi(t.type,a,n||t.key,s||t.ref,null)}function At(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,Gs(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"+Ra++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}dt=Aa.slice,z={__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}},Yt=0,ut.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=gt({},this.state),typeof t=="function"&&(t=t(gt({},i),this.props)),t&&gt(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Gs(this))},ut.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Gs(this))},ut.prototype.render=mt,Xt=[],ka=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ea=function(t,e){return t.__v.__b-e.__v.__b},On.__r=0,Ia=/(PointerCapture)$|Capture$/i,$s=0,js=Oa(!1),Hs=Oa(!0),Ra=0;var Jf=0;function L(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:--Jf,__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 Ys(){return(Ys=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 Zf=["context","children"];function Qf(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,Zf);return Ks(e,i)}function ep(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=tt(Qf,Ys({},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[Ua(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=tt(Va,{name:u},c):s[r]=c}var d=n?tt(Va,null,s):s;return tt(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ba:Nn)(this._vdom,this._root)}function Ua(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function tp(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[Ua(t)]=i,this._vdom=Ks(this._vdom,n),Nn(this._vdom,this._root)}}function ip(){Nn(this._vdom=null,this._root)}function Va(t,e){var i=this;return tt("slot",Ys({},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 np(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=ep,s.prototype.attributeChangedCallback=tp,s.prototype.disconnectedCallback=ip,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 Bt,_e,Xs,$a,Ki=0,ja=[],we=z,Ha=we.__b,Wa=we.__r,Ga=we.diffed,qa=we.__c,za=we.unmount,Ka=we.__;function mi(t,e){we.__h&&we.__h(_e,t,Ki||e),Ki=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return Ki=1,Ya(Ja,t)}function Ya(t,e,i){var n=mi(Bt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):Ja(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=_e,!_e.__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 g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.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)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=mi(Bt++,3);!we.__s&&eo(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Js(t,e){var i=mi(Bt++,4);!we.__s&&eo(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function he(t){return Ki=5,it(function(){return{current:t}},[])}function it(t,e){var i=mi(Bt++,7);return eo(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function qe(t,e){return Ki=8,it(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=mi(Bt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function sp(t,e){we.useDebugValue&&we.useDebugValue(e?e(t):t)}function Zs(){var t=mi(Bt++,11);if(!t.__){for(var e=_e.__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 op(){for(var t;t=ja.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Fn),t.__H.__h.forEach(Qs),t.__H.__h=[]}catch(e){t.__H.__h=[],we.__e(e,t.__v)}}we.__b=function(t){_e=null,Ha&&Ha(t)},we.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ka&&Ka(t,e)},we.__r=function(t){Wa&&Wa(t),Bt=0;var e=(_e=t.__c).__H;e&&(Xs===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Fn),e.__h.forEach(Qs),e.__h=[],Bt=0)),Xs=_e},we.diffed=function(t){Ga&&Ga(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ja.push(e)!==1&&$a===we.requestAnimationFrame||(($a=we.requestAnimationFrame)||rp)(op)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Xs=_e=null},we.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Fn),i.__h=i.__h.filter(function(n){return!n.__||Qs(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],we.__e(n,i.__v)}}),qa&&qa(t,e)},we.unmount=function(t){za&&za(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Fn(n)}catch(s){e=s}}),i.__H=void 0,e&&we.__e(e,i.__v))};var Xa=typeof requestAnimationFrame=="function";function rp(t){var e,i=function(){clearTimeout(n),Xa&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Xa&&(e=requestAnimationFrame(i))}function Fn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Qs(t){var e=_e;t.__c=t.__(),_e=e}function eo(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ja(t,e){return typeof e=="function"?e(t):e}const Yi={},Za=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Qa=t=>"init"in t,to=t=>!!t.write,el=t=>"v"in t||"e"in t,Bn=t=>{if("e"in t)throw t.e;if((Yi?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Un=new WeakMap,tl=t=>{var e;return Vn(t)&&!!((e=Un.get(t))!=null&&e[0])},ap=t=>{const e=Un.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},il=(t,e)=>{let i=Un.get(t);if(!i){i=[!0,new Set],Un.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Vn=t=>typeof(t==null?void 0:t.then)=="function",nl=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},io=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Vn(e))for(const r of n.d.keys())nl(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Vn(o)&&ap(o))},sl=(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},lp=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},no=()=>{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},cp=t=>(t.c||(t.c=no()),t.m||(t.m=no()),t.u||(t.u=no()),t.f||(t.f=lp()),t),dp=Symbol(),ol=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...g)=>h.read(...g),l=(h,...g)=>h.write(...g),c=(h,g)=>{var m;return(m=h.unstable_onInit)==null?void 0:m.call(h,g)},u=(h,g)=>{var m;return(m=h.onMount)==null?void 0:m.call(h,g)},...d)=>{const h=d[0]||(T=>{if((Yi?"production":void 0)!=="production"&&!T)throw new Error("Atom is undefined or null");let E=t.get(T);return E||(E={d:new Map,p:new Set,n:0},t.set(T,E),c==null||c(T,D)),E}),g=d[1]||(()=>{const T=[],E=p=>{try{p()}catch(_){T.push(_)}};do{r.f&&E(r.f);const p=new Set,_=p.add.bind(p);n.forEach(f=>{var S;return(S=e.get(f))==null?void 0:S.l.forEach(_)}),n.clear(),o.forEach(_),o.clear(),s.forEach(_),s.clear(),p.forEach(E),n.size&&m()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),m=d[2]||(()=>{const T=[],E=new WeakSet,p=new WeakSet,_=Array.from(n);for(;_.length;){const f=_[_.length-1],S=h(f);if(p.has(f)){_.pop();continue}if(E.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if((Yi?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");p.add(f),_.pop();continue}E.add(f);for(const I of sl(f,S,e))E.has(I)||_.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let M=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){M=!0;break}M&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const p=h(T);if(el(p)&&(e.has(T)&&i.get(T)!==p.n||Array.from(p.d).every(([O,F])=>v(O).n===F)))return p;p.d.clear();let _=!0;const f=()=>{e.has(T)&&(C(T),m(),g())},S=O=>{var F;if(Za(T,O)){const $=h(O);if(!el($))if(Qa(O))io(O,O.init,h);else throw new Error("no atom init");return Bn($)}const V=v(O);try{return Bn(V)}finally{p.d.set(O,V.n),tl(p.v)&&nl(T,p.v,V),(F=e.get(O))==null||F.t.add(T),_||f()}};let I,M;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Yi?"production":void 0)!=="production"&&!to(T)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&to(T)&&(M=(...O)=>{if((Yi?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return y(T,...O)}finally{m(),g()}}),M}},N=p.n;try{const O=a(T,S,x);return io(T,O,h),Vn(O)&&(il(O,()=>I==null?void 0:I.abort()),O.then(f,f)),p}catch(O){return delete p.v,p.e=O,++p.n,p}finally{_=!1,N!==p.n&&i.get(T)===N&&(i.set(T,p.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const p=E.pop(),_=h(p);for(const f of sl(p,_,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),y=d[5]||((T,...E)=>{let p=!0;const _=S=>Bn(v(S)),f=(S,...I)=>{var M;const x=h(S);try{if(Za(T,S)){if(!Qa(S))throw new Error("atom not writable");const N=x.n,O=I[0];io(S,O,h),C(S),N!==x.n&&(n.add(S),(M=r.c)==null||M.call(r,S),b(S));return}else return y(S,...I)}finally{p||(m(),g())}};try{return l(T,_,f,...E)}finally{p=!1}}),C=d[6]||(T=>{var E;const p=h(T),_=e.get(T);if(_&&!tl(p.v)){for(const[f,S]of p.d)if(!_.d.has(f)){const I=h(f);k(f).t.add(T),_.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of _.d||[])if(!p.d.has(f)){_.d.delete(f);const S=A(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const p=h(T);let _=e.get(T);if(!_){v(T);for(const f of p.d.keys())k(f).t.add(T);if(_={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(T,_),(E=r.m)==null||E.call(r,T),to(T)){const f=()=>{let S=!0;const I=(...M)=>{try{return y(T,...M)}finally{S||(m(),g())}};try{const M=u(T,I);M&&(_.u=()=>{S=!0;try{M()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return _}),A=d[8]||(T=>{var E;const p=h(T);let _=e.get(T);if(_&&!_.l.size&&!Array.from(_.t).some(f=>{var S;return(S=e.get(f))==null?void 0:S.d.has(T)})){_.u&&o.add(_.u),_=void 0,e.delete(T),(E=r.u)==null||E.call(r,T);for(const f of p.d.keys()){const S=A(f);S==null||S.t.delete(T)}return}return _}),R=[t,e,i,n,s,o,r,a,l,c,u,h,g,m,v,b,y,C,k,A],D={get:T=>Bn(v(T)),set:(T,...E)=>{try{return y(T,...E)}finally{m(),g()}},sub:(T,E)=>{const _=k(T).l;return _.add(E),g(),()=>{_.delete(E),A(T),g()}}};return Object.defineProperty(D,dp,{value:R}),D},up=cp,rl=il,so={};let hp=0;function $n(t,e){const i=`atom${++hp}`,n={toString(){return(so?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=fp,n.write=pp),n}function fp(t){return t(this)}function pp(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const gp=()=>{let t=0;const e=up({}),i=new WeakMap,n=new WeakMap,s=ol(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 mp(){return(so?"production":void 0)!=="production"?gp():ol()}let Xi;function vp(){return Xi||(Xi=mp(),(so?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Xi),globalThis.__JOTAI_DEFAULT_STORE__!==Xi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Xi}function al(t,e){for(var i in e)t[i]=e[i];return t}function ll(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 cl=Js;function dl(t,e){this.props=t,this.context=e}(dl.prototype=new ut).isPureReactComponent=!0,dl.prototype.shouldComponentUpdate=function(t,e){return ll(this.props,t)||ll(this.state,e)};var ul=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ul&&ul(t)};var _p=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function yp(t){function e(i){var n=al({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=_p,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var hl=function(t,e){return t==null?null:vt(vt(t).map(e))},bp={map:hl,forEach:hl,count:function(t){return t?vt(t).length:0},only:function(t){var e=vt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:vt},wp=z.__e;z.__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)}wp(t,e,i,n)};var fl=z.unmount;function pl(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=al({},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 pl(n,e,i)})),t}function gl(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return gl(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 oo(){this.__u=0,this.o=null,this.__b=null}function ml(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function jn(){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),fl&&fl(t)},(oo.prototype=new ut).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=ml(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]=gl(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)},oo.prototype.componentWillUnmount=function(){this.o=[]},oo.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]=pl(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&tt(mt,null,t.fallback);return s&&(s.__u&=-33),[tt(mt,null,e.__a?null:t.children),s]};var vl=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]}};(jn.prototype=new ut).__a=function(t){var e=this,i=ml(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),vl(e,t,n)):s()};i?i(o):o()}},jn.prototype.render=function(t){this.i=null,this.l=new Map;var e=vt(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},jn.prototype.componentDidUpdate=jn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){vl(t,i,e)})};var _l=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Sp=/^(?: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]/,Cp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Tp=/[A-Z0-9]/g,kp=typeof document<"u",Ep=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};ut.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(ut.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var yl=z.event;function Ip(){}function Rp(){return this.cancelBubble}function Ap(){return this.defaultPrevented}z.event=function(t){return yl&&(t=yl(t)),t.persist=Ip,t.isPropagationStopped=Rp,t.isDefaultPrevented=Ap,t.nativeEvent=t};var xp={enumerable:!1,configurable:!0,get:function(){return this.class}},bl=z.vnode;z.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||kp&&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"||Ep(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Cp.test(r)&&(r=l):l=r="oninput":o&&Sp.test(r)?r=r.replace(Tp,"-$&").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=vt(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=vt(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",xp)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=_l,bl&&bl(t)};var wl=z.__r;z.__r=function(t){wl&&wl(t),t.__c};var Sl=z.diffed;z.diffed=function(t){Sl&&Sl(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 Cl(t){return!!t&&t.$$typeof===_l}function Dp(t){return Cl(t)?Ks.apply(null,arguments):t}var Tl={};const Lp={},Mp=At(void 0);function kl(t){return De(Mp)||vp()}const ro=t=>typeof(t==null?void 0:t.then)=="function",ao=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Op=Tl.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(ao(t),t)}),lo=new WeakMap,El=(t,e)=>{let i=lo.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();ro(c)?(lo.set(c,i),o=c,c.then(r(c),a(c)),rl(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),rl(t,l)}),lo.set(t,i)),i};function co(t,e){const{delay:i,unstable_promiseStatus:n=!Tl.use}={},s=kl(),[[o,r,a],l]=Ya(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)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);ro(d)&&ao(El(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),sp(c),ro(c)){const u=El(c,()=>s.get(t));return n&&ao(u),Op(u)}return c}function Hn(t,e){const i=kl();return qe((...s)=>{if((Lp?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Il(t,e){return[co(t),Hn(t)]}const uo=At({});function Wn(t){const e=he(null);return e.current===null&&(e.current=t()),e.current}const ho=typeof window<"u",Rl=ho?Js:xe,Gn=At(null);function fo(t,e){t.indexOf(e)===-1&&t.push(e)}function po(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const xt=(t,e,i)=>i>e?e:i<t?t:i;let go=()=>{};const Dt={},Al=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function xl(t){return typeof t=="object"&&t!==null}const Dl=t=>/^0[^.\s]+$/u.test(t);function mo(t){let e;return()=>(e===void 0&&(e=t()),e)}const nt=t=>t,Pp=(t,e)=>i=>e(t(i)),Ji=(...t)=>t.reduce(Pp),Zi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class vo{constructor(){this.subscriptions=[]}add(e){return fo(this.subscriptions,e),()=>po(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 _t=t=>t*1e3,yt=t=>t/1e3;function Ll(t,e){return e?t*(1e3/e):0}const Ml=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Np=1e-7,Fp=12;function Bp(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=Ml(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Np&&++a<Fp);return r}function Qi(t,e,i,n){if(t===e&&i===n)return nt;const s=o=>Bp(o,0,1,t,i);return o=>o===0||o===1?o:Ml(s(o),e,n)}const Ol=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Pl=t=>e=>1-t(1-e),Nl=Qi(.33,1.53,.69,.99),_o=Pl(Nl),Fl=Ol(_o),Bl=t=>(t*=2)<1?.5*_o(t):.5*(2-Math.pow(2,-10*(t-1))),yo=t=>1-Math.sin(Math.acos(t)),Ul=Pl(yo),Vl=Ol(yo),Up=Qi(.42,0,1,1),Vp=Qi(0,0,.58,1),$l=Qi(.42,0,.58,1),$p=t=>Array.isArray(t)&&typeof t[0]!="number",jl=t=>Array.isArray(t)&&typeof t[0]=="number",jp={linear:nt,easeIn:Up,easeInOut:$l,easeOut:Vp,circIn:yo,circInOut:Vl,circOut:Ul,backIn:_o,backInOut:Fl,backOut:Nl,anticipate:Bl},Hp=t=>typeof t=="string",Hl=t=>{if(jl(t)){go(t.length===4);const[e,i,n,s]=t;return Qi(e,i,n,s)}else if(Hp(t))return jp[t];return t},qn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Wl={value:null};function Wp(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,g=!1)=>{const v=g&&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&&Wl.value&&Wl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Gp=40;function Gl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=qn.reduce((k,A)=>(k[A]=Wp(o,e?A:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:g,postRender:m}=r,v=()=>{const k=Dt.useManualTiming?s.timestamp:performance.now();i=!1,Dt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Gp),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),g.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:qn.reduce((k,A)=>{const R=r[A];return k[A]=(D,T=!1,E=!1)=>(i||b(),R.schedule(D,T,E)),k},{}),cancel:k=>{for(let A=0;A<qn.length;A++)r[qn[A]].cancel(k)},state:s,steps:r}}const{schedule:be,cancel:Ut,state:Oe,steps:bo}=Gl(typeof requestAnimationFrame<"u"?requestAnimationFrame:nt,!0);let zn;function qp(){zn=void 0}const ze={now:()=>(zn===void 0&&ze.set(Oe.isProcessing||Dt.useManualTiming?Oe.timestamp:performance.now()),zn),set:t=>{zn=t,queueMicrotask(qp)}},ql=t=>e=>typeof e=="string"&&e.startsWith(t),wo=ql("--"),zp=ql("var(--"),So=t=>zp(t)?Kp.test(t.split("/*")[0].trim()):!1,Kp=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,vi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},en={...vi,transform:t=>xt(0,1,t)},Kn={...vi,default:1},tn=t=>Math.round(t*1e5)/1e5,Co=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Yp(t){return t==null}const Xp=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,To=(t,e)=>i=>!!(typeof i=="string"&&Xp.test(i)&&i.startsWith(t)||e&&!Yp(i)&&Object.prototype.hasOwnProperty.call(i,e)),zl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(Co);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Jp=t=>xt(0,255,t),ko={...vi,transform:t=>Math.round(Jp(t))},Jt={test:To("rgb","red"),parse:zl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+ko.transform(t)+", "+ko.transform(e)+", "+ko.transform(i)+", "+tn(en.transform(n))+")"};function Zp(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 Eo={test:To("#"),parse:Zp,transform:Jt.transform},nn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Vt=nn("deg"),bt=nn("%"),K=nn("px"),Qp=nn("vh"),eg=nn("vw"),Kl={...bt,parse:t=>bt.parse(t)/100,transform:t=>bt.transform(t*100)},_i={test:To("hsl","hue"),parse:zl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+bt.transform(tn(e))+", "+bt.transform(tn(i))+", "+tn(en.transform(n))+")"},Ee={test:t=>Jt.test(t)||Eo.test(t)||_i.test(t),parse:t=>Jt.test(t)?Jt.parse(t):_i.test(t)?_i.parse(t):Eo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Jt.transform(t):_i.transform(t),getAnimatableNone:t=>{const e=Ee.parse(t);return e.alpha=0,Ee.transform(e)}},tg=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ig(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Co))==null?void 0:e.length)||0)+(((i=t.match(tg))==null?void 0:i.length)||0)>0}const Yl="number",Xl="color",ng="var",sg="var(",Jl="${}",og=/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 sn(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(og,l=>(Ee.test(l)?(n.color.push(o),s.push(Xl),i.push(Ee.parse(l))):l.startsWith(sg)?(n.var.push(o),s.push(ng),i.push(l)):(n.number.push(o),s.push(Yl),i.push(parseFloat(l))),++o,Jl)).split(Jl);return{values:i,split:a,indexes:n,types:s}}function Zl(t){return sn(t).values}function Ql(t){const{split:e,types:i}=sn(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===Yl?o+=tn(s[r]):a===Xl?o+=Ee.transform(s[r]):o+=s[r]}return o}}const rg=t=>typeof t=="number"?0:Ee.test(t)?Ee.getAnimatableNone(t):t;function ag(t){const e=Zl(t);return Ql(t)(e.map(rg))}const $t={test:ig,parse:Zl,createTransformer:Ql,getAnimatableNone:ag};function Io(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 lg({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=Io(l,a,t+1/3),o=Io(l,a,t),r=Io(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Yn(t,e){return i=>i>0?e:t}const Se=(t,e,i)=>t+(e-t)*i,Ro=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},cg=[Eo,Jt,_i],dg=t=>cg.find(e=>e.test(t));function ec(t){const e=dg(t);if(!e)return!1;let i=e.parse(t);return e===_i&&(i=lg(i)),i}const tc=(t,e)=>{const i=ec(t),n=ec(e);if(!i||!n)return Yn(t,e);const s={...i};return o=>(s.red=Ro(i.red,n.red,o),s.green=Ro(i.green,n.green,o),s.blue=Ro(i.blue,n.blue,o),s.alpha=Se(i.alpha,n.alpha,o),Jt.transform(s))},Ao=new Set(["none","hidden"]);function ug(t,e){return Ao.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function hg(t,e){return i=>Se(t,e,i)}function xo(t){return typeof t=="number"?hg:typeof t=="string"?So(t)?Yn:Ee.test(t)?tc:gg:Array.isArray(t)?ic:typeof t=="object"?Ee.test(t)?tc:fg:Yn}function ic(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>xo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function fg(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=xo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function pg(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 gg=(t,e)=>{const i=$t.createTransformer(e),n=sn(t),s=sn(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?Ao.has(t)&&!s.values.length||Ao.has(e)&&!n.values.length?ug(t,e):Ji(ic(pg(n,s),s.values),i):Yn(t,e)};function nc(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Se(t,e,i):xo(t)(t,e)}const mg=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>be.update(e,i),stop:()=>Ut(e),now:()=>Oe.isProcessing?Oe.timestamp:ze.now()}},sc=(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)})`},Xn=2e4;function Do(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<Xn;)e+=i,n=t.next(e);return e>=Xn?1/0:e}function vg(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(Do(n),Xn);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:yt(s)}}const _g=5;function oc(t,e,i){const n=Math.max(e-_g,0);return Ll(i-t(n),e-n)}const Ce={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},Lo=.001;function yg({duration:t=Ce.duration,bounce:e=Ce.bounce,velocity:i=Ce.velocity,mass:n=Ce.mass}){let s,o,r=1-e;r=xt(Ce.minDamping,Ce.maxDamping,r),t=xt(Ce.minDuration,Ce.maxDuration,yt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,g=Mo(c,r),m=Math.exp(-d);return Lo-h/g*m},o=c=>{const d=c*r*t,h=d*i+i,g=Math.pow(r,2)*Math.pow(c,2)*t,m=Math.exp(-d),v=Mo(Math.pow(c,2),r);return(-s(c)+Lo>0?-1:1)*((h-g)*m)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-Lo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=wg(s,o,a);if(t=_t(t),isNaN(l))return{stiffness:Ce.stiffness,damping:Ce.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const bg=12;function wg(t,e,i){let n=i;for(let s=1;s<bg;s++)n=n-t(n)/e(n);return n}function Mo(t,e){return t*Math.sqrt(1-e*e)}const Sg=["duration","bounce"],Cg=["stiffness","damping","mass"];function rc(t,e){return e.some(i=>t[i]!==void 0)}function Tg(t){let e={velocity:Ce.velocity,stiffness:Ce.stiffness,damping:Ce.damping,mass:Ce.mass,isResolvedFromDuration:!1,...t};if(!rc(t,Cg)&&rc(t,Sg))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*xt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ce.mass,stiffness:s,damping:o}}else{const i=yg(t);e={...e,...i,mass:Ce.mass},e.isResolvedFromDuration=!0}return e}function Jn(t=Ce.visualDuration,e=Ce.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:g}=Tg({...i,velocity:-yt(i.velocity||0)}),m=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,y=yt(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Ce.restSpeed.granular:Ce.restSpeed.default),s||(s=C?Ce.restDelta.granular:Ce.restDelta.default);let k;if(v<1){const R=Mo(y,v);k=D=>{const T=Math.exp(-v*y*D);return r-T*((m+v*y*b)/R*Math.sin(R*D)+b*Math.cos(R*D))}}else if(v===1)k=R=>r-Math.exp(-y*R)*(b+(m+y*b)*R);else{const R=y*Math.sqrt(v*v-1);k=D=>{const T=Math.exp(-v*y*D),E=Math.min(R*D,300);return r-T*((m+v*y*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const A={calculatedDuration:g&&d||null,next:R=>{const D=k(R);if(g)a.done=R>=d;else{let T=R===0?m:0;v<1&&(T=R===0?_t(m):oc(k,R,D));const E=Math.abs(T)<=n,p=Math.abs(r-D)<=s;a.done=E&&p}return a.value=a.done?r:D,a},toString:()=>{const R=Math.min(Do(A),Xn),D=sc(T=>A.next(R*T).value,R,30);return R+"ms "+D},toTransition:()=>{}};return A}Jn.applyToOptions=t=>{const e=vg(t,100,Jn);return t.ease=e.ease,t.duration=_t(e.duration),t.type="keyframes",t};function Oo({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},g=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=i*e;const b=d+v,y=r===void 0?b:r(b);y!==b&&(v=y-d);const C=E=>-v*Math.exp(-E/n),k=E=>y+C(E),A=E=>{const p=C(E),_=k(E);h.done=Math.abs(p)<=c,h.value=h.done?y:_};let R,D;const T=E=>{g(h.value)&&(R=E,D=Jn({keyframes:[h.value,m(h.value)],velocity:oc(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let p=!1;return!D&&R===void 0&&(p=!0,A(E),T(E)),R!==void 0&&E>=R?D.next(E-R):(!p&&A(E),h)}}}function kg(t,e,i){const n=[],s=i||Dt.mix||nc,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]||nt:e;a=Ji(l,a)}n.push(a)}return n}function Eg(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(go(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=kg(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=Zi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(xt(t[0],t[o-1],u)):c}function Ig(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Zi(0,e,n);t.push(Se(i,1,s))}}function Rg(t){const e=[0];return Ig(e,t.length-1),e}function Ag(t,e){return t.map(i=>i*e)}function xg(t,e){return t.map(()=>e||$l).splice(0,t.length-1)}function on({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=$p(n)?n.map(Hl):Hl(n),o={done:!1,value:e[0]},r=Ag(i&&i.length===e.length?i:Rg(e),t),a=Eg(r,e,{ease:Array.isArray(s)?s:xg(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Dg=t=>t!==null;function Po(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Dg),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Lg={decay:Oo,inertia:Oo,tween:on,keyframes:on,spring:Jn};function ac(t){typeof t.type=="string"&&(t.type=Lg[t.type])}class No{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 Mg=t=>t/100;class Fo extends No{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!==ze.now()&&this.tick(ze.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;ac(e);const{type:i=on,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||on;l!==on&&typeof a[0]!="number"&&(this.mixKeyframes=Ji(Mg,nc(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=Do(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:g,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 k=this.currentTime,A=n;if(d){const E=Math.min(this.currentTime,s)/a;let p=Math.floor(E),_=E%1;!_&&E>=1&&(_=1),_===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(h==="reverse"?(_=1-_,g&&(_-=g/a)):h==="mirror"&&(A=r)),k=xt(0,1,_)*a}const R=C?{done:!1,value:u[0]}:A.next(k);o&&(R.value=o(R.value));let{done:D}=R;!C&&l!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return T&&m!==Oo&&(R.value=Po(u,this.options,b,this.speed)),v&&v(R.value),T&&this.finish(),R}then(e,i){return this.finished.then(e,i)}get duration(){return yt(this.calculatedDuration)}get time(){return yt(this.currentTime)}set time(e){var i;e=_t(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(ze.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=yt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=mg,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(ze.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 Og(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Zt=t=>t*180/Math.PI,Bo=t=>{const e=Zt(Math.atan2(t[1],t[0]));return Uo(e)},Pg={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Bo,rotateZ:Bo,skewX:t=>Zt(Math.atan(t[1])),skewY:t=>Zt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Uo=t=>(t=t%360,t<0&&(t+=360),t),lc=Bo,cc=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),dc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Ng={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:cc,scaleY:dc,scale:t=>(cc(t)+dc(t))/2,rotateX:t=>Uo(Zt(Math.atan2(t[6],t[5]))),rotateY:t=>Uo(Zt(Math.atan2(-t[2],t[0]))),rotateZ:lc,rotate:lc,skewX:t=>Zt(Math.atan(t[4])),skewY:t=>Zt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Vo(t){return t.includes("scale")?1:0}function $o(t,e){if(!t||t==="none")return Vo(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Ng,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Pg,s=a}if(!s)return Vo(e);const o=n[e],r=s[1].split(",").map(Bg);return typeof o=="function"?o(r):r[o]}const Fg=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return $o(i,e)};function Bg(t){return parseFloat(t.trim())}const yi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],bi=new Set(yi),uc=t=>t===vi||t===K,Ug=new Set(["x","y","z"]),Vg=yi.filter(t=>!Ug.has(t));function $g(t){const e=[];return Vg.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Qt={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})=>$o(e,"x"),y:(t,{transform:e})=>$o(e,"y")};Qt.translateX=Qt.x,Qt.translateY=Qt.y;const ei=new Set;let jo=!1,Ho=!1,Wo=!1;function hc(){if(Ho){const t=Array.from(ei).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=$g(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)})}Ho=!1,jo=!1,ei.forEach(t=>t.complete(Wo)),ei.clear()}function fc(){ei.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ho=!0)})}function jg(){Wo=!0,fc(),hc(),Wo=!1}class Go{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?(ei.add(this),jo||(jo=!0,be.read(fc),be.resolveKeyframes(hc))):(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])}Og(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ei.delete(this)}cancel(){this.state==="scheduled"&&(ei.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Hg=t=>t.startsWith("--");function Wg(t,e,i){Hg(e)?t.style.setProperty(e,i):t.style[e]=i}const Gg=mo(()=>window.ScrollTimeline!==void 0),qg={};function zg(t,e){const i=mo(t);return()=>qg[e]??i()}const pc=zg(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),rn=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,gc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:rn([0,.65,.55,1]),circOut:rn([.55,0,1,.45]),backIn:rn([.31,.01,.66,-.59]),backOut:rn([.33,1.53,.69,.99])};function mc(t,e){if(t)return typeof t=="function"?pc()?sc(t,e):"ease-out":jl(t)?rn(t):Array.isArray(t)?t.map(i=>mc(i,e)||gc.easeOut):gc[t]}function Kg(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=mc(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 vc(t){return typeof t=="function"&&"applyToOptions"in t}function Yg({type:t,...e}){return vc(t)&&pc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Xg extends No{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,go(typeof e.type!="string");const c=Yg(e);this.animation=Kg(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Po(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Wg(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 yt(Number(e))}get time(){return yt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=_t(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&&Gg()?(this.animation.timeline=e,nt):i(this)}}const _c={anticipate:Bl,backInOut:Fl,circInOut:Vl};function Jg(t){return t in _c}function Zg(t){typeof t.ease=="string"&&Jg(t.ease)&&(t.ease=_c[t.ease])}const yc=10;class Qg extends Xg{constructor(e){Zg(e),ac(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 Fo({...r,autoplay:!1}),l=_t(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-yc).value,a.sample(l).value,yc),a.stop()}}const bc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&($t.test(t)||t==="0")&&!t.startsWith("url("));function em(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 tm(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=bc(s,e),a=bc(o,e);return!r||!a?!1:em(t)||(i==="spring"||vc(i))&&n}function qo(t){return xl(t)&&"offsetHeight"in t}const im=new Set(["opacity","clipPath","filter","transform"]),nm=mo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function sm(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!qo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return nm()&&i&&im.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const om=40;class rm extends No{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=ze.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Go;this.keyframeResolver=new g(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=ze.now(),tm(e,o,r,a)||((Dt.instantAnimations||!l)&&(u==null||u(Po(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>om?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},g=!c&&sm(h)?new Qg({...h,element:h.motionValue.owner.current}):new Fo(h);g.finished.then(()=>this.notifyFinished()).catch(nt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}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(),jg()),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 am=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function lm(t){const e=am.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function wc(t,e,i=1){const[n,s]=lm(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Al(r)?parseFloat(r):r}return So(s)?wc(s,e,i+1):s}function zo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Sc=new Set(["width","height","top","left","right","bottom",...yi]),cm={test:t=>t==="auto",parse:t=>t},Cc=t=>e=>e.test(t),Tc=[vi,K,bt,Vt,eg,Qp,cm],kc=t=>Tc.find(Cc(t));function dm(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Dl(t):!0}const um=new Set(["brightness","contrast","saturate","opacity"]);function hm(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(Co)||[];if(!n)return t;const s=i.replace(n,"");let o=um.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const fm=/\b([a-z-]*)\(.*?\)/gu,Ko={...$t,getAnimatableNone:t=>{const e=t.match(fm);return e?e.map(hm).join(" "):t}},Ec={...vi,transform:Math.round},Yo={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Vt,rotateX:Vt,rotateY:Vt,rotateZ:Vt,scale:Kn,scaleX:Kn,scaleY:Kn,scaleZ:Kn,skew:Vt,skewX:Vt,skewY:Vt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:en,originX:Kl,originY:Kl,originZ:K},zIndex:Ec,fillOpacity:en,strokeOpacity:en,numOctaves:Ec},pm={...Yo,color:Ee,backgroundColor:Ee,outlineColor:Ee,fill:Ee,stroke:Ee,borderColor:Ee,borderTopColor:Ee,borderRightColor:Ee,borderBottomColor:Ee,borderLeftColor:Ee,filter:Ko,WebkitFilter:Ko},Ic=t=>pm[t];function Rc(t,e){let i=Ic(t);return i!==Ko&&(i=$t),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const gm=new Set(["auto","none","0"]);function mm(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!gm.has(o)&&sn(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Rc(i,s)}class vm extends Go{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(),So(c))){const u=wc(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Sc.has(n)||e.length!==2)return;const[s,o]=e,r=kc(s),a=kc(o);if(r!==a)if(uc(r)&&uc(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Qt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||dm(e[s]))&&n.push(s);n.length&&mm(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=Qt[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]=Qt[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 _m(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 Ac=(t,e)=>e&&typeof t=="number"?e.transform(t):t,xc=30,ym=t=>!isNaN(parseFloat(t));class bm{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=ze.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=ze.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=ym(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 vo);const n=this.events[e].add(i);return e==="change"?()=>{n(),be.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=ze.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>xc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,xc);return Ll(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 wi(t,e){return new bm(t,e)}const{schedule:Xo}=Gl(queueMicrotask,!1),ht={x:!1,y:!1};function Dc(){return ht.x||ht.y}function wm(t){return t==="x"||t==="y"?ht[t]?null:(ht[t]=!0,()=>{ht[t]=!1}):ht.x||ht.y?null:(ht.x=ht.y=!0,()=>{ht.x=ht.y=!1})}function Lc(t,e){const i=_m(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function Mc(t){return!(t.pointerType==="touch"||Dc())}function Sm(t,e,i={}){const[n,s,o]=Lc(t,i),r=a=>{if(!Mc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Mc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Oc=(t,e)=>e?t===e?!0:Oc(t,e.parentElement):!1,Jo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Cm=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Tm(t){return Cm.has(t.tagName)||t.tabIndex!==-1}const Zn=new WeakSet;function Pc(t){return e=>{e.key==="Enter"&&t(e)}}function Zo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const km=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=Pc(()=>{if(Zn.has(i))return;Zo(i,"down");const s=Pc(()=>{Zo(i,"up")}),o=()=>Zo(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 Nc(t){return Jo(t)&&!Dc()}function Em(t,e,i={}){const[n,s,o]=Lc(t,i),r=a=>{const l=a.currentTarget;if(!Nc(a))return;Zn.add(l);const c=e(l,a),u=(g,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Zn.has(l)&&Zn.delete(l),Nc(g)&&typeof c=="function"&&c(g,{success:m})},d=g=>{u(g,l===window||l===document||i.useGlobalTarget||Oc(l,g.target))},h=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),qo(a)&&(a.addEventListener("focus",c=>km(c,s)),!Tm(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Fc(t){return xl(t)&&"ownerSVGElement"in t}function Im(t){return Fc(t)&&t.tagName==="svg"}const Ue=t=>!!(t&&t.getVelocity),Rm=[...Tc,Ee,$t],Am=t=>Rm.find(Cc(t)),an=At({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class xm extends ut{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=qo(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 Dm({children:t,isPresent:e,anchorX:i,root:n}){const s=Zs(),o=he(null),r=he({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(an);return cl(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const g=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(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
@@ -6,114 +6,114 @@ var Cw=Object.defineProperty;var Tw=(rt,z,Gt)=>z in rt?Cw(rt,z,{enumerable:!0,co
6
6
  ${g}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{_.removeChild(v),_.contains(v)&&_.removeChild(v)}},[e]),L(Ng,{isPresent:e,childRef:o,sizeRef:r,children:Ff(t,{ref:o})})}const Bg=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Mn(Vg),u=Us();let d=!0,h=Qe(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:g=>{c.set(g,!0);for(const v of c.values())if(!v)return;n&&n()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[i,c,n]);return o&&d&&(h={...h}),Qe(()=>{c.forEach((g,v)=>c.set(v,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=L(Fg,{isPresent:i,anchorX:a,root:l,children:t})),L(Pn.Provider,{value:h,children:t})};function Vg(){return new Map}function hc(t=!0){const e=De(Pn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Us();xe(()=>{if(t)return s(o)},[t]);const r=Ge(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Hn=t=>t.key||"";function fc(t){const e=[];return kf.forEach(t,i=>{Ja(i)&&e.push(i)}),e}const Ug=({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=Qe(()=>fc(t),[t]),h=r&&!c?[]:d.map(Hn),g=ue(!0),v=ue(d),_=Mn(()=>new Map),[S,b]=Ae(d),[T,k]=Ae(d);il(()=>{g.current=!1,v.current=d;for(let D=0;D<T.length;D++){const C=Hn(T[D]);h.includes(C)?_.delete(C):_.get(C)!==!0&&_.set(C,!1)}},[T,h.length,h.join("-")]);const A=[];if(d!==S){let D=[...d];for(let C=0;C<T.length;C++){const E=T[C],p=Hn(E);h.includes(p)||(D.splice(C,0,E),A.push(E))}return o==="wait"&&A.length&&(D=A),k(fc(D)),b(d),null}const{forceRender:R}=De(Zs);return L(ht,{children:T.map(D=>{const C=Hn(D),E=r&&!c?!1:d===T||h.includes(C),p=()=>{if(_.has(C))_.set(C,!0);else return;let m=!0;_.forEach(f=>{f||(m=!1)}),m&&(R==null||R(),k(v.current),r&&(u==null||u()),n&&n())};return L(Bg,{isPresent:E,initial:!g.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:p,anchorX:a,children:D},C)})})},pc=kt({strict:!1}),gc={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"]},vi={};for(const t in gc)vi[t]={isEnabled:e=>gc[t].some(i=>!!e[i])};function $g(t){for(const e in t)vi[e]={...vi[e],...t[e]}}const jg=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 Wn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||jg.has(t)}let mc=t=>!Wn(t);function vc(t){typeof t=="function"&&(mc=e=>e.startsWith("on")?!Wn(e):t(e))}try{vc(require("@emotion/is-prop-valid").default)}catch{}function Hg(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(mc(s)||i===!0&&Wn(s)||!e&&!Wn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Wg({children:t,isValidProp:e,...i}){e&&vc(e),i={...De(Zi),...i},i.isStatic=Mn(()=>i.isStatic);const n=Qe(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return L(Zi.Provider,{value:n,children:t})}function Gg(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 Gn=kt({});function qn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Qi(t){return typeof t=="string"||Array.isArray(t)}const $o=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],jo=["initial",...$o];function zn(t){return qn(t.animate)||jo.some(e=>Qi(t[e]))}function _c(t){return!!(zn(t)||t.variants)}function qg(t,e){if(zn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||Qi(i)?i:void 0,animate:Qi(n)?n:void 0}}return t.inherit!==!1?e:{}}function zg(t){const{initial:e,animate:i}=qg(t,De(Gn));return Qe(()=>({initial:e,animate:i}),[yc(e),yc(i)])}function yc(t){return Array.isArray(t)?t.join(" "):t}const Kg=Symbol.for("motionComponentSymbol");function _i(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Yg(t,e,i){return Ge(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):_i(i)&&(i.current=n))},[e])}const Ho=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),bc="data-"+Ho("framerAppearId"),wc=kt({});function Xg(t,e,i,n,s){var _,S;const{visualElement:o}=De(Gn),r=De(pc),a=De(Pn),l=De(Zi).reducedMotion,c=ue(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=De(wc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Jg(c.current,i,s,d);const h=ue(!1);Fa(()=>{u&&h.current&&u.update(i,a)});const g=i[bc],v=ue(!!g&&!((_=window.MotionHandoffIsComplete)!=null&&_.call(window,g))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,g)));return il(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Bo.render(u.render),v.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!v.current&&u.animationState&&u.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,g)}),v.current=!1))}),u}function Jg(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:Sc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&_i(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function Sc(t){if(t)return t.options.allowProjection!==!1?t.projection:Sc(t.parent)}function Zg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&$g(t);function o(a,l){let c;const u={...De(Zi),...a,layoutId:Qg(a)},{isStatic:d}=u,h=zg(a),g=n(a,d);if(!d&&Qs){em();const v=tm(u);c=v.MeasureLayout,h.visualElement=Xg(s,g,u,e,v.ProjectionNode)}return L(Gn.Provider,{value:h,children:[c&&h.visualElement?L(c,{visualElement:h.visualElement,...u}):null,i(s,a,Yg(g,h.visualElement,l),g,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Ef(o);return r[Kg]=s,r}function Qg({layoutId:t}){const e=De(Zs).id;return e&&t!==void 0?e+"-"+t:t}function em(t,e){De(pc).strict}function tm(t){const{drag:e,layout:i}=vi;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 en={};function im(t){for(const e in t)en[e]=t[e],lo(e)&&(en[e].isCSSVariable=!0)}function Cc(t,{layout:e,layoutId:i}){return gi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!en[t]||t==="opacity")}const nm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},sm=pi.length;function om(t,e,i){let n="",s=!0;for(let o=0;o<sm;o++){const r=pi[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=nc(a,Fo[r]);if(!l){s=!1;const u=nm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function Wo(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(gi.has(l)){r=!0;continue}else if(lo(l)){s[l]=c;continue}else{const u=nc(c,Fo[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=om(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 Go=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Tc(t,e,i){for(const n in e)!Ve(e[n])&&!Cc(n,i)&&(t[n]=e[n])}function rm({transformTemplate:t},e){return Qe(()=>{const i=Go();return Wo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function am(t,e){const i=t.style||{},n={};return Tc(n,i,t),Object.assign(n,rm(t,e)),n}function lm(t,e){const i={},n=am(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 cm={offset:"stroke-dashoffset",array:"stroke-dasharray"},dm={offset:"strokeDashoffset",array:"strokeDasharray"};function um(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?cm:dm;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function Ec(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(Wo(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&&um(d,s,o,r,!1)}const kc=()=>({...Go(),attrs:{}}),Ic=t=>typeof t=="string"&&t.toLowerCase()==="svg";function hm(t,e,i,n){const s=Qe(()=>{const o=kc();return Ec(o,e,Ic(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Tc(o,t.style,t),s.style={...o,...s.style}}return s}const fm=["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 qo(t){return typeof t!="string"||t.includes("-")?!1:!!(fm.indexOf(t)>-1||/[A-Z]/u.test(t))}function pm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(qo(i)?hm:lm)(n,o,r,i),c=Hg(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Qe(()=>Ve(d)?d.get():d,[d]);return Ze(i,{...u,children:h})}}function Rc(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function zo(t,e,i,n){if(typeof e=="function"){const[s,o]=Rc(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]=Rc(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Kn(t){return Ve(t)?t.get():t}function gm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:mm(i,n,s,t),renderState:e()}}const Ac=t=>(e,i)=>{const n=De(Gn),s=De(Pn),o=()=>gm(t,e,n,s);return i?o():Mn(o)};function mm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Kn(o[h]);let{initial:r,animate:a}=t;const l=zn(t),c=_c(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"&&!qn(d)){const h=Array.isArray(d)?d:[d];for(let g=0;g<h.length;g++){const v=zo(t,h[g]);if(v){const{transitionEnd:_,transition:S,...b}=v;for(const T in b){let k=b[T];if(Array.isArray(k)){const A=u?k.length-1:0;k=k[A]}k!==null&&(s[T]=k)}for(const T in _)s[T]=_[T]}}}return s}function Ko(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||Cc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const vm={useVisualState:Ac({scrapeMotionValuesFromProps:Ko,createRenderState:Go})};function xc(t,e,i){const n=Ko(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=pi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const _m={useVisualState:Ac({scrapeMotionValuesFromProps:xc,createRenderState:kc})};function ym(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...qo(n)?_m:vm,preloadedFeatures:t,useRender:pm(s),createVisualElement:e,Component:n};return Zg(r)}}function tn(t,e,i){const n=t.getProps();return zo(n,e,i!==void 0?i:n.custom,t)}const Yo=t=>Array.isArray(t);function bm(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,mi(i))}function wm(t){return Yo(t)?t[t.length-1]||0:t}function Sm(t,e){const i=tn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=wm(o[r]);bm(t,r,a)}}function Cm(t){return!!(Ve(t)&&t.add)}function Xo(t,e){const i=t.getValue("willChange");if(Cm(i))return i.add(e);if(!i&&Rt.WillChange){const n=new Rt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function Lc(t){return t.props[bc]}const Tm=t=>t!==null;function Em(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Tm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const km={type:"spring",stiffness:500,damping:25,restSpeed:10},Im=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Rm={type:"keyframes",duration:.8},Am={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},xm=(t,{keyframes:e})=>e.length>2?Rm:gi.has(t)?t.startsWith("scale")?Im(e[1]):km:Am;function Lm({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 Jo=(t,e,i,n={},s,o)=>r=>{const a=Po(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-pt(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};Lm(a)||Object.assign(u,xm(t,u)),u.duration&&(u.duration=pt(u.duration)),u.repeatDelay&&(u.repeatDelay=pt(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)),(Rt.instantAnimations||Rt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=Em(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Eo(u):new hg(u)};function Dm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Dc(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&&Dm(c,u))continue;const g={delay:i,...Po(o||{},u)},v=d.get();if(v!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===v&&!g.velocity)continue;let _=!1;if(window.MotionHandoffAnimation){const b=Lc(t);if(b){const T=window.MotionHandoffAnimation(b,u,we);T!==null&&(g.startTime=T,_=!0)}}Xo(t,u),d.start(Jo(u,d,h,t.shouldReduceMotion&&Xl.has(u)?{type:!1}:g,t,_));const S=d.animation;S&&l.push(S)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&Sm(t,r)})}),l}function Zo(t,e,i={}){var l;const n=tn(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(Dc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Om(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 Om(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(Mm).forEach((h,g)=>{h.notify("AnimationStart",e),a.push(Zo(h,e,{...r,delay:i+(u?0:n)+d(g)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Mm(t,e){return t.sortNodePosition(e)}function Pm(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>Zo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=Zo(t,e,i);else{const s=typeof e=="function"?tn(t,e,i.custom):e;n=Promise.all(Dc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Oc(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 Nm=jo.length;function Mc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?Mc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Nm;i++){const n=jo[i],s=t.props[n];(Qi(s)||s===!1)&&(e[n]=s)}return e}const Fm=[...$o].reverse(),Bm=$o.length;function Vm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Pm(t,i,n)))}function Um(t){let e=Vm(t),i=Pc(),n=!0;const s=l=>(c,u)=>{var h;const d=tn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:g,transitionEnd:v,..._}=d;c={...c,..._,...v}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=Mc(t.parent)||{},d=[],h=new Set;let g={},v=1/0;for(let S=0;S<Bm;S++){const b=Fm[S],T=i[b],k=c[b]!==void 0?c[b]:u[b],A=Qi(k),R=b===l?T.isActive:null;R===!1&&(v=S);let D=k===u[b]&&k!==c[b]&&A;if(D&&n&&t.manuallyAnimateOnMount&&(D=!1),T.protectedKeys={...g},!T.isActive&&R===null||!k&&!T.prevProp||qn(k)||typeof k=="boolean")continue;const C=$m(T.prevProp,k);let E=C||b===l&&T.isActive&&!D&&A||S>v&&A,p=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(b),{});R===!1&&(f={});const{prevResolvedValues:w={}}=T,I={...w,...f},x=M=>{E=!0,h.has(M)&&(p=!0,h.delete(M)),T.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in I){const F=f[M],G=w[M];if(g.hasOwnProperty(M))continue;let j=!1;Yo(F)&&Yo(G)?j=!Oc(F,G):j=F!==G,j?F!=null?x(M):h.add(M):F!==void 0&&h.has(M)?x(M):T.protectedKeys[M]=!0}T.prevProp=k,T.prevResolvedValues=f,T.isActive&&(g={...g,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(D&&C)||p)&&d.push(...m.map(M=>({animation:M,options:{type:b}})))}if(h.size){const S={};if(typeof c.initial!="boolean"){const b=tn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);b&&b.transition&&(S.transition=b.transition)}h.forEach(b=>{const T=t.getBaseTarget(b),k=t.getValue(b);k&&(k.liveStyle=!0),S[b]=T??null}),d.push({animation:S})}let _=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(_=!1),n=!1,_?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 g;return(g=h.animationState)==null?void 0:g.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=Pc(),n=!0}}}function $m(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Oc(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Pc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Bt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class jm extends Bt{constructor(e){super(e),e.animationState||(e.animationState=Um(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();qn(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 Hm=0;class Wm extends Bt{constructor(){super(...arguments),this.id=Hm++}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 Gm={animation:{Feature:jm},exit:{Feature:Wm}};function nn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function sn(t){return{point:{x:t.pageX,y:t.pageY}}}const qm=t=>e=>Vo(e)&&t(e,sn(e));function on(t,e,i,n){return nn(t,e,qm(i),n)}function Nc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function zm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Km(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 Fc=1e-4,Ym=1-Fc,Xm=1+Fc,Bc=.01,Jm=0-Bc,Zm=0+Bc;function je(t){return t.max-t.min}function Qm(t,e,i){return Math.abs(t-e)<=i}function Vc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=je(i)/je(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Ym&&t.scale<=Xm||isNaN(t.scale))&&(t.scale=1),(t.translate>=Jm&&t.translate<=Zm||isNaN(t.translate))&&(t.translate=0)}function rn(t,e,i,n){Vc(t.x,e.x,i.x,n?n.originX:void 0),Vc(t.y,e.y,i.y,n?n.originY:void 0)}function Uc(t,e,i){t.min=i.min+e.min,t.max=t.min+je(e)}function ev(t,e,i){Uc(t.x,e.x,i.x),Uc(t.y,e.y,i.y)}function $c(t,e,i){t.min=e.min-i.min,t.max=t.min+je(e)}function an(t,e,i){$c(t.x,e.x,i.x),$c(t.y,e.y,i.y)}const jc=()=>({translate:0,scale:1,origin:0,originPoint:0}),yi=()=>({x:jc(),y:jc()}),Hc=()=>({min:0,max:0}),ke=()=>({x:Hc(),y:Hc()});function tt(t){return[t("x"),t("y")]}function Qo(t){return t===void 0||t===1}function er({scale:t,scaleX:e,scaleY:i}){return!Qo(t)||!Qo(e)||!Qo(i)}function Zt(t){return er(t)||Wc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Wc(t){return Gc(t.x)||Gc(t.y)}function Gc(t){return t&&t!=="0%"}function Yn(t,e,i){const n=t-i,s=e*n;return i+s}function qc(t,e,i,n,s){return s!==void 0&&(t=Yn(t,s,n)),Yn(t,i,n)+e}function tr(t,e=0,i=1,n,s){t.min=qc(t.min,e,i,n,s),t.max=qc(t.max,e,i,n,s)}function zc(t,{x:e,y:i}){tr(t.x,e.translate,e.scale,e.originPoint),tr(t.y,i.translate,i.scale,i.originPoint)}const Kc=.999999999999,Yc=1.0000000000001;function tv(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&&wi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,zc(t,r)),n&&Zt(o.latestValues)&&wi(t,o.latestValues))}e.x<Yc&&e.x>Kc&&(e.x=1),e.y<Yc&&e.y>Kc&&(e.y=1)}function bi(t,e){t.min=t.min+e,t.max=t.max+e}function Xc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);tr(t,e,i,o,n)}function wi(t,e){Xc(t.x,e.x,e.scaleX,e.scale,e.originX),Xc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Jc(t,e){return Nc(Km(t.getBoundingClientRect(),e))}function iv(t,e,i){const n=Jc(t,i),{scroll:s}=e;return s&&(bi(n.x,s.offset.x),bi(n.y,s.offset.y)),n}const Zc=({current:t})=>t?t.ownerDocument.defaultView:null,Qc=(t,e)=>Math.abs(t-e);function nv(t,e){const i=Qc(t.x,e.x),n=Qc(t.y,e.y);return Math.sqrt(i**2+n**2)}class ed{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=nr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,v=nv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!v)return;const{point:_}=h,{timestamp:S}=Pe;this.history.push({..._,timestamp:S});const{onStart:b,onMove:T}=this.handlers;g||(b&&b(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=ir(g,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:v,onSessionEnd:_,resumeAnimation:S}=this.handlers;if(this.dragSnapToOrigin&&S&&S(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=nr(h.type==="pointercancel"?this.lastMoveEventInfo:ir(g,this.transformPagePoint),this.history);this.startEvent&&v&&v(h,b),_&&_(h,b)},!Vo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=sn(e),l=ir(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,nr(l,this.history)),this.removeListeners=Hi(on(this.contextWindow,"pointermove",this.handlePointerMove),on(this.contextWindow,"pointerup",this.handlePointerUp),on(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function ir(t,e){return e?{point:e(t.point)}:t}function td(t,e){return{x:t.x-e.x,y:t.y-e.y}}function nr({point:t},e){return{point:t,delta:td(t,id(e)),offset:td(t,sv(e)),velocity:ov(e,.1)}}function sv(t){return t[0]}function id(t){return t[t.length-1]}function ov(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=id(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>pt(e)));)i--;if(!n)return{x:0,y:0};const o=gt(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 rv(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Ce(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Ce(i,t,n.max):Math.min(t,i)),t}function nd(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 av(t,{top:e,left:i,bottom:n,right:s}){return{x:nd(t.x,i,s),y:nd(t.y,e,n)}}function sd(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 lv(t,e){return{x:sd(t.x,e.x),y:sd(t.y,e.y)}}function cv(t,e){let i=.5;const n=je(t),s=je(e);return s>n?i=Wi(e.min,e.max-n,t.min):n>s&&(i=Wi(t.min,t.max-s,e.min)),It(0,1,i)}function dv(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 sr=.35;function uv(t=sr){return t===!1?t=0:t===!0&&(t=sr),{x:od(t,"left","right"),y:od(t,"top","bottom")}}function od(t,e,i){return{min:rd(t,e),max:rd(t,i)}}function rd(t,e){return typeof t=="number"?t:t[e]||0}const hv=new WeakMap;class fv{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=ke(),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(sn(d).point)},r=(d,h)=>{const{drag:g,dragPropagation:v,onDragStart:_}=this.getProps();if(g&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Ig(g),!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),tt(b=>{let T=this.getAxisMotionValue(b).get()||0;if(mt.test(T)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[b];A&&(T=je(A)*(parseFloat(T)/100))}}this.originPoint[b]=T}),_&&we.postRender(()=>_(d,h)),Xo(this.visualElement,"transform");const{animationState:S}=this.visualElement;S&&S.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:v,onDirectionLock:_,onDrag:S}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:b}=h;if(v&&this.currentDirection===null){this.currentDirection=pv(b),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",h.point,b),this.updateAxis("y",h.point,b),this.visualElement.render(),S&&S(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>tt(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 ed(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Zc(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&&we.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||!Xn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=rv(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&&_i(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=av(n.layoutBox,e):this.constraints=!1,this.elastic=uv(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&tt(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=dv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!_i(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=iv(n,s.root,this.visualElement.getTransformPagePoint());let r=lv(s.layout.layoutBox,o);if(i){const a=i(zm(r));this.hasMutatedConstraints=!!a,a&&(r=Nc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=tt(u=>{if(!Xn(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,g=s?40:1e7,v={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,v)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return Xo(this.visualElement,e),n.start(Jo(e,n,0,i,this.visualElement,!1))}stopAnimation(){tt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){tt(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){tt(i=>{const{drag:n}=this.getProps();if(!Xn(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]-Ce(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!_i(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};tt(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=cv({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(),tt(r=>{if(!Xn(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Ce(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;hv.set(this.visualElement,this);const e=this.visualElement.current,i=on(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();_i(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()),we.read(n);const r=nn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(tt(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=sr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Xn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function pv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class gv extends Bt{constructor(e){super(e),this.removeGroupControls=et,this.removeListeners=et,this.controls=new fv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||et}unmount(){this.removeGroupControls(),this.removeListeners()}}const ad=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class mv extends Bt{constructor(){super(...arguments),this.removePointerDownListener=et}onPointerDown(e){this.session=new ed(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Zc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:ad(e),onStart:ad(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=on(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 Jn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ld(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const ln={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=ld(t,e.target.x),n=ld(t,e.target.y);return`${i}% ${n}%`}},vv={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Ft.parse(t);if(s.length>5)return n;const o=Ft.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=Ce(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 cd=!1;class _v extends at{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;im(yv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),cd&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Jn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,cd=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||we.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Bo.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 dd(t){const[e,i]=hc(),n=De(Zs);return L(_v,{...t,layoutGroup:n,switchLayoutGroup:De(wc),isPresent:e,safeToRemove:i})}const yv={borderRadius:{...ln,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ln,borderTopRightRadius:ln,borderBottomLeftRadius:ln,borderBottomRightRadius:ln,boxShadow:vv};function bv(t,e,i){const n=Ve(t)?t:mi(t);return n.start(Jo("",n,e,i)),n.animation}const wv=(t,e)=>t.depth-e.depth;class Sv{constructor(){this.children=[],this.isDirty=!1}add(e){eo(this.children,e),this.isDirty=!0}remove(e){to(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(wv),this.isDirty=!1,this.children.forEach(e)}}function Cv(t,e){const i=qe.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const ud=["TopLeft","TopRight","BottomLeft","BottomRight"],Tv=ud.length,hd=t=>typeof t=="string"?parseFloat(t):t,fd=t=>typeof t=="number"||K.test(t);function Ev(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,kv(n)),t.opacityExit=Ce(e.opacity??1,0,Iv(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<Tv;r++){const a=`border${ud[r]}Radius`;let l=pd(e,a),c=pd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||fd(l)===fd(c)?(t[a]=Math.max(Ce(hd(l),hd(c),n),0),(mt.test(c)||mt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Ce(e.rotate||0,i.rotate||0,n))}function pd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const kv=gd(0,.5,fl),Iv=gd(.5,.95,et);function gd(t,e,i){return n=>n<t?0:n>e?1:i(Wi(t,e,n))}function md(t,e){t.min=e.min,t.max=e.max}function it(t,e){md(t.x,e.x),md(t.y,e.y)}function vd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function _d(t,e,i,n,s){return t-=e,t=Yn(t,1/i,n),s!==void 0&&(t=Yn(t,1/s,n)),t}function Rv(t,e=0,i=1,n=.5,s,o=t,r=t){if(mt.test(e)&&(e=parseFloat(e),e=Ce(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Ce(o.min,o.max,n);t===o&&(a-=e),t.min=_d(t.min,e,i,a,s),t.max=_d(t.max,e,i,a,s)}function yd(t,e,[i,n,s],o,r){Rv(t,e[i],e[n],e[s],e.scale,o,r)}const Av=["x","scaleX","originX"],xv=["y","scaleY","originY"];function bd(t,e,i,n){yd(t.x,e,Av,i?i.x:void 0,n?n.x:void 0),yd(t.y,e,xv,i?i.y:void 0,n?n.y:void 0)}function wd(t){return t.translate===0&&t.scale===1}function Sd(t){return wd(t.x)&&wd(t.y)}function Cd(t,e){return t.min===e.min&&t.max===e.max}function Lv(t,e){return Cd(t.x,e.x)&&Cd(t.y,e.y)}function Td(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Ed(t,e){return Td(t.x,e.x)&&Td(t.y,e.y)}function kd(t){return je(t.x)/je(t.y)}function Id(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Dv{constructor(){this.members=[]}add(e){eo(this.members,e),e.scheduleRender()}remove(e){if(to(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 Ov(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:g,skewY:v}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),g&&(n+=`skewX(${g}deg) `),v&&(n+=`skewY(${v}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 or=["","X","Y","Z"],Mv=1e3;let Pv=0;function rr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Rd(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=Lc(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",we,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&Rd(n)}function Ad({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Pv++,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(Bv),this.nodes.forEach(jv),this.nodes.forEach(Hv),this.nodes.forEach(Vv)},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 Sv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new so),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=uc(r)&&!Og(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;we.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=Cv(h,250),Jn.hasAnimatedSinceResize&&(Jn.hasAnimatedSinceResize=!1,this.nodes.forEach(Dd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||Kv,{onLayoutAnimationStart:_,onLayoutAnimationComplete:S}=c.getProps(),b=!this.targetLayout||!Ed(this.targetLayout,g),T=!d&&h;if(this.options.layoutRoot||this.resumeFrom||T||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Po(v,"layout"),onPlay:_,onComplete:S};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,T)}else d||Dd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}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(),Pt(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(Wv),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&&Rd(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(xd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ld);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach($v),this.nodes.forEach(Nv),this.nodes.forEach(Fv)):this.nodes.forEach(Ld),this.clearAllSnapshots();const a=qe.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,ao.update.process(Pe),ao.preRender.process(Pe),ao.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Bo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Uv),this.sharedNodes.forEach(Gv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,we.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){we.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!je(this.snapshot.measuredBox.x)&&!je(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=ke(),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&&!Sd(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Zt(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)),Yv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Xv))){const{scroll:u}=this.root;u&&(bi(a.x,u.offset.x),bi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(it(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&&it(a,r),bi(a.x,d.offset.x),bi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();it(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&&wi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&wi(l,u.latestValues)}return Zt(this.latestValues)&&wi(l,this.latestValues),l}removeTransform(r){const a=ke();it(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;er(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();it(u,d),bd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&bd(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!==Pe.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=Pe.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),an(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),ev(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):it(this.target,this.layout.layoutBox),zc(this.target,this.targetDelta)):it(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),an(this.relativeTargetOrigin,this.target,g.target),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||er(this.parent.latestValues)||Wc(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 v;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(v=this.parent)!=null&&v.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Pe.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;it(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;tv(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=ke());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(vd(this.prevProjectionDelta.x,this.projectionDelta.x),vd(this.prevProjectionDelta.y,this.projectionDelta.y)),rn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Id(this.projectionDelta.x,this.prevProjectionDelta.x)||!Id(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}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=yi(),this.projectionDelta=yi(),this.projectionDeltaWithTransform=yi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),g=l?l.source:void 0,v=this.layout?this.layout.source:void 0,_=g!==v,S=this.getStack(),b=!S||S.members.length<=1,T=!!(_&&!b&&this.options.crossfade===!0&&!this.path.some(zv));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const R=A/1e3;Od(d.x,r.x,R),Od(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(an(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),qv(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&Lv(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),it(k,this.relativeTarget)),_&&(this.animationValues=u,Ev(u,c,this.latestValues,R,T,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},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&&(Pt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=we.update(()=>{Jn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=mi(0)),this.currentAnimation=bv(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(Mv),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&&Bd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=je(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=je(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}it(a,l),wi(a,u),rn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Dv),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&&rr("z",r,c,this.animationValues);for(let u=0;u<or.length;u++)rr(`rotate${or[u]}`,r,c,this.animationValues),rr(`skew${or[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=Kn(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=Kn(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Ov(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:g}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${g.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 v in en){if(u[v]===void 0)continue;const{correct:_,applyTo:S,isCSSVariable:b}=en[v],T=d==="none"?u[v]:_(u[v],c);if(S){const k=S.length;for(let A=0;A<k;A++)r[S[A]]=T}else b?this.options.visualElement.renderState.vars[v]=T:r[v]=T}this.options.layoutId&&(r.pointerEvents=c===this?Kn(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(xd),this.root.sharedNodes.clear()}}}function Nv(t){t.updateLayout()}function Fv(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"?tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(h);h.min=n[d].min,h.max=h.min+g}):Bd(o,e.layoutBox,n)&&tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(n[d]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=yi();rn(a,n,e.layoutBox);const l=yi();r?rn(l,t.applyTransform(s,!0),e.measuredBox):rn(l,n,e.layoutBox);const c=!Sd(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:g}=d;if(h&&g){const v=ke();an(v,e.layoutBox,h.layoutBox);const _=ke();an(_,n,g.layoutBox),Ed(v,_)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=_,t.relativeTargetOrigin=v,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 Bv(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 Vv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Uv(t){t.clearSnapshot()}function xd(t){t.clearMeasurements()}function Ld(t){t.isLayoutDirty=!1}function $v(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Dd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function jv(t){t.resolveTargetDelta()}function Hv(t){t.calcProjection()}function Wv(t){t.resetSkewAndRotation()}function Gv(t){t.removeLeadSnapshot()}function Od(t,e,i){t.translate=Ce(e.translate,0,i),t.scale=Ce(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function Md(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function qv(t,e,i,n){Md(t.x,e.x,i.x,n),Md(t.y,e.y,i.y,n)}function zv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Kv={duration:.45,ease:[.4,0,.1,1]},Pd=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Nd=Pd("applewebkit/")&&!Pd("chrome/")?Math.round:et;function Fd(t){t.min=Nd(t.min),t.max=Nd(t.max)}function Yv(t){Fd(t.x),Fd(t.y)}function Bd(t,e,i){return t==="position"||t==="preserve-aspect"&&!Qm(kd(e),kd(i),.2)}function Xv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Jv=Ad({attachResizeListener:(t,e)=>nn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ar={current:void 0},Vd=Ad({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ar.current){const t=new Jv({});t.mount(window),t.setOptions({layoutScroll:!0}),ar.current=t}return ar.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Zv={pan:{Feature:mv},drag:{Feature:gv,ProjectionNode:Vd,MeasureLayout:dd}};function Ud(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&&we.postRender(()=>o(e,sn(e)))}class Qv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=Rg(e,(i,n)=>(Ud(this.node,n,"Start"),s=>Ud(this.node,s,"End"))))}unmount(){}}class e_ extends Bt{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=Hi(nn(this.node.current,"focus",()=>this.onFocus()),nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function $d(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&&we.postRender(()=>o(e,sn(e)))}class t_ extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=Dg(e,(i,n)=>($d(this.node,n,"Start"),(s,{success:o})=>$d(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const lr=new WeakMap,cr=new WeakMap,i_=t=>{const e=lr.get(t.target);e&&e(t)},n_=t=>{t.forEach(i_)};function s_({root:t,...e}){const i=t||document;cr.has(i)||cr.set(i,{});const n=cr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(n_,{root:t,...e})),n[s]}function o_(t,e,i){const n=s_(e);return lr.set(t,i),n.observe(t),()=>{lr.delete(t),n.unobserve(t)}}const r_={some:0,all:1};class a_ extends Bt{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:r_[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 o_(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(l_(e,i))&&this.startObserver()}unmount(){}}function l_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const c_={inView:{Feature:a_},tap:{Feature:t_},focus:{Feature:e_},hover:{Feature:Qv}},d_={layout:{ProjectionNode:Vd,MeasureLayout:dd}},dr={current:null},jd={current:!1};function u_(){if(jd.current=!0,!!Qs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>dr.current=t.matches;t.addEventListener("change",e),e()}else dr.current=!1}const h_=new WeakMap;function f_(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ve(s))t.addValue(n,s);else if(Ve(o))t.addValue(n,mi(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,mi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const Hd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class p_{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=Oo,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=qe.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,we.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=zn(i),this.isVariantNode=_c(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 g=d[h];l[h]!==void 0&&Ve(g)&&g.set(l[h],!1)}}mount(e){this.current=e,h_.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)),jd.current||u_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:dr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Pt(this.notifyUpdate),Pt(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=gi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&we.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 vi){const i=vi[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):ke()}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<Hd.length;n++){const s=Hd[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=f_(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=mi(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"&&(nl(n)||ol(n))?n=parseFloat(n):!Pg(n)&&Ft.test(i)&&(n=ic(e,i)),this.setBaseTarget(e,Ve(n)?n.get():n)),Ve(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=zo(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&&!Ve(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 so),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Wd extends p_{constructor(){super(...arguments),this.KeyframeResolver=Cg}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;Ve(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function Gd(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 g_(t){return window.getComputedStyle(t)}class m_ extends Wd{constructor(){super(...arguments),this.type="html",this.renderInstance=Gd}readValueFromInstance(e,i){var n;if(gi.has(i))return(n=this.projection)!=null&&n.isProjecting?Ro(i):Hp(e,i);{const s=g_(e),o=(lo(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Jc(e,i)}build(e,i,n){Wo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return Ko(e,i,n)}}const qd=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 v_(t,e,i,n){Gd(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(qd.has(s)?s:Ho(s),e.attrs[s])}class __ extends Wd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(gi.has(i)){const n=tc(i);return n&&n.default||0}return i=qd.has(i)?i:Ho(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return xc(e,i,n)}build(e,i,n){Ec(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){v_(e,i,n,s)}mount(e){this.isSVGTag=Ic(e.tagName),super.mount(e)}}const y_=(t,e)=>qo(t)?new __(e):new m_(e,{allowProjection:t!==ht}),b_=ym({...Gm,...c_,...Zv,...d_},y_),Si=Gg(b_),w_=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region","skip-last-voice-sdk-id"],cn="widget-layout-id";function zd(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=zd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function At(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=zd(t))&&(n&&(n+=" "),n+=e);return n}const S_=Ln("listening"),ur=()=>tl(S_);function C_(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 Zn={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},Kd=Ln(Zn),T_=()=>{const t=On(Kd);return Ge(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Zn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Zn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Zn.speak_to_interrupt_text),i}),[t])},Qt=()=>Js(Kd),Yd=({size:t="large",className:e})=>{const i=Qt(),[n]=ur();return L("h1",{className:At({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Xd=({stream:t,chatMode:e})=>{const i=ue(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:L("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(m),v.contains(m)&&v.removeChild(m)}},[e]),L(xm,{isPresent:e,childRef:o,sizeRef:r,children:Dp(t,{ref:o})})}const Lm=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Wn(Mm),u=Zs();let d=!0,h=it(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:g=>{c.set(g,!0);for(const m of c.values())if(!m)return;n&&n()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[i,c,n]);return o&&d&&(h={...h}),it(()=>{c.forEach((g,m)=>c.set(m,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=L(Dm,{isPresent:i,anchorX:a,root:l,children:t})),L(Gn.Provider,{value:h,children:t})};function Mm(){return new Map}function Bc(t=!0){const e=De(Gn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Zs();xe(()=>{if(t)return s(o)},[t]);const r=qe(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Qn=t=>t.key||"";function Uc(t){const e=[];return bp.forEach(t,i=>{Cl(i)&&e.push(i)}),e}const Om=({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]=Bc(r),d=it(()=>Uc(t),[t]),h=r&&!c?[]:d.map(Qn),g=he(!0),m=he(d),v=Wn(()=>new Map),[b,y]=Ae(d),[C,k]=Ae(d);Rl(()=>{g.current=!1,m.current=d;for(let D=0;D<C.length;D++){const T=Qn(C[D]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let D=[...d];for(let T=0;T<C.length;T++){const E=C[T],p=Qn(E);h.includes(p)||(D.splice(T,0,E),A.push(E))}return o==="wait"&&A.length&&(D=A),k(Uc(D)),y(d),null}const{forceRender:R}=De(uo);return L(mt,{children:C.map(D=>{const T=Qn(D),E=r&&!c?!1:d===C||h.includes(T),p=()=>{if(v.has(T))v.set(T,!0);else return;let _=!0;v.forEach(f=>{f||(_=!1)}),_&&(R==null||R(),k(m.current),r&&(u==null||u()),n&&n())};return L(Lm,{isPresent:E,initial:!g.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:p,anchorX:a,children:D},T)})})},Vc=At({strict:!1}),$c={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"]},Si={};for(const t in $c)Si[t]={isEnabled:e=>$c[t].some(i=>!!e[i])};function Pm(t){for(const e in t)Si[e]={...Si[e],...t[e]}}const Nm=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 es(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Nm.has(t)}let jc=t=>!es(t);function Hc(t){typeof t=="function"&&(jc=e=>e.startsWith("on")?!es(e):t(e))}try{Hc(require("@emotion/is-prop-valid").default)}catch{}function Fm(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(jc(s)||i===!0&&es(s)||!e&&!es(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Bm({children:t,isValidProp:e,...i}){e&&Hc(e),i={...De(an),...i},i.isStatic=Wn(()=>i.isStatic);const n=it(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return L(an.Provider,{value:n,children:t})}function Um(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 ts=At({});function is(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ln(t){return typeof t=="string"||Array.isArray(t)}const Qo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],er=["initial",...Qo];function ns(t){return is(t.animate)||er.some(e=>ln(t[e]))}function Wc(t){return!!(ns(t)||t.variants)}function Vm(t,e){if(ns(t)){const{initial:i,animate:n}=t;return{initial:i===!1||ln(i)?i:void 0,animate:ln(n)?n:void 0}}return t.inherit!==!1?e:{}}function $m(t){const{initial:e,animate:i}=Vm(t,De(ts));return it(()=>({initial:e,animate:i}),[Gc(e),Gc(i)])}function Gc(t){return Array.isArray(t)?t.join(" "):t}const jm=Symbol.for("motionComponentSymbol");function Ci(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Hm(t,e,i){return qe(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):Ci(i)&&(i.current=n))},[e])}const tr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),qc="data-"+tr("framerAppearId"),zc=At({});function Wm(t,e,i,n,s){var v,b;const{visualElement:o}=De(ts),r=De(Vc),a=De(Gn),l=De(an).reducedMotion,c=he(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=De(zc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Gm(c.current,i,s,d);const h=he(!1);cl(()=>{u&&h.current&&u.update(i,a)});const g=i[qc],m=he(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,g)));return Rl(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Xo.render(u.render),m.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!m.current&&u.animationState&&u.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),m.current=!1))}),u}function Gm(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:Kc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Ci(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function Kc(t){if(t)return t.options.allowProjection!==!1?t.projection:Kc(t.parent)}function qm({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Pm(t);function o(a,l){let c;const u={...De(an),...a,layoutId:zm(a)},{isStatic:d}=u,h=$m(a),g=n(a,d);if(!d&&ho){Km();const m=Ym(u);c=m.MeasureLayout,h.visualElement=Wm(s,g,u,e,m.ProjectionNode)}return L(ts.Provider,{value:h,children:[c&&h.visualElement?L(c,{visualElement:h.visualElement,...u}):null,i(s,a,Hm(g,h.visualElement,l),g,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=yp(o);return r[jm]=s,r}function zm({layoutId:t}){const e=De(uo).id;return e&&t!==void 0?e+"-"+t:t}function Km(t,e){De(Vc).strict}function Ym(t){const{drag:e,layout:i}=Si;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 cn={};function Xm(t){for(const e in t)cn[e]=t[e],wo(e)&&(cn[e].isCSSVariable=!0)}function Yc(t,{layout:e,layoutId:i}){return bi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!cn[t]||t==="opacity")}const Jm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Zm=yi.length;function Qm(t,e,i){let n="",s=!0;for(let o=0;o<Zm;o++){const r=yi[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=Ac(a,Yo[r]);if(!l){s=!1;const u=Jm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function ir(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(bi.has(l)){r=!0;continue}else if(wo(l)){s[l]=c;continue}else{const u=Ac(c,Yo[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=Qm(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 nr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Xc(t,e,i){for(const n in e)!Ue(e[n])&&!Yc(n,i)&&(t[n]=e[n])}function ev({transformTemplate:t},e){return it(()=>{const i=nr();return ir(i,e,t),Object.assign({},i.vars,i.style)},[e])}function tv(t,e){const i=t.style||{},n={};return Xc(n,i,t),Object.assign(n,ev(t,e)),n}function iv(t,e){const i={},n=tv(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 nv={offset:"stroke-dashoffset",array:"stroke-dasharray"},sv={offset:"strokeDashoffset",array:"strokeDasharray"};function ov(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?nv:sv;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function Jc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(ir(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&&ov(d,s,o,r,!1)}const Zc=()=>({...nr(),attrs:{}}),Qc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function rv(t,e,i,n){const s=it(()=>{const o=Zc();return Jc(o,e,Qc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Xc(o,t.style,t),s.style={...o,...s.style}}return s}const av=["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 sr(t){return typeof t!="string"||t.includes("-")?!1:!!(av.indexOf(t)>-1||/[A-Z]/u.test(t))}function lv(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(sr(i)?rv:iv)(n,o,r,i),c=Fm(n,typeof i=="string",t),u=i!==mt?{...c,...l,ref:s}:{},{children:d}=n,h=it(()=>Ue(d)?d.get():d,[d]);return tt(i,{...u,children:h})}}function ed(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function or(t,e,i,n){if(typeof e=="function"){const[s,o]=ed(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]=ed(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function ss(t){return Ue(t)?t.get():t}function cv({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:dv(i,n,s,t),renderState:e()}}const td=t=>(e,i)=>{const n=De(ts),s=De(Gn),o=()=>cv(t,e,n,s);return i?o():Wn(o)};function dv(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=ss(o[h]);let{initial:r,animate:a}=t;const l=ns(t),c=Wc(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"&&!is(d)){const h=Array.isArray(d)?d:[d];for(let g=0;g<h.length;g++){const m=or(t,h[g]);if(m){const{transitionEnd:v,transition:b,...y}=m;for(const C in y){let k=y[C];if(Array.isArray(k)){const A=u?k.length-1:0;k=k[A]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function rr(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ue(n[r])||e.style&&Ue(e.style[r])||Yc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const uv={useVisualState:td({scrapeMotionValuesFromProps:rr,createRenderState:nr})};function id(t,e,i){const n=rr(t,e,i);for(const s in t)if(Ue(t[s])||Ue(e[s])){const o=yi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const hv={useVisualState:td({scrapeMotionValuesFromProps:id,createRenderState:Zc})};function fv(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...sr(n)?hv:uv,preloadedFeatures:t,useRender:lv(s),createVisualElement:e,Component:n};return qm(r)}}function dn(t,e,i){const n=t.getProps();return or(n,e,i!==void 0?i:n.custom,t)}const ar=t=>Array.isArray(t);function pv(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,wi(i))}function gv(t){return ar(t)?t[t.length-1]||0:t}function mv(t,e){const i=dn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=gv(o[r]);pv(t,r,a)}}function vv(t){return!!(Ue(t)&&t.add)}function lr(t,e){const i=t.getValue("willChange");if(vv(i))return i.add(e);if(!i&&Dt.WillChange){const n=new Dt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function nd(t){return t.props[qc]}const _v=t=>t!==null;function yv(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(_v),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const bv={type:"spring",stiffness:500,damping:25,restSpeed:10},wv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Sv={type:"keyframes",duration:.8},Cv={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Tv=(t,{keyframes:e})=>e.length>2?Sv:bi.has(t)?t.startsWith("scale")?wv(e[1]):bv:Cv;function kv({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 cr=(t,e,i,n={},s,o)=>r=>{const a=zo(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-_t(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};kv(a)||Object.assign(u,Tv(t,u)),u.duration&&(u.duration=_t(u.duration)),u.repeatDelay&&(u.repeatDelay=_t(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)),(Dt.instantAnimations||Dt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=yv(u.keyframes,a);if(h!==void 0){be.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Fo(u):new rm(u)};function Ev({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function sd(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&&Ev(c,u))continue;const g={delay:i,...zo(o||{},u)},m=d.get();if(m!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===m&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=nd(t);if(y){const C=window.MotionHandoffAnimation(y,u,be);C!==null&&(g.startTime=C,v=!0)}}lr(t,u),d.start(cr(u,d,h,t.shouldReduceMotion&&Sc.has(u)?{type:!1}:g,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{be.update(()=>{r&&mv(t,r)})}),l}function dr(t,e,i={}){var l;const n=dn(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(sd(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Iv(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 Iv(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(Rv).forEach((h,g)=>{h.notify("AnimationStart",e),a.push(dr(h,e,{...r,delay:i+(u?0:n)+d(g)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Rv(t,e){return t.sortNodePosition(e)}function Av(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>dr(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=dr(t,e,i);else{const s=typeof e=="function"?dn(t,e,i.custom):e;n=Promise.all(sd(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function od(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 xv=er.length;function rd(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?rd(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<xv;i++){const n=er[i],s=t.props[n];(ln(s)||s===!1)&&(e[n]=s)}return e}const Dv=[...Qo].reverse(),Lv=Qo.length;function Mv(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Av(t,i,n)))}function Ov(t){let e=Mv(t),i=ad(),n=!0;const s=l=>(c,u)=>{var h;const d=dn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:g,transitionEnd:m,...v}=d;c={...c,...v,...m}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=rd(t.parent)||{},d=[],h=new Set;let g={},m=1/0;for(let b=0;b<Lv;b++){const y=Dv[b],C=i[y],k=c[y]!==void 0?c[y]:u[y],A=ln(k),R=y===l?C.isActive:null;R===!1&&(m=b);let D=k===u[y]&&k!==c[y]&&A;if(D&&n&&t.manuallyAnimateOnMount&&(D=!1),C.protectedKeys={...g},!C.isActive&&R===null||!k&&!C.prevProp||is(k)||typeof k=="boolean")continue;const T=Pv(C.prevProp,k);let E=T||y===l&&C.isActive&&!D&&A||b>m&&A,p=!1;const _=Array.isArray(k)?k:[k];let f=_.reduce(s(y),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},M=O=>{E=!0,h.has(O)&&(p=!0,h.delete(O)),C.needsAnimating[O]=!0;const F=t.getValue(O);F&&(F.liveStyle=!1)};for(const O in I){const F=f[O],V=S[O];if(g.hasOwnProperty(O))continue;let $=!1;ar(F)&&ar(V)?$=!od(F,V):$=F!==V,$?F!=null?M(O):h.add(O):F!==void 0&&h.has(O)?M(O):C.protectedKeys[O]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(g={...g,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(D&&T)||p)&&d.push(..._.map(O=>({animation:O,options:{type:y}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const y=dn(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),k=t.getValue(y);k&&(k.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 g;return(g=h.animationState)==null?void 0:g.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=ad(),n=!0}}}function Pv(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!od(e,t):!1}function ti(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ad(){return{animate:ti(!0),whileInView:ti(),whileHover:ti(),whileTap:ti(),whileDrag:ti(),whileFocus:ti(),exit:ti()}}class jt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Nv extends jt{constructor(e){super(e),e.animationState||(e.animationState=Ov(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();is(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 Fv=0;class Bv extends jt{constructor(){super(...arguments),this.id=Fv++}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 Uv={animation:{Feature:Nv},exit:{Feature:Bv}};function un(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function hn(t){return{point:{x:t.pageX,y:t.pageY}}}const Vv=t=>e=>Jo(e)&&t(e,hn(e));function fn(t,e,i,n){return un(t,e,Vv(i),n)}function ld({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function $v({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function jv(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 cd=1e-4,Hv=1-cd,Wv=1+cd,dd=.01,Gv=0-dd,qv=0+dd;function je(t){return t.max-t.min}function zv(t,e,i){return Math.abs(t-e)<=i}function ud(t,e,i,n=.5){t.origin=n,t.originPoint=Se(e.min,e.max,t.origin),t.scale=je(i)/je(e),t.translate=Se(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Hv&&t.scale<=Wv||isNaN(t.scale))&&(t.scale=1),(t.translate>=Gv&&t.translate<=qv||isNaN(t.translate))&&(t.translate=0)}function pn(t,e,i,n){ud(t.x,e.x,i.x,n?n.originX:void 0),ud(t.y,e.y,i.y,n?n.originY:void 0)}function hd(t,e,i){t.min=i.min+e.min,t.max=t.min+je(e)}function Kv(t,e,i){hd(t.x,e.x,i.x),hd(t.y,e.y,i.y)}function fd(t,e,i){t.min=e.min-i.min,t.max=t.min+je(e)}function gn(t,e,i){fd(t.x,e.x,i.x),fd(t.y,e.y,i.y)}const pd=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ti=()=>({x:pd(),y:pd()}),gd=()=>({min:0,max:0}),ke=()=>({x:gd(),y:gd()});function st(t){return[t("x"),t("y")]}function ur(t){return t===void 0||t===1}function hr({scale:t,scaleX:e,scaleY:i}){return!ur(t)||!ur(e)||!ur(i)}function ii(t){return hr(t)||md(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function md(t){return vd(t.x)||vd(t.y)}function vd(t){return t&&t!=="0%"}function os(t,e,i){const n=t-i,s=e*n;return i+s}function _d(t,e,i,n,s){return s!==void 0&&(t=os(t,s,n)),os(t,i,n)+e}function fr(t,e=0,i=1,n,s){t.min=_d(t.min,e,i,n,s),t.max=_d(t.max,e,i,n,s)}function yd(t,{x:e,y:i}){fr(t.x,e.translate,e.scale,e.originPoint),fr(t.y,i.translate,i.scale,i.originPoint)}const bd=.999999999999,wd=1.0000000000001;function Yv(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&&Ei(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,yd(t,r)),n&&ii(o.latestValues)&&Ei(t,o.latestValues))}e.x<wd&&e.x>bd&&(e.x=1),e.y<wd&&e.y>bd&&(e.y=1)}function ki(t,e){t.min=t.min+e,t.max=t.max+e}function Sd(t,e,i,n,s=.5){const o=Se(t.min,t.max,s);fr(t,e,i,o,n)}function Ei(t,e){Sd(t.x,e.x,e.scaleX,e.scale,e.originX),Sd(t.y,e.y,e.scaleY,e.scale,e.originY)}function Cd(t,e){return ld(jv(t.getBoundingClientRect(),e))}function Xv(t,e,i){const n=Cd(t,i),{scroll:s}=e;return s&&(ki(n.x,s.offset.x),ki(n.y,s.offset.y)),n}const Td=({current:t})=>t?t.ownerDocument.defaultView:null,kd=(t,e)=>Math.abs(t-e);function Jv(t,e){const i=kd(t.x,e.x),n=kd(t.y,e.y);return Math.sqrt(i**2+n**2)}class Ed{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=gr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,m=Jv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!m)return;const{point:v}=h,{timestamp:b}=Oe;this.history.push({...v,timestamp:b});const{onStart:y,onMove:C}=this.handlers;g||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=pr(g,this.transformPagePoint),be.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:m,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=gr(h.type==="pointercancel"?this.lastMoveEventInfo:pr(g,this.transformPagePoint),this.history);this.startEvent&&m&&m(h,y),v&&v(h,y)},!Jo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=hn(e),l=pr(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Oe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,gr(l,this.history)),this.removeListeners=Ji(fn(this.contextWindow,"pointermove",this.handlePointerMove),fn(this.contextWindow,"pointerup",this.handlePointerUp),fn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Ut(this.updatePoint)}}function pr(t,e){return e?{point:e(t.point)}:t}function Id(t,e){return{x:t.x-e.x,y:t.y-e.y}}function gr({point:t},e){return{point:t,delta:Id(t,Rd(e)),offset:Id(t,Zv(e)),velocity:Qv(e,.1)}}function Zv(t){return t[0]}function Rd(t){return t[t.length-1]}function Qv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Rd(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>_t(e)));)i--;if(!n)return{x:0,y:0};const o=yt(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 e_(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Se(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Se(i,t,n.max):Math.min(t,i)),t}function Ad(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 t_(t,{top:e,left:i,bottom:n,right:s}){return{x:Ad(t.x,i,s),y:Ad(t.y,e,n)}}function xd(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 i_(t,e){return{x:xd(t.x,e.x),y:xd(t.y,e.y)}}function n_(t,e){let i=.5;const n=je(t),s=je(e);return s>n?i=Zi(e.min,e.max-n,t.min):n>s&&(i=Zi(t.min,t.max-s,e.min)),xt(0,1,i)}function s_(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 mr=.35;function o_(t=mr){return t===!1?t=0:t===!0&&(t=mr),{x:Dd(t,"left","right"),y:Dd(t,"top","bottom")}}function Dd(t,e,i){return{min:Ld(t,e),max:Ld(t,i)}}function Ld(t,e){return typeof t=="number"?t:t[e]||0}const r_=new WeakMap;class a_{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=ke(),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(hn(d).point)},r=(d,h)=>{const{drag:g,dragPropagation:m,onDragStart:v}=this.getProps();if(g&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=wm(g),!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),st(y=>{let C=this.getAxisMotionValue(y).get()||0;if(bt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[y];A&&(C=je(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&be.postRender(()=>v(d,h)),lr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:m,onDirectionLock:v,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=h;if(m&&this.currentDirection===null){this.currentDirection=l_(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=()=>st(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 Ed(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Td(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&&be.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||!rs(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=e_(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&&Ci(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=t_(n.layoutBox,e):this.constraints=!1,this.elastic=o_(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&st(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=s_(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!Ci(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Xv(n,s.root,this.visualElement.getTransformPagePoint());let r=i_(s.layout.layoutBox,o);if(i){const a=i($v(r));this.hasMutatedConstraints=!!a,a&&(r=ld(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=st(u=>{if(!rs(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,g=s?40:1e7,m={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:g,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 lr(this.visualElement,e),n.start(cr(e,n,0,i,this.visualElement,!1))}stopAnimation(){st(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){st(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){st(i=>{const{drag:n}=this.getProps();if(!rs(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]-Se(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!Ci(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};st(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=n_({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(),st(r=>{if(!rs(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Se(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;r_.set(this.visualElement,this);const e=this.visualElement.current,i=fn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();Ci(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()),be.read(n);const r=un(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(st(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=mr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function rs(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function l_(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class c_ extends jt{constructor(e){super(e),this.removeGroupControls=nt,this.removeListeners=nt,this.controls=new a_(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||nt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Md=t=>(e,i)=>{t&&be.postRender(()=>t(e,i))};class d_ extends jt{constructor(){super(...arguments),this.removePointerDownListener=nt}onPointerDown(e){this.session=new Ed(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Td(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:Md(e),onStart:Md(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&be.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=fn(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 as={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Od(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const mn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=Od(t,e.target.x),n=Od(t,e.target.y);return`${i}% ${n}%`}},u_={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=$t.parse(t);if(s.length>5)return n;const o=$t.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=Se(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 Pd=!1;class h_ extends ut{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;Xm(f_),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),Pd&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),as.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,Pd=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||be.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Xo.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 Nd(t){const[e,i]=Bc(),n=De(uo);return L(h_,{...t,layoutGroup:n,switchLayoutGroup:De(zc),isPresent:e,safeToRemove:i})}const f_={borderRadius:{...mn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:mn,borderTopRightRadius:mn,borderBottomLeftRadius:mn,borderBottomRightRadius:mn,boxShadow:u_};function p_(t,e,i){const n=Ue(t)?t:wi(t);return n.start(cr("",n,e,i)),n.animation}const g_=(t,e)=>t.depth-e.depth;class m_{constructor(){this.children=[],this.isDirty=!1}add(e){fo(this.children,e),this.isDirty=!0}remove(e){po(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(g_),this.isDirty=!1,this.children.forEach(e)}}function v_(t,e){const i=ze.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Ut(n),t(o-e))};return be.setup(n,!0),()=>Ut(n)}const Fd=["TopLeft","TopRight","BottomLeft","BottomRight"],__=Fd.length,Bd=t=>typeof t=="string"?parseFloat(t):t,Ud=t=>typeof t=="number"||K.test(t);function y_(t,e,i,n,s,o){s?(t.opacity=Se(0,i.opacity??1,b_(n)),t.opacityExit=Se(e.opacity??1,0,w_(n))):o&&(t.opacity=Se(e.opacity??1,i.opacity??1,n));for(let r=0;r<__;r++){const a=`border${Fd[r]}Radius`;let l=Vd(e,a),c=Vd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Ud(l)===Ud(c)?(t[a]=Math.max(Se(Bd(l),Bd(c),n),0),(bt.test(c)||bt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Se(e.rotate||0,i.rotate||0,n))}function Vd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const b_=$d(0,.5,Ul),w_=$d(.5,.95,nt);function $d(t,e,i){return n=>n<t?0:n>e?1:i(Zi(t,e,n))}function jd(t,e){t.min=e.min,t.max=e.max}function ot(t,e){jd(t.x,e.x),jd(t.y,e.y)}function Hd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Wd(t,e,i,n,s){return t-=e,t=os(t,1/i,n),s!==void 0&&(t=os(t,1/s,n)),t}function S_(t,e=0,i=1,n=.5,s,o=t,r=t){if(bt.test(e)&&(e=parseFloat(e),e=Se(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Se(o.min,o.max,n);t===o&&(a-=e),t.min=Wd(t.min,e,i,a,s),t.max=Wd(t.max,e,i,a,s)}function Gd(t,e,[i,n,s],o,r){S_(t,e[i],e[n],e[s],e.scale,o,r)}const C_=["x","scaleX","originX"],T_=["y","scaleY","originY"];function qd(t,e,i,n){Gd(t.x,e,C_,i?i.x:void 0,n?n.x:void 0),Gd(t.y,e,T_,i?i.y:void 0,n?n.y:void 0)}function zd(t){return t.translate===0&&t.scale===1}function Kd(t){return zd(t.x)&&zd(t.y)}function Yd(t,e){return t.min===e.min&&t.max===e.max}function k_(t,e){return Yd(t.x,e.x)&&Yd(t.y,e.y)}function Xd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Jd(t,e){return Xd(t.x,e.x)&&Xd(t.y,e.y)}function Zd(t){return je(t.x)/je(t.y)}function Qd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class E_{constructor(){this.members=[]}add(e){fo(this.members,e),e.scheduleRender()}remove(e){if(po(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 I_(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:g,skewY:m}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),g&&(n+=`skewX(${g}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 vr=["","X","Y","Z"],R_=1e3;let A_=0;function _r(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function eu(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=nd(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",be,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&eu(n)}function tu({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=A_++,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(L_),this.nodes.forEach(N_),this.nodes.forEach(F_),this.nodes.forEach(M_)},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 m_)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new vo),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=Fc(r)&&!Im(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;be.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=v_(h,250),as.hasAnimatedSinceResize&&(as.hasAnimatedSinceResize=!1,this.nodes.forEach(su)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const m=this.options.transition||c.getDefaultTransition()||j_,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),y=!this.targetLayout||!Jd(this.targetLayout,g),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 k={...zo(m,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,C)}else d||su(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}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(),Ut(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(B_),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&&eu(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(iu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(nu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(P_),this.nodes.forEach(x_),this.nodes.forEach(D_)):this.nodes.forEach(nu),this.clearAllSnapshots();const a=ze.now();Oe.delta=xt(0,1e3/60,a-Oe.timestamp),Oe.timestamp=a,Oe.isProcessing=!0,bo.update.process(Oe),bo.preRender.process(Oe),bo.render.process(Oe),Oe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Xo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(O_),this.sharedNodes.forEach(U_)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,be.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){be.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!je(this.snapshot.measuredBox.x)&&!je(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=ke(),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&&!Kd(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||ii(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)),H_(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(W_))){const{scroll:u}=this.root;u&&(ki(a.x,u.offset.x),ki(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(ot(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&&ot(a,r),ki(a.x,d.offset.x),ki(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();ot(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&&Ei(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),ii(u.latestValues)&&Ei(l,u.latestValues)}return ii(this.latestValues)&&Ei(l,this.latestValues),l}removeTransform(r){const a=ke();ot(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!ii(c.latestValues))continue;hr(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();ot(u,d),qd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return ii(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!==Oe.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=Oe.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),gn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),ot(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Kv(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ot(this.target,this.layout.layoutBox),yd(this.target,this.targetDelta)):ot(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),gn(this.relativeTargetOrigin,this.target,g.target),ot(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||hr(this.parent.latestValues)||md(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===Oe.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;ot(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Yv(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=ke());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Hd(this.prevProjectionDelta.x,this.projectionDelta.x),Hd(this.prevProjectionDelta.y,this.projectionDelta.y)),pn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Qd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Qd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}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=Ti(),this.projectionDelta=Ti(),this.projectionDeltaWithTransform=Ti()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Ti();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),g=l?l.source:void 0,m=this.layout?this.layout.source:void 0,v=g!==m,b=this.getStack(),y=!b||b.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some($_));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const R=A/1e3;ou(d.x,r.x,R),ou(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),V_(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&k_(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),ot(k,this.relativeTarget)),v&&(this.animationValues=u,y_(u,c,this.latestValues,R,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},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&&(Ut(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=be.update(()=>{as.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=wi(0)),this.currentAnimation=p_(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(R_),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&&du(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=je(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=je(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}ot(a,l),Ei(a,u),pn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new E_),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&&_r("z",r,c,this.animationValues);for(let u=0;u<vr.length;u++)_r(`rotate${vr[u]}`,r,c,this.animationValues),_r(`skew${vr[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=ss(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=ss(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!ii(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=I_(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:g}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${g.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 cn){if(u[m]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:y}=cn[m],C=d==="none"?u[m]:v(u[m],c);if(b){const k=b.length;for(let A=0;A<k;A++)r[b[A]]=C}else y?this.options.visualElement.renderState.vars[m]=C:r[m]=C}this.options.layoutId&&(r.pointerEvents=c===this?ss(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(iu),this.root.sharedNodes.clear()}}}function x_(t){t.updateLayout()}function D_(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"?st(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(h);h.min=n[d].min,h.max=h.min+g}):du(o,e.layoutBox,n)&&st(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(n[d]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=Ti();pn(a,n,e.layoutBox);const l=Ti();r?pn(l,t.applyTransform(s,!0),e.measuredBox):pn(l,n,e.layoutBox);const c=!Kd(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:g}=d;if(h&&g){const m=ke();gn(m,e.layoutBox,h.layoutBox);const v=ke();gn(v,n,g.layoutBox),Jd(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 L_(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 M_(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function O_(t){t.clearSnapshot()}function iu(t){t.clearMeasurements()}function nu(t){t.isLayoutDirty=!1}function P_(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function su(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function N_(t){t.resolveTargetDelta()}function F_(t){t.calcProjection()}function B_(t){t.resetSkewAndRotation()}function U_(t){t.removeLeadSnapshot()}function ou(t,e,i){t.translate=Se(e.translate,0,i),t.scale=Se(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function ru(t,e,i,n){t.min=Se(e.min,i.min,n),t.max=Se(e.max,i.max,n)}function V_(t,e,i,n){ru(t.x,e.x,i.x,n),ru(t.y,e.y,i.y,n)}function $_(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const j_={duration:.45,ease:[.4,0,.1,1]},au=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),lu=au("applewebkit/")&&!au("chrome/")?Math.round:nt;function cu(t){t.min=lu(t.min),t.max=lu(t.max)}function H_(t){cu(t.x),cu(t.y)}function du(t,e,i){return t==="position"||t==="preserve-aspect"&&!zv(Zd(e),Zd(i),.2)}function W_(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const G_=tu({attachResizeListener:(t,e)=>un(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yr={current:void 0},uu=tu({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yr.current){const t=new G_({});t.mount(window),t.setOptions({layoutScroll:!0}),yr.current=t}return yr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),q_={pan:{Feature:d_},drag:{Feature:c_,ProjectionNode:uu,MeasureLayout:Nd}};function hu(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&&be.postRender(()=>o(e,hn(e)))}class z_ extends jt{mount(){const{current:e}=this.node;e&&(this.unmount=Sm(e,(i,n)=>(hu(this.node,n,"Start"),s=>hu(this.node,s,"End"))))}unmount(){}}class K_ extends jt{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=Ji(un(this.node.current,"focus",()=>this.onFocus()),un(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fu(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&&be.postRender(()=>o(e,hn(e)))}class Y_ extends jt{mount(){const{current:e}=this.node;e&&(this.unmount=Em(e,(i,n)=>(fu(this.node,n,"Start"),(s,{success:o})=>fu(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const br=new WeakMap,wr=new WeakMap,X_=t=>{const e=br.get(t.target);e&&e(t)},J_=t=>{t.forEach(X_)};function Z_({root:t,...e}){const i=t||document;wr.has(i)||wr.set(i,{});const n=wr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(J_,{root:t,...e})),n[s]}function Q_(t,e,i){const n=Z_(e);return br.set(t,i),n.observe(t),()=>{br.delete(t),n.unobserve(t)}}const ey={some:0,all:1};class ty extends jt{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:ey[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 Q_(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(iy(e,i))&&this.startObserver()}unmount(){}}function iy({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const ny={inView:{Feature:ty},tap:{Feature:Y_},focus:{Feature:K_},hover:{Feature:z_}},sy={layout:{ProjectionNode:uu,MeasureLayout:Nd}},Sr={current:null},pu={current:!1};function oy(){if(pu.current=!0,!!ho)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Sr.current=t.matches;t.addEventListener("change",e),e()}else Sr.current=!1}const ry=new WeakMap;function ay(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ue(s))t.addValue(n,s);else if(Ue(o))t.addValue(n,wi(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,wi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const gu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class ly{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=Go,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=ze.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,be.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=ns(i),this.isVariantNode=Wc(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 g=d[h];l[h]!==void 0&&Ue(g)&&g.set(l[h],!1)}}mount(e){this.current=e,ry.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)),pu.current||oy(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Sr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Ut(this.notifyUpdate),Ut(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=bi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&be.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 Si){const i=Si[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):ke()}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<gu.length;n++){const s=gu[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=ay(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=wi(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"&&(Al(n)||Dl(n))?n=parseFloat(n):!Am(n)&&$t.test(i)&&(n=Rc(e,i)),this.setBaseTarget(e,Ue(n)?n.get():n)),Ue(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=or(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&&!Ue(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 vo),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class mu extends ly{constructor(){super(...arguments),this.KeyframeResolver=vm}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;Ue(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function vu(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 cy(t){return window.getComputedStyle(t)}class dy extends mu{constructor(){super(...arguments),this.type="html",this.renderInstance=vu}readValueFromInstance(e,i){var n;if(bi.has(i))return(n=this.projection)!=null&&n.isProjecting?Vo(i):Fg(e,i);{const s=cy(e),o=(wo(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Cd(e,i)}build(e,i,n){ir(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return rr(e,i,n)}}const _u=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 uy(t,e,i,n){vu(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(_u.has(s)?s:tr(s),e.attrs[s])}class hy extends mu{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(bi.has(i)){const n=Ic(i);return n&&n.default||0}return i=_u.has(i)?i:tr(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return id(e,i,n)}build(e,i,n){Jc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){uy(e,i,n,s)}mount(e){this.isSVGTag=Qc(e.tagName),super.mount(e)}}const fy=(t,e)=>sr(t)?new hy(e):new dy(e,{allowProjection:t!==mt}),py=fv({...Uv,...ny,...q_,...sy},fy),Ii=Um(py),gy=["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","region","skip-last-voice-sdk-id"],vn="widget-layout-id";function yu(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=yu(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function Lt(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=yu(t))&&(n&&(n+=" "),n+=e);return n}const my=$n("listening"),Cr=()=>Il(my);function vy(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 ls={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},bu=$n(ls),_y=()=>{const t=Hn(bu);return qe(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=ls.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=ls.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=ls.speak_to_interrupt_text),i}),[t])},ni=()=>co(bu),wu=({size:t="large",className:e})=>{const i=ni(),[n]=Cr();return L("h1",{className:Lt({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Su=({stream:t,chatMode:e})=>{const i=he(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:L("audio",{muted:!0,ref:i,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 E_="4.5.1",hr=Math.PI,Ci=2*hr,fr=hr/2,Jd=8.17579892,Zd="dual-combined",Qn="dual-horizontal",xt="single",vt="dual-vertical",Qd="bar-index",eu="bar-level",es="gradient",tu=60,iu="click",k_="fullscreenchange",nu="resize",I_="#111",su="",ou="A",ru="B",au="C",lu="D",cu="468",ts="sans-serif",R_="#0f0",A_="#7f7f7f22",Ti=10,du="create",uu="fschange",x_="lores",L_=nu,pr="user",D_="#000c",hu="#fff",O_="#4f4",fu="#888",M_="#555",gr="bark",dn="linear",Ei="log",mr="mel",pu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],gu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:pu}],["rainbow",{dir:"h",colorStops:["#817",...pu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],un={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:es,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ei,gradient:gu[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:su,width:void 0},P_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],N_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],F_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],vr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],B_=["ERR_INVALID_MODE","Invalid mode"],V_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],U_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],$_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],j_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],H_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class nt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const mu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),vu=t=>{for(const e in t)return!1;return!0},is=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],W_=(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 G_{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||(vu(i)&&!vu(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 gu)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 nt(P_)}}if(!s.createGain)throw new nt(N_);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(L_),this._fsTimeout=0)},tu))};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(k_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(uu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},tu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(iu,u))};window.addEventListener(iu,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(du)}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=is(e,[xt,Qn,vt,Zd]),this._input.disconnect(),this._input.connect(this._chLayout!=xt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=xt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=is(e,[es,Qd,eu])}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=is(e,[Ei,gr,mr,dn]),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||un.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(pr)}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(x_)}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 nt(vr);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 nt(vr);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 nt(B_,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||un.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 nt(V_);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=-fr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return mu("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){mu("stereo","channelLayout"),this.channelLayout=e?vt:xt}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=is(e,[su,ou,ru,au,lu,cu],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(pr)}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 E_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new nt(U_);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==xt&&!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==xt?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(un))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 nt($_);if(typeof i!="object")throw new nt(j_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new nt(H_);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||I_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(pr)}setFreqRange(e,i){if(e<1||i<1)throw new nt(vr);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,g=s.width>>1,v=s.height>>1,_=o==vt&&!u,S=o==Qn,b=c%10!=0,T=b&&this._frequencyScale==Ei,k=this._showLeds&&b&&!u,A=this._lumiBars&&b&&!u,R=this._alphaBars&&!A&&c!=Ti,D=this._outlineBars&&b&&!A&&!k,C=this._roundBars&&b&&!A&&!k,E=o!=vt||h>0&&!A,p=s.height-(_&&!k?.5:0)>>_,m=p*(A||u?1:1-h)|0,f=s.width-g*(S||l!=0),w=_?s.height-p*2:0,I=g*(l==-1&&!S&&!u);let x=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,O=Math.min(g,v);d&&o!=vt&&([x,O]=[O,x]);const N=Z=>e.push({...Z,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=Z=>{const te=this._freqToBin(Z,"floor"),ie=this._binToFreq(te),ne=this._binToFreq(te+1),me=Math.log2(Z/ie)/Math.log2(ne/ie);return[te,me]};let F,G,j;if(T){const Z=(se,ge,pe)=>+se.toPrecision(pe?Math.max(ge,1+Math.log10(se)|0):ge),te=se=>{const ge=[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],pe=Math.log10(se)|0,St=se/10**pe;let ct=1;for(;ct<ge.length&&St>ge[ct];)ct++;return St-ge[ct-1]<ge[ct]-St&&ct--,(ge[ct]*10**(pe+5)|0)/1e5},ie=[0,24,12,8,6,4,3,2,1][c],ne=i?10**(3/(ie*10)):2**(1/ie),me=ne**.5;let Le=i?7.94328235/(ie%2?1:me):Jd;do{let se=Le;const ge=Z(se/me,4,!0),pe=Z(se*me,4,!0),[St,ct]=M(ge),[bn,Ct]=M(pe);i?se=ie<4?te(se):Z(se,se.toString()[0]<5?3:2):se=Z(se,4,!0),se>=a&&N({posX:0,freq:se,freqLo:ge,freqHi:pe,binLo:St,binHi:bn,ratioLo:ct,ratioHi:Ct}),Le*=ne}while(Le<=r);F=f/e.length,e.forEach((se,ge)=>se.posX=I+ge*F);const ye=e[0],he=e[e.length-1];G=this._freqScaling(ye.freqLo),j=f/(this._freqScaling(he.freqHi)-G),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=M(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=M(r))}else if(b){const Z=[0,24,12,8,6,4,3,2,1][c]*10,te=ie=>{switch(this._frequencyScale){case gr:return 1960/(26.81/(ie+.53)-1);case mr:return 700*(2**ie-1);case dn:return ie}};F=f/Z,G=this._freqScaling(a),j=f/(this._freqScaling(r)-G);for(let ie=0,ne=0;ie<Z;ie++,ne+=F){const me=te(G+ne/j),Le=te(G+(ne+F/2)/j),ye=te(G+(ne+F)/j),[he,se]=M(me),[ge,pe]=M(ye);N({posX:I+ne,freq:Le,freqLo:me,freqHi:ye,binLo:he,binHi:ge,ratioLo:se,ratioHi:pe})}}else{F=1,G=this._freqScaling(a),j=f/(this._freqScaling(r)-G);const Z=this._freqToBin(a,"floor"),te=this._freqToBin(r);let ie=-999;for(let ne=Z;ne<=te;ne++){const me=this._binToFreq(ne),Le=I+Math.round(j*(this._freqScaling(me)-G));if(Le>ie)N({posX:Le,freq:me,freqLo:me,freqHi:me,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),ie=Le;else if(e.length){const ye=e[e.length-1];ye.binHi=ne,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let J=0,Y=0;if(k){const Z=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),te=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],ie=this._ledParams,[ne,me,Le]=ie||te[c];let ye,he=m;if(ie){const se=2*Z;let ge;ye=ne+1;do ye--,ge=he/ye/(1+me),Y=ge*me;while((ge<se||Y<se)&&ye>1)}else{const se=540/me;Y=Math.min(me*Z,Math.max(2,he/se+.1|0))}E&&(he+=Y),ie||(ye=Math.min(ne,he/(Y*2)|0)),J=Le>=1?Le:F*Le,this._leds=[ye,J,Y,he/ye-Y]}const H=Math.min(F-1,n*(n>0&&n<1?F:1));b&&(F-=Math.max(k?J:0,H)),e.forEach((Z,te)=>{let ie=Z.posX,ne=F;b&&(n==0&&!k?(ie|=0,ne|=0,te>0&&ie>e[te-1].posX+e[te-1].width&&(ie--,ne++)):ie+=Math.max(k?J:0,H)/2,Z.posX=ie),Z.barCenter=ie+(F==1?0:ne/2),Z.width=ne});const ce=[];for(const Z of[0,1]){const te=o==vt?(p+w)*Z:0,ie=te+p,ne=te+m-(!k||E?0:Y);ce.push({channelTop:te,channelBottom:ie,analyzerBottom:ne})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:g,centerY:v,channelCoords:ce,channelHeight:p,channelGap:w,initialX:I,innerRadius:x,outerRadius:O,scaleMin:G,unitWidth:j},this._flg={isAlpha:R,isBands:b,isLeds:k,isLumi:A,isOctaves:T,isOutline:D,isRound:C,noLedGap:E},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,g=d.canvas,v=h.canvas,_=[],S=this._chLayout==Qn,b=this._chLayout==vt,T=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=T/34|0,R=g.height>>1,D=A>>1,C=R*(c?.7:1.5),E=D*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=Ei))_.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==dn?_.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):_.push(8e3,16e3);else{let O=Jd;for(let N=-1;N<11;N++)for(let M=0;M<12;M++){if(O>=this._minFreq&&O<=this._maxFreq){const F=k[M],G=F=="C";(F&&c&&!l&&!S||G)&&_.push(c?[O,F+(G?N:"")]:O)}O*=p}}v.width=v.height=Math.max(T*.15,(n<<1)+b*A);const m=v.width>>1,f=m-A*.7,w=(O,N)=>{const M=Ci*(O/r.width),F=M-fr,G=f*Math.cos(F),j=f*Math.sin(F);h.save(),h.translate(m+G,m+j),h.rotate(M),h.fillText(N,0,0),h.restore()};g.width|=0,d.fillStyle=h.strokeStyle=D_,d.fillRect(0,0,g.width,g.height),h.arc(m,m,m-A/2,0,Ci),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=hu,d.font=`${R}px ${ts}`,h.font=`${D}px ${ts}`,d.textAlign=h.textAlign="center";let I=-C/4,x=-E;for(const O of _){const[N,M]=Array.isArray(O)?O:[O,O<1e3?O|0:`${(O/100|0)/10}k`],F=o*(this._freqScaling(N)-s),G=g.height*.75,j=M[0]=="C",J=R*(c&&!l&&!S?j?1.2:.6:3);if(d.fillStyle=h.fillStyle=j&&!l&&!S?O_:hu,c){const Y=a==Ei,H=a==dn;let ce=["C"];if((Y||N>2e3||!H&&N>250||(!u||b)&&(!H&&N>125||N>1e3))&&ce.push("G"),(Y||N>4e3||!H&&N>500||(!u||b)&&(!H&&N>250||N>2e3))&&ce.push("E"),(H&&N>4e3||(!u||b)&&(Y||N>2e3||!H&&N>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=I+C/2&&F<=e&&(d.fillText(M,S&&l==-1?e-F:i+F,G,J),(S||l&&(F>C||l==1))&&d.fillText(M,S&&l!=1?e+F:(i||r.width)-F,G,J),I=F+Math.min(J,d.measureText(M).width)/2),F>=x+E&&F<e-E&&(w(S&&l==1?e-F:F,M),(S||l&&(F>E||l==1))&&w(S&&l!=-1?e+F:-F,M),x=F)}}_draw(e){this._runId=requestAnimationFrame(U=>this._draw(U));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:g,centerX:v,centerY:_,channelCoords:S,channelHeight:b,channelGap:T,initialX:k,innerRadius:A,outerRadius:R}=this._aux,{_bars:D,canvas:C,_canvasGradients:E,_chLayout:p,_colorMode:m,_ctx:f,_energy:w,_fadePeaks:I,fillAlpha:x,_fps:O,_linearAmplitude:N,_lineWidth:M,maxDecibels:F,minDecibels:G,_mirror:j,_mode:J,overlay:Y,_radial:H,showBgColor:ce,showPeaks:Z,useCanvas:te,_weightingFilter:ie}=this,ne=this._scaleX.canvas,me=this._scaleR.canvas,Le=O*this._peakFadeTime/1e3,ye=O**2,he=this._gravity*1e3,se=O*this._peakHoldTime/1e3,ge=p==Zd,pe=p==Qn,St=p==vt,ct=p==xt,bn=a&&this._trueLeds&&m==es,Ct=H?C.width:this._aux.analyzerWidth,Wr=k+Ct,wn=Z&&this._peakLine&&J==Ti,$t=H?R-A:g,vw=$t/this._pixelRatio,[_w,Rw,Sn,Gr]=this._leds||[];w.val>0&&O>0&&(this._spinAngle+=this._spinSpeed*Ci/60/O);const yw=U=>{if(this._reflexRatio>0&&!l&&!H){let de,Tt;this.reflexFit||St?(de=St&&U==0?b+T:0,Tt=b-g):(de=C.height-g*2,Tt=g),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,C.height),f.drawImage(C,0,S[U].channelTop,C.width,g,0,de,C.width,Tt),f.restore()}},bw=()=>{this.showScaleX&&(H?(f.save(),f.translate(v,_),this._spinSpeed&&f.rotate(this._spinAngle+fr),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ne,0,C.height-ne.height))},ww=U=>{const de=U**2,Tt=424.36,Be=11599.29,ks=25122.25,jt=544496.41,Ot=148693636,oi=ri=>20*Math.log10(ri);switch(ie){case ou:const ri=Ot*de**2/((de+Tt)*Math.sqrt((de+Be)*(de+jt))*(de+Ot));return 2+oi(ri);case ru:const ai=Ot*de*U/((de+Tt)*Math.sqrt(de+ks)*(de+Ot));return .17+oi(ai);case au:const Kr=Ot*de/((de+Tt)*(de+Ot));return .06+oi(Kr);case lu:const Is=((103791848e-2-de)**2+108076816e-2*de)/((9837328-de)**2+11723776*de),Yr=U/68966888496476e-18*Math.sqrt(Is/((de+79919.29)*(de+1345600)));return oi(Yr);case cu:const Rs=-4737338981378384e-39*U**6+2043828333606125e-30*U**4-1363894795463638e-22*de+1,li=1306612257412824e-34*U**5-2118150887518656e-26*U**3+.0005559488023498642*U,Je=.0001246332637532143*U/Math.hypot(Rs,li);return 18.2+oi(Je)}return 0},qr=(U,de,Tt)=>{f.beginPath(),f.moveTo(U,de),f.lineTo(U,Tt),f.stroke()},zr=U=>{if(U&&M){const de=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=de}},si=U=>Math.max(0,(U*_w|0)*(Gr+Sn)-Sn),Sw=U=>{w.val=U,w.peak>0&&(w.hold--,w.hold<0&&(w.peak+=w.hold*he/ye/C.height*this._pixelRatio)),U>=w.peak&&(w.peak=U,w.hold=se)};Y&&f.clearRect(0,0,C.width,C.height);let qh=0;const zh=D.length,Kh=ct?1:2;for(let U=0;U<Kh;U++){const{channelTop:de,channelBottom:Tt,analyzerBottom:Be}=S[U],ks=this._gradients[this._selectedGrads[U]],jt=ks.colorStops,Ot=jt.length,oi=!ce||a&&!Y?"#000":ks.bgColor,ri=St&&H&&U?-1:1,ai=!U&&j==-1||U&&j==1,Kr=!pe||U&&j!=1?0:Ct>>(U||!ai),Is=pe&&ai?-1:1,Yr=()=>{const q=ne.height,X=q>>1,ee=N?100:F,be=N?0:G,Re=N?20:5,Ke=g/(ee-be),Et=j!=-1&&(!pe||U==0||j==1),Ht=j!=1&&(!pe||U!=j);f.save(),f.fillStyle=fu,f.font=`${X}px ${ts}`,f.textAlign="right",f.lineWidth=1;for(let Wt=ee;Wt>be;Wt-=Re){const Pi=de+(ee-Wt)*Ke,Me=Wt%2==0|0;if(Me){const We=Pi+X*(Pi==de?.8:.35);Et&&f.fillText(Wt,q*.85,We),Ht&&f.fillText(Wt,(pe?Ct:C.width)-q*.1,We),f.strokeStyle=fu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=M_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+q*Me*Et,~~Pi+.5),f.lineTo(Wr-q*Me*Ht,~~Pi+.5),f.stroke()}f.restore()},Rs=(q,X)=>{const ee=dt[q]+(q<dt.length-1?(dt[q+1]-dt[q])*X:0);return isNaN(ee)?-1/0:ee},li=(q,X=Is)=>X*Ci*((q+Kr)/C.width)+this._spinAngle,Je=(q,X,ee)=>{const be=A+X*ri,Re=li(q,ee);return[v+be*Math.cos(Re),_+be*Math.sin(Re)]},Xr=(q,X,ee,be,Re)=>{f.beginPath();for(const Ke of j&&!pe?[1,-1]:[Is]){const[Et,Ht]=d?[li(q,Ke),li(q+ee,Ke)]:[];f.moveTo(...Je(q,X,Ke)),f.lineTo(...Je(q,X+be,Ke)),d?f.arc(v,_,A+(X+be)*ri,Et,Ht,Ke!=1):f.lineTo(...Je(q+ee,X+be,Ke)),f.lineTo(...Je(q+ee,X,Ke)),d&&!Re&&f.arc(v,_,A+X*ri,Ht,Et,Ke==1)}zr(Re),f.fill()},Jr=(q=0,X=0)=>{let ee;if(m==es&&!bn||J==Ti)ee=E[U];else{const be=m==Qd?X%Ot:jt.findLastIndex(Re=>a?si(q)<=si(Re.level):q<=Re.level);ee=jt[be].color}f.fillStyle=f.strokeStyle=ee};if(te){if(pe&&!H){const q=Ct*(U+ai),X=ai?-1:1;f.setTransform(X,0,0,1,q,0)}if((!Y||ce)&&(Y&&(f.globalAlpha=this.bgAlpha),f.fillStyle=oi,(U==0||!H&&!ge)&&f.fillRect(k,de-T,Ct,(Y&&this.reflexAlpha==1?g:b)+T),f.globalAlpha=1),this.showScaleY&&!l&&!H&&(U==0||!ge)&&Yr(),a?(f.setLineDash([Gr,Sn]),f.lineWidth=D[0].width):f.lineWidth=u?Math.min(M,D[0].width/2):M,f.save(),!H){const q=new Path2D;q.rect(0,de,C.width,g),f.clip(q)}}let dt=this._fftData[U];this._analyzer[U].getFloatFrequencyData(dt),ie&&(dt=dt.map((q,X)=>q+ww(this._binToFreq(X)))),f.beginPath();let Cn=[];for(let q=0;q<zh;q++){const X=D[q],{posX:ee,barCenter:be,width:Re,freq:Ke,binLo:Et,binHi:Ht,ratioLo:Wt,ratioHi:Pi}=X;let Me=Math.max(Rs(Et,Wt),Rs(Ht,Pi));for(let ve=Et+1;ve<Ht;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),X.value[U]=Me,qh+=Me,X.peak[U]>0&&X.alpha[U]>0&&(X.hold[U]--,X.hold[U]<0)){if(I&&!wn){const ve=!o||u&&M>0?1:o?X.peak[U]:x;X.alpha[U]=ve*(1+X.hold[U]/Le)}else X.peak[U]+=X.hold[U]*he/ye/vw;X.alpha[U]<=0&&(X.peak[U]=0)}if(Me>=X.peak[U]&&(X.peak[U]=Me,X.hold[U]=se,X.alpha[U]=!o||u&&M>0?1:o?Me:x),!te)continue;f.globalAlpha=l||o?Me:u?x:1,Jr(Me,q);const We=l?$t:a?si(Me):Me*$t|0;if(J==Ti){const ve=q?0:(this._normalizedB(dt[D[1].binLo])*$t+We)/2;if(H){if(q==0&&(pe&&f.moveTo(...Je(0,0)),f.lineTo(...Je(0,ee<0?ve:We))),ee>=0){const ot=[ee,We];f.lineTo(...Je(...ot)),Cn.push(ot)}}else{if(q==0)if(j==-1&&!pe)f.moveTo(k,Be-(ee<k?ve:We));else{const ot=Et?this._normalizedB(dt[Et-1])*$t:We;f.moveTo(k-M,Be-ot)}(pe||j!=-1||ee>=k)&&f.lineTo(ee,Be-We)}}else if(a){if(ce&&!Y&&(U==0||!ge)){const ve=f.globalAlpha;f.strokeStyle=A_,f.globalAlpha=1,qr(be,de,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(bn){const ve=l?0:jt.findLastIndex(ci=>si(Me)<=si(ci.level));let ot=Be;for(let ci=Ot-1;ci>=ve;ci--){f.strokeStyle=jt[ci].color;let Xh=Be-(ci==ve?We:si(jt[ci].level));qr(be,ot,Xh),ot=Xh-Sn}}else qr(be,Be,Be-We)}else if(ee>=k)if(H)Xr(ee,0,Re,We,u);else if(d){const ve=Re/2,ot=Be+ve;f.beginPath(),f.moveTo(ee,ot),f.lineTo(ee,ot-We),f.arc(be,ot-We,ve,hr,Ci),f.lineTo(ee+Re,ot),zr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(ee,Be+ve,Re,-We-ve),zr(u),f.fill()}const Ni=X.peak[U],Yh=X.alpha[U];if(Ni>0&&Yh>0&&Z&&!wn&&!l&&ee>=k&&ee<Wr){if(I?f.globalAlpha=Yh:u&&M>0?f.globalAlpha=1:o&&(f.globalAlpha=Ni),(m==eu||bn)&&Jr(Ni),a){const ve=si(Ni);ve>=Sn&&f.fillRect(ee,Be-ve,Re,Gr)}else if(!H)f.fillRect(ee,Be-Ni*$t,Re,2);else if(J!=Ti){const ve=Ni*$t;Xr(ee,ve,Re,!this._radialInvert||St||ve+A>=2?-2:2)}}}if(te){if(f.globalAlpha=1,J==Ti){if(Jr(),H&&!pe){if(j){let q;for(;q=Cn.pop();)f.lineTo(...Je(...q,-1))}f.closePath()}if(M>0&&f.stroke(),x>0){if(H){const q=pe?li(Ct>>1):0,X=pe?li(Ct):Ci;f.moveTo(...Je(pe?Ct>>1:0,0)),f.arc(v,_,A,q,X,pe?!ai:!0)}else f.lineTo(Wr,Be),f.lineTo(k,Be);f.globalAlpha=x,f.fill(),f.globalAlpha=1}if((wn||H&&Z)&&(Cn=[],f.beginPath(),D.forEach((q,X)=>{let ee=q.posX,be=q.peak[U],Re=X?"lineTo":"moveTo";if(H&&ee<0){const Ke=D[X+1];be=W_(ee,be,Ke.posX,Ke.peak[U],0),ee=0}be*=$t,wn?(f[Re](...H?Je(ee,be):[ee,Be-be]),H&&j&&!pe&&Cn.push([ee,be])):be>0&&Xr(ee,be,1,-2)}),wn)){let q;for(;q=Cn.pop();)f.lineTo(...Je(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),pe&&!H&&f.setTransform(1,0,0,1,0,0),(!pe&&!ge||U)&&yw(U)}}if(Sw(qh/(zh<<Kh-1)),te&&(j&&!H&&!pe&&(f.setTransform(-1,0,0,1,C.width-k,0),f.drawImage(C,k,0,v,C.height,0,0,v,C.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),bw()),this.showFPS){const U=ne.height;f.font=`bold ${U}px ${ts}`,f.fillStyle=R_,f.textAlign="right",f.fillText(Math.round(O),C.width-U,U*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case Ei:return Math.log2(e);case gr:return 26.81*e/(1960+e)-.53;case mr:return Math.log2(1+e/700);case dn: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==vt,g=1-s,v=d?e.height:e.height*(1-s*!h)|0;for(const _ of[0,1]){const S=this._gradients[this._selectedGrads[_]],b=S.colorStops,T=S.dir=="h";let k;if(n?k=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):k=i.createLinearGradient(...T?[l,0,l+o,0]:[0,0,0,v]),b){const A=h&&!this._splitGradient&&(!T||n);for(let R=0;R<1+A;R++){const D=b.length-1;b.forEach((C,E)=>{let p=C.pos;if(A&&(p/=2),h&&!d&&!n&&!T&&(p*=g,!A&&p>.5*g&&(p+=.5*s)),R==1)if(n||d){const m=D-E;C=b[m],p=1-C.pos/2}else E==0&&p>0&&k.addColorStop(.5,C.color),p+=.5;k.addColorStop(p,C.color),h&&E==D&&p<.5&&k.addColorStop(.5,C.color)})}}this._canvasGradients[_]=k}}_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!=du&&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=uu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new nt(F_,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(un).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...un,...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 q_={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}]}},_u=({stream:t,className:e,onClick:i})=>{var o;const n=ue(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new G_(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",q_[((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]),L("div",{onClick:i,className:At("w-full",e),ref:n})},yu=Ln(null),bu=({className:t,debug:e=!1})=>{const i=Js(yu);return!e||!i||!(i.region||i.dc)?null:L("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&L("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&L("span",{children:" · "}),i.dc&&L("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
16
+ */const yy="4.5.1",Tr=Math.PI,Ri=2*Tr,kr=Tr/2,Cu=8.17579892,Tu="dual-combined",cs="dual-horizontal",Mt="single",wt="dual-vertical",ku="bar-index",Eu="bar-level",ds="gradient",Iu=60,Ru="click",by="fullscreenchange",Au="resize",wy="#111",xu="",Du="A",Lu="B",Mu="C",Ou="D",Pu="468",us="sans-serif",Sy="#0f0",Cy="#7f7f7f22",Ai=10,Nu="create",Fu="fschange",Ty="lores",ky=Au,Er="user",Ey="#000c",Bu="#fff",Iy="#4f4",Uu="#888",Ry="#555",Ir="bark",_n="linear",xi="log",Rr="mel",Vu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],$u=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Vu}],["rainbow",{dir:"h",colorStops:["#817",...Vu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],yn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Mt,colorMode:ds,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:xi,gradient:$u[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:xu,width:void 0},Ay=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],xy=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Dy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Ar=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Ly=["ERR_INVALID_MODE","Invalid mode"],My=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Oy=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Py=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Ny=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],Fy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class rt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const ju=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Hu=t=>{for(const e in t)return!1;return!0},hs=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],By=(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 Uy{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||(Hu(i)&&!Hu(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 $u)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 rt(Ay)}}if(!s.createGain)throw new rt(xy);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(ky),this._fsTimeout=0)},Iu))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Au,l,{signal:c}),n.addEventListener(by,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Fu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Iu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Ru,u))};window.addEventListener(Ru,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(Nu)}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=hs(e,[Mt,cs,wt,Tu]),this._input.disconnect(),this._input.connect(this._chLayout!=Mt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Mt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=hs(e,[ds,ku,Eu])}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=hs(e,[xi,Ir,Rr,_n]),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||yn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Er)}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(Ty)}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 rt(Ar);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 rt(Ar);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 rt(Ly,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||yn.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 rt(My);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=-kr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return ju("stereo","channelLayout"),this._chLayout!=Mt}set stereo(e){ju("stereo","channelLayout"),this.channelLayout=e?wt:Mt}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=hs(e,[xu,Du,Lu,Mu,Ou,Pu],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Er)}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 yy}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new rt(Oy);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==Mt&&!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==Mt?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(yn))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 rt(Py);if(typeof i!="object")throw new rt(Ny);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new rt(Fy);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||wy,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(Er)}setFreqRange(e,i){if(e<1||i<1)throw new rt(Ar);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,g=s.width>>1,m=s.height>>1,v=o==wt&&!u,b=o==cs,y=c%10!=0,C=y&&this._frequencyScale==xi,k=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,R=this._alphaBars&&!A&&c!=Ai,D=this._outlineBars&&y&&!A&&!k,T=this._roundBars&&y&&!A&&!k,E=o!=wt||h>0&&!A,p=s.height-(v&&!k?.5:0)>>v,_=p*(A||u?1:1-h)|0,f=s.width-g*(b||l!=0),S=v?s.height-p*2:0,I=g*(l==-1&&!b&&!u);let M=Math.min(s.width,s.height)*.375*(o==wt?1:this._radius)|0,x=Math.min(g,m);d&&o!=wt&&([M,x]=[x,M]);const N=Z=>e.push({...Z,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=Z=>{const Y=this._freqToBin(Z,"floor"),ie=this._binToFreq(Y),se=this._binToFreq(Y+1),ge=Math.log2(Z/ie)/Math.log2(se/ie);return[Y,ge]};let F,V,$;if(C){const Z=(pe,ne,oe)=>+pe.toPrecision(oe?Math.max(ne,1+Math.log10(pe)|0):ne),Y=pe=>{const ne=[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(pe)|0,Qe=pe/10**oe;let ft=1;for(;ft<ne.length&&Qe>ne[ft];)ft++;return Qe-ne[ft-1]<ne[ft]-Qe&&ft--,(ne[ft]*10**(oe+5)|0)/1e5},ie=[0,24,12,8,6,4,3,2,1][c],se=i?10**(3/(ie*10)):2**(1/ie),ge=se**.5;let Fe=i?7.94328235/(ie%2?1:ge):Cu;do{let pe=Fe;const ne=Z(pe/ge,4,!0),oe=Z(pe*ge,4,!0),[Qe,ft]=O(ne),[xn,Et]=O(oe);i?pe=ie<4?Y(pe):Z(pe,pe.toString()[0]<5?3:2):pe=Z(pe,4,!0),pe>=a&&N({posX:0,freq:pe,freqLo:ne,freqHi:oe,binLo:Qe,binHi:xn,ratioLo:ft,ratioHi:Et}),Fe*=se}while(Fe<=r);F=f/e.length,e.forEach((pe,ne)=>pe.posX=I+ne*F);const me=e[0],Ie=e[e.length-1];V=this._freqScaling(me.freqLo),$=f/(this._freqScaling(Ie.freqHi)-V),me.freqLo<a&&(me.freqLo=a,[me.binLo,me.ratioLo]=O(a)),Ie.freqHi>r&&(Ie.freqHi=r,[Ie.binHi,Ie.ratioHi]=O(r))}else if(y){const Z=[0,24,12,8,6,4,3,2,1][c]*10,Y=ie=>{switch(this._frequencyScale){case Ir:return 1960/(26.81/(ie+.53)-1);case Rr:return 700*(2**ie-1);case _n:return ie}};F=f/Z,V=this._freqScaling(a),$=f/(this._freqScaling(r)-V);for(let ie=0,se=0;ie<Z;ie++,se+=F){const ge=Y(V+se/$),Fe=Y(V+(se+F/2)/$),me=Y(V+(se+F)/$),[Ie,pe]=O(ge),[ne,oe]=O(me);N({posX:I+se,freq:Fe,freqLo:ge,freqHi:me,binLo:Ie,binHi:ne,ratioLo:pe,ratioHi:oe})}}else{F=1,V=this._freqScaling(a),$=f/(this._freqScaling(r)-V);const Z=this._freqToBin(a,"floor"),Y=this._freqToBin(r);let ie=-999;for(let se=Z;se<=Y;se++){const ge=this._binToFreq(se),Fe=I+Math.round($*(this._freqScaling(ge)-V));if(Fe>ie)N({posX:Fe,freq:ge,freqLo:ge,freqHi:ge,binLo:se,binHi:se,ratioLo:0,ratioHi:0}),ie=Fe;else if(e.length){const me=e[e.length-1];me.binHi=se,me.freqHi=ge,me.freq=(me.freqLo*ge)**.5}}}let Q=0,J=0;if(k){const Z=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Y=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],ie=this._ledParams,[se,ge,Fe]=ie||Y[c];let me,Ie=_;if(ie){const pe=2*Z;let ne;me=se+1;do me--,ne=Ie/me/(1+ge),J=ne*ge;while((ne<pe||J<pe)&&me>1)}else{const pe=540/ge;J=Math.min(ge*Z,Math.max(2,Ie/pe+.1|0))}E&&(Ie+=J),ie||(me=Math.min(se,Ie/(J*2)|0)),Q=Fe>=1?Fe:F*Fe,this._leds=[me,Q,J,Ie/me-J]}const G=Math.min(F-1,n*(n>0&&n<1?F:1));y&&(F-=Math.max(k?Q:0,G)),e.forEach((Z,Y)=>{let ie=Z.posX,se=F;y&&(n==0&&!k?(ie|=0,se|=0,Y>0&&ie>e[Y-1].posX+e[Y-1].width&&(ie--,se++)):ie+=Math.max(k?Q:0,G)/2,Z.posX=ie),Z.barCenter=ie+(F==1?0:se/2),Z.width=se});const de=[];for(const Z of[0,1]){const Y=o==wt?(p+S)*Z:0,ie=Y+p,se=Y+_-(!k||E?0:J);de.push({channelTop:Y,channelBottom:ie,analyzerBottom:se})}this._aux={analyzerHeight:_,analyzerWidth:f,centerX:g,centerY:m,channelCoords:de,channelHeight:p,channelGap:S,initialX:I,innerRadius:M,outerRadius:x,scaleMin:V,unitWidth:$},this._flg={isAlpha:R,isBands:y,isLeds:k,isLumi:A,isOctaves:C,isOutline:D,isRound:T,noLedGap:E},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,g=d.canvas,m=h.canvas,v=[],b=this._chLayout==cs,y=this._chLayout==wt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,R=g.height>>1,D=A>>1,T=R*(c?.7:1.5),E=D*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=xi))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==_n?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=Cu;for(let N=-1;N<11;N++)for(let O=0;O<12;O++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[O],V=F=="C";(F&&c&&!l&&!b||V)&&v.push(c?[x,F+(V?N:"")]:x)}x*=p}}m.width=m.height=Math.max(C*.15,(n<<1)+y*A);const _=m.width>>1,f=_-A*.7,S=(x,N)=>{const O=Ri*(x/r.width),F=O-kr,V=f*Math.cos(F),$=f*Math.sin(F);h.save(),h.translate(_+V,_+$),h.rotate(O),h.fillText(N,0,0),h.restore()};g.width|=0,d.fillStyle=h.strokeStyle=Ey,d.fillRect(0,0,g.width,g.height),h.arc(_,_,_-A/2,0,Ri),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=Bu,d.font=`${R}px ${us}`,h.font=`${D}px ${us}`,d.textAlign=h.textAlign="center";let I=-T/4,M=-E;for(const x of v){const[N,O]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(N)-s),V=g.height*.75,$=O[0]=="C",Q=R*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?Iy:Bu,c){const J=a==xi,G=a==_n;let de=["C"];if((J||N>2e3||!G&&N>250||(!u||y)&&(!G&&N>125||N>1e3))&&de.push("G"),(J||N>4e3||!G&&N>500||(!u||y)&&(!G&&N>250||N>2e3))&&de.push("E"),(G&&N>4e3||(!u||y)&&(J||N>2e3||!G&&N>500))&&de.push("D","F","A","B"),!de.includes(O[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(O,b&&l==-1?e-F:i+F,V,Q),(b||l&&(F>T||l==1))&&d.fillText(O,b&&l!=1?e+F:(i||r.width)-F,V,Q),I=F+Math.min(Q,d.measureText(O).width)/2),F>=M+E&&F<e-E&&(S(b&&l==1?e-F:F,O),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,O),M=F)}}_draw(e){this._runId=requestAnimationFrame(j=>this._draw(j));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:g,centerX:m,centerY:v,channelCoords:b,channelHeight:y,channelGap:C,initialX:k,innerRadius:A,outerRadius:R}=this._aux,{_bars:D,canvas:T,_canvasGradients:E,_chLayout:p,_colorMode:_,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:M,_fps:x,_linearAmplitude:N,_lineWidth:O,maxDecibels:F,minDecibels:V,_mirror:$,_mode:Q,overlay:J,_radial:G,showBgColor:de,showPeaks:Z,useCanvas:Y,_weightingFilter:ie}=this,se=this._scaleX.canvas,ge=this._scaleR.canvas,Fe=x*this._peakFadeTime/1e3,me=x**2,Ie=this._gravity*1e3,pe=x*this._peakHoldTime/1e3,ne=p==Tu,oe=p==cs,Qe=p==wt,ft=p==Mt,xn=a&&this._trueLeds&&_==ds,Et=G?T.width:this._aux.analyzerWidth,ma=k+Et,Dn=Z&&this._peakLine&&Q==Ai,Gt=G?R-A:g,bS=Gt/this._pixelRatio,[wS,DS,Ln,va]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ri/60/x);const SS=j=>{if(this._reflexRatio>0&&!l&&!G){let ue,It;this.reflexFit||Qe?(ue=Qe&&j==0?y+C:0,It=y-g):(ue=T.height-g*2,It=g),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,b[j].channelTop,T.width,g,0,ue,T.width,It),f.restore()}},CS=()=>{this.showScaleX&&(G?(f.save(),f.translate(m,v),this._spinSpeed&&f.rotate(this._spinAngle+kr),f.drawImage(ge,-ge.width>>1,-ge.width>>1),f.restore()):f.drawImage(se,0,T.height-se.height))},TS=j=>{const ue=j**2,It=424.36,Be=11599.29,Bs=25122.25,qt=544496.41,Ft=148693636,di=ui=>20*Math.log10(ui);switch(ie){case Du:const ui=Ft*ue**2/((ue+It)*Math.sqrt((ue+Be)*(ue+qt))*(ue+Ft));return 2+di(ui);case Lu:const hi=Ft*ue*j/((ue+It)*Math.sqrt(ue+Bs)*(ue+Ft));return .17+di(hi);case Mu:const ba=Ft*ue/((ue+It)*(ue+Ft));return .06+di(ba);case Ou:const Us=((103791848e-2-ue)**2+108076816e-2*ue)/((9837328-ue)**2+11723776*ue),wa=j/68966888496476e-18*Math.sqrt(Us/((ue+79919.29)*(ue+1345600)));return di(wa);case Pu:const Vs=-4737338981378384e-39*j**6+2043828333606125e-30*j**4-1363894795463638e-22*ue+1,fi=1306612257412824e-34*j**5-2118150887518656e-26*j**3+.0005559488023498642*j,et=.0001246332637532143*j/Math.hypot(Vs,fi);return 18.2+di(et)}return 0},_a=(j,ue,It)=>{f.beginPath(),f.moveTo(j,ue),f.lineTo(j,It),f.stroke()},ya=j=>{if(j&&O){const ue=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=ue}},ci=j=>Math.max(0,(j*wS|0)*(va+Ln)-Ln),kS=j=>{S.val=j,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*Ie/me/T.height*this._pixelRatio)),j>=S.peak&&(S.peak=j,S.hold=pe)};J&&f.clearRect(0,0,T.width,T.height);let $f=0;const jf=D.length,Hf=ft?1:2;for(let j=0;j<Hf;j++){const{channelTop:ue,channelBottom:It,analyzerBottom:Be}=b[j],Bs=this._gradients[this._selectedGrads[j]],qt=Bs.colorStops,Ft=qt.length,di=!de||a&&!J?"#000":Bs.bgColor,ui=Qe&&G&&j?-1:1,hi=!j&&$==-1||j&&$==1,ba=!oe||j&&$!=1?0:Et>>(j||!hi),Us=oe&&hi?-1:1,wa=()=>{const q=se.height,X=q>>1,te=N?100:F,ye=N?0:V,Re=N?20:5,Ye=g/(te-ye),Rt=$!=-1&&(!oe||j==0||$==1),zt=$!=1&&(!oe||j!=$);f.save(),f.fillStyle=Uu,f.font=`${X}px ${us}`,f.textAlign="right",f.lineWidth=1;for(let Kt=te;Kt>ye;Kt-=Re){const Hi=ue+(te-Kt)*Ye,Me=Kt%2==0|0;if(Me){const Ge=Hi+X*(Hi==ue?.8:.35);Rt&&f.fillText(Kt,q*.85,Ge),zt&&f.fillText(Kt,(oe?Et:T.width)-q*.1,Ge),f.strokeStyle=Uu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=Ry,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+q*Me*Rt,~~Hi+.5),f.lineTo(ma-q*Me*zt,~~Hi+.5),f.stroke()}f.restore()},Vs=(q,X)=>{const te=pt[q]+(q<pt.length-1?(pt[q+1]-pt[q])*X:0);return isNaN(te)?-1/0:te},fi=(q,X=Us)=>X*Ri*((q+ba)/T.width)+this._spinAngle,et=(q,X,te)=>{const ye=A+X*ui,Re=fi(q,te);return[m+ye*Math.cos(Re),v+ye*Math.sin(Re)]},Sa=(q,X,te,ye,Re)=>{f.beginPath();for(const Ye of $&&!oe?[1,-1]:[Us]){const[Rt,zt]=d?[fi(q,Ye),fi(q+te,Ye)]:[];f.moveTo(...et(q,X,Ye)),f.lineTo(...et(q,X+ye,Ye)),d?f.arc(m,v,A+(X+ye)*ui,Rt,zt,Ye!=1):f.lineTo(...et(q+te,X+ye,Ye)),f.lineTo(...et(q+te,X,Ye)),d&&!Re&&f.arc(m,v,A+X*ui,zt,Rt,Ye==1)}ya(Re),f.fill()},Ca=(q=0,X=0)=>{let te;if(_==ds&&!xn||Q==Ai)te=E[j];else{const ye=_==ku?X%Ft:qt.findLastIndex(Re=>a?ci(q)<=ci(Re.level):q<=Re.level);te=qt[ye].color}f.fillStyle=f.strokeStyle=te};if(Y){if(oe&&!G){const q=Et*(j+hi),X=hi?-1:1;f.setTransform(X,0,0,1,q,0)}if((!J||de)&&(J&&(f.globalAlpha=this.bgAlpha),f.fillStyle=di,(j==0||!G&&!ne)&&f.fillRect(k,ue-C,Et,(J&&this.reflexAlpha==1?g:y)+C),f.globalAlpha=1),this.showScaleY&&!l&&!G&&(j==0||!ne)&&wa(),a?(f.setLineDash([va,Ln]),f.lineWidth=D[0].width):f.lineWidth=u?Math.min(O,D[0].width/2):O,f.save(),!G){const q=new Path2D;q.rect(0,ue,T.width,g),f.clip(q)}}let pt=this._fftData[j];this._analyzer[j].getFloatFrequencyData(pt),ie&&(pt=pt.map((q,X)=>q+TS(this._binToFreq(X)))),f.beginPath();let Mn=[];for(let q=0;q<jf;q++){const X=D[q],{posX:te,barCenter:ye,width:Re,freq:Ye,binLo:Rt,binHi:zt,ratioLo:Kt,ratioHi:Hi}=X;let Me=Math.max(Vs(Rt,Kt),Vs(zt,Hi));for(let ve=Rt+1;ve<zt;ve++)pt[ve]>Me&&(Me=pt[ve]);if(Me=this._normalizedB(Me),X.value[j]=Me,$f+=Me,X.peak[j]>0&&X.alpha[j]>0&&(X.hold[j]--,X.hold[j]<0)){if(I&&!Dn){const ve=!o||u&&O>0?1:o?X.peak[j]:M;X.alpha[j]=ve*(1+X.hold[j]/Fe)}else X.peak[j]+=X.hold[j]*Ie/me/bS;X.alpha[j]<=0&&(X.peak[j]=0)}if(Me>=X.peak[j]&&(X.peak[j]=Me,X.hold[j]=pe,X.alpha[j]=!o||u&&O>0?1:o?Me:M),!Y)continue;f.globalAlpha=l||o?Me:u?M:1,Ca(Me,q);const Ge=l?Gt:a?ci(Me):Me*Gt|0;if(Q==Ai){const ve=q?0:(this._normalizedB(pt[D[1].binLo])*Gt+Ge)/2;if(G){if(q==0&&(oe&&f.moveTo(...et(0,0)),f.lineTo(...et(0,te<0?ve:Ge))),te>=0){const ct=[te,Ge];f.lineTo(...et(...ct)),Mn.push(ct)}}else{if(q==0)if($==-1&&!oe)f.moveTo(k,Be-(te<k?ve:Ge));else{const ct=Rt?this._normalizedB(pt[Rt-1])*Gt:Ge;f.moveTo(k-O,Be-ct)}(oe||$!=-1||te>=k)&&f.lineTo(te,Be-Ge)}}else if(a){if(de&&!J&&(j==0||!ne)){const ve=f.globalAlpha;f.strokeStyle=Cy,f.globalAlpha=1,_a(ye,ue,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(xn){const ve=l?0:qt.findLastIndex(pi=>ci(Me)<=ci(pi.level));let ct=Be;for(let pi=Ft-1;pi>=ve;pi--){f.strokeStyle=qt[pi].color;let Gf=Be-(pi==ve?Ge:ci(qt[pi].level));_a(ye,ct,Gf),ct=Gf-Ln}}else _a(ye,Be,Be-Ge)}else if(te>=k)if(G)Sa(te,0,Re,Ge,u);else if(d){const ve=Re/2,ct=Be+ve;f.beginPath(),f.moveTo(te,ct),f.lineTo(te,ct-Ge),f.arc(ye,ct-Ge,ve,Tr,Ri),f.lineTo(te+Re,ct),ya(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(te,Be+ve,Re,-Ge-ve),ya(u),f.fill()}const Wi=X.peak[j],Wf=X.alpha[j];if(Wi>0&&Wf>0&&Z&&!Dn&&!l&&te>=k&&te<ma){if(I?f.globalAlpha=Wf:u&&O>0?f.globalAlpha=1:o&&(f.globalAlpha=Wi),(_==Eu||xn)&&Ca(Wi),a){const ve=ci(Wi);ve>=Ln&&f.fillRect(te,Be-ve,Re,va)}else if(!G)f.fillRect(te,Be-Wi*Gt,Re,2);else if(Q!=Ai){const ve=Wi*Gt;Sa(te,ve,Re,!this._radialInvert||Qe||ve+A>=2?-2:2)}}}if(Y){if(f.globalAlpha=1,Q==Ai){if(Ca(),G&&!oe){if($){let q;for(;q=Mn.pop();)f.lineTo(...et(...q,-1))}f.closePath()}if(O>0&&f.stroke(),M>0){if(G){const q=oe?fi(Et>>1):0,X=oe?fi(Et):Ri;f.moveTo(...et(oe?Et>>1:0,0)),f.arc(m,v,A,q,X,oe?!hi:!0)}else f.lineTo(ma,Be),f.lineTo(k,Be);f.globalAlpha=M,f.fill(),f.globalAlpha=1}if((Dn||G&&Z)&&(Mn=[],f.beginPath(),D.forEach((q,X)=>{let te=q.posX,ye=q.peak[j],Re=X?"lineTo":"moveTo";if(G&&te<0){const Ye=D[X+1];ye=By(te,ye,Ye.posX,Ye.peak[j],0),te=0}ye*=Gt,Dn?(f[Re](...G?et(te,ye):[te,Be-ye]),G&&$&&!oe&&Mn.push([te,ye])):ye>0&&Sa(te,ye,1,-2)}),Dn)){let q;for(;q=Mn.pop();)f.lineTo(...et(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),oe&&!G&&f.setTransform(1,0,0,1,0,0),(!oe&&!ne||j)&&SS(j)}}if(kS($f/(jf<<Hf-1)),Y&&($&&!G&&!oe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,m,T.height,0,0,m,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),CS()),this.showFPS){const j=se.height;f.font=`bold ${j}px ${us}`,f.fillStyle=Sy,f.textAlign="right",f.fillText(Math.round(x),T.width-j,j*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case xi:return Math.log2(e);case Ir:return 26.81*e/(1960+e)-.53;case Rr:return Math.log2(1+e/700);case _n: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==wt,g=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 k;if(n?k=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):k=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,m]),y){const A=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+A;R++){const D=y.length-1;y.forEach((T,E)=>{let p=T.pos;if(A&&(p/=2),h&&!d&&!n&&!C&&(p*=g,!A&&p>.5*g&&(p+=.5*s)),R==1)if(n||d){const _=D-E;T=y[_],p=1-T.pos/2}else E==0&&p>0&&k.addColorStop(.5,T.color),p+=.5;k.addColorStop(p,T.color),h&&E==D&&p<.5&&k.addColorStop(.5,T.color)})}}this._canvasGradients[v]=k}}_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!=Nu&&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=Fu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new rt(Dy,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(yn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...yn,...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 Vy={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}]}},Wu=({stream:t,className:e,onClick:i})=>{var o;const n=he(null),s=ni();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Uy(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",Vy[((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]),L("div",{onClick:i,className:Lt("w-full",e),ref:n})},Gu=$n(null),qu=({className:t,debug:e=!1})=>{const i=co(Gu);return!e||!i||!(i.region||i.dc)?null:L("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&L("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&L("span",{children:" · "}),i.dc&&L("span",{"data-testid":"connection-info-dc",children:["dc: ",i.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 wu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),z_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),Su=t=>{const e=z_(t);return e.charAt(0).toUpperCase()+e.slice(1)},K_=(...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(),$y=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),Ku=t=>{const e=$y(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();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var Y_={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
26
+ */var Hy={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
27
27
  * @license lucide-preact v0.515.0 - ISC
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 X_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Ze("svg",{...Y_,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])=>Ze(l,c)),...ft(s)]);/**
31
+ */const Wy=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>tt("svg",{...Hy,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])=>tt(l,c)),...vt(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 He=(t,e)=>{const i=({class:n="",children:s,...o})=>Ze(X_,{...o,iconNode:e,class:K_(`lucide-${wu(Su(t))}`,`lucide-${wu(t)}`,n)},s);return i.displayName=Su(t),i};/**
36
+ */const He=(t,e)=>{const i=({class:n="",children:s,...o})=>tt(Wy,{...o,iconNode:e,class:jy(`lucide-${zu(Ku(t))}`,`lucide-${zu(t)}`,n)},s);return i.displayName=Ku(t),i};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const Cu=He("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
41
+ */const Yu=He("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const J_=He("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
46
+ */const Gy=He("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
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 Tu=He("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 Xu=He("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.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const Z_=He("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
56
+ */const qy=He("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
57
57
  * @license lucide-preact v0.515.0 - ISC
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 Q_=He("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const zy=He("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 ey=He("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 Ky=He("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.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const ty=He("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
71
+ */const Yy=He("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
72
72
  * @license lucide-preact v0.515.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const iy=He("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
76
+ */const Xy=He("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
77
77
  * @license lucide-preact v0.515.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const ny=He("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
81
+ */const Jy=He("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
82
82
  * @license lucide-preact v0.515.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
85
85
  * See the LICENSE file in the root directory of this source tree.
86
- */const sy=He("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
86
+ */const Zy=He("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
87
87
  * @license lucide-preact v0.515.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const oy=He("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
91
+ */const Qy=He("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
92
92
  * @license lucide-preact v0.515.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const ry=He("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
96
+ */const e0=He("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const ay=He("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
101
+ */const t0=He("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const ly=He("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
106
+ */const i0=He("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
107
107
  * @license lucide-preact v0.515.0 - ISC
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 _r=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Eu=Ln(!1),cy=()=>tl(Eu),Lt=({children:t,className:e,onClick:i,tooltip:n})=>L("button",{title:n,onClick:i,className:At("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),ku=({call:t,chatMode:e})=>{const[i,n]=cy(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return L("div",{className:"flex items-center justify-center gap-2",children:[!e&&L(Lt,{tooltip:i?"Unmute":"Mute",onClick:s,className:At(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?L(ey,{className:"w-5 h-5 text-black dark:text-white"}):L(ty,{className:"w-5 h-5 text-black dark:text-white"})}),L(Lt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:L(ny,{className:"w-4 h-4 text-black dark:text-white"})})]})},Iu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>L(Si.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&&L(_u,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),L(Xd,{stream:t.remoteStream,chatMode:i}),L(Yd,{size:"small"}),L(ku,{call:t,chatMode:i}),L(bu,{debug:n})]});function dy(){const[t,e]=Ae(!1),i=Qt();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 L("div",{children:[L(Lt,{tooltip:"More",onClick:()=>e(!t),children:L(Tu,{className:"text-black dark:text-white"})}),t&&L("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:[L(Lt,{tooltip:"More",onClick:()=>e(!t),children:L(Tu,{className:"text-black dark:text-white"})}),L("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&L("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",L(ay,{className:"w-4 h-4"})]}),i.report_issue_url&&L("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",L(ly,{className:"w-4 h-4"})]}),i.view_history_url&&L("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",L(Z_,{className:"w-4 h-4"})]})]})]})]})}function uy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ns={exports:{}},hy=ns.exports,Ru;function fy(){return Ru||(Ru=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(hy,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(_,S){var b=_[S];if(typeof b.bind=="function")return b.bind(_);try{return Function.prototype.bind.call(b,_)}catch{return function(){return Function.prototype.apply.apply(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(_){return _==="debug"&&(_="log"),typeof console===i?!1:_==="trace"&&n?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),S=0;S<s.length;S++){var b=s[S];this[b]=S<_?e:this.methodFactory(b,_,this.name)}if(this.log=this.debug,typeof console===i&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==i&&(u.call(this),this[_].apply(this,arguments))}}function h(_,S,b){return c(_)||d.apply(this,arguments)}function g(_,S){var b=this,T,k,A,R="loglevel";typeof _=="string"?R+=":"+_:typeof _=="symbol"&&(R=void 0);function D(f){var w=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=w;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+w+";"}catch{}}}function C(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var w=window.document.cookie,I=encodeURIComponent(R),x=w.indexOf(I+"=");x!==-1&&(f=/^([^;]+)/.exec(w.slice(x+I.length+1))[1])}catch{}return b.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var w=f;if(typeof w=="string"&&b.levels[w.toUpperCase()]!==void 0&&(w=b.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=b.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+f)}b.name=_,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||h,b.getLevel=function(){return A??k??T},b.setLevel=function(f,w){return A=p(f),w!==!1&&D(A),u.call(b)},b.setDefaultLevel=function(f){k=p(f),C()||b.setLevel(f,!1)},b.resetLevel=function(){A=null,E(),u.call(b)},b.enableAll=function(f){b.setLevel(b.levels.TRACE,f)},b.disableAll=function(f){b.setLevel(b.levels.SILENT,f)},b.rebuild=function(){if(r!==b&&(T=p(r.getLevel())),u.call(b),r===b)for(var f in o)o[f].rebuild()},T=p(r?r.getLevel():"WARN");var m=C();m!=null&&(A=p(m)),u.call(b)}r=new g,r.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[S];return b||(b=o[S]=new g(S,r.methodFactory)),b};var v=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=v),r},r.getLoggers=function(){return o},r.default=r,r})}(ns)),ns.exports}var py=fy();const gy=uy(py),my=()=>new Date().toISOString().replace("T"," ").replace("Z",""),vy="[ai-agent-widget]",oe=gy.getLogger("telnyx-ai-agent-widget"),_y=oe.methodFactory;oe.methodFactory=(t,e,i)=>{const n=_y(t,e,i);return function(...s){n(my(),vy,...s)}},oe.setLevel("info");function yy({onCapture:t,onClose:e}){const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae(null),[a,l]=Ae(!0);xe(()=>((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){oe.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,g=h.getContext("2d");if(!g)return;h.width=d.videoWidth,h.height=d.videoHeight,g.drawImage(d,0,0,h.width,h.height);const v=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(_=>_.stop()),t(v),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return L("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:[L("div",{className:"absolute top-2 right-2 z-10",children:L(Lt,{tooltip:"Close",onClick:u,children:L(_r,{className:"text-white w-5 h-5"})})}),L("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&L("div",{className:"absolute text-white text-center",children:L("p",{className:"text-sm",children:"Loading camera..."})}),o&&L("div",{className:"text-white text-center max-w-xs",children:[L("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),L("p",{className:"text-xs",children:o}),L("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&&L(ht,{children:[L("video",{ref:i,autoPlay:!0,playsInline:!0,className:At("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),L("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&L("div",{className:"p-3 flex justify-center",children:L("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:[L(Cu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const yr=["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"],by=["audio","lang","mark","p","s","sub","w"],Au=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function xu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function Lu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Du=yr.filter(t=>!by.includes(t)),wy=xu(yr,"gi"),Ou=xu(Du,"gi"),Sy=Lu(yr,"i"),Cy=Lu(Du,"i"),Ty=new RegExp(`${Ou.source}|${Au.source}`,"i");function Ey(t){const e=Ty.test(t),i=e?wy:Ou,n=e?Sy:Cy;return t.replace(i,"").replace(n,"").replace(Au,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function ky({item:t,containerRef:e}){const i=ue(null),n=t.role==="assistant"?Ey(t.content):t.content;return xe(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),L("li",{className:At("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[L("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),L("div",{className:At("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&L("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&L("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&&L("p",{className:At("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const Iy=({transcript:t,call:e})=>{const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=ur();xe(()=>()=>{o.forEach(C=>URL.revokeObjectURL(C.preview))},[o]),xe(()=>{if(c.length===0)return;const C=t.filter(E=>E.role==="user"&&!E.id.startsWith("optimistic-"));if(C.length>0){const E=C[C.length-1];u(p=>p.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=C=>new Promise((E,p)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=p,m.readAsDataURL(C)}),g=async C=>{if(C.type.startsWith("image/"))try{const E=await h(C),p=URL.createObjectURL(C),m={id:Date.now().toString(),file:C,base64:E,preview:p};r(f=>[...f,m])}catch(E){oe.error("Error processing image:",E)}},v=C=>{r(E=>{const p=E.find(m=>m.id===C);return p&&URL.revokeObjectURL(p.preview),E.filter(m=>m.id!==C)})},_=C=>{const E=C.target,p=E.files;p&&p.length>0&&(Array.from(p).forEach(g),E.value="")},S=C=>{var p;const E=(p=C.clipboardData)==null?void 0:p.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&g(f)}})},b=()=>{var C;(C=n.current)==null||C.click()},T=()=>{l(!0)},k=C=>{fetch(C).then(E=>E.blob()).then(E=>{const p=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(E=>{oe.error("Error processing camera capture:",E)})},A=async()=>{var p;const C=i.current&&i.current.value.trim()!=="",E=o.length>0;if(C||E){const m=((p=i.current)==null?void 0:p.value)||"",f=new Date,w={id:`optimistic-${f.getTime()}`,role:"user",content:m,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,w]),E&&d("processing_image"),e.sendConversationMessage(m,o.map(I=>I.base64)),i.current&&(i.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},R=C=>{C.key==="Enter"&&(C.preventDefault(),A())},D=[...t,...c];return L("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:[L("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((C,E)=>L(ky,{item:C,containerRef:s},C.id+E))}),o.length>0&&L("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(C=>L("div",{className:"relative",children:[L("img",{src:C.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),L("button",{onClick:()=>v(C.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:L(_r,{className:"w-3 h-3"})})]},C.id))}),L("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:[L("input",{ref:i,type:"text",onKeyDown:R,onPaste:S,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),L("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:_,className:"hidden"}),L(Lt,{tooltip:"Attach image",onClick:b,children:L(iy,{className:"text-[#969696] w-4 h-4"})}),L(Lt,{tooltip:"Take photo",onClick:T,children:L(Cu,{className:"text-[#969696] w-4 h-4"})}),L(Lt,{tooltip:"Send",children:L(oy,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&L(yy,{onCapture:k,onClose:()=>l(!1)})]})};function Ry({onCollapse:t}){return L("div",{className:"flex items-center justify-between w-full",children:[L(dy,{}),L(Lt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:L(_r,{className:"text-black dark:text-white"})})]})}const Ay=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>L(Ug,{children:L(Si.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:[L("div",{className:"p-4 text-center",children:[L(Ry,{onCollapse:e}),!n&&L(_u,{className:"h-[144px]",stream:t.remoteStream}),L(Yd,{size:"large",className:"mb-4"}),L(ku,{call:t,chatMode:n}),L(bu,{className:"mt-2",debug:s})]}),L(Xd,{stream:t.remoteStream,chatMode:n}),L(Iy,{call:t,transcript:i})]})});function Mu(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 B(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 Pu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),xy=new Uint8Array(16);function Ly(){if(!Pu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Pu(xy)}for(var Nu=[],ss=0;ss<256;++ss)Nu[ss]=(ss+256).toString(16).substr(1);function ki(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||Ly)();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=Nu;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 Dy={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},Oy={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:My,SDP_CREATE_ANSWER_FAILED:Py,SDP_SET_LOCAL_DESCRIPTION_FAILED:Ny,SDP_SET_REMOTE_DESCRIPTION_FAILED:Fu,SDP_SEND_FAILED:Bu,MEDIA_MICROPHONE_PERMISSION_DENIED:Fy,MEDIA_DEVICE_NOT_FOUND:By,MEDIA_GET_USER_MEDIA_FAILED:Vu,HOLD_FAILED:Vy,INVALID_CALL_PARAMETERS:Uy,BYE_SEND_FAILED:$y,SUBSCRIBE_FAILED:jy,PEER_CLOSED_DURING_INIT:br,WEBSOCKET_CONNECTION_FAILED:Hy,WEBSOCKET_ERROR:Wy,RECONNECTION_EXHAUSTED:wr,GATEWAY_FAILED:Gy,LOGIN_FAILED:Uu,INVALID_CREDENTIALS:qy,AUTHENTICATION_REQUIRED:zy,ICE_RESTART_FAILED:Ky,NETWORK_OFFLINE:Yy,SESSION_NOT_REATTACHED:$u,UNEXPECTED_ERROR:ju}=Dy,{HIGH_RTT:Xy,HIGH_JITTER:Jy,HIGH_PACKET_LOSS:Zy,LOW_MOS:Hu,LOW_LOCAL_AUDIO:os,LOW_INBOUND_AUDIO:rs,LOW_BYTES_RECEIVED:Sr,LOW_BYTES_SENT:Wu,RECORDING_UNAVAILABLE:Qy,RECORDING_BUFFER_OVERFLOW:e0,ICE_CONNECTIVITY_LOST:t0,ICE_GATHERING_TIMEOUT:i0,ICE_GATHERING_EMPTY:n0,PEER_CONNECTION_FAILED:s0,ONLY_HOST_ICE_CANDIDATES:o0,ANSWER_WHILE_PEER_ACTIVE:r0,ICE_CANDIDATE_PAIR_CHANGED:a0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:l0,MULTIPLE_ACTIVE_CALLS_DETECTED:c0,DUPLICATE_INBOUND_ANSWER:d0,SHARED_REMOTE_ELEMENT_OVERWRITE:u0,TOKEN_EXPIRING_SOON:h0,UNKNOWN_REATTACHED_SESSION:f0,SIGNALING_RECOVERY_REQUIRED:p0,MEDIA_RECOVERY_REQUIRED:g0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:m0}=Oy,Gu="wss://rtc.telnyx.com",qu={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},zu={urls:"stun:stun.l.google.com:19302"},v0={urls:"stun:stun.telnyx.com:3478"},_0={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},y0={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},b0={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},w0={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},S0=[v0,zu,_0,y0,b0,w0],C0=[{urls:"stun:stundev.telnyx.com:3478"},zu,{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 P;(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"})(P||(P={}));const T0={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}},E0={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 Ne(t,e){const i=E0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Vt 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,Vt.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 Ii(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Fy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return By}return Vu}function re(t,e,i,n){const s=T0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Vt({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 k0 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 Cr 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 I0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ku(t,e){return t(e={exports:{}},e.exports),e.exports}var R0=Ku(function(t){var e,i;e=I0,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(S,b){var T=S[b];if(typeof T.bind=="function")return T.bind(S);try{return Function.prototype.bind.call(T,S)}catch{return function(){return Function.prototype.apply.apply(T,[S,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(S,b){for(var T=0;T<r.length;T++){var k=r[T];this[k]=T<S?n:this.methodFactory(k,S,b)}this.log=this.debug}function u(S,b,T){return function(){typeof console!==s&&(c.call(this,b,T),this[S].apply(this,arguments))}}function d(S,b,T){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(S)||u.apply(this,arguments)}function h(S,b,T){var k,A=this;b=b??"WARN";var R="loglevel";function D(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(R)+"=");m!==-1&&(E=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return A.levels[E]===void 0&&(E=void 0),E}}typeof S=="string"?R+=":"+S:typeof S=="symbol"&&(R=void 0),A.name=S,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=T||d,A.getLevel=function(){return k},A.setLevel=function(E,p){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(k=E,p!==!1&&function(m){var f=(r[m]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=f)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+f+";"}catch{}}}(E),c.call(A,E,S),typeof console===s&&E<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(E){b=E,D()||A.setLevel(E,!1)},A.resetLevel=function(){A.setLevel(b,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; 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 C=D();C==null&&(C=b),A.setLevel(C,!1)}var g=new h,v={};g.getLogger=function(S){if(typeof S!="symbol"&&typeof S!="string"||S==="")throw new TypeError("You must supply a name when creating a logger.");var b=v[S];return b||(b=v[S]=new h(S,g.getLevel(),g.methodFactory)),b};var _=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=_),g},g.getLoggers=function(){return v},g.default=g,g},t.exports?t.exports=i():e.log=i()});const Yu={debug:0,info:1,warn:2,error:3};class A0{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||Yu[e]<Yu[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 Xu=null;const y=R0.getLogger("telnyx"),as={trace:0,debug:1,info:2,warn:3,error:4};let Ju=as.info;function Zu(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 x0=y.methodFactory;y.methodFactory=(t,e,i)=>{const n=x0(t,e,i);return function(...s){if(as[t]>=Ju){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Xu;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?Zu(a[0]):{args:a.map(Zu)}),o.addEntry(t,l,c)}}},y.setLevel("debug",!1);const ls=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{y.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Qu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},cs=t=>t instanceof Function||typeof t=="function",hn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,L0=/^(ws|wss):\/\//,eh=(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?eh(a,r):{result:s}},ds=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),fn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Tr=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 th({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?D0(n,t):n,i=s}),resolve:e,reject:i}}const D0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Er="telnyx-voice-sdk-id",us="telnyx-voice-sdk-session-id",hs="telnyx-voice-sdk-session-id-stored-at",kr="telnyx-voice-sdk-active-calls",O0=9e4;function ih(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(hs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=O0}function pn(){return sessionStorage.getItem(Er)}function Ir(t,e=Date.now()){sessionStorage.setItem(us,t),sessionStorage.setItem(hs,String(e))}function nh(){sessionStorage.removeItem(Er),sessionStorage.removeItem(us),sessionStorage.removeItem(hs)}function ei(){(function(t){try{sessionStorage.removeItem(t)}catch(e){y.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(kr)}function sh(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return y.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(kr);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return y.debug("Active-calls recovery marker payload was malformed — discarded."),ei(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(y.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),ei(),null):i.calls.length===0?(y.debug("Active-calls recovery marker had no call records — discarded."),ei(),null):i}catch(i){return y.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),ei(),null}}function oh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void ei();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){y.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(kr,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Fe,_t,Q;(function(t){t.Offer="offer",t.Answer="answer"})(Fe||(Fe={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(_t||(_t={})),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"}(Q||(Q={}));const st={generic:"event",[Q.Display]:"participantData",[Q.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},M0={invalidCredentialsOptions:"InvalidCredentialsOptions"},rh=8e6,P0={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!0};var W,Rr,Ye,yt,Oe,Ri;(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"})(W||(W={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Rr||(Rr={})),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"}(Ye||(Ye={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(yt||(yt={})),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"}(Oe||(Oe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ri||(Ri={}));const Ai="GLOBAL",ze={},gn=(t,e)=>`${t}|${e}`,ah=(t,e=Ai)=>gn(t,e)in ze,Ut=(t,e,i=Ai)=>{const n=gn(t,i);n in ze||(ze[n]=[]),ze[n].push(e)},lh=(t,e,i=Ai)=>{const n=function(s){bt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},bt=(t,e,i=Ai)=>{if(!ah(t,i))return!1;const n=gn(t,i);if(cs(e))for(let s=ze[n].length-1;s>=0;s--){const o=ze[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&ze[n].splice(s,1)}else ze[n]=[];return ze[n].length===0&&delete ze[n],!0},V=(t,e,i=Ai,n=!0)=>{const s=n&&i!==Ai;if(!ah(t,i))return s&&V(t,e),!1;const o=gn(t,i),r=ze[o].length;if(!r)return s&&V(t,e),!1;for(let a=r-1;a>=0;a--)ze[o][a](e);return s&&V(t,e),!0},Ar=t=>{const e=gn(t,"");Object.keys(ze).filter(i=>i.indexOf(e)===0).forEach(i=>delete ze[i])};let N0=typeof WebSocket<"u"?WebSocket:null;const F0=0,B0=1,V0=2,ch=3;class fs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Gu,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;y.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Gu),i&&(this._host=(r=>`${L0.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===B0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===F0}get closing(){return!!this._wsClient&&this._wsClient.readyState===V0}get closed(){return!!this._wsClient&&this._wsClient.readyState===ch}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){y.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=pn();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"),y.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 N0(e.toString()),this.socketGeneration+=1,y.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){y.error("WebSocket connection failed:",n);const s=re(Hy,n);V(P.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=g=>{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:v,error:_}=eh(g);return _?c(_):l(v)};lh(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),bt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return y.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Cr(s.id,o,this.socketGeneration));c(new k0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return y.debug(`SEND:
111
+ */const xr=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ju=$n(!1),n0=()=>Il(Ju),Ot=({children:t,className:e,onClick:i,tooltip:n})=>L("button",{title:n,onClick:i,className:Lt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Zu=({call:t,chatMode:e})=>{const[i,n]=n0(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return L("div",{className:"flex items-center justify-center gap-2",children:[!e&&L(Ot,{tooltip:i?"Unmute":"Mute",onClick:s,className:Lt(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?L(Ky,{className:"w-5 h-5 text-black dark:text-white"}):L(Yy,{className:"w-5 h-5 text-black dark:text-white"})}),L(Ot,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:L(Jy,{className:"w-4 h-4 text-black dark:text-white"})})]})},Qu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>L(Ii.div,{layoutId:vn,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&&L(Wu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),L(Su,{stream:t.remoteStream,chatMode:i}),L(wu,{size:"small"}),L(Zu,{call:t,chatMode:i}),L(qu,{debug:n})]});function s0(){const[t,e]=Ae(!1),i=ni();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 L("div",{children:[L(Ot,{tooltip:"More",onClick:()=>e(!t),children:L(Xu,{className:"text-black dark:text-white"})}),t&&L("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:[L(Ot,{tooltip:"More",onClick:()=>e(!t),children:L(Xu,{className:"text-black dark:text-white"})}),L("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&L("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",L(t0,{className:"w-4 h-4"})]}),i.report_issue_url&&L("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",L(i0,{className:"w-4 h-4"})]}),i.view_history_url&&L("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",L(qy,{className:"w-4 h-4"})]})]})]})]})}function o0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fs={exports:{}},r0=fs.exports,eh;function a0(){return eh||(eh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(r0,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 g(v,b){var y=this,C,k,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function D(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),M=S.indexOf(I+"=");M!==-1&&(f=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var S=f;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: "+f)}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??k??C},y.setLevel=function(f,S){return A=p(f),S!==!1&&D(A),u.call(y)},y.setDefaultLevel=function(f){k=p(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var _=T();_!=null&&(A=p(_)),u.call(y)}r=new g,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 g(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})}(fs)),fs.exports}var l0=a0();const c0=o0(l0),d0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),u0="[ai-agent-widget]",re=c0.getLogger("telnyx-ai-agent-widget"),h0=re.methodFactory;re.methodFactory=(t,e,i)=>{const n=h0(t,e,i);return function(...s){n(d0(),u0,...s)}},re.setLevel("info");function f0({onCapture:t,onClose:e}){const i=he(null),n=he(null),s=he(null),[o,r]=Ae(null),[a,l]=Ae(!0);xe(()=>((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,g=h.getContext("2d");if(!g)return;h.width=d.videoWidth,h.height=d.videoHeight,g.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 L("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:[L("div",{className:"absolute top-2 right-2 z-10",children:L(Ot,{tooltip:"Close",onClick:u,children:L(xr,{className:"text-white w-5 h-5"})})}),L("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&L("div",{className:"absolute text-white text-center",children:L("p",{className:"text-sm",children:"Loading camera..."})}),o&&L("div",{className:"text-white text-center max-w-xs",children:[L("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),L("p",{className:"text-xs",children:o}),L("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&&L(mt,{children:[L("video",{ref:i,autoPlay:!0,playsInline:!0,className:Lt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),L("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&L("div",{className:"p-3 flex justify-center",children:L("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:[L(Yu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const Dr=["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"],p0=["audio","lang","mark","p","s","sub","w"],th=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ih(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function nh(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const sh=Dr.filter(t=>!p0.includes(t)),g0=ih(Dr,"gi"),oh=ih(sh,"gi"),m0=nh(Dr,"i"),v0=nh(sh,"i"),_0=new RegExp(`${oh.source}|${th.source}`,"i");function y0(t){const e=_0.test(t),i=e?g0:oh,n=e?m0:v0;return t.replace(i,"").replace(n,"").replace(th,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function b0({item:t,containerRef:e}){const i=he(null),n=t.role==="assistant"?y0(t.content):t.content;return xe(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),L("li",{className:Lt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[L("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),L("div",{className:Lt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&L("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&L("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&&L("p",{className:Lt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const w0=({transcript:t,call:e})=>{const i=he(null),n=he(null),s=he(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=Cr();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{if(c.length===0)return;const T=t.filter(E=>E.role==="user"&&!E.id.startsWith("optimistic-"));if(T.length>0){const E=T[T.length-1];u(p=>p.filter(_=>_.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,p)=>{const _=new FileReader;_.onload=()=>E(_.result),_.onerror=p,_.readAsDataURL(T)}),g=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),p=URL.createObjectURL(T),_={id:Date.now().toString(),file:T,base64:E,preview:p};r(f=>[...f,_])}catch(E){re.error("Error processing image:",E)}},m=T=>{r(E=>{const p=E.find(_=>_.id===T);return p&&URL.revokeObjectURL(p.preview),E.filter(_=>_.id!==T)})},v=T=>{const E=T.target,p=E.files;p&&p.length>0&&(Array.from(p).forEach(g),E.value="")},b=T=>{var p;const E=(p=T.clipboardData)==null?void 0:p.items;E&&Array.from(E).forEach(_=>{if(_.type.startsWith("image/")){const f=_.getAsFile();f&&g(f)}})},y=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const p=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(E=>{re.error("Error processing camera capture:",E)})},A=async()=>{var p;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){const _=((p=i.current)==null?void 0:p.value)||"",f=new Date,S={id:`optimistic-${f.getTime()}`,role:"user",content:_,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),E&&d("processing_image"),e.sendConversationMessage(_,o.map(I=>I.base64)),i.current&&(i.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),A())},D=[...t,...c];return L("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:[L("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((T,E)=>L(b0,{item:T,containerRef:s},T.id+E))}),o.length>0&&L("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>L("div",{className:"relative",children:[L("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),L("button",{onClick:()=>m(T.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:L(xr,{className:"w-3 h-3"})})]},T.id))}),L("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:[L("input",{ref:i,type:"text",onKeyDown:R,onPaste:b,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),L("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),L(Ot,{tooltip:"Attach image",onClick:y,children:L(Xy,{className:"text-[#969696] w-4 h-4"})}),L(Ot,{tooltip:"Take photo",onClick:C,children:L(Yu,{className:"text-[#969696] w-4 h-4"})}),L(Ot,{tooltip:"Send",children:L(Qy,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&L(f0,{onCapture:k,onClose:()=>l(!1)})]})};function S0({onCollapse:t}){return L("div",{className:"flex items-center justify-between w-full",children:[L(s0,{}),L(Ot,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:L(xr,{className:"text-black dark:text-white"})})]})}const C0=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>L(Om,{children:L(Ii.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:[L("div",{className:"p-4 text-center",children:[L(S0,{onCollapse:e}),!n&&L(Wu,{className:"h-[144px]",stream:t.remoteStream}),L(wu,{size:"large",className:"mb-4"}),L(Zu,{call:t,chatMode:n}),L(qu,{className:"mt-2",debug:s})]}),L(Su,{stream:t.remoteStream,chatMode:n}),L(w0,{call:t,transcript:i})]})});function rh(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 B(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 ah=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),T0=new Uint8Array(16);function k0(){if(!ah)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ah(T0)}for(var lh=[],ps=0;ps<256;++ps)lh[ps]=(ps+256).toString(16).substr(1);function Di(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||k0)();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=lh;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 E0={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},I0={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:R0,SDP_CREATE_ANSWER_FAILED:A0,SDP_SET_LOCAL_DESCRIPTION_FAILED:x0,SDP_SET_REMOTE_DESCRIPTION_FAILED:ch,SDP_SEND_FAILED:dh,MEDIA_MICROPHONE_PERMISSION_DENIED:uh,MEDIA_DEVICE_NOT_FOUND:hh,MEDIA_GET_USER_MEDIA_FAILED:Lr,HOLD_FAILED:D0,INVALID_CALL_PARAMETERS:L0,BYE_SEND_FAILED:M0,SUBSCRIBE_FAILED:O0,PEER_CLOSED_DURING_INIT:Mr,WEBSOCKET_CONNECTION_FAILED:P0,WEBSOCKET_ERROR:N0,RECONNECTION_EXHAUSTED:Or,GATEWAY_FAILED:F0,LOGIN_FAILED:fh,INVALID_CREDENTIALS:B0,AUTHENTICATION_REQUIRED:U0,ICE_RESTART_FAILED:V0,NETWORK_OFFLINE:$0,SESSION_NOT_REATTACHED:ph,UNEXPECTED_ERROR:gh}=E0,{HIGH_RTT:j0,HIGH_JITTER:H0,HIGH_PACKET_LOSS:W0,LOW_MOS:mh,LOW_LOCAL_AUDIO:gs,LOW_INBOUND_AUDIO:ms,LOW_BYTES_RECEIVED:Pr,LOW_BYTES_SENT:vh,RECORDING_UNAVAILABLE:G0,RECORDING_BUFFER_OVERFLOW:q0,ICE_CONNECTIVITY_LOST:z0,ICE_GATHERING_TIMEOUT:K0,ICE_GATHERING_EMPTY:Y0,PEER_CONNECTION_FAILED:X0,ONLY_HOST_ICE_CANDIDATES:J0,ANSWER_WHILE_PEER_ACTIVE:Z0,ICE_CANDIDATE_PAIR_CHANGED:Q0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:eb,MULTIPLE_ACTIVE_CALLS_DETECTED:tb,DUPLICATE_INBOUND_ANSWER:ib,SHARED_REMOTE_ELEMENT_OVERWRITE:nb,TOKEN_EXPIRING_SOON:sb,UNKNOWN_REATTACHED_SESSION:ob,SIGNALING_RECOVERY_REQUIRED:rb,MEDIA_RECOVERY_REQUIRED:ab,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:lb}=I0,_h="wss://rtc.telnyx.com",yh={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},bh={urls:"stun:stun.l.google.com:19302"},cb={urls:"stun:stun.telnyx.com:3478"},db={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},ub={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},hb={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},fb={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},pb=[cb,bh,db,ub,hb,fb],gb=[{urls:"stun:stundev.telnyx.com:3478"},bh,{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 P;(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"})(P||(P={}));const mb={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}},vb={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 Pe(t,e){const i=vb[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Ht 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,Ht.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 Li(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return uh;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return hh}return Lr}function ae(t,e,i,n){const s=mb[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Ht({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 _b 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 Nr 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 yb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function wh(t,e){return t(e={exports:{}},e.exports),e.exports}var bb=wh(function(t){var e,i;e=yb,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 k=r[C];this[k]=C<b?n:this.methodFactory(k,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(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,y,C){var k,A=this;y=y??"WARN";var R="loglevel";function D(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var p=window.document.cookie,_=p.indexOf(encodeURIComponent(R)+"=");_!==-1&&(E=/^([^;]+)/.exec(p.slice(_))[1])}catch{}return A.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=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 k},A.setLevel=function(E,p){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(k=E,p!==!1&&function(_){var f=(r[_]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=f)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+f+";"}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,D()||A.setLevel(E,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; 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 T=D();T==null&&(T=y),A.setLevel(T,!1)}var g=new h,m={};g.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,g.getLevel(),g.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return m},g.default=g,g},t.exports?t.exports=i():e.log=i()});const Sh={debug:0,info:1,warn:2,error:3};class wb{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||Sh[e]<Sh[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 Ch=null;const w=bb.getLogger("telnyx"),vs={trace:0,debug:1,info:2,warn:3,error:4};let Th=vs.info;function kh(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 Sb=w.methodFactory;w.methodFactory=(t,e,i)=>{const n=Sb(t,e,i);return function(...s){if(vs[t]>=Th){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Ch;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?kh(a[0]):{args:a.map(kh)}),o.addEntry(t,l,c)}}},w.setLevel("debug",!1);const _s=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}},Eh=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},ys=t=>t instanceof Function||typeof t=="function",bn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Cb=/^(ws|wss):\/\//,Ih=(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?Ih(a,r):{result:s}},bs=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),wn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Fr=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 Rh({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?Tb(n,t):n,i=s}),resolve:e,reject:i}}const Tb=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Br="telnyx-voice-sdk-id",ws="telnyx-voice-sdk-session-id",Ss="telnyx-voice-sdk-session-id-stored-at",Ur="telnyx-voice-sdk-active-calls",kb=9e4;function Ah(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(Ss));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=kb}function Sn(){return sessionStorage.getItem(Br)}function Vr(t,e=Date.now()){sessionStorage.setItem(ws,t),sessionStorage.setItem(Ss,String(e))}function xh(){sessionStorage.removeItem(Br),sessionStorage.removeItem(ws),sessionStorage.removeItem(Ss)}function si(){(function(t){try{sessionStorage.removeItem(t)}catch(e){w.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Ur)}function Dh(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}}(Ur);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."),si(),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."),si(),null):i.calls.length===0?(w.debug("Active-calls recovery marker had no call records — discarded."),si(),null):i}catch(i){return w.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),si(),null}}function Lh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void si();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){w.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Ur,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Ne,St,ee;(function(t){t.Offer="offer",t.Answer="answer"})(Ne||(Ne={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(St||(St={})),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"}(ee||(ee={}));const at={generic:"event",[ee.Display]:"participantData",[ee.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Eb={invalidCredentialsOptions:"InvalidCredentialsOptions"},Mh=8e6,Oh={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 W,$r,Xe,Ct,Le,Mi;(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"})(W||(W={})),function(t){t.Participant="participant",t.Moderator="moderator"}($r||($r={})),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"}(Xe||(Xe={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Ct||(Ct={})),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"}(Le||(Le={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Mi||(Mi={}));const Oi="GLOBAL",Ke={},Cn=(t,e)=>`${t}|${e}`,Ph=(t,e=Oi)=>Cn(t,e)in Ke,Wt=(t,e,i=Oi)=>{const n=Cn(t,i);n in Ke||(Ke[n]=[]),Ke[n].push(e)},Nh=(t,e,i=Oi)=>{const n=function(s){Tt(t,n,i),e(s)};return n.prototype.targetRef=e,Wt(t,n,i)},Tt=(t,e,i=Oi)=>{if(!Ph(t,i))return!1;const n=Cn(t,i);if(ys(e))for(let s=Ke[n].length-1;s>=0;s--){const o=Ke[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Ke[n].splice(s,1)}else Ke[n]=[];return Ke[n].length===0&&delete Ke[n],!0},U=(t,e,i=Oi,n=!0)=>{const s=n&&i!==Oi;if(!Ph(t,i))return s&&U(t,e),!1;const o=Cn(t,i),r=Ke[o].length;if(!r)return s&&U(t,e),!1;for(let a=r-1;a>=0;a--)Ke[o][a](e);return s&&U(t,e),!0},jr=t=>{const e=Cn(t,"");Object.keys(Ke).filter(i=>i.indexOf(e)===0).forEach(i=>delete Ke[i])};let Ib=typeof WebSocket<"u"?WebSocket:null;const Rb=0,Ab=1,xb=2,Fh=3;class Cs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=_h,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":_h),i&&(this._host=(r=>`${Cb.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===Ab}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Rb}get closing(){return!!this._wsClient&&this._wsClient.readyState===xb}get closed(){return!!this._wsClient&&this._wsClient.readyState===Fh}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=Sn();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 Ib(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(P0,n);U(P.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=g=>{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}=Ih(g);return v?c(v):l(m)};Nh(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),Tt(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 Nr(s.id,o,this.socketGeneration));c(new _b(s.id,i,r))},i),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(y.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;cs(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=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),V(P.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.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}),V(P.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=re(Wy);return V(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),V(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),V(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Qu(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(Er,a)),this._unsetTimer(r.id),y.debug(`RECV:
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;ys(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}),U(P.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}),U(P.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(N0);return U(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),U(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),U(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Eh(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(Br,a)),this._unsetTimer(r.id),w.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Oe[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!V(r.id,r)){const l=Tr(r);V(P.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!==ch?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),V(P.SocketClose,{code:qu.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))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Cr(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)),V(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class xi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const dh={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 Ue extends xi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Mu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in dh)n&&i.hasOwnProperty(n)&&(i[dh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class uh extends Ue{constructor(e){super(),this.method=Q.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class U0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>B(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Tr(i))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const i=new uh(pn());this.pendingRequestId=i.request.id,this.gatewayStateTask=th({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=th({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class xr extends Ue{constructor(e){super(),this.method=Q.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Li{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 Li.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.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(),y.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(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.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?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.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&&(Li.isCriticalMethod(n)?(y.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")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.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){y.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&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=re(Yy);V(P.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){y.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 y.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&&(y.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(pn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.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`)):(y.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,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(p0);V(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.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){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(g0);V(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Li.CRITICAL_METHODS=new Set([Q.Modify,Q.Bye,Q.Ping]);var hh="2.27.9",Lr=hh;class $0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Lr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class j0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class fh extends Ue{toString(){return Q.Invite}}class ph extends Ue{toString(){return Q.Answer}}class gh extends Ue{toString(){return Q.Attach}}class H0 extends Ue{toString(){return Q.Bye}}class W0 extends Ue{toString(){return Q.Candidate}}class G0 extends Ue{toString(){return Q.EndOfCandidates}}class ps extends Ue{toString(){return Q.Modify}}class mh extends Ue{toString(){return Q.Info}}class q0 extends Ue{toString(){return Q.Broadcast}}class z0 extends Ue{toString(){return Q.Subscribe}}class K0 extends Ue{toString(){return Q.Unsubscribe}}class Y0 extends Ue{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:Lr,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 ti{constructor(e){if(this.options=e,this.uuid=ki(),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 Li(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ju=(n=as[i])!==null&&n!==void 0?n:as.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 fs(this),this.registerAgent=new U0(this)}get __logger(){return y}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(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 y.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}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Li.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>B(this,void 0,void 0,function*(){if(s instanceof Cr)throw y.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=re(zy,s,void 0,!0);V(P.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 B(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()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||fn(this.options)}broadcast(e){}disconnect(){return B(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(),y.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return bt(e,i,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=re(Uu,e);V(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){nh()}_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<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(h0);V(P.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 B(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)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(fn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=re(qy,void 0,s);return void V(P.Error,{error:o,type:M0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return B(this,void 0,void 0,function*(){let a;const l=!!pn(),c=l&&(this.sessionid&&ih()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?ih(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(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,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new $0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new Y0({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:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&Ir(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return B(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){y.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(qu).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)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.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&&Ar(this.relayProtocol);for(const l in this.subscriptions)Ar(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Ir(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){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=re(wr);return void V(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(m0);V(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.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],bt(e,null,i)):(delete this.subscriptions[e],Ar(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},cs(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.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(),y.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&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new xr(pn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.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([W.Early,W.Active,W.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){y.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 y.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 y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.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){Ut(e,i)}static off(e){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),mn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=hn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.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=Ne(u0);V(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},vh=(t,e)=>{const i=hn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},_h=(t,e)=>B(void 0,void 0,void 0,function*(){const i=hn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),X0=t=>{t&&t.readyState==="live"&&t.stop()},vn=t=>{mn(t)&&t.getTracks().forEach(X0),t=null},vs=t=>B(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.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){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),_n=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(vn(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}),yh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>B(void 0,void 0,void 0,function*(){const n=yield _n(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}),J0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Dr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,bh=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=>Dr(a)):[]},Or=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Mr(t);return i.includes(e)||n.includes(e)},Mr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Di=(t,e=null,i=null)=>{if(!mn(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}})},Pr=t=>{Di(t,"audio",!0)},ys=t=>{Di(t,"audio",!1)};function Z0(){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:!!vs}}catch(t){return t.message}}var Ee;function wh(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 Sh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function Ch(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"})(Ee||(Ee={}));const Th=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 Q0 extends xi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),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 eb extends xi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{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 A0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Xu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.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 B(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(),y.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 y.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 g=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],v=new Date;this._lastIntermediateFlushTime=v;const _=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(v.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:v.toISOString()}),stats:h},g.length>0?{logs:g}:{}),{segment:d}),i?{flushReason:i}:{});return y.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:g.length,callId:e.callId,flushReason:i}),_}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return B(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 y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.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 B(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 B(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}`;y.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 g=JSON.stringify(e),v=(o||r)&&g.length<=le.KEEPALIVE_BODY_LIMIT_BYTES;let _;for(let S=0;S<=le.RETRY_DELAYS_MS.length;S++){try{const T=yield fetch(u,Object.assign({method:"POST",headers:h,body:g},v?{keepalive:!0}:{}));if(T.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:S+1,status:T.status});{const k=yield T.text();_=new Error(`Call report POST failed with status ${T.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:S+1,status:T.status,error:k})}}catch(T){_=T,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:S+1,error:T})}const b=le.RETRY_DELAYS_MS[S];if(b===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${b}ms`,{attempt:S+2}),yield new Promise(T=>setTimeout(T,b))}throw y.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:_}),_ instanceof Error?_: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,g,v,_,S;if(this.statsBuffer.length<2)return!1;const b=this.statsBuffer[this.statsBuffer.length-1],T=this.statsBuffer[this.statsBuffer.length-2],k=(e=b.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const A=((i=b.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=b.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=b.transport)===null||s===void 0?void 0:s.iceState)==="failed",D=this._positiveDelta((o=b.ice)===null||o===void 0?void 0:o.requestsSent,(r=T.ice)===null||r===void 0?void 0:r.requestsSent),C=this._positiveDelta((a=b.ice)===null||a===void 0?void 0:a.responsesReceived,(l=T.ice)===null||l===void 0?void 0:l.responsesReceived),E=D>0&&C===0,p=this._positiveDelta((u=(c=b.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=T.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((v=(g=b.audio)===null||g===void 0?void 0:g.inbound)===null||v===void 0?void 0:v.bytesReceived,(S=(_=T.audio)===null||_===void 0?void 0:_.inbound)===null||S===void 0?void 0:S.bytesReceived);return A||R||E||p>0&&m===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(rs,!1),this._trackBreach(Sr,!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(le.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 B(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 g=null;s.forEach(p=>{switch(p.type){case"outbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(r=p);break;case"inbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(a=p);break;case"media-playout":p.kind==="audio"&&(l=p);break;case"remote-inbound-rtp":p.kind==="audio"&&(c=p);break;case"remote-outbound-rtp":p.kind==="audio"&&(u=p);break;case"candidate-pair":(p.nominated||p.state==="succeeded")&&h.push(p);break;case"transport":g=p}});const v=g==null?void 0:g.selectedCandidatePairId,_=v?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,v):void 0,S=this._getCodec(s,r==null?void 0:r.codecId),b=this._getCodec(s,a==null?void 0:a.codecId);if(d=(_==null?void 0:_.type)==="candidate-pair"?_:v?h.find(p=>p.id===v)||h[h.length-1]||null:h[h.length-1]||null,r){const p=this._getOutboundAudioLevel(s,r);if(p!==null&&this.intervalAudioLevels.outbound.push(p),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const w=8*m*1e3/f;this.intervalBitrates.outbound.push(w)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const p=this._getInboundAudioLevel(s,a);if(p!==null&&this.intervalAudioLevels.inbound.push(p),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const w=8*m*1e3/f;this.intervalBitrates.inbound.push(w)}}this.previousStats.inboundBytes=a.bytesReceived}let T,k,A,R,D;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(T=this._resolveCandidate(s,d.localCandidateId),k=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},T?{local:T}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(a0)),this.previousCandidatePairSnapshot=A),r&&(R=this._getLocalAudioTrackSnapshot(),D=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,D),this.previousStats.timestamp=o.getTime();const C=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||C>=E){const p=this._createStatsEntry(this.intervalStartTime,o,r,a,d,T,k,g,R,D,l,c,u,S,b);this.statsBuffer.push(p),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(p,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.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 y.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>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,g,v,_,S,b;if(!this.onWarning)return;const T=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(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 R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,D=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const C=R-this._prevPacketsReceived,E=D-this._prevPacketsLost,p=C+E;p>0&&(A=E/p*100)}this._prevPacketsReceived=R,this._prevPacketsLost=D}if(this._trackBreach(Xy,T!==void 0&&T>le.THRESHOLD_RTT_MS),this._trackBreach(Jy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Zy,A!==void 0&&A>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(rs,!1):this._trackLowInboundAudio(e),T!==void 0&&k!==void 0&&A!==void 0){const R=93.2-.11*k-2.5*A-.01*(1e3*T),D=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Hu,D<le.THRESHOLD_MOS)}else this._trackBreach(Hu,!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 R=(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,D=e.audio.inbound.bytesReceived;this._trackBreach(Sr,!this._isHeld&&R!==void 0&&D-R==0)}if(((v=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||v===void 0?void 0:v.bytesSent)!==void 0){const R=(b=(S=(_=this._previousStatsEntryForWarnings)===null||_===void 0?void 0:_.audio)===null||S===void 0?void 0:S.outbound)===null||b===void 0?void 0:b.bytesSent,D=e.audio.outbound.bytesSent;this._trackBreach(Wu,R!==void 0&&D-R==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<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(os,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(os)):this._trackBreach(os,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(os,!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(rs,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(rs,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]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.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=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,g,v,_){const S={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(S.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}:{}),v?{codec:this._buildCodecSnapshot(v,n.codecId)}:{})),s&&(S.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}:{}),_?{codec:this._buildCodecSnapshot(_,s.codecId)}:{})),o&&(S.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}),S.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&&(S.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&&(S.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||g){const b={};if(h){const T=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),b.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:T,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}g&&(b.outbound=this._withoutUndefined({packetsSent:g.packetsSent,bytesSent:g.bytesSent,reportsCount:g.reportsCount,roundTripTime:g.roundTripTime,totalPacketSendDelay:g.totalPacketSendDelay})),S.remoteRtcp=b}return S}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.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;y.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 y.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,y.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:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class $e{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 y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Qy),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 y.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(),y.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,y.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return B(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.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)<=$e.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),B(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||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.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+$e.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+$e.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(e0))}}_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()*$e.BYTES_PER_SAMPLE+$e.FRAMES_PER_SECOND*$e.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:rh}_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=>{y.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 B(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void y.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=>{y.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 B(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<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=$e.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 y.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}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=$e.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.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=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.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)}}$e.RETRY_DELAYS_MS=[500,1e3,2e3],$e.KEEPALIVE_BODY_LIMIT_BYTES=61440,$e.PACKET_OVERHEAD_BYTES=160,$e.BYTES_PER_SAMPLE=4,$e.FRAMES_PER_SECOND=100;class tb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return B(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return B(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){y.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 B(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)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Eh=Ku(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,m,f,w){var I,x,O;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((x=p._events)?(x.newListener&&(p.emit("newListener",m,f.listener?f.listener:f),x=p._events),O=x[m]):(x=p._events=new n,p._eventsCount=0),O){if(typeof O=="function"?O=x[m]=w?[f,O]:[O,f]:w?O.unshift(f):O.push(f),!O.warned&&(I=o(p))&&0<I&&O.length>I){O.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+O.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=m,N.count=O.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else O=x[m]=f,++p._eventsCount;return p}function a(p,m,f){function w(){p.removeListener(m,w),I||(I=!0,f.apply(p,arguments))}var I=!1;return w.listener=f,w}function l(p){var m=this._events;if(m){var f=m[p];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(p,m){for(var f=Array(m);m--;)f[m]=p[m];return f}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(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var m,f,w,I,x,O,N,M=p==="error";if(O=this._events)M=M&&O.error==null;else if(!M)return!1;if(N=this.domain,M){if(m=arguments[1],!N){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(f=O[p]))return!1;var G=typeof f=="function";switch(w=arguments.length){case 1:(function(j,J,Y){if(J)j.call(Y);else for(var H=j.length,ce=c(j,H),Z=0;Z<H;++Z)ce[Z].call(Y)})(f,G,this);break;case 2:(function(j,J,Y,H){if(J)j.call(Y,H);else for(var ce=j.length,Z=c(j,ce),te=0;te<ce;++te)Z[te].call(Y,H)})(f,G,this,arguments[1]);break;case 3:(function(j,J,Y,H,ce){if(J)j.call(Y,H,ce);else for(var Z=j.length,te=c(j,Z),ie=0;ie<Z;++ie)te[ie].call(Y,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(j,J,Y,H,ce,Z){if(J)j.call(Y,H,ce,Z);else for(var te=j.length,ie=c(j,te),ne=0;ne<te;++ne)ie[ne].call(Y,H,ce,Z)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(w-1),x=1;x<w;x++)I[x-1]=arguments[x];(function(j,J,Y,H){if(J)j.apply(Y,H);else for(var ce=j.length,Z=c(j,ce),te=0;te<ce;++te)Z[te].apply(Y,H)})(f,G,this,I)}return!0},s.prototype.addListener=function(p,m){return r(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return r(this,p,m,!0)},s.prototype.once=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,m)),this},s.prototype.prependOnceListener=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,m)),this},s.prototype.removeListener=function(p,m){var f,w,I,x,O;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(w=this._events))return this;if(!(f=w[p]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete w[p],w.removeListener&&this.emit("removeListener",p,f.listener||m));else if(typeof f!="function"){for(I=-1,x=f.length;0<x--;)if(f[x]===m||f[x].listener&&f[x].listener===m){O=f[x].listener,I=x;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete w[p]}else(function(N,M){for(var F=M,G=F+1,j=N.length;G<j;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);w.removeListener&&this.emit("removeListener",p,O||m)}return this},s.prototype.removeAllListeners=function(p){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[p]&&(--this._eventsCount==0?this._events=new n:delete f[p]),this;if(arguments.length===0){for(var w,I=Object.keys(f),x=0;x<I.length;++x)(w=I[x])!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[p])=="function")this.removeListener(p,m);else if(m)do this.removeListener(p,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(p){var m,f,w=this._events;return w?f=(m=w[p])?typeof m=="function"?[m.listener||m]:function(I){for(var x=Array(I.length),O=0;O<x.length;++O)x[O]=I[O].listener||I[O];return x}(m):[]:f=[],f},s.listenerCount=function(p,m){return typeof p.listenerCount=="function"?p.listenerCount(m):l.call(p,m)},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 g=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,v=[],_=0;256>_;++_)v.push((_+256).toString(16).substr(1));function S(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(v[p[m+0]]+v[p[m+1]]+v[p[m+2]]+v[p[m+3]]+"-"+v[p[m+4]]+v[p[m+5]]+"-"+v[p[m+6]]+v[p[m+7]]+"-"+v[p[m+8]]+v[p[m+9]]+"-"+v[p[m+10]]+v[p[m+11]]+v[p[m+12]]+v[p[m+13]]+v[p[m+14]]+v[p[m+15]]).toLowerCase();if(!function(w){return typeof w=="string"&&g.test(w)}(f))throw TypeError("Stringified UUID is invalid");return f}function b(p,m,f){var w=(p=p||{}).random||(p.rng||h)();return w[6]=64|15&w[6],w[8]=128|63&w[8],S(w)}function T(p,m){if(!p||!m)return{};const f={...p};if(f.localCandidateId){const w=m.get(f.localCandidateId);f.local={...w}}if(f.remoteCandidateId){const w=m.get(f.remoteCandidateId);f.remote={...w}}return f}function k(p,m,f){return 8*function(w,I,x){const O=w[x],N=I?I[x]:null;return O===null||N===null?null:(O-N)/(w.timestamp-I.timestamp)*1e3}(p,m,f)}function A(p){if(!p.entries)return p;const m={};return p.forEach(function(f,w){m[w]=f}),m}function R(p,m,f={}){if(!p)return null;let w={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(w.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of p.values())switch(I.type){case"outbound-rtp":{const x=I.mediaType||I.kind,O={};let N={};if(!["audio","video"].includes(x))continue;if(I.codecId){const M=p.get(I.codecId);M&&(O.clockRate=M.clockRate,O.mimeType=M.mimeType,O.payloadType=M.payloadType)}N=p.get(I.mediaSourceId)||p.get(I.trackId)||{},w[x].outbound.push({...I,...O,track:{...N}});break}case"inbound-rtp":{let x=I.mediaType||I.kind,O={};const N={};if(!["audio","video"].includes(x))if(I.id.includes("Video"))x="video";else{if(!I.id.includes("Audio"))continue;x="audio"}if(I.codecId){const M=p.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!w.connection.id&&I.transportId){const M=p.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=p.get(M.selectedCandidatePairId);w.connection=T(F,p)}}O=p.get(I.mediaSourceId)||p.get(I.trackId)||{},w[x].inbound.push({...I,...N,track:{...O}});break}case"peer-connection":w.connection.dataChannelsClosed=I.dataChannelsClosed,w.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let x=I.mediaType||I.kind;const O={};if(!["audio","video"].includes(x))if(I.id.includes("Video"))x="video";else{if(!I.id.includes("Audio"))continue;x="audio"}if(I.codecId){const N=p.get(I.codecId);N&&(O.clockRate=N.clockRate,O.mimeType=N.mimeType,O.payloadType=N.payloadType)}if(!w.connection.id&&I.transportId){const N=p.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=p.get(N.selectedCandidatePairId);w.connection=T(M,p)}}w.remote[x].inbound.push({...I,...O});break}case"remote-outbound-rtp":{if(!f.remote)break;const x=I.mediaType||I.kind,O={};if(!["audio","video"].includes(x))continue;if(I.codecId){const N=p.get(I.codecId);N&&(O.clockRate=N.clockRate,O.mimeType=N.mimeType,O.payloadType=N.payloadType)}w.remote[x].outbound.push({...I,...O});break}}if(!w.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(w.connection=T(I,p));return w=function(I,x){return x&&(I.audio.inbound.map(O=>{let N=x.audio.inbound.find(M=>M.id===O.id);O.bitrate=k(O,N,"bytesReceived"),O.packetRate=k(O,N,"packetsReceived")}),I.audio.outbound.map(O=>{let N=x.audio.outbound.find(M=>M.id===O.id);O.bitrate=k(O,N,"bytesSent"),O.packetRate=k(O,N,"packetsSent")}),I.video.inbound.map(O=>{let N=x.video.inbound.find(M=>M.id===O.id);O.bitrate=k(O,N,"bytesReceived"),O.packetRate=k(O,N,"packetsReceived")}),I.video.outbound.map(O=>{let N=x.video.outbound.find(M=>M.id===O.id);O.bitrate=k(O,N,"bytesSent"),O.packetRate=k(O,N,"packetsSent")})),I}(w,m),w}let D,C={},E=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:m})}async addConnection(p){const{pc:m,peerId:f}=p;let{connectionId:w,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(w&&w in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${w}.`);for(let O in this.peersToMonitor[f]){const N=this.peersToMonitor[f][O];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const x=m.getConfiguration();return x.iceServers&&x.iceServers.forEach(function(O){delete O.credential}),w||(w=b()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:w,data:{options:p,peerConfiguration:x}}),this.monitorPeer({peerId:f,connectionId:w,pc:m,remote:I}),{connectionId:w}}getTimeline(p){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),p?this.timeline.filter(m=>m.tag===p):this.timeline}get logger(){const p=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(p){let m,{connectionId:f,pc:w}=p;if(!w&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(w=this.peersToMonitor[I][f].pc,m=I)}else if(w){if(!(w instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let x in this.peersToMonitor[I])this.peersToMonitor[I][x].pc===w&&(f=x,m=I)}if(!w||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,w),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let m in this.peersToMonitor[p]){let f=this.peersToMonitor[p][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),E.forEach(p=>{this.removeTrackEventListeners(p)}),E=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(p){let{peerId:m,connectionId:f,pc:w,remote:I}=p;if(!w)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const x={pc:w,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=x}else this.peersToMonitor[m]={[f]:x};this.addPeerConnectionEventListeners(m,f,w),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let m={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);m[p]=this.peersToMonitor[p]}else m=this.peersToMonitor;let f=[];for(const w in m)for(const I in m[w]){const x=m[w][I],O=x.pc;if(O&&!this.checkIfConnectionIsClosed(w,I,O))try{const N=this.getTimestamp(),M=O.getStats(null);if(M){const F=await M,G=this.getTimestamp(),j=A(F),J={remote:x.options.remote},Y=R(F,x.stats.parsed,J),H={event:"stats",tag:"stats",peerId:w,connectionId:I,timeTaken:G-N,data:Y};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=j),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(j)),f.push(H),x.stats.parsed=Y}else this.logger.error(`PeerConnection from peer ${w} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const m in this.peersToMonitor[p]){const f=this.peersToMonitor[p][m].pc;this.checkIfConnectionIsClosed(p,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,m,f){const w=this.isConnectionClosed(f);if(w){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:m,tag:"connection",data:"closed"})}return w}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(m=>(p({stream:m}),m),m=>(p({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const m={...p};for(const w in m){var f=m[w];this.statsToMonitor.includes(f.type)||delete m[w]}return m}get peerConnectionListeners(){return{icecandidate:(p,m,f,w)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",w),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:m,data:w.candidate})},track:(p,m,f,w)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,w);const I=w.track,x=w.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=x),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:x?this.getStreamDetails(x):null,track:I?this.getMediaTrackDetails(I):null,title:w.track.kind+":"+w.track.id+" "+w.streams.map(function(O){return"stream:"+O.id})}})},signalingstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(p,m,f,w)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:m,error:{errorCode:w.errorCode}})},connectionstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:f.connectionState})},negotiationneeded:(p,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:m})},datachannel:(p,m,f,w)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,w),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:m,data:w.channel})}}}addPeerConnectionEventListeners(p,m,f){this.logger.debug(`Adding event listeners for peer ${p} and connection ${m}.`),C[m]={},Object.keys(this.peerConnectionListeners).forEach(w=>{C[m][w]=this.peerConnectionListeners[w].bind(this,p,m,f),f.addEventListener(w,C[m][w],!1)})}parseGetUserMedia(p){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(m.data.details=this.parseStream(p.stream),p.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(p){const m={audio:[],video:[]};return p.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(p,m){C[p.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(w=>{C[p.id][w]=f[w].bind(this),p.addEventListener(w,C[p.id][w])}),C[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let w=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(w)}},1e3)}removeTrackEventListeners(p){if(p.id in C){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{p.removeEventListener(f,C[p.id][f])}),clearInterval(C[p.id].readyState),delete C[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const m={...p,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,m){p in C&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,C[p][f],!1)}),delete C[p]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(w){return w},function(w){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,w.name),Promise.reject(w)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(bs=Eh)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var ib=Eh.WebRTCStats;function nb(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 sb(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 ob extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class rb extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class ab extends xi{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 lb(t,e){const i=ki();let n=!1;const s=new ib({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&V(P.StatsFrame,function({data:a}){var l,c,u,d,h,g,v,_;const{audio:S,remote:b}=a,{audio:T}=b,k=(c=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=T.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(g=(h=S.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&g!==void 0?g:-1,D=(_=(v=S.inbound[0])===null||v===void 0?void 0:v.packetsLost)!==null&&_!==void 0?_:-1,C=nb({jitter:1e3*k,rtt:1e3*A,packetsLost:D,packetsReceived:R});return{jitter:k,rtt:A,mos:C,quality:sb(C),inboundAudio:S.inbound[0],outboundAudio:S.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}}(r),t.uuid),yield t.execute(new ab(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new ob(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();V(P.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 rb(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 kh=(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:st.conferenceUpdate,call:t.calls[s],canvasInfo:cb(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);V(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);V(P.Notification,l,t.uuid);break}}},cb=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Qu(e)},Ih=["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"],db={"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 ae(t,e){return`telnyx:call:${t}:${e}`}function Rh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Nr(t){for(const e of Ih)try{performance.clearMarks(ae(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{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=()=>B(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return B(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 g=h[0].sender,v=g==null?void 0:g.transport;v&&(d.dtlsState=v.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(v=>{v.type==="candidate-pair"&&v.state==="succeeded"&&(d.candidatePairState=v.state,g.forEach(_=>{_.type==="local-candidate"&&_.id===v.localCandidateId&&(d.localCandidateType=_.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:_.address,port:_.port,protocol:_.protocol,candidateType:_.candidateType}),_.type==="remote-candidate"&&_.id===v.remoteCandidateId&&(d.remoteCandidateType=_.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:_.address,port:_.port,protocol:_.protocol,candidateType:_.candidateType})})),v.type==="transport"&&(d.dtlsCipher=v.dtlsCipher,d.srtpCipher=v.srtpCipher,d.tlsVersion=v.tlsVersion,v.dtlsState&&(d.dtlsState=v.dtlsState))})}catch(g){y.error("Error gathering connection state details:",g)}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=Ne(t0);V(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(s0);V(P.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(ae(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(ae(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(ae(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(ae(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;y.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)},y.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?(y.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&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(ae(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 B(this,void 0,void 0,function*(){performance.mark(ae(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 Vt&&V(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":V(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.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(ae(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&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(ae(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=function(s,o,r){const a=Rh(ae(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Ih){if(d==="new-call-start")continue;const h=Rh(ae(s,d));h!==void 0&&l.push({label:db[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void y.info(`${l} No timing data collected`);const c=Math.max(...a.map(v=>v.label.length),4)+2,u=(v,_)=>{for(;v.length<_;)v+=" ";return v},d=(v,_)=>{for(;v.length<_;)v=" "+v;return v},h=u("Step",c)+d("Delta",14)+d("From Start",14);let g="";for(let v=0;v<h.length;v++)g+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${g}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const v of a){const _=v.delta.toFixed(2)+"ms",S=v.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(v.label,c)}${d(_,14)}${d(S,14)}`)}y.info(`${l} ${g}`)})(n),Nr(this.options.id)}createPeerConnection(){return B(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:Fe.Offer}),performance.mark(ae(this.options.id,"set-remote-description")),!this.instance))throw re(br);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>B(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),V(P.Error,{error:re(Ii(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(()=>B(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 re(br);if(!this.options.localStream&&!i)throw re(n?Ii(n):Vu,n??void 0);performance.mark(ae(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&mn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(ae(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Ne(n0);V(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(i0);V(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return B(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw re(br);this.isDebugEnabled&&(this.statsReporter=lb(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(mn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Th(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&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Th(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);y.info("Add transceiver",e,i)}}_createOffer(){return B(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,y.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(ae(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(ae(this.options.id,"set-local-description")),performance.mark(ae(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createOffer error:",e),e instanceof Vt?e:re(My,e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),re(Fu,i)}})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return y.debug("Skipping negotiation, state:",this.instance.signalingState),y.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:Fe.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(ae(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(ae(this.options.id,"set-local-description")),performance.mark(ae(this.options.id,"ice-gathering-started")),e}catch(e){throw y.error("Peer _createAnswer error:",e),e instanceof Vt?e:re(Py,e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),re(Ny,i)}})}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(mn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,B(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 _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return y.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){Nr(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)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=Lr;class Ah{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Rr.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._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=S=>{const b=S<0||!this._lastSerno||this._lastSerno&&S===this._lastSerno+1;return b&&S>=0&&(this._lastSerno=S),b},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(S=>{S.forEach(b=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const k in T.constraints)if(T.constraints.hasOwnProperty(k)&&T.constraints[k]!==b[k])return}T.callback(b)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:g},ringtoneFile:v,ringbackFile:_}=e;this.options=Object.assign({},P0,{audio:h,video:g,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:v,ringbackFile:_,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.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=wh(this.options.ringtoneFile,"_ringtone"),this._ringback=wh(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 B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=_t.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(ae(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Vt?e:re(ju,e instanceof Error?e:void 0);return V(P.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 B(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&&y.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=Ne(r0);return V(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.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(ae(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=_t.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(ae(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Vt?d:re(ju,d instanceof Error?d:void 0);return V(P.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(){Sh(this._ringtone)}stopRingtone(){Ch(this._ringtone)}playRingback(){Sh(this._ringback)}stopRingback(){Ch(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return B(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,g=this._captureHangupCallerStack(),v=c.initiator||"app:call.hangup",_=this._state<W.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||_.cause,this.causeCode=c.causeCode||_.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:[]],y.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:v,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:g}),c.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const S=new H0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let b;try{yield Promise.race([this._execute(S),new Promise(T=>{b=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),T()},5e3)})])}catch(T){y.error("telnyx_rtc.bye failed!",T);const k=re($y,T);V(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{b&&clearTimeout(b)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new ps({sessid:this.session.sessionid,action:Ri.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new ps({sessid:this.session.sessionid,action:Ri.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new ps({sessid:this.session.sessionid,action:Ri.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new mh({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 mh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ys(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Pr(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ys(this.options.localStream):Pr(this.options.localStream)}toggleAudioMute(){y.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 B(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 y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void V(P.Warning,{warning:Ne(l0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Dr(l.track),localTracks:bh(this.options.localStream)});try{c=yield gs({audio:{deviceId:{exact:e}}})}catch(h){const g=re(Ii(h),h);return void V(P.MediaError,g,((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 g=re(Ii(h),h);return V(P.MediaError,g,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(v=>v.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,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Dr(l.track),localTracks:bh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Di(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Di(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Di(e,"video",null)}setVideoDevice(e){return B(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 gs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ms(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(){ys(this.options.remoteStream)}undeaf(){Pr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Di(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.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 y.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"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.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[W.Hangup,W.Destroy,W.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=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case W.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(ae(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(y.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&&_h(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 tb,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Q.Answer:if(performance.mark(ae(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>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Q.Media:if(performance.mark(ae(this.id,"telnyx-rtc-media")),this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Q.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===_t.Inbound?_t.Outbound:_t.Inbound,c={type:st[i],call:this,displayName:o,displayNumber:r,displayDirection:l};V(P.Notification,c,this.id)||V(P.Notification,c,this.session.uuid);break}case Q.Candidate:this._addIceCandidate(n);break;case Q.Info:case Q.Event:{const o=Object.assign(Object.assign({},n),{type:st.generic,call:this});V(P.Notification,o,this.id)||V(P.Notification,o,this.session.uuid);break}case Q.Ringing:performance.mark(ae(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 Q.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 B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return y.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:Ye.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const g=[];for(const v in s)g.push(Object.assign({callId:s[v][0],index:Number(v)},ls(s[v][1])));this._dispatchConferenceUpdate({action:Ye.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ye.Add,callId:o,index:r},ls(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ye.Modify,callId:o,index:r},ls(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ye.Delete,callId:o,index:r},ls(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ye.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 B(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:Ye.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Or(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 B(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,kh(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Or(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(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=re(Vy,e);return V(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new ps(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ri.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>B(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(y.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;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=re(Ky,i);V(P.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 B(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Fe.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(ae(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>B(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=re(Fu,n);V(P.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){y.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=Ne(o0);y.warn(`[${this.id}] Warning ${i.code}: ${i.message}`),V(P.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 y.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(ae(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${ws}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(W.Requesting),a=new fh(l);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new gh(l):new ph(l);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ae(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>B(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=re(Bu,c);V(P.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){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(this._isTerminatingOrTerminated())return;if(!e)return y.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-${ws}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(W.Requesting),o=new fh(r);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new gh(r):new ph(r);break;default:return y.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(ae(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>B(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=re(Bu,a);V(P.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){y.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?(y.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?(y.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 W0({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 y.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(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new G0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(ae(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(ae(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=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(ae(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.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&&ms(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:st.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),V(P.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:st.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&V(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(V(P.Notification,e,this.id,!1)||V(P.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=Ne(d0);return V(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.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:g,onNotification:v,recoveredCallId:_,wasHeldBeforeRecovery:S}=this.options;var b;this.options.id=d?d.toString():ki(),this.id=this.options.id,_&&(this.recoveredCallId=_,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!S),h&&(b=h,Object.keys(b).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),g||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ut(P.MediaError,this._onMediaError,this.id),Ut(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),cs(v)&&Ut(P.Notification,v.bind(this),this.id);const T=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",D=this.session.options.debugLogMaxEntries||1e3;if(T&&(this._callReportCollector=new le({enabled:!0,interval:k,intermediateReportInterval:A},{enabled:!0,level:R,maxEntries:D}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=C=>{var E,p,m,f;V(P.Warning,{warning:C,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),C.code===Sr&&this._state!==W.Held?(p=(E=this.session).reportNoRtp)===null||p===void 0||p.call(E,this.id,"inbound"):C.code===Wu&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(m=this.session).reportNoRtp)===null||f===void 0||f.call(m,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const C={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:rh,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 $e(C,E);const p=(l=this.session.connection)===null||l===void 0?void 0:l.host;p&&this._callRecorder._setHost(p),this._callRecorder.onWarning=m=>{V(P.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),y.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)}_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(),Nr(this.id),y.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;vn(s),vn(o),vh(r,s),vh(a,o),bt(P.MediaError,null,this.id),bt(P.PeerConnectionFailureError,null,this.id),bt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.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 g=this.session.options,v=g.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},v?{anonymousLogin:{targetType:v.target_type,targetId:v.target_id,targetVersionId:v.target_version_id,targetParams:this._sanitizeClientOption(v.target_params)}}:{}),connection:{env:g.env,host:g.host,project:g.project,region:(e=this.session.region)!==null&&e!==void 0?e:g.region,dc:this.session.dc,rtcIp:g.rtcIp,rtcPort:g.rtcPort,autoReconnect:(i=g.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=g.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=g.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:g.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=g.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=g.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=g.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:g.enableCallReports!==!1,intervalMs:g.callReportInterval||5e3,flushIntervalMs:(h=g.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:g.debugLogLevel||"debug",debugLogMaxEntries:g.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 y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.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=>{y.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void y.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=>{y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.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 y.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),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ah.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ni extends Ah{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Q0(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 eb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return B(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return B(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",()=>B(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 ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return B(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&_h(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(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
+ `),Le[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!U(r.id,r)){const l=Fr(r);U(P.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!==Fh?(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}),U(P.SocketClose,{code:yh.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=>{Tt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Nr(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)),U(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",e)}}Cs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Pi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Di()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const Bh={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ve extends Pi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=rh(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in Bh)n&&i.hasOwnProperty(n)&&(i[Bh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Uh extends Ve{constructor(e){super(),this.method=ee.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Db{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>B(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Fr(i))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const i=new Uh(Sn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Rh({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Le.REGISTER,Le.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Rh({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Hr extends Ve{constructor(e){super(),this.method=ee.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ni{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 Ni.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&&(Ni.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($0);U(P.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 Hr(Sn());(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=Pe(rb);U(P.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=Pe(ab);U(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Ni.CRITICAL_METHODS=new Set([ee.Modify,ee.Bye,ee.Ping]);var Vh="2.27.10",Wr=Vh;class Lb extends Ve{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:Wr,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Mb extends Ve{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class $h extends Ve{toString(){return ee.Invite}}class jh extends Ve{toString(){return ee.Answer}}class Hh extends Ve{toString(){return ee.Attach}}class Ob extends Ve{toString(){return ee.Bye}}class Pb extends Ve{toString(){return ee.Candidate}}class Nb extends Ve{toString(){return ee.EndOfCandidates}}class Ts extends Ve{toString(){return ee.Modify}}class Wh extends Ve{toString(){return ee.Info}}class Fb extends Ve{toString(){return ee.Broadcast}}class Bb extends Ve{toString(){return ee.Subscribe}}class Ub extends Ve{toString(){return ee.Unsubscribe}}class Vb extends Ve{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:Wr,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 oi{constructor(e){if(this.options=e,this.uuid=Di(),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 Ni(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Th=(n=vs[i])!==null&&n!==void 0?n:vs.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 Cs(this),this.registerAgent=new Db(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(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=Ni.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?Cs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>B(this,void 0,void 0,function*(){if(s instanceof Nr)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(U0,s,void 0,!0);U(P.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 B(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()},oi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&w.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return bs(this.options)||wn(this.options)}broadcast(e){}disconnect(){return B(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 Wt(e,i,this.uuid),this}off(e,i){return Tt(e,i,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new Cs(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(fh,e);U(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){xh()}_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<=oi.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-oi.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=Pe(sb);U(P.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 B(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)),bs(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(wn(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(B0,void 0,s);return void U(P.Error,{error:o,type:Eb.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r,a;return B(this,void 0,void 0,function*(){let l;const c=!!Sn(),u=c&&(this.sessionid&&Ah()?this.sessionid:function(h=Date.now()){const g=sessionStorage.getItem(ws);return g?Ah(h)?g:(sessionStorage.removeItem(ws),sessionStorage.removeItem(Ss),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,g=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 Lb(this.options.login,this.options.password||this.options.passwd,this.options.login_token,u,g,c,m)}else l=new Vb({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&&Vr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return B(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(yh).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&&jr(this.relayProtocol);for(const l in this.subscriptions)jr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Vr(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(Or);return void U(P.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=Pe(lb);U(P.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],Tt(e,null,i)):(delete this.subscriptions[e],jr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},ys(i)&&Wt(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(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){w.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.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 Hr(Sn()))),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([W.Early,W.Active,W.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){Wt(e,i)}static off(e){Tt(e)}static uuid(){return Di()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}oi.TOKEN_EXPIRY_WARNING_SECONDS=120,oi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const ks=t=>navigator.mediaDevices.getUserMedia(t),Tn=t=>t&&t instanceof MediaStream,Es=(t,e,i)=>{const n=bn(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=Pe(nb);U(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},Gh=(t,e)=>{const i=bn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},qh=(t,e)=>B(void 0,void 0,void 0,function*(){const i=bn(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}}),$b=t=>{t&&t.readyState==="live"&&t.stop()},kn=t=>{Tn(t)&&t.getTracks().forEach($b),t=null},Is=t=>B(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 ks(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 ks(s)}catch(o){throw w.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),En=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Ct.AudioIn||s===Ct.AudioOut,video:!s||s===Ct.Video}))(t)).catch(s=>(w.error(s),null));if(n){if(kn(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}),zh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Rs=(t,e,i)=>B(void 0,void 0,void 0,function*(){const n=yield En(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}),jb=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Gr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,Kh=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=>Gr(a)):[]},qr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=zr(t);return i.includes(e)||n.includes(e)},zr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Fi=(t,e=null,i=null)=>{if(!Tn(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}})},Kr=t=>{Fi(t,"audio",!0)},As=t=>{Fi(t,"audio",!1)};function Hb(){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:!!Is}}catch(t){return t.message}}var Te;function Yh(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 Xh(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 Jh(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"})(Te||(Te={}));const Zh=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 Wb extends Pi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Di(),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 Gb extends Pi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ce{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 wb(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Ch=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:ce.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 B(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 g=(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},g.length>0?{logs:g}:{}),{segment:d}),i?{flushReason:i}:{});return w.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:g.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return B(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 B(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 B(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 g=JSON.stringify(e),m=(o||r)&&g.length<=ce.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=ce.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:g},m?{keepalive:!0}:{}));if(C.ok)return void w.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=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:k})}}catch(C){v=C,w.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const y=ce.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,g,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],k=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const A=((i=y.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=y.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",D=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=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=D>0&&T===0,p=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=(g=y.audio)===null||g===void 0?void 0:g.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||R||E||p>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(ms,!1),this._trackBreach(Pr,!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(ce.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 B(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 g=null;s.forEach(p=>{switch(p.type){case"outbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(r=p);break;case"inbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(a=p);break;case"media-playout":p.kind==="audio"&&(l=p);break;case"remote-inbound-rtp":p.kind==="audio"&&(c=p);break;case"remote-outbound-rtp":p.kind==="audio"&&(u=p);break;case"candidate-pair":(p.nominated||p.state==="succeeded")&&h.push(p);break;case"transport":g=p}});const m=g==null?void 0:g.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(p=>p.id===m)||h[h.length-1]||null:h[h.length-1]||null,r){const p=this._getOutboundAudioLevel(s,r);if(p!==null&&this.intervalAudioLevels.outbound.push(p),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*_*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const p=this._getInboundAudioLevel(s,a);if(p!==null&&this.intervalAudioLevels.inbound.push(p),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,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*_*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,A,R,D;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=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}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(Q0)),this.previousCandidatePairSnapshot=A),r&&(R=this._getLocalAudioTrackSnapshot(),D=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,D),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const p=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,g,R,D,l,c,u,b,y);this.statsBuffer.push(p),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(p,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:ce.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>=ce.STATS_FLUSH_THRESHOLD||o>=ce.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,g,m,v,b,y;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(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 R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,D=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=D-this._prevPacketsLost,p=T+E;p>0&&(A=E/p*100)}this._prevPacketsReceived=R,this._prevPacketsLost=D}if(this._trackBreach(j0,C!==void 0&&C>ce.THRESHOLD_RTT_MS),this._trackBreach(H0,k!==void 0&&k>ce.THRESHOLD_JITTER_MS),this._trackBreach(W0,A!==void 0&&A>ce.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(ms,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&A!==void 0){const R=93.2-.11*k-2.5*A-.01*(1e3*C),D=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(mh,D<ce.THRESHOLD_MOS)}else this._trackBreach(mh,!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 R=(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,D=e.audio.inbound.bytesReceived;this._trackBreach(Pr,!this._isHeld&&R!==void 0&&D-R==0)}if(((m=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||m===void 0?void 0:m.bytesSent)!==void 0){const R=(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,D=e.audio.outbound.bytesSent;this._trackBreach(vh,R!==void 0&&D-R==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<=ce.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(gs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ce.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(gs)):this._trackBreach(gs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(gs,!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(ms,!1);const o=s<=ce.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(ms,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]>=ce.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ce.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=Pe(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,g,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||g){const y={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=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:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}g&&(y.outbound=this._withoutUndefined({packetsSent:g.packetsSent,bytesSent:g.bytesSent,reportsCount:g.reportsCount,roundTripTime:g.roundTripTime,totalPacketSendDelay:g.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:[]}}}ce.INITIAL_COLLECTION_INTERVAL_MS=1e3,ce.STATS_FLUSH_THRESHOLD=300,ce.LOGS_FLUSH_THRESHOLD=800,ce.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ce.CONSECUTIVE_BREACHES_REQUIRED=3,ce.THRESHOLD_RTT_MS=.4,ce.THRESHOLD_JITTER_MS=30,ce.THRESHOLD_PACKET_LOSS_PCT=1,ce.THRESHOLD_MOS=3.5,ce.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ce.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ce.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,ce.WARNING_THROTTLE_MS=15e3,ce.RETRY_DELAYS_MS=[500,1e3,2e3],ce.KEEPALIVE_BODY_LIMIT_BYTES=61440;class $e{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(G0),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 B(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)<=$e.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),B(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+$e.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+$e.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,w.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(q0))}}_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()*$e.BYTES_PER_SAMPLE+$e.FRAMES_PER_SECOND*$e.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:Mh}_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 B(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 B(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<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=$e.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=$e.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=Pe(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)}}$e.RETRY_DELAYS_MS=[500,1e3,2e3],$e.KEEPALIVE_BODY_LIMIT_BYTES=61440,$e.PACKET_OVERHEAD_BYTES=160,$e.BYTES_PER_SAMPLE=4,$e.FRAMES_PER_SECOND=100;class qb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return B(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 B(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 B(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 xs,Qh=wh(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,_,f,S){var I,M,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((M=p._events)?(M.newListener&&(p.emit("newListener",_,f.listener?f.listener:f),M=p._events),x=M[_]):(M=p._events=new n,p._eventsCount=0),x){if(typeof x=="function"?x=M[_]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(p))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+_+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=_,N.count=x.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(N)}}else x=M[_]=f,++p._eventsCount;return p}function a(p,_,f){function S(){p.removeListener(_,S),I||(I=!0,f.apply(p,arguments))}var I=!1;return S.listener=f,S}function l(p){var _=this._events;if(_){var f=_[p];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(p,_){for(var f=Array(_);_--;)f[_]=p[_];return f}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(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var _,f,S,I,M,x,N,O=p==="error";if(x=this._events)O=O&&x.error==null;else if(!O)return!1;if(N=this.domain,O){if(_=arguments[1],!N){if(_ instanceof Error)throw _;var F=new Error('Uncaught, unspecified "error" event. ('+_+")");throw F.context=_,F}return _||(_=new Error('Uncaught, unspecified "error" event')),_.domainEmitter=this,_.domain=N,_.domainThrown=!1,N.emit("error",_),!1}if(!(f=x[p]))return!1;var V=typeof f=="function";switch(S=arguments.length){case 1:(function($,Q,J){if(Q)$.call(J);else for(var G=$.length,de=c($,G),Z=0;Z<G;++Z)de[Z].call(J)})(f,V,this);break;case 2:(function($,Q,J,G){if(Q)$.call(J,G);else for(var de=$.length,Z=c($,de),Y=0;Y<de;++Y)Z[Y].call(J,G)})(f,V,this,arguments[1]);break;case 3:(function($,Q,J,G,de){if(Q)$.call(J,G,de);else for(var Z=$.length,Y=c($,Z),ie=0;ie<Z;++ie)Y[ie].call(J,G,de)})(f,V,this,arguments[1],arguments[2]);break;case 4:(function($,Q,J,G,de,Z){if(Q)$.call(J,G,de,Z);else for(var Y=$.length,ie=c($,Y),se=0;se<Y;++se)ie[se].call(J,G,de,Z)})(f,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($,Q,J,G){if(Q)$.apply(J,G);else for(var de=$.length,Z=c($,de),Y=0;Y<de;++Y)Z[Y].apply(J,G)})(f,V,this,I)}return!0},s.prototype.addListener=function(p,_){return r(this,p,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,_){return r(this,p,_,!0)},s.prototype.once=function(p,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,_)),this},s.prototype.prependOnceListener=function(p,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,_)),this},s.prototype.removeListener=function(p,_){var f,S,I,M,x;if(typeof _!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[p]))return this;if(f===_||f.listener&&f.listener===_)--this._eventsCount==0?this._events=new n:(delete S[p],S.removeListener&&this.emit("removeListener",p,f.listener||_));else if(typeof f!="function"){for(I=-1,M=f.length;0<M--;)if(f[M]===_||f[M].listener&&f[M].listener===_){x=f[M].listener,I=M;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[p]}else(function(N,O){for(var F=O,V=F+1,$=N.length;V<$;F+=1,V+=1)N[F]=N[V];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",p,x||_)}return this},s.prototype.removeAllListeners=function(p){var _,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[p]&&(--this._eventsCount==0?this._events=new n:delete f[p]),this;if(arguments.length===0){for(var S,I=Object.keys(f),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(_=f[p])=="function")this.removeListener(p,_);else if(_)do this.removeListener(p,_[_.length-1]);while(_[0]);return this},s.prototype.listeners=function(p){var _,f,S=this._events;return S?f=(_=S[p])?typeof _=="function"?[_.listener||_]:function(I){for(var M=Array(I.length),x=0;x<M.length;++x)M[x]=I[x].listener||I[x];return M}(_):[]:f=[],f},s.listenerCount=function(p,_){return typeof p.listenerCount=="function"?p.listenerCount(_):l.call(p,_)},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 g=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,m=[],v=0;256>v;++v)m.push((v+256).toString(16).substr(1));function b(p){var _=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(m[p[_+0]]+m[p[_+1]]+m[p[_+2]]+m[p[_+3]]+"-"+m[p[_+4]]+m[p[_+5]]+"-"+m[p[_+6]]+m[p[_+7]]+"-"+m[p[_+8]]+m[p[_+9]]+"-"+m[p[_+10]]+m[p[_+11]]+m[p[_+12]]+m[p[_+13]]+m[p[_+14]]+m[p[_+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&g.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function y(p,_,f){var S=(p=p||{}).random||(p.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(p,_){if(!p||!_)return{};const f={...p};if(f.localCandidateId){const S=_.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=_.get(f.remoteCandidateId);f.remote={...S}}return f}function k(p,_,f){return 8*function(S,I,M){const x=S[M],N=I?I[M]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(p,_,f)}function A(p){if(!p.entries)return p;const _={};return p.forEach(function(f,S){_[S]=f}),_}function R(p,_,f={}){if(!p)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of p.values())switch(I.type){case"outbound-rtp":{const M=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(M))continue;if(I.codecId){const O=p.get(I.codecId);O&&(x.clockRate=O.clockRate,x.mimeType=O.mimeType,x.payloadType=O.payloadType)}N=p.get(I.mediaSourceId)||p.get(I.trackId)||{},S[M].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let M=I.mediaType||I.kind,x={};const N={};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=p.get(I.codecId);O&&(N.clockRate=O.clockRate,N.mimeType=O.mimeType,N.payloadType=O.payloadType)}if(!S.connection.id&&I.transportId){const O=p.get(I.transportId);if(O&&O.selectedCandidatePairId){const F=p.get(O.selectedCandidatePairId);S.connection=C(F,p)}}x=p.get(I.mediaSourceId)||p.get(I.trackId)||{},S[M].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let M=I.mediaType||I.kind;const x={};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 N=p.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=p.get(I.transportId);if(N&&N.selectedCandidatePairId){const O=p.get(N.selectedCandidatePairId);S.connection=C(O,p)}}S.remote[M].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const M=I.mediaType||I.kind,x={};if(!["audio","video"].includes(M))continue;if(I.codecId){const N=p.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[M].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,p));return S=function(I,M){return M&&(I.audio.inbound.map(x=>{let N=M.audio.inbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=M.audio.outbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=M.video.inbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=M.video.outbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,_),S}let D,T={},E=[];e.WebRTCStats=class extends s{constructor(p){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 _={...p};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(p,_){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:_})}async addConnection(p){const{pc:_,peerId:f}=p;let{connectionId:S,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(_&&_ instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];if(N.pc===_)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const M=_.getConfiguration();return M.iceServers&&M.iceServers.forEach(function(x){delete x.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:p,peerConfiguration:M}}),this.monitorPeer({peerId:f,connectionId:S,pc:_,remote:I}),{connectionId:S}}getTimeline(p){return this.timeline=this.timeline.sort((_,f)=>_.timestamp.getTime()-f.timestamp.getTime()),p?this.timeline.filter(_=>_.tag===p):this.timeline}get logger(){const p=_=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(_)>-1};return{error(..._){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",..._)},warn(..._){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",..._)},info(..._){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",..._)},debug(..._){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",..._)}}}removeConnection(p){let _,{connectionId:f,pc:S}=p;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].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&&(f=M,_=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[_][f],Object.values(this.peersToMonitor[_]).length===0&&delete this.peersToMonitor[_],{connectionId:f}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let _ in this.peersToMonitor[p]){let f=this.peersToMonitor[p][_].pc;this.removePeerConnectionEventListeners(_,f)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),E.forEach(p=>{this.removeTrackEventListeners(p)}),E=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(p){let{peerId:_,connectionId:f,pc:S,remote:I}=p;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const M={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[_]){if(f in this.peersToMonitor[_])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[_][f]=M}else this.peersToMonitor[_]={[f]:M};this.addPeerConnectionEventListeners(_,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(_=>{this.emitEvent(_)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let _={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);_[p]=this.peersToMonitor[p]}else _=this.peersToMonitor;let f=[];for(const S in _)for(const I in _[S]){const M=_[S][I],x=M.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),O=x.getStats(null);if(O){const F=await O,V=this.getTimestamp(),$=A(F),Q={remote:M.options.remote},J=R(F,M.stats.parsed,Q),G={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:V-N,data:J};this.rawStats===!0&&(G.rawStats=F),this.statsObject===!0&&(G.statsObject=$),this.filteredStats===!0&&(G.filteredStats=this.filteroutStats($)),f.push(G),M.stats.parsed=J}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const _ in this.peersToMonitor[p]){const f=this.peersToMonitor[p][_].pc;this.checkIfConnectionIsClosed(p,_,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,_,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:_,tag:"connection",data:"closed"})}return S}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(_=>(p({stream:_}),_),_=>(p({error:_}),Promise.reject(_)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const _={...p};for(const S in _){var f=_[S];this.statsToMonitor.includes(f.type)||delete _[S]}return _}get peerConnectionListeners(){return{icecandidate:(p,_,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:_,data:S.candidate})},track:(p,_,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,S);const I=S.track,M=S.streams[0];p in this.peersToMonitor&&_ in this.peersToMonitor[p]&&(this.peersToMonitor[p][_].stream=M),this.addTrackEventListeners(I,_),this.emitEvent({event:"ontrack",tag:"track",peerId:p,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(x){return"stream:"+x.id})}})},signalingstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:_,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:_,data:f.iceConnectionState})},icegatheringstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:_,data:f.iceGatheringState})},icecandidateerror:(p,_,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:_,error:{errorCode:S.errorCode}})},connectionstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:_,data:f.connectionState})},negotiationneeded:(p,_,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:_})},datachannel:(p,_,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:_,data:S.channel})}}}addPeerConnectionEventListeners(p,_,f){this.logger.debug(`Adding event listeners for peer ${p} and connection ${_}.`),T[_]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[_][S]=this.peerConnectionListeners[S].bind(this,p,_,f),f.addEventListener(S,T[_][S],!1)})}parseGetUserMedia(p){try{const _={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(_.data.details=this.parseStream(p.stream),p.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(_)}catch{}}parseStream(p){const _={audio:[],video:[]};return p.getTracks().forEach(f=>{_[f.kind].push(this.getMediaTrackDetails(f))}),_}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:_=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:_}})},unmute:_=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:_}})},overconstrained:_=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:_}})},ended:_=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:_}}),this.removeTrackEventListeners(_.target)}}}addTrackEventListeners(p,_){T[p.id]={};const f=this.getTrackEventObject(_);Object.keys(f).forEach(S=>{T[p.id][S]=f[S].bind(this),p.addEventListener(S,T[p.id][S])}),T[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(S)}},1e3)}removeTrackEventListeners(p){if(p.id in T){const _=this.getTrackEventObject();Object.keys(_).forEach(f=>{p.removeEventListener(f,T[p.id][f])}),clearInterval(T[p.id].readyState),delete T[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const _={...p,timestamp:new Date};this.addToTimeline(_),_.tag&&this.emit(_.tag,_)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,_){p in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{_.removeEventListener(f,T[p][f],!1)}),delete T[p]),_.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),_.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const _=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),_.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(xs=Qh)&&xs.__esModule&&Object.prototype.hasOwnProperty.call(xs,"default")&&xs.default;var zb=Qh.WebRTCStats;function Kb(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 Yb(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 Xb extends Pi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class Jb extends Pi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class Zb extends Pi{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 Qb(t,e){const i=Di();let n=!1;const s=new zb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&U(P.StatsFrame,function({data:a}){var l,c,u,d,h,g,m,v;const{audio:b,remote:y}=a,{audio:C}=y,k=(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,R=(g=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&g!==void 0?g:-1,D=(v=(m=b.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,T=Kb({jitter:1e3*k,rtt:1e3*A,packetsLost:D,packetsReceived:R});return{jitter:k,rtt:A,mos:T,quality:Yb(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new Zb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(n)w.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new Xb(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=>B(this,void 0,void 0,function*(){const a=s.getTimeline();U(P.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 Jb(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 ef=(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:at.conferenceUpdate,call:t.calls[s],canvasInfo:ew(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Xe.LayerInfo},a);U(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Xe.LayoutInfo},a);U(P.Notification,l,t.uuid);break}}},ew=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Eh(e)},tf=["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"],tw={"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 nf(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function sf(t,e,i){const n=nf(le(t,"new-call-start"));if(n===void 0)return{mode:e,direction:i,steps:[]};const s=[];for(const a of tf){if(a==="new-call-start")continue;const l=nf(le(t,a));l!==void 0&&s.push({label:tw[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 Yr(t){for(const e of tf)try{performance.clearMarks(le(t,e))}catch{w.warn("Clearing performance marks is failed")}}class ri{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=()=>B(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 B(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 g=h[0].sender,m=g==null?void 0:g.transport;m&&(d.dtlsState=m.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(m=>{m.type==="candidate-pair"&&m.state==="succeeded"&&(d.candidatePairState=m.state,g.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(g){w.error("Error gathering connection state details:",g)}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=Pe(z0);U(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Pe(X0);U(P.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},ri.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===Ne.Offer}get isAnswer(){return this.type===Ne.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 B(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 Ht&&U(P.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":U(P.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&&Es(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=sf(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 g="";for(let m=0;m<h.length;m++)g+="-";w.info(`${l} Call establishment timing breakdown:`),w.info(`${l} ${h}`),w.info(`${l} ${g}`),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} ${g}`)}(n),Yr(this.options.id)}createPeerConnection(){return B(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:Ne.Offer}),performance.mark(le(this.options.id,"set-remote-description")),!this.instance))throw ae(Mr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>B(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),U(P.Error,{error:ae(Li(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(()=>B(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(Mr);if(!this.options.localStream&&!i)throw ae(n?Li(n):Lr,n??void 0);performance.mark(le(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Tn(this.options.localStream)&&(w.info("Muting local audio tracks on start"),As(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=Pe(Y0);U(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Pe(K0);U(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ri.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return B(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ae(Mr);this.isDebugEnabled&&(this.statsReporter=Qb(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(Tn(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}=Zh(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&&Es(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}=Zh(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 B(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 Ht?e:ae(R0,e)}}})}_setRemoteDescription(e){return B(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(ch,i)}})}_createAnswer(){return B(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:Ne.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 Ht?e:ae(A0,e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw w.error("Peer _setLocalDescription error:",i),ae(x0,i)}})}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(Tn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,B(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 Rs(s,a,Ct.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield Rs(r,l,Ct.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return Is(e)})}_isOffer(){return this.type===Ne.Offer}_isAnswer(){return this.type===Ne.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 B(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 B(this,void 0,void 0,function*(){Yr(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)})}}ri.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ri.ICE_RESTART_TIMEOUT_MS=15e3;const Ds=Wr;class of{constructor(e,i){var n;this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=$r.Participant,this.extension=null,this._state=W.New,this._prevState=W.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._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(k=>{if(k.callback){if(k.constraints){for(const A in k.constraints)if(k.constraints.hasOwnProperty(A)&&k.constraints[A]!==C[A])return}k.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:u,remoteElement:d,options:h,mediaConstraints:{audio:g,video:m},ringtoneFile:v,ringbackFile:b}=e;this.options=Object.assign({},Oh,{audio:g,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:Oh.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=Yh(this.options.ringtoneFile,"_ringtone"),this._ringback=Yh(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 B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=St.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(le(this.id,"new-peer")),this.peer=new ri(Ne.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 Ht?e:ae(gh,e instanceof Error?e:void 0);return U(P.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 B(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=Pe(Z0);return U(P.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=St.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 ri(Ne.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 Ht?d:ae(gh,d instanceof Error?d:void 0);return U(P.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(){Xh(this._ringtone)}stopRingtone(){Jh(this._ringtone)}playRingback(){Xh(this._ringback)}stopRingback(){Jh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return B(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,g=this._captureHangupCallerStack(),m=c.initiator||"app:call.hangup",v=this._state<W.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:g}),c.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new Ob({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 k=ae(M0,C);U(P.Error,{error:k,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(W.Destroy)})}hold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new Wh({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 Wh({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,As(this.options.localStream)}unmuteAudio(){w.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Kr(this.options.localStream)}_applyDesiredAudioMuteState(){w.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?As(this.options.localStream):Kr(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 B(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 U(P.Warning,{warning:Pe(eb),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:Gr(l.track),localTracks:Kh(this.options.localStream)});try{c=yield ks({audio:{deviceId:{exact:e}}})}catch(h){const g=ae(Li(h),h);return void U(P.MediaError,g,((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 g=ae(Li(h),h);return U(P.MediaError,g,((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:Gr(l.track),localTracks:Kh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Fi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Fi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Fi(e,"video",null)}setVideoDevice(e){return B(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 ks({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Es(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(){As(this.options.remoteStream)}undeaf(){Kr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Fi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return B(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[W.Hangup,W.Destroy,W.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=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:at.callUpdate,call:this}),e){case W.Purge:w.info(`[${this.id}] Entering Purge state.`);break;case W.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&&qh(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 qb,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case ee.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>=W.Active)return;this._state>=W.Early&&this.setState(W.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case ee.Media:if(performance.mark(le(this.id,"telnyx-rtc-media")),this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case ee.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===St.Inbound?St.Outbound:St.Inbound,c={type:at[i],call:this,displayName:o,displayNumber:r,displayDirection:l};U(P.Notification,c,this.id)||U(P.Notification,c,this.session.uuid);break}case ee.Candidate:this._addIceCandidate(n);break;case ee.Info:case ee.Event:{const o=Object.assign(Object.assign({},n),{type:at.generic,call:this});U(P.Notification,o,this.id)||U(P.Notification,o,this.session.uuid);break}case ee.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 ee.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 B(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:Xe.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const g=[];for(const m in s)g.push(Object.assign({callId:s[m][0],index:Number(m)},_s(s[m][1])));this._dispatchConferenceUpdate({action:Xe.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Xe.Add,callId:o,index:r},_s(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Xe.Modify,callId:o,index:r},_s(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Xe.Delete,callId:o,index:r},_s(s)));break;case"clear":this._dispatchConferenceUpdate({action:Xe.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 B(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:Xe.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)});qr(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 B(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,ef(this.session,o)):w.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfInfo subscription error:",s)});qr(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(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){w.error(`Failed to ${e.action} on call ${this.id}`);const i=ae(D0,e);return U(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Ts(Object.assign(Object.assign({sessid:this.session.sessionid,action:Mi.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=>B(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(V0,i);U(P.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 B(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Ne.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(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>B(this,void 0,void 0,function*(){w.error("Call setRemoteDescription Error: ",n);const s=ae(ch,n);U(P.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=Pe(J0);w.warn(`[${this.id}] Warning ${i.code}: ${i.message}`),U(P.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-${Ds}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Ne.Offer:this.setState(W.Requesting),a=new $h(l);break;case Ne.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new Hh(l):new jh(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===Ne.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>B(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${r} error:`,c);const u=ae(dh,c);U(P.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-${Ds}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Ne.Offer:this.setState(W.Requesting),o=new $h(r);break;case Ne.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new Hh(r):new jh(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===Ne.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>B(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${s} error:`,a);const l=ae(dh,a);U(P.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 Pb({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 Nb({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&&Es(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:at.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),w.error(`Media error (${i}): ${n}`,e),U(P.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:at.peerConnectionFailureError,error:e.error}),w.error("Peer connection failure error"),e.warning&&U(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:at.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:at.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(U(P.Notification,e,this.id,!1)||U(P.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=Pe(ib);return U(P.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:g,onNotification:m,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var y;this.options.id=d?d.toString():Di(),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||{}),g||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Wt(P.MediaError,this._onMediaError,this.id),Wt(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Wt(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),ys(m)&&Wt(P.Notification,m.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",D=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new ce({enabled:!0,interval:k,intermediateReportInterval:A},{enabled:!0,level:R,maxEntries:D}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,p,_,f;U(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===Pr&&this._state!==W.Held?(p=(E=this.session).reportNoRtp)===null||p===void 0||p.call(E,this.id,"inbound"):T.code===vh&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(_=this.session).reportNoRtp)===null||f===void 0||f.call(_,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const T={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:Mh,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 $e(T,E);const p=(l=this.session.connection)===null||l===void 0?void 0:l.host;p&&this._callRecorder._setHost(p),this._callRecorder.onWarning=_=>{U(P.Warning,{warning:_,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.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 sf(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(),Yr(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;kn(s),kn(o),Gh(r,s),Gh(a,o),Tt(P.MediaError,null,this.id),Tt(P.PeerConnectionFailureError,null,this.id),Tt(P.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 g=this.session.options,m=g.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:g.env,host:g.host,project:g.project,region:(e=this.session.region)!==null&&e!==void 0?e:g.region,dc:this.session.dc,rtcIp:g.rtcIp,rtcPort:g.rtcPort,autoReconnect:(i=g.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=g.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=g.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:g.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=g.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=g.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=g.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:g.enableCallReports!==!1,intervalMs:g.callReportInterval||5e3,flushIntervalMs:(h=g.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:g.debugLogLevel||"debug",debugLogMaxEntries:g.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===St.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ds,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 B(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===St.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ds,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")}}of.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ai extends of{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Wb(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 Gb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return B(this,void 0,void 0,function*(){this.screenShare instanceof ai&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return B(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",()=>B(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 ai(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return B(this,void 0,void 0,function*(){this.screenShare instanceof ai&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&qh(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(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+=`
117
117
  ${r.type}
118
118
  `,Object.keys(r).forEach(a=>{o.includes(a)||(n+=` ${a}: ${r[a]}
119
- `)}))}),y.info(n)}),2e3)}}class Ss extends ti{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=>Ss.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=Ne(c0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};V(P.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),y.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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){y.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return B(this,void 0,void 0,function*(){try{const n=yield vs({audio:e,video:i});return vn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){y.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(W.Purge),y.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 B(this,void 0,void 0,function*(){y.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(W.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(lh(P.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 _n().catch(e=>{const i=re(Ii(e),e);return V(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return _n(yt.Video).catch(e=>(V(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return _n(yt.AudioIn).catch(e=>{const i=re(Ii(e),e);return V(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return _n(yt.AudioOut).catch(e=>(y.error("getAudioOutDevices",e),V(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return _s(e,i,n)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(i=>B(void 0,void 0,void 0,function*(){const n=[],s=yield vs({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<yh.length;r++){const[a,l]=yh[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 vn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(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=Mu(e,["micId","micLabel"]);return J0(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield _s(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?C0:S0}}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=hn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=hn(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 q0({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 B(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new z0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Mr(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 B(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new K0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Mr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ni.setStateTelnyx(e)}}Ss.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class xh{constructor(e,i){this.code=i,this.message=e}}class ub{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new j0(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:g,params:v={},voice_sdk_id:_}=e,S=v==null?void 0:v.callID,b=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,k=d.calls[S],A=(i=k==null?void 0:k.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),R=new Set(Object.keys(d.calls));if(Array.isArray(v==null?void 0:v.reattached_sessions)&&R.size){y.debug(`Reattach: active call IDs before cleanup check: [${Array.from(R).join(", ")}].`);const p=v.reattached_sessions.length===0,m=v.reattached_sessions.some(f=>R.has(f));if(p||!m)for(const f of Object.keys(d.calls)){const w=d.calls[f];y.debug(`Session not reattached — terminating active call ${f} `);const I=re($u);V(P.Error,{error:I,callId:f,sessionId:d.sessionid},d.uuid),w.hangup({},!1)}}if(Array.isArray(v==null?void 0:v.reattached_sessions)&&d.sessionid){const p=sh();if(p&&p.calls.length>0)if(p.sessionId!==d.sessionid)y.debug(`Recovery markers were saved for a different sessid (saved=${p.sessionId}, current=${d.sessionid}) — ignoring all.`),ei();else{const m=new Set(v.reattached_sessions),f=[];for(const w of p.calls)try{if(m.has(w.id)){y.debug(`Recovery marker for call ${w.id} was reattached — keeping for Attach element restore.`),f.push(w);continue}y.info(`Recovery marker for call ${w.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=re($u);V(P.Error,{error:I,callId:w.id,sessionId:d.sessionid,customHeaders:w.customHeaders},d.uuid)}catch(I){y.debug(`Recovery marker for a saved call failed to process (callId=${w==null?void 0:w.id}) — skipping: ${I instanceof Error?I.message:String(I)}`),f.push(w)}oh(f,p.sessionId,p.storedAt)}}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const D=({recoveredCallId:p,forceRelayCandidateForRecovery:m,mutedMicOnStart:f,remoteElement:w,localElement:I,wasHeldBeforeRecovery:x}={})=>{var O,N,M,F,G,j;const J={audio:!0,video:d.options.video,remoteSdp:v.sdp,destinationNumber:v.callee_id_number,remoteCallerName:v.caller_id_name,remoteCallerNumber:v.caller_id_number,callerName:v.callee_id_name,callerNumber:v.callee_id_number,attach:g===Q.Attach,mediaSettings:v.mediaSettings,debug:(O=d.options.debug)!==null&&O!==void 0&&O,debugOutput:(N=d.options.debugOutput)!==null&&N!==void 0?N:"socket",trickleIce:(M=d.options.trickleIce)!==null&&M!==void 0&&M,prefetchIceCandidates:(F=d.options.prefetchIceCandidates)===null||F===void 0||F,forceRelayCandidate:typeof m=="boolean"?m:(G=d.options.forceRelayCandidate)!==null&&G!==void 0&&G,keepConnectionAliveOnSocketClose:(j=d.options.keepConnectionAliveOnSocketClose)!==null&&j!==void 0&&j,mutedMicOnStart:f??d.options.mutedMicOnStart};S&&(J.id=S),v.telnyx_call_control_id&&(J.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(J.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(J.telnyxLegId=v.telnyx_leg_id),v.client_state&&(J.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(J.customHeaders=v.dialogParams.custom_headers),p&&(J.recoveredCallId=p),x&&(J.wasHeldBeforeRecovery=x),w!==void 0&&(J.remoteElement=w),I!==void 0&&(J.localElement=I),performance.mark(ae(J.id,"new-call-start"));const Y=new ni(d,J);return Y.nodeId=this.nodeId,Y},C=new uh(_),E=new xr(_);switch(g){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!S||!k)return void y.error(`Received ${g} for non existing call:`,v);k.handleMessage(e),this._ack(h,g);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(E);break;case Q.Punt:d.options.keepConnectionAliveOnSocketClose&&A?(y.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(h,g)):(y.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case Q.Invite:{const f=D();f.direction=_t.Inbound,f.playRingtone(),f.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(f.id),this._ack(h,g);break}case Q.Attach:{const f=k||null;if(Object.keys(d.calls).length===0){let w,I;y.warn(`[${new Date().toISOString()}][${S}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${S}`);let x=!1,O=!1;const N=sh();if(N&&N.sessionId===d.sessionid){const F=N.calls.find(G=>G!==null&&typeof G=="object"&&G.id===S);F&&(w=F.remoteElement,I=F.localElement,x=F.wasHeld===!0,typeof F.forceRelayCandidate=="boolean"&&(O=F.forceRelayCandidate),(w||I)&&y.info(`[${S}] Attach: restoring per-call media elements from recovery marker (remoteElement=${w??"<none>"}, localElement=${I??"<none>"}).`),typeof F.forceRelayCandidate=="boolean"&&y.info(`[${S}] Attach: restoring forceRelayCandidate=${F.forceRelayCandidate} from recovery marker.`))}const M=D({recoveredCallId:S,forceRelayCandidateForRecovery:O,remoteElement:w,localElement:I,wasHeldBeforeRecovery:x});M.answer(),this.session.emitMultipleActiveCallsWarning(M.id),this._ack(h,g);break}if(f){const w=f.id,I=f.state==="held",x=f.shouldForceRelayCandidateForRecovery();x&&y.warn(`[${new Date().toISOString()}][${S}] Attach: forcing relay candidate for recovery`),y.info(`[${new Date().toISOString()}][${S}] Attach: recovering active call ${w}.`),f.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const O=D({recoveredCallId:w,forceRelayCandidateForRecovery:x,mutedMicOnStart:f.isAudioMuted,remoteElement:f.options.remoteElement,localElement:f.options.localElement,wasHeldBeforeRecovery:I});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,g);break}y.warn(`Attach: callID ${S} does not match any active calls. `),V(P.Warning,{warning:Ne(f0),callId:S,params:v,sessionId:d.sessionid},d.uuid),this._ack(h,g);break}case Q.Event:case"webrtc.event":if(!b)return void y.error("Verto received an unknown event:",v);const p=d.relayProtocol,m=b.split(".")[0];d._existsSubscription(p,b)?V(p,v,b):b===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(p,m)?V(p,v,m):d.calls.hasOwnProperty(b)?d.calls[b].handleMessage(e):V(P.Notification,v,d.uuid);break;case Q.Info:v.type=st.generic,V(P.Notification,v,d.uuid);break;case Q.ClientReady:this.session.execute(C);break;case"ai_conversation":V(P.AIConversationMessage,{method:"ai_conversation",params:v,voice_sdk_id:_},d.uuid);break;default:{const f=Tr(e);if(f){switch(f){case Oe.REGISTER:case Oe.REGED:if(!this.isDuplicateGatewayState(f,[Oe.REGED,Oe.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,f===Oe.REGED&&this.session.resetReconnectAttempts();const w=(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;w&&(d.callReportId=w,y.debug("Captured call_report_id from REGED:",w));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 x=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;x&&(d.region=x),y.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),v.type=st.vertoClientReady,V(P.Ready,v,d.uuid)}break;case Oe.UNREGED:case Oe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const w=new xh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=re(Uu,w);V(P.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(C)},this.reconnectDelay());break;case Oe.FAILED:case Oe.FAIL_WAIT:case Oe.TIMEOUT:if(!this.isDuplicateGatewayState(f,[Oe.FAILED,Oe.FAIL_WAIT,Oe.TIMEOUT])){const w=re(Gy,new Error(`Gateway state: ${f}`));if(V(P.Error,{error:w,sessionId:d.sessionid},d.uuid),d.options.skipLastVoiceSdkId=!0,y.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 xh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const x=re(wr,I);V(P.Error,{error:x,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const I=re(wr,new Error("Connection Retry Failed"));V(P.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(y.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(I=>{var x;return((x=I.peer)===null||x===void 0?void 0:x.instance)&&!I.signalingStateClosed}))return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();y.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:y.warn("GatewayState message unknown method:",e)}break}y.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&y.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 B(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 g=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},v={nodeId:this.nodeId,channels:[o],handler:({data:S})=>{const b=h||this._retrieveCallId(S,o);if(b&&i.calls.hasOwnProperty(b)){const T=i.calls[b];T._addChannel(o),T.extension=r,T.handleConferenceUpdate(S,e).then(k=>{k==="INVALID_PACKET"&&g()})}}},_=yield i.vertoSubscribe(v).catch(S=>{y.error("liveArray subscription error:",S);const b=re(jy,S);V(P.Error,{error:b,sessionId:i.sessionid},i.uuid)});Or(_,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&i._existsSubscription(n,o)){const{callId:_=null}=i.subscriptions[n][o];if(g=i.calls[_]||null,_!==null){const S={type:st.conferenceUpdate,action:Ye.Leave,conferenceName:r,participantId:Number(u),role:d};V(P.Notification,S,_,!1)||V(P.Notification,S,i.uuid),g===null&&bt(P.Notification,null,_)}}const v=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:_=[]})=>{g&&(g.channels=g.channels.filter(S=>!_.includes(S)))}).catch(_=>{y.error("liveArray unsubscribe error:",_)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":kh(this.session,e);break;case"logo-info":{const i={type:st.conferenceUpdate,action:Ye.LogoInfo,logo:e.logoURL};V(P.Notification,i,this.session.uuid);break}}}}class hb extends Ss{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new ub(this),window.addEventListener("beforeunload",i=>{if(y.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return nh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(y.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{y.debug(`beforeunload: flushing call report for ${s.id}.`),s.flushIntermediateCallReport({type:"page-unload"})}catch(o){y.debug(`beforeunload: failed to flush call report for ${s.id}: ${o instanceof Error?o.message:String(o)}`)}}),!this.sessionid||n.length===0)return y.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void ei();y.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),oh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];y.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()&&(y.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Ir(this.sessionid))})}validateOptions(){return ds(this.options)||fn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw re(Uy,void 0,"Error: destinationNumber is required");const i=new ni(this,e);return e.id||y.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(ae(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!!fn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return B(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),ds(this.options)?this.handleLoginOnSocketOpen():fn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class fb extends hb{constructor(e){super(e),y.info(`SDK version: ${hh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Z0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ee.not_supported},{browserName:"Firefox",supported:Ee.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",features:["audio"],supported:Ee.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",features:["audio"],supported:Ee.partial}]}]}}function pb(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 Lh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Dh={exports:{}},Oh;function gb(){return Oh||(Oh=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 g=new s(u,d||l,h),v=i?i+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],g]:l._events[v].push(g):(l._events[v]=g,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,g=new Array(h);d<h;d++)g[d]=u[d].fn;return g},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,g){var v=i?i+l:l;if(!this._events[v])return!1;var _=this._events[v],S=arguments.length,b,T;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),S){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,c),!0;case 3:return _.fn.call(_.context,c,u),!0;case 4:return _.fn.call(_.context,c,u,d),!0;case 5:return _.fn.call(_.context,c,u,d,h),!0;case 6:return _.fn.call(_.context,c,u,d,h,g),!0}for(T=1,b=new Array(S-1);T<S;T++)b[T-1]=arguments[T];_.fn.apply(_.context,b)}else{var k=_.length,A;for(T=0;T<k;T++)switch(_[T].once&&this.removeListener(l,_[T].fn,void 0,!0),S){case 1:_[T].fn.call(_[T].context);break;case 2:_[T].fn.call(_[T].context,c);break;case 3:_[T].fn.call(_[T].context,c,u);break;case 4:_[T].fn.call(_[T].context,c,u,d);break;default:if(!b)for(A=1,b=new Array(S-1);A<S;A++)b[A-1]=arguments[A];_[T].fn.apply(_[T].context,b)}}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 g=this._events[h];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&r(this,h);else{for(var v=0,_=[],S=g.length;v<S;v++)(g[v].fn!==c||d&&!g[v].once||u&&g[v].context!==u)&&_.push(g[v]);_.length?this._events[h]=_.length===1?_[0]:_: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}(Dh)),Dh.exports}var mb=gb();const Fr=Lh(mb),Br=new Fr;var Vr={exports:{}},vb=Vr.exports,Mh;function _b(){return Mh||(Mh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(vb,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(_,S){var b=_[S];if(typeof b.bind=="function")return b.bind(_);try{return Function.prototype.bind.call(b,_)}catch{return function(){return Function.prototype.apply.apply(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(_){return _==="debug"&&(_="log"),typeof console===i?!1:_==="trace"&&n?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),S=0;S<s.length;S++){var b=s[S];this[b]=S<_?e:this.methodFactory(b,_,this.name)}if(this.log=this.debug,typeof console===i&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==i&&(u.call(this),this[_].apply(this,arguments))}}function h(_,S,b){return c(_)||d.apply(this,arguments)}function g(_,S){var b=this,T,k,A,R="loglevel";typeof _=="string"?R+=":"+_:typeof _=="symbol"&&(R=void 0);function D(f){var w=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=w;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+w+";"}catch{}}}function C(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var w=window.document.cookie,I=encodeURIComponent(R),x=w.indexOf(I+"=");x!==-1&&(f=/^([^;]+)/.exec(w.slice(x+I.length+1))[1])}catch{}return b.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var w=f;if(typeof w=="string"&&b.levels[w.toUpperCase()]!==void 0&&(w=b.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=b.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+f)}b.name=_,b.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},b.methodFactory=S||h,b.getLevel=function(){return A??k??T},b.setLevel=function(f,w){return A=p(f),w!==!1&&D(A),u.call(b)},b.setDefaultLevel=function(f){k=p(f),C()||b.setLevel(f,!1)},b.resetLevel=function(){A=null,E(),u.call(b)},b.enableAll=function(f){b.setLevel(b.levels.TRACE,f)},b.disableAll=function(f){b.setLevel(b.levels.SILENT,f)},b.rebuild=function(){if(r!==b&&(T=p(r.getLevel())),u.call(b),r===b)for(var f in o)o[f].rebuild()},T=p(r?r.getLevel():"WARN");var m=C();m!=null&&(A=p(m)),u.call(b)}r=new g,r.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var S=o[_];return S||(S=o[_]=new g(_,r.methodFactory)),S};var v=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=v),r},r.getLoggers=function(){return o},r.default=r,r})}(Vr)),Vr.exports}var yb=_b();const bb=Lh(yb),wb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=bb.getLogger("telnyx-ai-agent"),Sb=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=Sb(t,e,i);return function(...s){n(wb(),"-",...s)}},fe.setLevel("info");function Cb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Tb=10,Eb=500,kb=100,Ib=300,Ph=20;class Rb{constructor(e){$(this,"remoteIntervalId",null);$(this,"localIntervalId",null);$(this,"remoteStream",null);$(this,"localStream",null);$(this,"remoteAudioContext",null);$(this,"remoteSource",null);$(this,"remoteAnalyser",null);$(this,"localAudioContext",null);$(this,"localSource",null);$(this,"localAnalyser",null);$(this,"thinkingStartTime",null);$(this,"lastState",null);$(this,"userIsSpeaking",!1);$(this,"lastUserAudioTime",null);$(this,"userSpeechStartTime",null);$(this,"remoteSilenceStartTime",null);$(this,"remoteSilenceThresholdMs");$(this,"userSilenceStartTime",null);$(this,"isFirstAgentSpeech",!0);$(this,"monitorStartTime",null);$(this,"volumeThreshold");$(this,"silenceDurationMs");$(this,"minSpeechDurationMs");$(this,"maxLatencyMs");$(this,"updateAgentState",Cb(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Br.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Tb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Eb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??kb,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??Ib}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){fe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,fe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(fe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;fe.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&&fe.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,Ph)}startLocalMonitor(){if(!this.localStream){fe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,fe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(fe.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&&fe.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,Ph)}destroy(){this.stopAudioStreamMonitor()}}function Ab(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function xb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Lb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Cs(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Db(t){if(!Cs(t))return null;const e=t.params;return pb(e)?e.item:null}function Ob(t){if(!Cs(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 Mb(t){if(!Cs(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 Pb(t){var e;return Cs(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function Nb(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 Fb=3e4;function Bb(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 Ur(t){return JSON.stringify({error:t})}class Vb{constructor(e){$(this,"registry",new Map);$(this,"toolTimeouts",new Map);$(this,"inFlight",new Set);$(this,"completed",new Set);$(this,"generation",0);$(this,"getActiveCall");$(this,"timeoutMs");$(this,"events");$(this,"handleEvent",e=>{const i=Ob(e);if(i){this.ingestToolSettings(i);return}const n=Db(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Fb,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){fe.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)){fe.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){fe.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,Ur("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{fe.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,Ur("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,Bb(u),!1,s,o)}catch(u){const d=u instanceof Nh?"timeout":"handler_error";fe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,Ur(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 Nh(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){fe.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){fe.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){fe.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){fe.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 Nh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Es=class Es{constructor(e){$(this,"enabled");$(this,"getActiveCall");$(this,"events");$(this,"subscriptionConfirmed",!1);$(this,"subscribeAttempts",0);$(this,"handleEvent",e=>{if(!this.enabled)return;if(Pb(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Mb(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Ub(i.delta)}catch(s){fe.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>=Es.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){fe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){fe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}};$(Es,"MAX_SUBSCRIBE_ATTEMPTS",10);let $r=Es;function Ub(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function $b(t){return xb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function jb(t){if(!Lb(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 Hb extends Fr{constructor(i){super();$(this,"telnyxRTC");$(this,"transcript",[]);$(this,"onSocketMessage",i=>{if(Ab(i))switch(i.params.type){case"response.text.delta":{const n=$b(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Nb(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=jb(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)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage)}}const Dt=t=>typeof t=="object"&&t!==null,Fh=t=>{const e=Dt(t)&&Dt(t.result)?t.result:t;if(!(!Dt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Wb=t=>Dt(t)&&Dt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Gb=(t,e)=>{if(!e||!Dt(t)||!Dt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Dt(i.params))return;const n=i.params;Dt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class qb extends Fr{constructor(i){super();$(this,"telnyxRTC");$(this,"transcription");$(this,"removeLoginSuccessHook",null);$(this,"authenticated",!1);$(this,"authenticating",!1);$(this,"agentId");$(this,"versionId");$(this,"widgetVersion");$(this,"conversationId");$(this,"debug");$(this,"audioStreamMonitor");$(this,"clientTools");$(this,"streamingAudio");$(this,"activeCall");$(this,"chatMode");$(this,"dc",null);$(this,"region",null);$(this,"callReportId",null);$(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)});$(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});$(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});$(this,"onSocketMessage",i=>{const n=Fh(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});$(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()))});$(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});$(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,fe.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 fb({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(P.Ready,this.onClientReady),this.telnyxRTC.on(P.Error,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketClose,this.onSocketClose),this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(P.Notification,this.onNotification),this.transcription=new Hb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Br.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Rb(i.vad),this.clientTools=new Vb({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(P.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new $r({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(P.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(P.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(P.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(P.Ready,this.onClientReady),this.telnyxRTC.off(P.Error,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketClose,this.onSocketClose),this.telnyxRTC.off(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(P.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(),Br.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){fe.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 fe.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 fe.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=g=>{c===g&&(this.authenticating=!1)},d=function(g){const v=Wb(g),_=c;return v&&Gb(g,a),n.call(this,g).then(S=>{const b=v?Fh(S):void 0;return l&&b!==void 0&&(u(_),r({sessionId:b})),S})},h=function(g){const v=++c;if(l){const _={sessionId:i.sessionid||null};o(_)}return s.call(this,g).finally(()=>{l&&i.login===h&&u(v)})};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}))}}var Bh={exports:{}},yn={},Vh;function zb(){if(Vh)return yn;Vh=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 yn.Fragment=e,yn.jsx=i,yn.jsxs=i,yn}var Uh;function Kb(){return Uh||(Uh=1,Bh.exports=zb()),Bh.exports}Kb(),kt(void 0),kt(null);const Yb=(t,e,i,n,s,o,r,a,l,c)=>new qb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Ts=10,$h=5e3,Xb=[46001,46003],Jb=["login incorrect","authentication required","authentication failed"];function jh(t){var n;const e=t.code;if(e&&Xb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Jb.some(s=>i.includes(s))}const Zb=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[g,v]=Ae(!1),[_,S]=Ae(null),[b,T]=Ae(!1),k=ue(0),A=ue(null),R=ue(null),D=ue(!1),C=ue(!1),E=ue(0),p=ue(0),m=Ge(()=>{A.current&&(clearTimeout(A.current),A.current=null)},[]),f=Ge(()=>{m(),k.current=0,C.current=!0,T(!1),S(null)},[m]),w=Ge(()=>{m(),T(!1)},[m]),I=Ge(x=>{if(m(),k.current>=Ts){oe.error(`Max login retry attempts (${Ts}) exceeded`),T(!1);return}k.current+=1;const O=E.current,N=p.current;oe.info(`Scheduling login retry attempt ${k.current}/${Ts} in ${$h}ms due to: ${x}`),T(!0),A.current=window.setTimeout(()=>{var G;A.current=null;const M=R.current,F=M==null?void 0:M.telnyxRTC;if(E.current!==O||p.current!==N||M!=null&&M.isAuthenticating){oe.info("Skipping login retry because a newer socket/login is already in progress"),w();return}if(D.current||C.current||M!=null&&M.isAuthenticated){oe.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(oe.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(G=F==null?void 0:F.socketDisconnect)==null||G.call(F))},$h)},[m,w,f]);return xe(()=>{if(!t)return;const x=Yb(t,e,i,n,s,o,r,a,l,u);D.current=!1,C.current=!1,v(!1),S(null),T(!1),R.current=x;const O=()=>{oe.info("Agent connected successfully"),D.current=!0,v(!0),f()},N=()=>{oe.info("Agent disconnected"),D.current=!1,C.current=!1,v(!1)},M=H=>{if(oe.error("AI Agent error:",H),jh(H)){if(D.current||C.current){oe.debug("Ignoring retryable error — login already succeeded");return}k.current<Ts?(S(null),I(H.message)):(S(H),T(!1))}else S(H),T(!1)},F=x.telnyxRTC??null,G=()=>{p.current+=1,C.current=!1},j=()=>{oe.info("Login succeeded; clearing pending login retry flow"),f()},J=()=>{E.current+=1,C.current=!1},Y=()=>{C.current=!1};return x.on("agent.connected",O),x.on("agent.disconnected",N),x.on("agent.error",M),x.on("agent.login.started",G),x.on("agent.login.success",j),F&&typeof F=="object"&&(F.on(P.SocketOpen,J),F.on(P.SocketClose,Y)),x.connect(),h(x),()=>{m(),x.off("agent.connected",O),x.off("agent.disconnected",N),x.off("agent.error",M),x.off("agent.login.started",G),x.off("agent.login.success",j),F&&typeof F=="object"&&(F.off(P.SocketOpen,J),F.off(P.SocketClose,Y)),x.disconnect(),D.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:g,error:_,isReconnecting:b}},Qb="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",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"};function ew(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 Hh(){const t=document.querySelector(Qb);return t instanceof HTMLElement?t:null}function wt(t,e,i){const n=i||Hh();if(!n){oe.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),oe.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const tw=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=On(yu);xe(()=>{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??Hh()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const D=t.telnyxRTC,C={dc:(D==null?void 0:D.dc)??null,region:(D==null?void 0:D.region)??null,callReportId:(D==null?void 0:D.callReportId)??null};l(C),wt(Xe.AGENT_CONNECTED,C,c)},d=()=>{l(null),wt(Xe.AGENT_DISCONNECTED,void 0,c)},h=R=>{const D={message:R.message,name:R.name};if(jh(R)){oe.debug("Ignoring retryable agent.error in widget event layer"),wt(Xe.AGENT_ERROR,D,c);return}o(R),wt(Xe.AGENT_ERROR,D,c)},g=R=>{var D;s(R),wt(Xe.CONVERSATION_UPDATE,{type:R.type,callState:(D=R.call)==null?void 0:D.state},c)},v=R=>{wt(Xe.TRANSCRIPT_ITEM,R,c)},_=R=>{wt(Xe.CONVERSATION_AGENT_STATE,R,c)},S=R=>{wt(Xe.AGENT_AUDIO_MUTE,{muted:R},c)},T=t.telnyxRTC,k=R=>{r(R);const D=ew(R);D&&wt(Xe.CLIENT_TOOLS_CONFIGURED,{tools:D},c)},A=R=>{const D=R,C={code:D==null?void 0:D.code,reason:D==null?void 0:D.reason,wasClean:D==null?void 0:D.wasClean,timestamp:new Date().toISOString()};oe.info("[socket.close]",C),wt(Xe.SOCKET_CLOSE,C,c)};return T&&typeof T=="object"&&(T.on(P.SocketMessage,k),T.on(P.SocketClose,A)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",g),t.on("transcript.item",v),t.on("conversation.agent.state",_),t.on("agent.audio.mute",S),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",g),t.off("transcript.item",v),t.off("conversation.agent.state",_),t.off("agent.audio.mute",S),T&&typeof T=="object"&&(T.off(P.SocketMessage,k),T.off(P.SocketClose,A))}},[t,n,s,o,r,l])},iw=2e3;async function nw(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Wh(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 sw=(t,e)=>{const[i,n]=Ae([]),[,s]=ur(),o=ue(e);xe(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return xe(()=>{if(!t)return;const c=h=>{n(g=>{const v=g[g.length-1];if(h.role==="assistant"&&v&&Wh(v.id)===Wh(h.id)&&v.role==="assistant"){const _=o.current.showUserPerceivedLatency&&r.current!==void 0&&v.userPerceivedLatencyMs===void 0,S=o.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,b={...v,content:v.content+h.content,timestamp:h.timestamp,..._&&{userPerceivedLatencyMs:r.current},...S&&{greetingLatencyMs:a.current}};return _&&(r.current=void 0),S&&(a.current=void 0),[...g.slice(0,-1),b]}if(h.role==="assistant"){s(b=>b==="thinking"||b==="processing_image"?"speaking":b);const _=o.current.showUserPerceivedLatency&&r.current!==void 0,S=o.current.showGreetingLatency&&a.current!==void 0;if(_||S){const b={...h,..._&&{userPerceivedLatencyMs:r.current},...S&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,b]}r.current=void 0,a.current=void 0}if(h.role==="user"){const _=g.findIndex(b=>b.id===h.id);if(_!==-1){const b=[...g];return b[_]={...g[_],content:h.content,timestamp:h.timestamp,attachments:h.attachments},b}if(v&&v.role==="user"&&h.timestamp.getTime()-v.timestamp.getTime()<iw){const T={...v,id:h.id,content:v.content+" "+h.content,timestamp:h.timestamp,attachments:[...v.attachments||[],...h.attachments||[]]};return[...g.slice(0,-1),T]}const S=h.attachments&&h.attachments.length>0;s(S?"processing_image":"thinking")}return[...g,h]})},u=({state:h,userPerceivedLatencyMs:g,greetingLatencyMs:v,thinkingStartedAt:_})=>{(g!==void 0||v!==void 0)&&oe.info(`[AgentState] state=${h} userPerceivedLatencyMs=${g} greetingLatencyMs=${v} thinkingStartedAt=${_}`),h==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),v!==void 0&&(a.current=v)):h==="listening"&&s(S=>S==="processing_image"||S==="thinking"?S:"listening")},d=h=>{var v;const g=(v=h.call)==null?void 0:v.state;(g==="destroy"||g==="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 g=await nw(h);d.push(g)}catch(g){throw oe.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},Oi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class ow{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),oe.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&&(oe.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(Oi.INVOKED,this.boundInvoked),e.on(Oi.COMPLETED,this.boundCompleted),e.on(Oi.ERROR,this.boundError),this.handlers.size>0&&oe.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Oi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Oi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Oi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function jr(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const rw=(t,e)=>{const i=ue(null);i.current===null&&(i.current=new ow),Vs(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){oe.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]),xe(()=>{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=>{jr(s(),Xe.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{jr(s(),Xe.CLIENT_TOOL_COMPLETED,o)},onError:o=>{jr(s(),Xe.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},aw=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=Qt(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=sw(e,i),d=ue(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(g=>{g.enabled=!1,oe.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[n,t]),r){case"collapsed":return L(Iu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return L(Ay,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return L(Iu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Hr=()=>L(Si.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:L("div",{className:"rounded-full animate-spin",children:L(Q_,{})})}),lw=({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 L(Hr,{});case"done":case"purged":case"destroy":return null;case"active":return L(aw,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return L(Hr,{})}},cw=({className:t})=>L("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:[L("g",{clipPath:"url(#:R5lfm:)",children:[L("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"}),L("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"}),L("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"}),L("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"}),L("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"})]}),L("defs",{children:L("clipPath",{id:":R5lfm:",children:L("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Gh(){const t=Qt();return t.logo_icon_url?L("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:L("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):L(cw,{className:"w-8 h-8 mr-2"})}const dw=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=ue(!1),r=Ge(async()=>{if(!t){oe.error("Client is not initialized.");return}if(!n){oe.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){oe.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,oe.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?L(Si.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:[L(Gh,{}),"Connecting..."]}):L(Si.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:[L(Gh,{}),s.start_call_text]})},uw='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-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-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}.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}.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-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-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-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}.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-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-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)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.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-\\[\\#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-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)}}.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-\\[\\#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-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',hw=({children:t})=>L("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:L("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),fw={duration:.1,ease:"circOut"},pw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?L(hw,{children:t}):t;return L("div",{ref:i,className:At(n.theme==="dark"&&"dark"),children:L(Wg,{transition:fw,children:[L("style",{children:uw}),o]})})},gw=t=>L(Si.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:[L(J_,{className:"w-8 h-8 text-red-400"}),L("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),L("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[L("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),L("li",{children:["Make sure that the"," ",L("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"," ",L(ry,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&L("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:[L(sy,{className:"w-4 h-4"}),"Retry"]})]});function Mi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function mw({"agent-id":t,debug:e,"trickle-ice":i,"call-destination-number":n,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":h,region:g,"skip-last-voice-sdk-id":v,environment:_,position:S="fixed","version-id":b}){const T=Mi(e),k=Mi(i),A=Mi(h),R=v===void 0?!0:Mi(v),D=Qe(()=>{if(l)try{return JSON.parse(l)}catch(he){oe.error("Invalid JSON for vad attribute:",l,he);return}},[l]),C=Qe(()=>({showUserPerceivedLatency:Mi(c),showGreetingLatency:Mi(u)}),[c,u]),{client:E,error:p,isConnected:m,isReconnecting:f}=Zb(t,_,b,T,k,D,d,A,g,R),[w,I]=Ae(null),[x,O]=Ae(!1),[N,M]=Ae(!1),[F,G]=Ae(!1),[j,J]=Ae(!1),Y=On(Eu),H=T_(),ce={};if(n&&(ce.destinationNumber=n),s&&(ce.callerNumber=s),o&&(ce.callerName=o),r)try{ce.customHeaders=JSON.parse(r)}catch(he){oe.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{ce.audio=JSON.parse(a);const he=ce.audio;if(typeof he=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(ge=>{se[ge]||oe.warn(`Audio constraint not supported by browser: ${ge}`)})}}catch(he){oe.error("Invalid JSON for call-audio attribute:",a,he)}const Z=Ge(()=>{O(!1)},[]),te=Ge(he=>{var se;if(((se=he.call)==null?void 0:se.state)==="destroy")return Y(!1),J(!0),I(null);I(he)},[Y]),ie=Ge(()=>{O(!1),f||M(!0)},[f]),ne=Ge(()=>{oe.info("User triggered retry"),M(!1),O(!0),E&&E.connect()},[E]),me=Ge(he=>{if(C_(he)){const se=he.params.widget_settings;se&&Object.keys(se).length>0&&(H(se),G(!0))}},[H]),Le=ue(null);return tw(E,{onReady:Z,onConversationUpdate:te,onError:ie,onConfigMessage:me},Le),rw(E,Le),L(pw,{position:S,rootRef:Le,children:t?N||p?L(gw,{agentId:t,onRetry:ne}):x||f?L(Hr,{message:f?"Retrying...":void 0}):w!=null&&w.call?L(lw,{call:w.call,client:E,latencySettings:C,chatMode:A,debug:T}):F?L(dw,{client:E,callProps:ce,chatMode:A&&!j,isReady:m&&!!E}):null:L("div",{children:"Please provide an assistant ID."})})}cf(mw,"telnyx-ai-agent",w_,{shadow:!0})})();
119
+ `)}))}),w.info(n)}),2e3)}}class Ls extends oi{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=>Ls.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=Pe(tb),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};U(P.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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){w.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return B(this,void 0,void 0,function*(){try{const n=yield Is({audio:e,video:i});return kn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(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(W.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 B(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(W.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(Nh(P.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 En().catch(e=>{const i=ae(Li(e),e);return U(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return En(Ct.Video).catch(e=>(U(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return En(Ct.AudioIn).catch(e=>{const i=ae(Li(e),e);return U(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return En(Ct.AudioOut).catch(e=>(w.error("getAudioOutDevices",e),U(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return Rs(e,i,n)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(i=>B(void 0,void 0,void 0,function*(){const n=[],s=yield Is({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<zh.length;r++){const[a,l]=zh[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 kn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(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=rh(e,["micId","micLabel"]);return jb(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield Rs(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?gb:pb}}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=bn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=bn(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 Fb({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 B(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Bb({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=zr(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 B(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new Ub({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=zr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ai.setStateTelnyx(e)}}Ls.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class rf{constructor(e,i){this.code=i,this.message=e}}class iw{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new Mb(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:g,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,k=d.calls[b],A=(i=k==null?void 0:k.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),R=new Set(Object.keys(d.calls));if(Array.isArray(m==null?void 0:m.reattached_sessions)&&R.size){w.debug(`Reattach: active call IDs before cleanup check: [${Array.from(R).join(", ")}].`);const p=m.reattached_sessions.length===0,_=m.reattached_sessions.some(f=>R.has(f));if(p||!_)for(const f of Object.keys(d.calls)){const S=d.calls[f];w.debug(`Session not reattached — terminating active call ${f} `);const I=ae(ph);U(P.Error,{error:I,callId:f,sessionId:d.sessionid},d.uuid),S.hangup({},!1)}}if(Array.isArray(m==null?void 0:m.reattached_sessions)&&d.sessionid){const p=Dh();if(p&&p.calls.length>0)if(p.sessionId!==d.sessionid)w.debug(`Recovery markers were saved for a different sessid (saved=${p.sessionId}, current=${d.sessionid}) — ignoring all.`),si();else{const _=new Set(m.reattached_sessions),f=[];for(const S of p.calls)try{if(_.has(S.id)){w.debug(`Recovery marker for call ${S.id} was reattached — keeping for Attach element restore.`),f.push(S);continue}w.info(`Recovery marker for call ${S.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=ae(ph);U(P.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)}`),f.push(S)}Lh(f,p.sessionId,p.storedAt)}}if(C==="channelPvtData")return this._handlePvtEvent(m.pvtData);const D=({recoveredCallId:p,forceRelayCandidateForRecovery:_,mutedMicOnStart:f,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M}={})=>{var x,N,O,F,V,$;const Q={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:g===ee.Attach,mediaSettings:m.mediaSettings,debug:(x=d.options.debug)!==null&&x!==void 0&&x,debugOutput:(N=d.options.debugOutput)!==null&&N!==void 0?N:"socket",trickleIce:(O=d.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(F=d.options.prefetchIceCandidates)!==null&&F!==void 0&&F,forceRelayCandidate:typeof _=="boolean"?_:(V=d.options.forceRelayCandidate)!==null&&V!==void 0&&V,keepConnectionAliveOnSocketClose:($=d.options.keepConnectionAliveOnSocketClose)!==null&&$!==void 0&&$,mutedMicOnStart:f??d.options.mutedMicOnStart};b&&(Q.id=b),m.telnyx_call_control_id&&(Q.telnyxCallControlId=m.telnyx_call_control_id),m.telnyx_session_id&&(Q.telnyxSessionId=m.telnyx_session_id),m.telnyx_leg_id&&(Q.telnyxLegId=m.telnyx_leg_id),m.client_state&&(Q.clientState=m.client_state),m.dialogParams&&m.dialogParams.custom_headers&&m.dialogParams.custom_headers.length&&(Q.customHeaders=m.dialogParams.custom_headers),p&&(Q.recoveredCallId=p),M&&(Q.wasHeldBeforeRecovery=M),S!==void 0&&(Q.remoteElement=S),I!==void 0&&(Q.localElement=I),performance.mark(le(Q.id,"new-call-start"));const J=new ai(d,Q);return J.nodeId=this.nodeId,J},T=new Uh(v),E=new Hr(v);switch(g){case ee.Answer:case ee.Display:case ee.Candidate:case ee.Ringing:case ee.Bye:case ee.Media:if(!b||!k)return void w.error(`Received ${g} for non existing call:`,m);k.handleMessage(e),this._ack(h,g);break;case ee.Ping:this.session.setPingReceived(),this.session.execute(E);break;case ee.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,g)):(w.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case ee.Invite:{const f=D();f.direction=St.Inbound,f.playRingtone(),f.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(f.id),this._ack(h,g);break}case ee.Attach:{const f=k||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,x=!1;const N=Dh();if(N&&N.sessionId===d.sessionid){const F=N.calls.find(V=>V!==null&&typeof V=="object"&&V.id===b);F&&(S=F.remoteElement,I=F.localElement,M=F.wasHeld===!0,typeof F.forceRelayCandidate=="boolean"&&(x=F.forceRelayCandidate),(S||I)&&w.info(`[${b}] Attach: restoring per-call media elements from recovery marker (remoteElement=${S??"<none>"}, localElement=${I??"<none>"}).`),typeof F.forceRelayCandidate=="boolean"&&w.info(`[${b}] Attach: restoring forceRelayCandidate=${F.forceRelayCandidate} from recovery marker.`))}const O=D({recoveredCallId:b,forceRelayCandidateForRecovery:x,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,g);break}if(f){const S=f.id,I=f.state==="held",M=f.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}.`),f.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const x=D({recoveredCallId:S,forceRelayCandidateForRecovery:M,mutedMicOnStart:f.isAudioMuted,remoteElement:f.options.remoteElement,localElement:f.options.localElement,wasHeldBeforeRecovery:I});x.answer(),this.session.emitMultipleActiveCallsWarning(x.id),this._ack(h,g);break}w.warn(`Attach: callID ${b} does not match any active calls. `),U(P.Warning,{warning:Pe(ob),callId:b,params:m,sessionId:d.sessionid},d.uuid),this._ack(h,g);break}case ee.Event:case"webrtc.event":if(!y)return void w.error("Verto received an unknown event:",m);const p=d.relayProtocol,_=y.split(".")[0];d._existsSubscription(p,y)?U(p,m,y):y===d.sessionid?this._handleSessionEvent(m.eventData):d._existsSubscription(p,_)?U(p,m,_):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(P.Notification,m,d.uuid);break;case ee.Info:m.type=at.generic,U(P.Notification,m,d.uuid);break;case ee.ClientReady:this.session.execute(T);break;case"ai_conversation":U(P.AIConversationMessage,{method:"ai_conversation",params:m,voice_sdk_id:v},d.uuid);break;default:{const f=Fr(e);if(f){switch(f){case Le.REGISTER:case Le.REGED:if(!this.isDuplicateGatewayState(f,[Le.REGED,Le.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,f===Le.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=at.vertoClientReady,U(P.Ready,m,d.uuid)}break;case Le.UNREGED:case Le.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const S=new rf("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=ae(fh,S);U(P.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(T)},this.reconnectDelay());break;case Le.FAILED:case Le.FAIL_WAIT:case Le.TIMEOUT:if(!this.isDuplicateGatewayState(f,[Le.FAILED,Le.FAIL_WAIT,Le.TIMEOUT])){const S=ae(F0,new Error(`Gateway state: ${f}`));if(U(P.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 rf("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const M=ae(Or,I);U(P.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(Or,new Error("Connection Retry Failed"));U(P.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 B(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 g=()=>{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(k=>{k==="INVALID_PACKET"&&g()})}}},v=yield i.vertoSubscribe(m).catch(b=>{w.error("liveArray subscription error:",b);const y=ae(O0,b);U(P.Error,{error:y,sessionId:i.sessionid},i.uuid)});qr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(g=i.calls[v]||null,v!==null){const b={type:at.conferenceUpdate,action:Xe.Leave,conferenceName:r,participantId:Number(u),role:d};U(P.Notification,b,v,!1)||U(P.Notification,b,i.uuid),g===null&&Tt(P.Notification,null,v)}}const m=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:m}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.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":ef(this.session,e);break;case"logo-info":{const i={type:at.conferenceUpdate,action:Xe.LogoInfo,logo:e.logoURL};U(P.Notification,i,this.session.uuid);break}}}}class nw extends Ls{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new iw(this),window.addEventListener("beforeunload",i=>{if(w.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return xh(),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 si();w.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),Lh(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."),Vr(this.sessionid))})}validateOptions(){return bs(this.options)||wn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(L0,void 0,"Error: destinationNumber is required");const i=new ai(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!!wn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return B(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),bs(this.options)?this.handleLoginOnSocketOpen():wn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}function af(t){return{options:t,statsSamples:[]}}function sw(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,g=new Map,m={host:0,srflx:0,prflx:0,relay:0};a.forEach(E=>{switch(E.type){case"local-candidate":{const p=E;m[p.candidateType]++,g.set(p.id,p);break}case"remote-candidate":{const p=E;h.set(p.id,p);break}case"candidate-pair":{const p=E;u.push(p);break}case"transport":{const p=E;typeof p.selectedCandidatePairId=="string"&&d.add(p.selectedCandidatePairId);break}}});const v=function(E,p,_,f){var S,I;const M=E.find(V=>p.has(V.id)),x=E.find(V=>V.selected===!0),N=E.find(V=>V.nominated===!0&&V.state==="succeeded"),O=E.filter(V=>V.state==="succeeded"),F=(I=(S=M??x)!==null&&S!==void 0?S:N)!==null&&I!==void 0?I:O.length===1?O[0]:void 0;return F?Object.assign(Object.assign({},F),{localCandidate:_.get(F.localCandidateId),remoteCandidate:f.get(F.remoteCandidateId)}):null}(u,d,g,h),b=m.relay>0,y=m.srflx===0&&m.relay===0&&m.prflx===0,C=l.iceGatheringState,k=l.iceConnectionState,A=C==="complete",R=((c=v==null?void 0:v.localCandidate)===null||c===void 0?void 0:c.candidateType)==="relay",{hasMultipleNetworkInterfaces:D,vpnDetected:T}=function(E){if(E.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const p=Array.from(E.values());return{hasMultipleNetworkInterfaces:new Set(p.filter(_=>_.candidateType==="host").map(_=>_.address)).size>=2,vpnDetected:p.some(_=>_.networkType==="vpn")}}(g);return{candidateGatheringCompleted:A,gatheringComplete:A,candidateCounts:m,candidates:Array.from(g.values()),hasRelayCandidate:b,onlyHostCandidates:y,isTurnRequired:R,hasMultipleNetworkInterfaces:D,vpnDetected:T,hasSelectedPair:!!v,selectedPair:v??void 0,iceGatheringState:C,iceConnectionState:k}}(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 g=Array.isArray(h.urls)?h.urls:[h.urls],m=l.filter(y=>g.some(C=>ow(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 lf(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(e=>/^turns?:/i.test(e))}function cf(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 df(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 ow(t,e,i){var n;if(!t||!e||cf(t)!==cf(e))return!1;const s=df(e);if(s===void 0)return!0;const o=(n=df(t))!==null&&n!==void 0?n:i==null?void 0:i.toLowerCase();return o===void 0||o===s}const Xr=2e3,rw=100,uf=.01,aw="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 lw(){var t;return B(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 cw(t,e,i){return B(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 g=a-Date.now();g>0&&(yield new Promise(m=>setTimeout(m,Math.min(rw,g))))}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 dw(t,e){return B(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=()=>B(this,void 0,void 0,function*(){const d=n.mimeType||i||"audio/webm",h=yield(g=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(g)}catch{m(void 0)}}));var g;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 hf(t){var e,i;return B(this,void 0,void 0,function*(){const n=function(g){var m,v;const b=g&&typeof g=="object"?g:void 0;return{sampleDurationMs:Math.max(0,(m=b==null?void 0:b.sampleDurationMs)!==null&&m!==void 0?m:Xr),silenceThreshold:Math.min(1,Math.max(0,(v=b==null?void 0:b.silenceThreshold)!==null&&v!==void 0?v:uf)),record:(b==null?void 0:b.record)===!0,warnOnRecording:b==null?void 0:b.warnOnRecording}}(t.options.microphone),s=yield function(){var g;return B(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((g=navigator.permissions)===null||g===void 0?void 0:g.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}})}(),{report:o,stream:r}=yield lw(),a=yield function(){var g;return B(this,void 0,void 0,function*(){if(typeof navigator<"u"&&typeof((g=navigator.mediaDevices)===null||g===void 0?void 0:g.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 g=yield function(m,v,b){var y,C,k;return B(this,void 0,void 0,function*(){m.activeCapturePerformed=!0,m.recordingPerformed=b.record,b.record&&b.warnOnRecording&&b.warnOnRecording(aw);const[A,R]=yield Promise.all([cw(v,(y=b.sampleDurationMs)!==null&&y!==void 0?y:Xr,(C=b.silenceThreshold)!==null&&C!==void 0?C:uf),b.record?dw(v,(k=b.sampleDurationMs)!==null&&k!==void 0?k:Xr):Promise.resolve(void 0)]);return A&&(m.audioLevel=A.audioLevel,m.audioDetected=A.audioDetected,m.audioLevelStats=A.audioLevelStats),R&&(m.recordingDataUrl=R.recordingDataUrl,m.recordingMimeType=R.recordingMimeType,m.recordingDurationMs=R.recordingDurationMs,m.recordingPerformed=!0),R})}(c,r,n);g&&(c.playbackPerformed=yield(u=g.recordingDataUrl,d=g.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise(m=>{let v,b=!1;const y=setTimeout(()=>C(!1),d),C=k=>{b||(b=!0,clearTimeout(y),v&&(v.onended=null,v.onerror=null,v.paused||v.pause(),v.src=""),m(k))};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(g=>g.stop())}catch{}}var u,d;const h=function(g){const m=[],v=(y,C)=>m.push({code:y,message:C,source:"microphone"});g.currentPermissionState==="denied"&&v("microphone_permission_denied","Microphone permission has been denied by the user."),g.deviceAvailable===!1&&v("microphone_no_device","No audio input device is available.");const b=g.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."]}[g.captureError]:void 0;return b&&v(...b),g.activeCapturePerformed&&g.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 Jr=300,Zr=500,Qr=30,ea=100,ta=.02,ia=.05,Ms=8e3;function lt(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function na(t){const e=t.filter(o=>lt(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 sa(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 Bi(t,e){let i=0,n=!1;for(const s of t){const o=lt(s[e]);o!==void 0&&(i+=o,n=!0)}return n?i:void 0}function Ui(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 uw(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 ff(t,e){if(t!==void 0&&e!==void 0)return lt(e-t)}function pf(t,e){var i,n;if(!t.some(c=>Ui(c,`${e}-rtp`,!0).length>0))return;const s=t.map(c=>function(u,d){const h=Ui(u,`${d}-rtp`,!0);return d==="outbound"?{packets:Bi(h,"packetsSent"),bytes:Bi(h,"bytesSent")}:{packets:Bi(h,"packetsReceived"),bytes:Bi(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=ff(o.packets,r.packets),l=ff(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&uw(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 gf(t,e){const i=[];for(const n of t)for(const s of Ui(n,e,!0)){const o=lt(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&i.push(r)}}return i}function mf(t){const e=Bi(t,"packetsReceived"),i=Bi(t,"packetsLost"),n=t.map(r=>lt(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 vf(t){let e;return t.forEach(i=>{e===void 0&&(e=lt(i.timestamp))}),e}function hw(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,i=pf(e,"inbound"),n=pf(e,"outbound"),s=na(function(g){var m;const v=[];for(const b of g){let y=!1;const C=Ui(b,"remote-inbound-rtp",!0);for(const k of C){const A=lt(k.roundTripTime);if(A!==void 0){const R=1e3*A;R>=0&&(v.push(R),y=!0)}}if(!y){const k=lt((m=sa(b))===null||m===void 0?void 0:m.currentRoundTripTime);if(k!==void 0){const A=1e3*k;A>=0&&v.push(A)}}}return v}(e)),o=(r=na(gf(e,"inbound-rtp")),a=na(gf(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(g,m,v){var b;if(g.length===0)return;const y=g[g.length-1],C=Ui(y,"inbound-rtp",!0),k=Ui(y,"remote-inbound-rtp",!0),A=function(_,f){return _.packetLossFraction===void 0?f:f.packetLossFraction===void 0?_:f.packetLossFraction>_.packetLossFraction?f:_}(mf(C),mf(k));let R=v==null?void 0:v.packets,D=(b=A.packetsReceived)!==null&&b!==void 0?b:m==null?void 0:m.packets;const T=A.packetsLost,E=A.packetLossFraction,p=sa(y);return R===void 0&&(R=lt(p==null?void 0:p.packetsSent)),D===void 0&&(D=lt(p==null?void 0:p.packetsReceived)),R!==void 0||D!==void 0||T!==void 0?{packetsSent:R,packetsReceived:D,packetsLost:T,packetLossFraction:E}:void 0}(e,i,n),c=function(g,m,v){if(g.length===0)return;const b=g[g.length-1];let y=v==null?void 0:v.bytes,C=m==null?void 0:m.bytes;const k=sa(b);return y===void 0&&(y=lt(k==null?void 0:k.bytesSent)),C===void 0&&(C=lt(k==null?void 0:k.bytesReceived)),y!==void 0||C!==void 0?{bytesSent:y,bytesReceived:C}:void 0}(e,i,n),u=function(g,m,v){if(g.length<2)return;const b=g[0],y=g[g.length-1],C=vf(b),k=vf(y);if(C===void 0||k===void 0)return;const A=(k-C)/1e3;if(A<=0)return;const R=(v==null?void 0:v.bytesDelta)!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/A:void 0,D=(m==null?void 0:m.bytesDelta)!==void 0&&m.bytesDelta>=0?8*m.bytesDelta/A:void 0;return R!==void 0||D!==void 0?{outbound:R,inbound:D}:void 0}(e,i,n),d=function(g,m,v){let b=!1,y="good";return(g==null?void 0:g.average)!==void 0&&(b=!0,g.average>=Zr?y="poor":g.average>=Jr&&y==="good"&&(y="fair")),(m==null?void 0:m.average)!==void 0&&(b=!0,m.average>=ea?y="poor":m.average>=Qr&&y==="good"&&(y="fair")),(v==null?void 0:v.packetLossFraction)!==void 0&&(b=!0,v.packetLossFraction>=ia?y="poor":v.packetLossFraction>=ta&&y==="good"&&(y="fair")),b?y:"unknown"}(s,o,l),h=function(g,m,v,b){const y=[];return(g==null?void 0:g.average)!==void 0&&(g.average>=Zr?y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (poor: ≥${Zr}ms threshold)`,source:"network"}):g.average>=Jr&&y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (degraded: ≥${Jr}ms threshold)`,source:"network"})),(m==null?void 0:m.average)!==void 0&&(m.average>=ea?y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (poor: ≥${ea}ms threshold)`,source:"network"}):m.average>=Qr&&y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (degraded: ≥${Qr}ms threshold)`,source:"network"})),(v==null?void 0:v.packetLossFraction)!==void 0&&(v.packetLossFraction>=ia?y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (poor: ≥${100*ia}% threshold)`,source:"network"}):v.packetLossFraction>=ta&&y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (degraded: ≥${100*ta}% threshold)`,source:"network"})),b&&(b.outbound!==void 0&&b.outbound<Ms&&y.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(b.outbound)} bps (<${Ms} bps threshold)`,source:"network"}),b.inbound!==void 0&&b.inbound<Ms&&y.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(b.inbound)} bps (<${Ms} 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 _f(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function oa(t,e){return t.find(i=>i.label===e)}class fw{constructor(){this.startedAtMonoMs=yf()}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=oa(o.steps,"ICE candidate gathering started"),a=oa(o.steps,"All ICE candidates gathered"),l=_f(r&&a?a.fromStart-r.fromStart:void 0);l!==void 0&&(s.iceGatheringMs=l);const c=oa(o.steps,"First server-reflexive/relay candidate found"),u=_f(r&&c?c.fromStart-r.fromStart:void 0);u!==void 0&&(s.firstNonHostCandidateMs=u)}}catch{}return s}complete(e){const i=yf()-this.startedAtMonoMs;Number.isFinite(i)&&i>=0&&(e.totalMs=i)}}function yf(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function ra(){return new fw}const Pt={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"},In={LowBitrate:"network_low_bitrate",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},aa={CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureFailed:"microphone_capture_failed"},li=()=>({reasons:[],warnings:[]}),bf={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function We(t,e){return t?e?bf[t]>=bf[e]?t:e:t:e}function Je(t,e,i){return{code:t,message:e,source:i}}function Rn(t,e,i){return{code:t,message:e,source:i}}function wf(t,e=!1){var i;if(!t)return li();const n=li(),{reasons:s,warnings:o}=n,r=t.candidates.length>0;r||(s.push(Je(Pt.NoCandidates,"No ICE candidates were gathered.","ice")),n.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(Rn(Pt.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(Je(Pt.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),n.verdict=We(n.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(Je(Pt.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),n.verdict=We(n.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(Je(Pt.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),n.verdict=We(n.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(Je(Pt.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),n.verdict=We(n.verdict,"degraded"));const l=((i=t.serverCandidateComparison)!==null&&i!==void 0?i:[]).filter(({hasCandidates:c})=>!c);return l.length>0&&o.push(Rn(Pt.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(Rn(Pt.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(Rn(Pt.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!n.verdict&&r&&(n.verdict="ready"),n}function pw(t){if(t.established&&!t.error)return li();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[Je("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function Sf(t,e=!0){var i;if(!t)return li();const n=li(),{reasons:s,warnings:o}=n,r=e?t.reasons:(i=t.reasons)===null||i===void 0?void 0:i.filter(({code:l})=>l!==In.LowBitrate);switch(r!=null&&r.length&&(s.push(...r),n.verdict="degraded"),t.quality){case"poor":s.push(Je(In.PoorQuality,"Network quality is poor.","network")),n.verdict=We(n.verdict,"blocked");break;case"fair":o.push(Rn(In.FairQuality,"Network quality is fair.","network")),n.verdict=We(n.verdict,"degraded");break;case"good":n.verdict=We(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=We(n.verdict,"ready"):l>0?(s.push(Je(In.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),n.verdict=We(n.verdict,"blocked")):(s.push(Je(In.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),n.verdict=We(n.verdict,"blocked"))}return n}function gw(t){var e;if(!t)return li();const i=li();!((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 la{constructor(e){this.options=e}run(){return B(this,void 0,void 0,function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(af(this.options));default:return this.runFull()}})}runFull(){return B(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?Vi({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}:Vi({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 B(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=ra();let l;try{return r=yield Promise.all(o.map(c=>B(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:lf(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=Vi({serverTests:r,timings:a.build()},void 0,{networkOnly:!0}),l}catch(c){return l=Vi({timings:a.build()},Os(c),{networkOnly:!0}),l}finally{l!=null&&l.timings&&a.complete(l.timings)}})}runTest(e){return B(this,void 0,void 0,function*(){const i=af(e.diagnosticOptions),n=ra();let s,o,r,a=!1;const l=c=>{c.callId===(s==null?void 0:s.id)&&(o=Os(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?sw(i):void 0,u=e.modules.network?hw(i):void 0,d=e.modules.microphone?yield hf(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=Os(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 B(this,void 0,void 0,function*(){const i=ra();let n;try{return n=Vi({microphone:this.options.microphone?yield hf(e):void 0,timings:i.build()},e.error),n}catch(s){return e.error=Os(s),n=Vi({timings:i.build()},e.error),n}finally{n!=null&&n.timings&&i.complete(n.timings)}})}waitForCallEstablishment(e){return B(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 Cf(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 B(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 Cf(Math.min(a,Math.max(0,l-Date.now())))}})}}function Vi(t,e,i){const{verdict:n,reasons:s,warnings:o}=function(r,a,l={}){var c,u;const d=[wf(r.ice),Sf(r.network),gw(r.microphone),...((c=r.serverTests)!==null&&c!==void 0?c:[]).flatMap(v=>[wf(v.ice,l.networkOnly&&lf(v.server)),Sf(v.network,!l.networkOnly),pw(v)])],h=d.flatMap(v=>v.reasons),g=d.flatMap(v=>v.warnings);let m=d.reduce((v,b)=>We(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 uh:h.push(Je(aa.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),m=We(m,"permission_denied");break;case hh:h.push(Je(aa.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),m=We(m,"blocked");break;case Lr:h.push(Je(aa.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),m=We(m,"blocked");break;default:h.push(Je("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),m=We(m,"blocked")}return{verdict:m??"inconclusive",reasons:h,warnings:g}}(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 Os(t){return t instanceof Error?t:new Error(String(t))}function Cf(t){return new Promise(e=>setTimeout(e,t))}const Tf="+1-872-231-5806";class mw extends nw{constructor(e){super(e),w.info(`SDK version: ${Vh}`)}newCall(e){return super.newCall(e)}runPreCall(e={}){var i,n;return B(this,void 0,void 0,function*(){const s={client:this,destinationNumber:(i=e.destinationNumber)!==null&&i!==void 0?i:Tf,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 la(s).run()})}runNetworkCheck(e={}){var i;return B(this,void 0,void 0,function*(){const n={client:this,destinationNumber:Tf,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(i=e.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new la(n).run()})}runMicrophoneCheck(e={}){var i;return B(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 la(n).run()})}static webRTCInfo(){return Hb()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Te.not_supported},{browserName:"Firefox",supported:Te.not_supported},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",features:["audio"],supported:Te.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",features:["audio"],supported:Te.partial}]}]}}function vw(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 kf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ef={exports:{}},If;function _w(){return If||(If=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 g=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],g]:l._events[m].push(g):(l._events[m]=g,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,g=new Array(h);d<h;d++)g[d]=u[d].fn;return g},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,g){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,g),!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 k=v.length,A;for(C=0;C<k;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 g=this._events[h];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&r(this,h);else{for(var m=0,v=[],b=g.length;m<b;m++)(g[m].fn!==c||d&&!g[m].once||u&&g[m].context!==u)&&v.push(g[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}(Ef)),Ef.exports}var yw=_w();const ca=kf(yw),da=new ca;var ua={exports:{}},bw=ua.exports,Rf;function ww(){return Rf||(Rf=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(bw,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 g(v,b){var y=this,C,k,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function D(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,I=encodeURIComponent(R),M=S.indexOf(I+"=");M!==-1&&(f=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var S=f;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: "+f)}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??k??C},y.setLevel=function(f,S){return A=p(f),S!==!1&&D(A),u.call(y)},y.setDefaultLevel=function(f){k=p(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var _=T();_!=null&&(A=p(_)),u.call(y)}r=new g,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 g(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})}(ua)),ua.exports}var Sw=ww();const Cw=kf(Sw),Tw=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=Cw.getLogger("telnyx-ai-agent"),kw=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=kw(t,e,i);return function(...s){n(Tw(),"-",...s)}},fe.setLevel("info");function Ew(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Iw=10,Rw=500,Aw=100,xw=300,Af=20;class Dw{constructor(e){H(this,"remoteIntervalId",null);H(this,"localIntervalId",null);H(this,"remoteStream",null);H(this,"localStream",null);H(this,"remoteAudioContext",null);H(this,"remoteSource",null);H(this,"remoteAnalyser",null);H(this,"localAudioContext",null);H(this,"localSource",null);H(this,"localAnalyser",null);H(this,"thinkingStartTime",null);H(this,"lastState",null);H(this,"userIsSpeaking",!1);H(this,"lastUserAudioTime",null);H(this,"userSpeechStartTime",null);H(this,"remoteSilenceStartTime",null);H(this,"remoteSilenceThresholdMs");H(this,"userSilenceStartTime",null);H(this,"isFirstAgentSpeech",!0);H(this,"monitorStartTime",null);H(this,"volumeThreshold");H(this,"silenceDurationMs");H(this,"minSpeechDurationMs");H(this,"maxLatencyMs");H(this,"updateAgentState",Ew(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,da.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Iw,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Rw,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Aw,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??xw}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){fe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,fe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(fe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;fe.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&&fe.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,Af)}startLocalMonitor(){if(!this.localStream){fe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,fe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(fe.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&&fe.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,Af)}destroy(){this.stopAudioStreamMonitor()}}function Lw(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Mw(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Ow(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Ps(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Pw(t){if(!Ps(t))return null;const e=t.params;return vw(e)?e.item:null}function Nw(t){if(!Ps(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 Fw(t){if(!Ps(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 Bw(t){var e;return Ps(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function Uw(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 Vw=3e4;function $w(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 ha(t){return JSON.stringify({error:t})}class jw{constructor(e){H(this,"registry",new Map);H(this,"toolTimeouts",new Map);H(this,"inFlight",new Set);H(this,"completed",new Set);H(this,"generation",0);H(this,"getActiveCall");H(this,"timeoutMs");H(this,"events");H(this,"handleEvent",e=>{const i=Nw(e);if(i){this.ingestToolSettings(i);return}const n=Pw(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Vw,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){fe.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)){fe.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){fe.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,ha("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{fe.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,ha("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,$w(u),!1,s,o)}catch(u){const d=u instanceof xf?"timeout":"handler_error";fe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,ha(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 xf(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){fe.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){fe.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){fe.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){fe.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 xf extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Fs=class Fs{constructor(e){H(this,"enabled");H(this,"getActiveCall");H(this,"events");H(this,"subscriptionConfirmed",!1);H(this,"subscribeAttempts",0);H(this,"handleEvent",e=>{if(!this.enabled)return;if(Bw(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Fw(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Hw(i.delta)}catch(s){fe.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>=Fs.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){fe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){fe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}};H(Fs,"MAX_SUBSCRIBE_ATTEMPTS",10);let fa=Fs;function Hw(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Ww(t){return Mw(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Gw(t){if(!Ow(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 qw extends ca{constructor(i){super();H(this,"telnyxRTC");H(this,"transcript",[]);H(this,"onSocketMessage",i=>{if(Lw(i))switch(i.params.type){case"response.text.delta":{const n=Ww(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Uw(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=Gw(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)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage)}}const Nt=t=>typeof t=="object"&&t!==null,Df=t=>{const e=Nt(t)&&Nt(t.result)?t.result:t;if(!(!Nt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},zw=t=>Nt(t)&&Nt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Kw=(t,e)=>{if(!e||!Nt(t)||!Nt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Nt(i.params))return;const n=i.params;Nt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class Yw extends ca{constructor(i){super();H(this,"telnyxRTC");H(this,"transcription");H(this,"removeLoginSuccessHook",null);H(this,"authenticated",!1);H(this,"authenticating",!1);H(this,"agentId");H(this,"versionId");H(this,"widgetVersion");H(this,"conversationId");H(this,"debug");H(this,"audioStreamMonitor");H(this,"clientTools");H(this,"streamingAudio");H(this,"activeCall");H(this,"chatMode");H(this,"dc",null);H(this,"region",null);H(this,"callReportId",null);H(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)});H(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});H(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});H(this,"onSocketMessage",i=>{const n=Df(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});H(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()))});H(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});H(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,fe.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 mw({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,prefetchIceCandidates:i.prefetchIceCandidates,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(P.Ready,this.onClientReady),this.telnyxRTC.on(P.Error,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketClose,this.onSocketClose),this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(P.Notification,this.onNotification),this.transcription=new qw(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),da.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Dw(i.vad),this.clientTools=new jw({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(P.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new fa({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(P.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(P.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(P.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(P.Ready,this.onClientReady),this.telnyxRTC.off(P.Error,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketClose,this.onSocketClose),this.telnyxRTC.off(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(P.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(),da.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){fe.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 fe.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 fe.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=g=>{c===g&&(this.authenticating=!1)},d=function(g){const m=zw(g),v=c;return m&&Kw(g,a),n.call(this,g).then(b=>{const y=m?Df(b):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),b})},h=function(g){const m=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,g).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}))}}var Lf={exports:{}},An={},Mf;function Xw(){if(Mf)return An;Mf=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 An.Fragment=e,An.jsx=i,An.jsxs=i,An}var Of;function Jw(){return Of||(Of=1,Lf.exports=Xw()),Lf.exports}Jw(),At(void 0),At(null);const Zw=(t,e,i,n,s,o,r,a,l,c,u)=>new Yw({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,prefetchIceCandidates:o,vad:r,conversationId:a,chatMode:l,region:c,skipLastVoiceSdkId:u??!0}),Ns=10,Pf=5e3,Qw=[46001,46003],eS=["login incorrect","authentication required","authentication failed"];function Nf(t){var n;const e=t.code;if(e&&Qw.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return eS.some(s=>i.includes(s))}const tS=(t,e,i,n,s,o,r,a,l,c,u)=>{const d=u??!0,[h,g]=Ae(null),[m,v]=Ae(!1),[b,y]=Ae(null),[C,k]=Ae(!1),A=he(0),R=he(null),D=he(null),T=he(!1),E=he(!1),p=he(0),_=he(0),f=qe(()=>{R.current&&(clearTimeout(R.current),R.current=null)},[]),S=qe(()=>{f(),A.current=0,E.current=!0,k(!1),y(null)},[f]),I=qe(()=>{f(),k(!1)},[f]),M=qe(x=>{if(f(),A.current>=Ns){re.error(`Max login retry attempts (${Ns}) exceeded`),k(!1);return}A.current+=1;const N=p.current,O=_.current;re.info(`Scheduling login retry attempt ${A.current}/${Ns} in ${Pf}ms due to: ${x}`),k(!0),R.current=window.setTimeout(()=>{var $;R.current=null;const F=D.current,V=F==null?void 0:F.telnyxRTC;if(p.current!==N||_.current!==O||F!=null&&F.isAuthenticating){re.info("Skipping login retry because a newer socket/login is already in progress"),I();return}if(T.current||E.current||F!=null&&F.isAuthenticated){re.info("Skipping login retry because login already succeeded before retry timeout fired"),S();return}D.current&&(re.info(`Executing reconnect attempt ${A.current} (socket disconnect)`),($=V==null?void 0:V.socketDisconnect)==null||$.call(V))},Pf)},[f,I,S]);return xe(()=>{if(!t)return;const x=Zw(t,e,i,n,s,o,r,a,l,c,d);T.current=!1,E.current=!1,v(!1),y(null),k(!1),D.current=x;const N=()=>{re.info("Agent connected successfully"),T.current=!0,v(!0),S()},O=()=>{re.info("Agent disconnected"),T.current=!1,E.current=!1,v(!1)},F=de=>{if(re.error("AI Agent error:",de),Nf(de)){if(T.current||E.current){re.debug("Ignoring retryable error — login already succeeded");return}A.current<Ns?(y(null),M(de.message)):(y(de),k(!1))}else y(de),k(!1)},V=x.telnyxRTC??null,$=()=>{_.current+=1,E.current=!1},Q=()=>{re.info("Login succeeded; clearing pending login retry flow"),S()},J=()=>{p.current+=1,E.current=!1},G=()=>{E.current=!1};return x.on("agent.connected",N),x.on("agent.disconnected",O),x.on("agent.error",F),x.on("agent.login.started",$),x.on("agent.login.success",Q),V&&typeof V=="object"&&(V.on(P.SocketOpen,J),V.on(P.SocketClose,G)),x.connect(),g(x),()=>{f(),x.off("agent.connected",N),x.off("agent.disconnected",O),x.off("agent.error",F),x.off("agent.login.started",$),x.off("agent.login.success",Q),V&&typeof V=="object"&&(V.off(P.SocketOpen,J),V.off(P.SocketClose,G)),x.disconnect(),T.current=!1,D.current=null}},[t,e,i,n,s,o,r,a,l,c,u,d,f,S,M]),{client:h,isConnected:m,error:b,isReconnecting:C}},iS="telnyx-ai-agent",Ze={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",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"};function nS(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 Ff(){const t=document.querySelector(iS);return t instanceof HTMLElement?t:null}function kt(t,e,i){const n=i||Ff();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 sS=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=he(null),l=Hn(Gu);xe(()=>{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??Ff()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const D=t.telnyxRTC,T={dc:(D==null?void 0:D.dc)??null,region:(D==null?void 0:D.region)??null,callReportId:(D==null?void 0:D.callReportId)??null};l(T),kt(Ze.AGENT_CONNECTED,T,c)},d=()=>{l(null),kt(Ze.AGENT_DISCONNECTED,void 0,c)},h=R=>{const D={message:R.message,name:R.name};if(Nf(R)){re.debug("Ignoring retryable agent.error in widget event layer"),kt(Ze.AGENT_ERROR,D,c);return}o(R),kt(Ze.AGENT_ERROR,D,c)},g=R=>{var D;s(R),kt(Ze.CONVERSATION_UPDATE,{type:R.type,callState:(D=R.call)==null?void 0:D.state},c)},m=R=>{kt(Ze.TRANSCRIPT_ITEM,R,c)},v=R=>{kt(Ze.CONVERSATION_AGENT_STATE,R,c)},b=R=>{kt(Ze.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const D=nS(R);D&&kt(Ze.CLIENT_TOOLS_CONFIGURED,{tools:D},c)},A=R=>{const D=R,T={code:D==null?void 0:D.code,reason:D==null?void 0:D.reason,wasClean:D==null?void 0:D.wasClean,timestamp:new Date().toISOString()};re.info("[socket.close]",T),kt(Ze.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(P.SocketMessage,k),C.on(P.SocketClose,A)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",g),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",g),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),C&&typeof C=="object"&&(C.off(P.SocketMessage,k),C.off(P.SocketClose,A))}},[t,n,s,o,r,l])},oS=2e3;async function rS(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Bf(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 aS=(t,e)=>{const[i,n]=Ae([]),[,s]=Cr(),o=he(e);xe(()=>{o.current=e},[e]);const r=he(void 0),a=he(void 0);return xe(()=>{if(!t)return;const c=h=>{n(g=>{const m=g[g.length-1];if(h.role==="assistant"&&m&&Bf(m.id)===Bf(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),[...g.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,[...g,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=g.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(m&&m.role==="user"&&h.timestamp.getTime()-m.timestamp.getTime()<oS){const C={...m,id:h.id,content:m.content+" "+h.content,timestamp:h.timestamp,attachments:[...m.attachments||[],...h.attachments||[]]};return[...g.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,h]})},u=({state:h,userPerceivedLatencyMs:g,greetingLatencyMs:m,thinkingStartedAt:v})=>{(g!==void 0||m!==void 0)&&re.info(`[AgentState] state=${h} userPerceivedLatencyMs=${g} greetingLatencyMs=${m} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),m!==void 0&&(a.current=m)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var m;const g=(m=h.call)==null?void 0:m.state;(g==="destroy"||g==="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 g=await rS(h);d.push(g)}catch(g){throw re.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},$i={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class lS{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($i.INVOKED,this.boundInvoked),e.on($i.COMPLETED,this.boundCompleted),e.on($i.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($i.INVOKED,this.boundInvoked),this.boundCompleted&&e.off($i.COMPLETED,this.boundCompleted),this.boundError&&e.off($i.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function pa(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const cS=(t,e)=>{const i=he(null);i.current===null&&(i.current=new lS),Js(()=>{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]),xe(()=>{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=>{pa(s(),Ze.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{pa(s(),Ze.CLIENT_TOOL_COMPLETED,o)},onError:o=>{pa(s(),Ze.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},dS=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=ni(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=aS(e,i),d=he(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(g=>{g.enabled=!1,re.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[n,t]),r){case"collapsed":return L(Qu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return L(C0,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return L(Qu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},ga=()=>L(Ii.div,{layoutId:vn,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:L("div",{className:"rounded-full animate-spin",children:L(zy,{})})}),uS=({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 L(ga,{});case"done":case"purged":case"destroy":return null;case"active":return L(dS,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return L(ga,{})}},hS=({className:t})=>L("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:[L("g",{clipPath:"url(#:R5lfm:)",children:[L("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"}),L("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"}),L("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"}),L("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"}),L("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"})]}),L("defs",{children:L("clipPath",{id:":R5lfm:",children:L("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Uf(){const t=ni();return t.logo_icon_url?L("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:L("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):L(hS,{className:"w-8 h-8 mr-2"})}const fS=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=ni(),o=he(!1),r=qe(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 xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,re.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?L(Ii.div,{layoutId:vn,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:[L(Uf,{}),"Connecting..."]}):L(Ii.button,{layoutId:vn,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:[L(Uf,{}),s.start_call_text]})},pS='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-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-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}.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}.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-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-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-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}.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-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-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)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.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-\\[\\#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-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)}}.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-\\[\\#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-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',gS=({children:t})=>L("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:L("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),mS={duration:.1,ease:"circOut"},vS=({children:t,position:e="fixed",rootRef:i})=>{const n=ni(),o=(e??n.position??"fixed")==="fixed"?L(gS,{children:t}):t;return L("div",{ref:i,className:Lt(n.theme==="dark"&&"dark"),children:L(Bm,{transition:mS,children:[L("style",{children:pS}),o]})})},_S=t=>L(Ii.div,{layoutId:vn,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:[L(Gy,{className:"w-8 h-8 text-red-400"}),L("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),L("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[L("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),L("li",{children:["Make sure that the"," ",L("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"," ",L(e0,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&L("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:[L(Zy,{className:"w-4 h-4"}),"Retry"]})]});function ji(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Vf(t,e){return t===void 0?e:ji(t)}function yS({"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":g,region:m,"skip-last-voice-sdk-id":v,environment:b,position:y="fixed","version-id":C}){const k=ji(e),A=Vf(i,!0),R=Vf(n,!0),D=ji(g),T=v===void 0?!0:ji(v),E=it(()=>{if(c)try{return JSON.parse(c)}catch(ne){re.error("Invalid JSON for vad attribute:",c,ne);return}},[c]),p=it(()=>({showUserPerceivedLatency:ji(u),showGreetingLatency:ji(d)}),[u,d]),{client:_,error:f,isConnected:S,isReconnecting:I}=tS(t,b,C,k,A,R,E,h,D,m,T),[M,x]=Ae(null),[N,O]=Ae(!1),[F,V]=Ae(!1),[$,Q]=Ae(!1),[J,G]=Ae(!1),de=Hn(Ju),Z=_y(),Y={};if(s&&(Y.destinationNumber=s),o&&(Y.callerNumber=o),r&&(Y.callerName=r),a)try{Y.customHeaders=JSON.parse(a)}catch(ne){re.error("Invalid JSON for call-custom-headers attribute:",a,ne)}if(l)try{Y.audio=JSON.parse(l);const ne=Y.audio;if(typeof ne=="object"){const oe=navigator.mediaDevices.getSupportedConstraints();Object.keys(ne).forEach(Qe=>{oe[Qe]||re.warn(`Audio constraint not supported by browser: ${Qe}`)})}}catch(ne){re.error("Invalid JSON for call-audio attribute:",l,ne)}const ie=qe(()=>{O(!1)},[]),se=qe(ne=>{var oe;if(((oe=ne.call)==null?void 0:oe.state)==="destroy")return de(!1),G(!0),x(null);x(ne)},[de]),ge=qe(()=>{O(!1),I||V(!0)},[I]),Fe=qe(()=>{re.info("User triggered retry"),V(!1),O(!0),_&&_.connect()},[_]),me=qe(ne=>{if(vy(ne)){const oe=ne.params.widget_settings;oe&&Object.keys(oe).length>0&&(Z(oe),Q(!0))}},[Z]),Ie=he(null);return sS(_,{onReady:ie,onConversationUpdate:se,onError:ge,onConfigMessage:me},Ie),cS(_,Ie),L(vS,{position:y,rootRef:Ie,children:t?F||f?L(_S,{agentId:t,onRetry:Fe}):N||I?L(ga,{message:I?"Retrying...":void 0}):M!=null&&M.call?L(uS,{call:M.call,client:_,latencySettings:p,chatMode:D,debug:k}):$?L(fS,{client:_,callProps:Y,chatMode:D&&!J,isReady:S&&!!_}):null:L("div",{children:"Please provide an assistant ID."})})}np(yS,"telnyx-ai-agent",gy,{shadow:!0})})();