@telnyx/ai-agent-widget 0.33.4 → 0.33.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bundle.min.js +24 -24
  2. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- var vb=Object.defineProperty;var _b=(nt,G,jt)=>G in nt?vb(nt,G,{enumerable:!0,configurable:!0,writable:!0,value:jt}):nt[G]=jt;var X=(nt,G,jt)=>_b(nt,typeof G!="symbol"?G+"":G,jt);(function(){"use strict";var nt,G,jt,$t,kr,xr,Er,Ir,ps,gs,ms,Ar,An={},Rr=[],_h=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Rn=Array.isArray;function at(t,e){for(var n in e)t[n]=e[n];return t}function vs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ke(t,e,n){var i,s,r,o={};for(r in e)r=="key"?i=e[r]:r=="ref"?s=e[r]:o[r]=e[r];if(arguments.length>2&&(o.children=arguments.length>3?nt.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)o[r]===void 0&&(o[r]=t.defaultProps[r]);return Ln(t,o,i,s,null)}function Ln(t,e,n,i,s){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++jt,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(r),r}function lt(t){return t.children}function it(t,e){this.props=t,this.context=e}function on(t,e){if(e==null)return t.__?on(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?on(t):null}function Lr(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Lr(t)}}function _s(t){(!t.__d&&(t.__d=!0)&&$t.push(t)&&!_i.__r++||kr!=G.debounceRendering)&&((kr=G.debounceRendering)||xr)(_i)}function _i(){for(var t,e,n,i,s,r,o,a=1;$t.length;)$t.length>a&&$t.sort(Er),t=$t.shift(),a=$t.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,r=[],o=[],e.__P&&((n=at({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),ys(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,r,s??on(i),!!(32&i.__u),o),n.__v=i.__v,n.__.__k[n.__i]=n,Or(r,n,o),n.__e!=s&&Lr(n)));_i.__r=0}function Pr(t,e,n,i,s,r,o,a,l,c,u){var d,f,m,v,y,w,_=i&&i.__k||Rr,T=e.length;for(l=yh(n,e,_,l,T),d=0;d<T;d++)(m=n.__k[d])!=null&&(f=m.__i==-1?An:_[m.__i]||An,m.__i=d,w=ys(t,m,f,s,r,o,a,l,c,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&bs(f.ref,null,m),u.push(m.ref,m.__c||v,m)),y==null&&v!=null&&(y=v),4&m.__u||f.__k===m.__k?l=Dr(m,l,t):typeof m.type=="function"&&w!==void 0?l=w:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=y,l}function yh(t,e,n,i,s){var r,o,a,l,c,u=n.length,d=u,f=0;for(t.__k=new Array(s),r=0;r<s;r++)(o=e[r])!=null&&typeof o!="boolean"&&typeof o!="function"?(l=r+f,(o=t.__k[r]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Ln(null,o,null,null,null):Rn(o)?Ln(lt,{children:o},null,null,null):o.constructor==null&&o.__b>0?Ln(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,a=null,(c=o.__i=bh(o,n,l,d))!=-1&&(d--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?f--:s<u&&f++),typeof o.type!="function"&&(o.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,o.__u|=4))):t.__k[r]=null;if(d)for(r=0;r<u;r++)(a=n[r])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=on(a)),Vr(a,a));return i}function Dr(t,e,n){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Dr(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=on(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ct(t,e){return e=e||[],t==null||typeof t=="boolean"||(Rn(t)?t.some(function(n){ct(n,e)}):e.push(t)),e}function bh(t,e,n,i){var s,r,o=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&o==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,r=n+1;s>=0||r<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&o==l.key&&a==l.type)return s;s--}if(r<e.length){if((l=e[r])&&(2&l.__u)==0&&o==l.key&&a==l.type)return r;r++}}return-1}function Mr(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||_h.test(e)?n:n+"px"}function yi(t,e,n,i,s){var r,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Mr(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Mr(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(Ir,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?i?n.u=i.u:(n.u=ps,t.addEventListener(e,r?ms:gs,r)):t.removeEventListener(e,r?ms:gs,r);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Nr(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ps++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function ys(t,e,n,i,s,r,o,a,l,c){var u,d,f,m,v,y,w,_,T,x,I,A,M,S,C,p,g,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),r=[a=e.__e=n.__e]),(u=G.__b)&&u(e);e:if(typeof h=="function")try{if(_=e.props,T="prototype"in h&&h.prototype.render,x=(u=h.contextType)&&i[u.__c],I=u?x?x.props.value:u.__:i,n.__c?w=(d=e.__c=n.__c).__=d.__E:(T?e.__c=d=new h(_,I):(e.__c=d=new it(_,I),d.constructor=h,d.render=Sh),x&&x.sub(d),d.props=_,d.state||(d.state={}),d.context=I,d.__n=i,f=d.__d=!0,d.__h=[],d._sb=[]),T&&d.__s==null&&(d.__s=d.state),T&&h.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=at({},d.__s)),at(d.__s,h.getDerivedStateFromProps(_,d.__s))),m=d.props,v=d.state,d.__v=e,f)T&&h.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),T&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(T&&h.getDerivedStateFromProps==null&&_!==m&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(_,I),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(_,d.__s,I)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=_,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),A=0;A<d._sb.length;A++)d.__h.push(d._sb[A]);d._sb=[],d.__h.length&&o.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(_,d.__s,I),T&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(m,v,y)})}if(d.context=I,d.props=_,d.__P=t,d.__e=!1,M=G.__r,S=0,T){for(d.state=d.__s,d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),C=0;C<d._sb.length;C++)d.__h.push(d._sb[C]);d._sb=[]}else do d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++S<25);d.state=d.__s,d.getChildContext!=null&&(i=at(at({},i),d.getChildContext())),T&&!f&&d.getSnapshotBeforeUpdate!=null&&(y=d.getSnapshotBeforeUpdate(m,v)),p=u,u!=null&&u.type===lt&&u.key==null&&(p=Fr(u.props.children)),a=Pr(t,Rn(p)?p:[p],e,n,i,s,r,o,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),w&&(d.__E=d.__=null)}catch(b){if(e.__v=null,l||r!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;r[r.indexOf(a)]=null,e.__e=a}else for(g=r.length;g--;)vs(r[g]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=wh(n.__e,e,n,i,s,r,o,l,c);return(u=G.diffed)&&u(e),128&e.__u?void 0:a}function Or(t,e,n){for(var i=0;i<n.length;i++)bs(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(r){r.call(s)})}catch(r){G.__e(r,s.__v)}})}function Fr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Rn(t)?t.map(Fr):at({},t)}function wh(t,e,n,i,s,r,o,a,l){var c,u,d,f,m,v,y,w=n.props,_=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"),r!=null){for(c=0;c<r.length;c++)if((m=r[c])&&"setAttribute"in m==!!T&&(T?m.localName==T:m.nodeType==3)){t=m,r[c]=null;break}}if(t==null){if(T==null)return document.createTextNode(_);t=document.createElementNS(s,T,_.is&&_),a&&(G.__m&&G.__m(e,r),a=!1),r=null}if(T==null)w===_||a&&t.data==_||(t.data=_);else{if(r=r&&nt.call(t.childNodes),w=n.props||An,!a&&r!=null)for(w={},c=0;c<t.attributes.length;c++)w[(m=t.attributes[c]).name]=m.value;for(c in w)if(m=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=m;else if(!(c in _)){if(c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _)continue;yi(t,c,null,m,s)}}for(c in _)m=_[c],c=="children"?f=m:c=="dangerouslySetInnerHTML"?u=m:c=="value"?v=m:c=="checked"?y=m:a&&typeof m!="function"||w[c]===m||yi(t,c,m,w[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=""),Pr(e.type=="template"?t.content:t,Rn(f)?f:[f],e,n,i,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,r,o,r?r[0]:n.__k&&on(n,0),a,l),r!=null)for(c=r.length;c--;)vs(r[c]);a||(c="value",T=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[c]||T=="progress"&&!v||T=="option"&&v!=w[c])&&yi(t,c,v,w[c],s),c="checked",y!=null&&y!=t[c]&&yi(t,c,y,w[c],s))}return t}function bs(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){G.__e(s,n)}}function Vr(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||bs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){G.__e(r,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Vr(i[s],e,n||typeof t.type!="function");n||vs(t.__e),t.__c=t.__=t.__e=void 0}function Sh(t,e,n){return this.constructor(t,n)}function bi(t,e,n){var i,s,r,o;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],o=[],ys(e,t=(!i&&n||e).__k=Ke(lt,null,[t]),s||An,An,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?nt.call(e.childNodes):null,r,!i&&n?n:s?s.__e:e.firstChild,i,o),Or(r,t,o)}function Br(t,e){bi(t,e,Br)}function ws(t,e,n){var i,s,r,o,a=at({},t.props);for(r in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)r=="key"?i=e[r]:r=="ref"?s=e[r]:a[r]=e[r]===void 0&&o!=null?o[r]:e[r];return arguments.length>2&&(a.children=arguments.length>3?nt.call(arguments,2):n),Ln(t.type,a,i||t.key,s||t.ref,null)}function bt(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&i.forEach(function(o){o.__e=!0,_s(o)})},this.sub=function(r){i.add(r);var o=r.componentWillUnmount;r.componentWillUnmount=function(){i&&i.delete(r),o&&o.call(r)}}),n.children}return e.__c="__cC"+Ar++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}nt=Rr.slice,G={__e:function(t,e,n,i){for(var s,r,o;e=e.__;)if((s=e.__c)&&!s.__)try{if((r=s.constructor)&&r.getDerivedStateFromError!=null&&(s.setState(r.getDerivedStateFromError(t)),o=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),o=s.__d),o)return s.__E=s}catch(a){t=a}throw t}},jt=0,it.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=at({},this.state),typeof t=="function"&&(t=t(at({},n),this.props)),t&&at(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),_s(this))},it.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),_s(this))},it.prototype.render=lt,$t=[],xr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Er=function(t,e){return t.__v.__b-e.__v.__b},_i.__r=0,Ir=/(PointerCapture)$|Capture$/i,ps=0,gs=Nr(!1),ms=Nr(!0),Ar=0;var Ch=0;function R(t,e,n,i,s,r){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?o=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ch,__i:-1,__u:0,__source:s,__self:r};if(typeof t=="function"&&(o=t.defaultProps))for(a in o)l[a]===void 0&&(l[a]=o[a]);return G.vnode&&G.vnode(c),c}function Ss(){return(Ss=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var Th=["context","children"];function kh(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var r,o,a={},l=Object.keys(i);for(o=0;o<l.length;o++)s.indexOf(r=l[o])>=0||(a[r]=i[r]);return a}(t,Th);return ws(e,n)}function xh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ke(kh,Ss({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],r={},o=0,a=n.attributes,l=n.childNodes;for(o=a.length;o--;)a[o].name!=="slot"&&(r[a[o].name]=a[o].value,r[Ur(a[o].name)]=a[o].value);for(o=l.length;o--;){var c=e(l[o],null),u=l[o].slot;u?r[u]=Ke(jr,{name:u},c):s[o]=c}var d=i?Ke(jr,null,s):s;return Ke(i||n.nodeName.toLowerCase(),r,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Br:bi)(this._vdom,this._root)}function Ur(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Eh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ur(t)]=n,this._vdom=ws(this._vdom,i),bi(this._vdom,this._root)}}function Ih(){bi(this._vdom=null,this._root)}function jr(t,e){var n=this;return Ke("slot",Ss({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Ah(t,e,n,i){function s(){var r=Reflect.construct(HTMLElement,[],s);return r._vdomComponent=t,r._root=i&&i.shadow?r.attachShadow({mode:i.mode||"open"}):r,r}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=xh,s.prototype.attributeChangedCallback=Eh,s.prototype.disconnectedCallback=Ih,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=n,n.forEach(function(r){Object.defineProperty(s.prototype,r,{get:function(){return this._vdom.props[r]},set:function(o){this._vdom?this.attributeChangedCallback(r,null,o):(this._props||(this._props={}),this._props[r]=o,this.connectedCallback());var a=typeof o;o!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(r,o)}})}),customElements.define(e,s)}var It,pe,Cs,$r,Pn=0,Hr=[],ye=G,Gr=ye.__b,Wr=ye.__r,zr=ye.diffed,qr=ye.__c,Kr=ye.unmount,Xr=ye.__;function rn(t,e){ye.__h&&ye.__h(pe,t,Pn||e),Pn=0;var n=pe.__H||(pe.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ee(t){return Pn=1,Yr(Qr,t)}function Yr(t,e,n){var i=rn(It++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Qr(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=pe,!pe.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(f){return!!f.__c});if(u.every(function(f){return!f.__N}))return!r||r.call(this,a,l,c);var d=i.__c.props!==a;return u.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(d=!0)}}),r&&r.call(this,a,l,c)||d};pe.__f=!0;var r=pe.shouldComponentUpdate,o=pe.componentWillUpdate;pe.componentWillUpdate=function(a,l,c){if(this.__e){var u=r;r=void 0,s(a,l,c),r=u}o&&o.call(this,a,l,c)},pe.shouldComponentUpdate=s}return i.__N||i.__}function Ae(t,e){var n=rn(It++,3);!ye.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,pe.__H.__h.push(n))}function Jr(t,e){var n=rn(It++,4);!ye.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,pe.__h.push(n))}function de(t){return Pn=5,Xe(function(){return{current:t}},[])}function Xe(t,e){var n=rn(It++,7);return xs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function We(t,e){return Pn=8,Xe(function(){return t},e)}function Re(t){var e=pe.context[t.__c],n=rn(It++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(pe)),e.props.value):t.__}function Rh(t,e){ye.useDebugValue&&ye.useDebugValue(e?e(t):t)}function Ts(){var t=rn(It++,11);if(!t.__){for(var e=pe.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function Lh(){for(var t;t=Hr.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(wi),t.__H.__h.forEach(ks),t.__H.__h=[]}catch(e){t.__H.__h=[],ye.__e(e,t.__v)}}ye.__b=function(t){pe=null,Gr&&Gr(t)},ye.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Xr&&Xr(t,e)},ye.__r=function(t){Wr&&Wr(t),It=0;var e=(pe=t.__c).__H;e&&(Cs===pe?(e.__h=[],pe.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(wi),e.__h.forEach(ks),e.__h=[],It=0)),Cs=pe},ye.diffed=function(t){zr&&zr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Hr.push(e)!==1&&$r===ye.requestAnimationFrame||(($r=ye.requestAnimationFrame)||Ph)(Lh)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Cs=pe=null},ye.__c=function(t,e){e.some(function(n){try{n.__h.forEach(wi),n.__h=n.__h.filter(function(i){return!i.__||ks(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ye.__e(i,n.__v)}}),qr&&qr(t,e)},ye.unmount=function(t){Kr&&Kr(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{wi(i)}catch(s){e=s}}),n.__H=void 0,e&&ye.__e(e,n.__v))};var Zr=typeof requestAnimationFrame=="function";function Ph(t){var e,n=function(){clearTimeout(i),Zr&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Zr&&(e=requestAnimationFrame(n))}function wi(t){var e=pe,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),pe=e}function ks(t){var e=pe;t.__c=t.__(),pe=e}function xs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Qr(t,e){return typeof e=="function"?e(t):e}const Dn={},ea=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ta=t=>"init"in t,Es=t=>!!t.write,na=t=>"v"in t||"e"in t,Si=t=>{if("e"in t)throw t.e;if((Dn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Ci=new WeakMap,ia=t=>{var e;return Ti(t)&&!!((e=Ci.get(t))!=null&&e[0])},Dh=t=>{const e=Ci.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},sa=(t,e)=>{let n=Ci.get(t);if(!n){n=[!0,new Set],Ci.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},Ti=t=>typeof(t==null?void 0:t.then)=="function",oa=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Is=(t,e,n)=>{const i=n(t),s="v"in i,r=i.v;if(Ti(e))for(const o of i.d.keys())oa(t,e,n(o));i.v=e,delete i.e,(!s||!Object.is(r,i.v))&&(++i.n,Ti(r)&&Dh(r))},ra=(t,e,n)=>{var i;const s=new Set;for(const r of((i=n.get(t))==null?void 0:i.t)||[])n.has(r)&&s.add(r);for(const r of e.p)s.add(r);return s},Mh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},As=()=>{const t={},e=new WeakMap,n=i=>{var s,r;(s=e.get(t))==null||s.forEach(o=>o(i)),(r=e.get(i))==null||r.forEach(o=>o())};return n.add=(i,s)=>{const r=i||t,o=(e.has(r)?e:e.set(r,new Set)).get(r);return o.add(s),()=>{o==null||o.delete(s),o.size||e.delete(r)}},n},Nh=t=>(t.c||(t.c=As()),t.m||(t.m=As()),t.u||(t.u=As()),t.f||(t.f=Mh()),t),Oh=Symbol(),aa=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,r=new Set,o={},a=(f,...m)=>f.read(...m),l=(f,...m)=>f.write(...m),c=(f,m)=>{var v;return(v=f.unstable_onInit)==null?void 0:v.call(f,m)},u=(f,m)=>{var v;return(v=f.onMount)==null?void 0:v.call(f,m)},...d)=>{const f=d[0]||(S=>{if((Dn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let C=t.get(S);return C||(C={d:new Map,p:new Set,n:0},t.set(S,C),c==null||c(S,M)),C}),m=d[1]||(()=>{const S=[],C=p=>{try{p()}catch(g){S.push(g)}};do{o.f&&C(o.f);const p=new Set,g=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(g)}),i.clear(),r.forEach(g),r.clear(),s.forEach(g),s.clear(),p.forEach(C),i.size&&v()}while(i.size||r.size||s.size);if(S.length)throw new AggregateError(S)}),v=d[2]||(()=>{const S=[],C=new WeakSet,p=new WeakSet,g=Array.from(i);for(;g.length;){const h=g[g.length-1],b=f(h);if(p.has(h)){g.pop();continue}if(C.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Dn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),g.pop();continue}C.add(h);for(const E of ra(h,b,e))C.has(E)||g.push(E)}for(let h=S.length-1;h>=0;--h){const[b,E]=S[h];let P=!1;for(const L of E.d.keys())if(L!==b&&i.has(L)){P=!0;break}P&&(y(b),T(b)),n.delete(b)}}),y=d[3]||(S=>{var C;const p=f(S);if(na(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([D,U])=>y(D).n===U)))return p;p.d.clear();let g=!0;const h=()=>{e.has(S)&&(T(S),v(),m())},b=D=>{var U;if(ea(S,D)){const j=f(D);if(!na(j))if(ta(D))Is(D,D.init,f);else throw new Error("no atom init");return Si(j)}const Y=y(D);try{return Si(Y)}finally{p.d.set(D,Y.n),ia(p.v)&&oa(S,p.v,Y),(U=e.get(D))==null||U.t.add(S),g||h()}};let E,P;const L={get signal(){return E||(E=new AbortController),E.signal},get setSelf(){return(Dn?"production":void 0)!=="production"&&!Es(S)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&Es(S)&&(P=(...D)=>{if((Dn?"production":void 0)!=="production"&&g&&console.warn("setSelf function cannot be called in sync"),!g)try{return _(S,...D)}finally{v(),m()}}),P}},N=p.n;try{const D=a(S,b,L);return Is(S,D,f),Ti(D)&&(sa(D,()=>E==null?void 0:E.abort()),D.then(h,h)),p}catch(D){return delete p.v,p.e=D,++p.n,p}finally{g=!1,N!==p.n&&n.get(S)===N&&(n.set(S,p.n),i.add(S),(C=o.c)==null||C.call(o,S))}}),w=d[4]||(S=>{const C=[S];for(;C.length;){const p=C.pop(),g=f(p);for(const h of ra(p,g,e)){const b=f(h);n.set(h,b.n),C.push(h)}}}),_=d[5]||((S,...C)=>{let p=!0;const g=b=>Si(y(b)),h=(b,...E)=>{var P;const L=f(b);try{if(ea(S,b)){if(!ta(b))throw new Error("atom not writable");const N=L.n,D=E[0];Is(b,D,f),T(b),N!==L.n&&(i.add(b),(P=o.c)==null||P.call(o,b),w(b));return}else return _(b,...E)}finally{p||(v(),m())}};try{return l(S,g,h,...C)}finally{p=!1}}),T=d[6]||(S=>{var C;const p=f(S),g=e.get(S);if(g&&!ia(p.v)){for(const[h,b]of p.d)if(!g.d.has(h)){const E=f(h);x(h).t.add(S),g.d.add(h),b!==E.n&&(i.add(h),(C=o.c)==null||C.call(o,h),w(h))}for(const h of g.d||[])if(!p.d.has(h)){g.d.delete(h);const b=I(h);b==null||b.t.delete(S)}}}),x=d[7]||(S=>{var C;const p=f(S);let g=e.get(S);if(!g){y(S);for(const h of p.d.keys())x(h).t.add(S);if(g={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,g),(C=o.m)==null||C.call(o,S),Es(S)){const h=()=>{let b=!0;const E=(...P)=>{try{return _(S,...P)}finally{b||(v(),m())}};try{const P=u(S,E);P&&(g.u=()=>{b=!0;try{P()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return g}),I=d[8]||(S=>{var C;const p=f(S);let g=e.get(S);if(g&&!g.l.size&&!Array.from(g.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){g.u&&r.add(g.u),g=void 0,e.delete(S),(C=o.u)==null||C.call(o,S);for(const h of p.d.keys()){const b=I(h);b==null||b.t.delete(S)}return}return g}),A=[t,e,n,i,s,r,o,a,l,c,u,f,m,v,y,w,_,T,x,I],M={get:S=>Si(y(S)),set:(S,...C)=>{try{return _(S,...C)}finally{v(),m()}},sub:(S,C)=>{const g=x(S).l;return g.add(C),m(),()=>{g.delete(C),I(S),m()}}};return Object.defineProperty(M,Oh,{value:A}),M},Fh=Nh,la=sa,Rs={};let Vh=0;function ki(t,e){const n=`atom${++Vh}`,i={toString(){return(Rs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=Bh,i.write=Uh),i}function Bh(t){return t(this)}function Uh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const jh=()=>{let t=0;const e=Fh({}),n=new WeakMap,i=new WeakMap,s=aa(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),r=new Set;return e.m.add(void 0,a=>{r.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{r.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>r,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,f]of a)"init"in d&&u(d,f)}finally{--t}}};s.set(l)}})};function $h(){return(Rs?"production":void 0)!=="production"?jh():aa()}let Mn;function Hh(){return Mn||(Mn=$h(),(Rs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Mn),globalThis.__JOTAI_DEFAULT_STORE__!==Mn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Mn}function ca(t,e){for(var n in e)t[n]=e[n];return t}function da(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}var ua=Jr;function ha(t,e){this.props=t,this.context=e}(ha.prototype=new it).isPureReactComponent=!0,ha.prototype.shouldComponentUpdate=function(t,e){return da(this.props,t)||da(this.state,e)};var fa=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),fa&&fa(t)};var Gh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Wh(t){function e(n){var i=ca({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Gh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var pa=function(t,e){return t==null?null:ct(ct(t).map(e))},zh={map:pa,forEach:pa,count:function(t){return t?ct(t).length:0},only:function(t){var e=ct(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ct},qh=G.__e;G.__e=function(t,e,n,i){if(t.then){for(var s,r=e;r=r.__;)if((s=r.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}qh(t,e,n,i)};var ga=G.unmount;function ma(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=ca({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return ma(i,e,n)})),t}function va(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return va(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Ls(){this.__u=0,this.o=null,this.__b=null}function _a(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function xi(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),ga&&ga(t)},(Ls.prototype=new it).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=_a(i.__v),r=!1,o=function(){r||(r=!0,n.__R=null,s?s(a):a())};n.__R=o;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=va(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Ls.prototype.componentWillUnmount=function(){this.o=[]},Ls.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=ma(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&Ke(lt,null,t.fallback);return s&&(s.__u&=-33),[Ke(lt,null,e.__a?null:t.children),s]};var ya=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(xi.prototype=new it).__a=function(t){var e=this,n=_a(e.__v),i=e.l.get(t);return i[0]++,function(s){var r=function(){e.props.revealOrder?(i.push(s),ya(e,t,i)):s()};n?n(r):r()}},xi.prototype.render=function(t){this.i=null,this.l=new Map;var e=ct(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},xi.prototype.componentDidUpdate=xi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){ya(t,n,e)})};var ba=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Kh=/^(?: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]/,Xh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Yh=/[A-Z0-9]/g,Jh=typeof document<"u",Zh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};it.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(it.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var wa=G.event;function Qh(){}function ef(){return this.cancelBubble}function tf(){return this.defaultPrevented}G.event=function(t){return wa&&(t=wa(t)),t.persist=Qh,t.isPropagationStopped=ef,t.isDefaultPrevented=tf,t.nativeEvent=t};var nf={enumerable:!1,configurable:!0,get:function(){return this.class}},Sa=G.vnode;G.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},r=i.indexOf("-")===-1;for(var o in n){var a=n[o];if(!(o==="value"&&"defaultValue"in n&&a==null||Jh&&o==="children"&&i==="noscript"||o==="class"||o==="className")){var l=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?o="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Zh(n.type)?l==="onfocus"?o="onfocusin":l==="onblur"?o="onfocusout":Xh.test(o)&&(o=l):l=o="oninput":r&&Kh.test(o)?o=o.replace(Yh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[o=l]&&(o="oninputCapture"),s[o]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",nf)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ba,Sa&&Sa(t)};var Ca=G.__r;G.__r=function(t){Ca&&Ca(t),t.__c};var Ta=G.diffed;G.diffed=function(t){Ta&&Ta(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value)};function ka(t){return!!t&&t.$$typeof===ba}function sf(t){return ka(t)?ws.apply(null,arguments):t}var xa={};const of={},rf=bt(void 0);function Ea(t){return Re(rf)||Hh()}const Ps=t=>typeof(t==null?void 0:t.then)=="function",Ds=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},af=xa.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ds(t),t)}),Ms=new WeakMap,Ia=(t,e)=>{let n=Ms.get(t);return n||(n=new Promise((i,s)=>{let r=t;const o=c=>u=>{r===c&&i(u)},a=c=>u=>{r===c&&s(u)},l=()=>{try{const c=e();Ps(c)?(Ms.set(c,n),r=c,c.then(o(c),a(c)),la(c,l)):i(c)}catch(c){s(c)}};t.then(o(t),a(t)),la(t,l)}),Ms.set(t,n)),n};function Ns(t,e){const{delay:n,unstable_promiseStatus:i=!xa.use}={},s=Ea(),[[r,o,a],l]=Yr(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=r;if((o!==s||a!==t)&&(l(),c=s.get(t)),Ae(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);Ps(d)&&Ds(Ia(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),u},[s,t,n,i]),Rh(c),Ps(c)){const u=Ia(c,()=>s.get(t));return i&&Ds(u),af(u)}return c}function Ei(t,e){const n=Ea();return We((...s)=>{if((of?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function Aa(t,e){return[Ns(t),Ei(t)]}const Os=bt({});function Ii(t){const e=de(null);return e.current===null&&(e.current=t()),e.current}const Fs=typeof window<"u",Ra=Fs?Jr:Ae,Ai=bt(null);function Vs(t,e){t.indexOf(e)===-1&&t.push(e)}function Bs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const wt=(t,e,n)=>n>e?e:n<t?t:n;let Us=()=>{};const St={},La=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Pa(t){return typeof t=="object"&&t!==null}const Da=t=>/^0[^.\s]+$/u.test(t);function js(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ye=t=>t,lf=(t,e)=>n=>e(t(n)),Nn=(...t)=>t.reduce(lf),On=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class $s{constructor(){this.subscriptions=[]}add(e){return Vs(this.subscriptions,e),()=>Bs(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let r=0;r<s;r++){const o=this.subscriptions[r];o&&o(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const dt=t=>t*1e3,ut=t=>t/1e3;function Ma(t,e){return e?t*(1e3/e):0}const Na=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,cf=1e-7,df=12;function uf(t,e,n,i,s){let r,o,a=0;do o=e+(n-e)/2,r=Na(o,i,s)-t,r>0?n=o:e=o;while(Math.abs(r)>cf&&++a<df);return o}function Fn(t,e,n,i){if(t===e&&n===i)return Ye;const s=r=>uf(r,0,1,t,n);return r=>r===0||r===1?r:Na(s(r),e,i)}const Oa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Fa=t=>e=>1-t(1-e),Va=Fn(.33,1.53,.69,.99),Hs=Fa(Va),Ba=Oa(Hs),Ua=t=>(t*=2)<1?.5*Hs(t):.5*(2-Math.pow(2,-10*(t-1))),Gs=t=>1-Math.sin(Math.acos(t)),ja=Fa(Gs),$a=Oa(Gs),hf=Fn(.42,0,1,1),ff=Fn(0,0,.58,1),Ha=Fn(.42,0,.58,1),pf=t=>Array.isArray(t)&&typeof t[0]!="number",Ga=t=>Array.isArray(t)&&typeof t[0]=="number",gf={linear:Ye,easeIn:hf,easeInOut:Ha,easeOut:ff,circIn:Gs,circInOut:$a,circOut:ja,backIn:Hs,backInOut:Ba,backOut:Va,anticipate:Ua},mf=t=>typeof t=="string",Wa=t=>{if(Ga(t)){Us(t.length===4);const[e,n,i,s]=t;return Fn(e,n,i,s)}else if(mf(t))return gf[t];return t},Ri=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],za={value:null};function vf(t,e){let n=new Set,i=new Set,s=!1,r=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){o.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,f=!1,m=!1)=>{const y=m&&s?n:i;return f&&o.add(d),y.has(d)||y.add(d),d},cancel:d=>{i.delete(d),o.delete(d)},process:d=>{if(a=d,s){r=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&za.value&&za.value.frameloop[e].push(l),l=0,n.clear(),s=!1,r&&(r=!1,u.process(d))}};return u}const _f=40;function qa(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,o=Ri.reduce((x,I)=>(x[I]=vf(r,e?I:void 0),x),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:f,render:m,postRender:v}=o,y=()=>{const x=St.useManualTiming?s.timestamp:performance.now();n=!1,St.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(x-s.timestamp,_f),1)),s.timestamp=x,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),f.process(s),m.process(s),v.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(y))},w=()=>{n=!0,i=!0,s.isProcessing||t(y)};return{schedule:Ri.reduce((x,I)=>{const A=o[I];return x[I]=(M,S=!1,C=!1)=>(n||w(),A.schedule(M,S,C)),x},{}),cancel:x=>{for(let I=0;I<Ri.length;I++)o[Ri[I]].cancel(x)},state:s,steps:o}}const{schedule:ve,cancel:At,state:Pe,steps:Ws}=qa(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ye,!0);let Li;function yf(){Li=void 0}const $e={now:()=>(Li===void 0&&$e.set(Pe.isProcessing||St.useManualTiming?Pe.timestamp:performance.now()),Li),set:t=>{Li=t,queueMicrotask(yf)}},Ka=t=>e=>typeof e=="string"&&e.startsWith(t),zs=Ka("--"),bf=Ka("var(--"),qs=t=>bf(t)?wf.test(t.split("/*")[0].trim()):!1,wf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,an={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Vn={...an,transform:t=>wt(0,1,t)},Pi={...an,default:1},Bn=t=>Math.round(t*1e5)/1e5,Ks=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Sf(t){return t==null}const Cf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Xs=(t,e)=>n=>!!(typeof n=="string"&&Cf.test(n)&&n.startsWith(t)||e&&!Sf(n)&&Object.prototype.hasOwnProperty.call(n,e)),Xa=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,r,o,a]=i.match(Ks);return{[t]:parseFloat(s),[e]:parseFloat(r),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},Tf=t=>wt(0,255,t),Ys={...an,transform:t=>Math.round(Tf(t))},Ht={test:Xs("rgb","red"),parse:Xa("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ys.transform(t)+", "+Ys.transform(e)+", "+Ys.transform(n)+", "+Bn(Vn.transform(i))+")"};function kf(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const Js={test:Xs("#"),parse:kf,transform:Ht.transform},Un=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Rt=Un("deg"),ht=Un("%"),W=Un("px"),xf=Un("vh"),Ef=Un("vw"),Ya={...ht,parse:t=>ht.parse(t)/100,transform:t=>ht.transform(t*100)},ln={test:Xs("hsl","hue"),parse:Xa("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ht.transform(Bn(e))+", "+ht.transform(Bn(n))+", "+Bn(Vn.transform(i))+")"},ke={test:t=>Ht.test(t)||Js.test(t)||ln.test(t),parse:t=>Ht.test(t)?Ht.parse(t):ln.test(t)?ln.parse(t):Js.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ht.transform(t):ln.transform(t),getAnimatableNone:t=>{const e=ke.parse(t);return e.alpha=0,ke.transform(e)}},If=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Af(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Ks))==null?void 0:e.length)||0)+(((n=t.match(If))==null?void 0:n.length)||0)>0}const Ja="number",Za="color",Rf="var",Lf="var(",Qa="${}",Pf=/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 jn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let r=0;const a=e.replace(Pf,l=>(ke.test(l)?(i.color.push(r),s.push(Za),n.push(ke.parse(l))):l.startsWith(Lf)?(i.var.push(r),s.push(Rf),n.push(l)):(i.number.push(r),s.push(Ja),n.push(parseFloat(l))),++r,Qa)).split(Qa);return{values:n,split:a,indexes:i,types:s}}function el(t){return jn(t).values}function tl(t){const{split:e,types:n}=jn(t),i=e.length;return s=>{let r="";for(let o=0;o<i;o++)if(r+=e[o],s[o]!==void 0){const a=n[o];a===Ja?r+=Bn(s[o]):a===Za?r+=ke.transform(s[o]):r+=s[o]}return r}}const Df=t=>typeof t=="number"?0:ke.test(t)?ke.getAnimatableNone(t):t;function Mf(t){const e=el(t);return tl(t)(e.map(Df))}const Lt={test:Af,parse:el,createTransformer:tl,getAnimatableNone:Mf};function Zs(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function Nf({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,r=0,o=0;if(!e)s=r=o=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Zs(l,a,t+1/3),r=Zs(l,a,t),o=Zs(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(r*255),blue:Math.round(o*255),alpha:i}}function Di(t,e){return n=>n>0?e:t}const be=(t,e,n)=>t+(e-t)*n,Qs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Of=[Js,Ht,ln],Ff=t=>Of.find(e=>e.test(t));function nl(t){const e=Ff(t);if(!e)return!1;let n=e.parse(t);return e===ln&&(n=Nf(n)),n}const il=(t,e)=>{const n=nl(t),i=nl(e);if(!n||!i)return Di(t,e);const s={...n};return r=>(s.red=Qs(n.red,i.red,r),s.green=Qs(n.green,i.green,r),s.blue=Qs(n.blue,i.blue,r),s.alpha=be(n.alpha,i.alpha,r),Ht.transform(s))},eo=new Set(["none","hidden"]);function Vf(t,e){return eo.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Bf(t,e){return n=>be(t,e,n)}function to(t){return typeof t=="number"?Bf:typeof t=="string"?qs(t)?Di:ke.test(t)?il:$f:Array.isArray(t)?sl:typeof t=="object"?ke.test(t)?il:Uf:Di}function sl(t,e){const n=[...t],i=n.length,s=t.map((r,o)=>to(r)(r,e[o]));return r=>{for(let o=0;o<i;o++)n[o]=s[o](r);return n}}function Uf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=to(t[s])(t[s],e[s]));return s=>{for(const r in i)n[r]=i[r](s);return n}}function jf(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const r=e.types[s],o=t.indexes[r][i[r]],a=t.values[o]??0;n[s]=a,i[r]++}return n}const $f=(t,e)=>{const n=Lt.createTransformer(e),i=jn(t),s=jn(e);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?eo.has(t)&&!s.values.length||eo.has(e)&&!i.values.length?Vf(t,e):Nn(sl(jf(i,s),s.values),n):Di(t,e)};function ol(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?be(t,e,n):to(t)(t,e)}const Hf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ve.update(e,n),stop:()=>At(e),now:()=>Pe.isProcessing?Pe.timestamp:$e.now()}},rl=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let r=0;r<s;r++)i+=Math.round(t(r/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Mi=2e4;function no(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Mi;)e+=n,i=t.next(e);return e>=Mi?1/0:e}function Gf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(no(i),Mi);return{type:"keyframes",ease:r=>i.next(s*r).value/e,duration:ut(s)}}const Wf=5;function al(t,e,n){const i=Math.max(e-Wf,0);return Ma(n-t(i),e-i)}const we={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},io=.001;function zf({duration:t=we.duration,bounce:e=we.bounce,velocity:n=we.velocity,mass:i=we.mass}){let s,r,o=1-e;o=wt(we.minDamping,we.maxDamping,o),t=wt(we.minDuration,we.maxDuration,ut(t)),o<1?(s=c=>{const u=c*o,d=u*t,f=u-n,m=so(c,o),v=Math.exp(-d);return io-f/m*v},r=c=>{const d=c*o*t,f=d*n+n,m=Math.pow(o,2)*Math.pow(c,2)*t,v=Math.exp(-d),y=so(Math.pow(c,2),o);return(-s(c)+io>0?-1:1)*((f-m)*v)/y}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-io+u*d},r=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const a=5/t,l=Kf(s,r,a);if(t=dt(t),isNaN(l))return{stiffness:we.stiffness,damping:we.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:o*2*Math.sqrt(i*c),duration:t}}}const qf=12;function Kf(t,e,n){let i=n;for(let s=1;s<qf;s++)i=i-t(i)/e(i);return i}function so(t,e){return t*Math.sqrt(1-e*e)}const Xf=["duration","bounce"],Yf=["stiffness","damping","mass"];function ll(t,e){return e.some(n=>t[n]!==void 0)}function Jf(t){let e={velocity:we.velocity,stiffness:we.stiffness,damping:we.damping,mass:we.mass,isResolvedFromDuration:!1,...t};if(!ll(t,Yf)&&ll(t,Xf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,r=2*wt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:we.mass,stiffness:s,damping:r}}else{const n=zf(t);e={...e,...n,mass:we.mass},e.isResolvedFromDuration=!0}return e}function Ni(t=we.visualDuration,e=we.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const r=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:r},{stiffness:l,damping:c,mass:u,duration:d,velocity:f,isResolvedFromDuration:m}=Jf({...n,velocity:-ut(n.velocity||0)}),v=f||0,y=c/(2*Math.sqrt(l*u)),w=o-r,_=ut(Math.sqrt(l/u)),T=Math.abs(w)<5;i||(i=T?we.restSpeed.granular:we.restSpeed.default),s||(s=T?we.restDelta.granular:we.restDelta.default);let x;if(y<1){const A=so(_,y);x=M=>{const S=Math.exp(-y*_*M);return o-S*((v+y*_*w)/A*Math.sin(A*M)+w*Math.cos(A*M))}}else if(y===1)x=A=>o-Math.exp(-_*A)*(w+(v+_*w)*A);else{const A=_*Math.sqrt(y*y-1);x=M=>{const S=Math.exp(-y*_*M),C=Math.min(A*M,300);return o-S*((v+y*_*w)*Math.sinh(C)+A*w*Math.cosh(C))/A}}const I={calculatedDuration:m&&d||null,next:A=>{const M=x(A);if(m)a.done=A>=d;else{let S=A===0?v:0;y<1&&(S=A===0?dt(v):al(x,A,M));const C=Math.abs(S)<=i,p=Math.abs(o-M)<=s;a.done=C&&p}return a.value=a.done?o:M,a},toString:()=>{const A=Math.min(no(I),Mi),M=rl(S=>I.next(A*S).value,A,30);return A+"ms "+M},toTransition:()=>{}};return I}Ni.applyToOptions=t=>{const e=Gf(t,100,Ni);return t.ease=e.ease,t.duration=dt(e.duration),t.type="keyframes",t};function oo({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:r=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],f={done:!1,value:d},m=C=>a!==void 0&&C<a||l!==void 0&&C>l,v=C=>a===void 0?l:l===void 0||Math.abs(a-C)<Math.abs(l-C)?a:l;let y=n*e;const w=d+y,_=o===void 0?w:o(w);_!==w&&(y=_-d);const T=C=>-y*Math.exp(-C/i),x=C=>_+T(C),I=C=>{const p=T(C),g=x(C);f.done=Math.abs(p)<=c,f.value=f.done?_:g};let A,M;const S=C=>{m(f.value)&&(A=C,M=Ni({keyframes:[f.value,v(f.value)],velocity:al(x,C,f.value),damping:s,stiffness:r,restDelta:c,restSpeed:u}))};return S(0),{calculatedDuration:null,next:C=>{let p=!1;return!M&&A===void 0&&(p=!0,I(C),S(C)),A!==void 0&&C>=A?M.next(C-A):(!p&&I(C),f)}}}function Zf(t,e,n){const i=[],s=n||St.mix||ol,r=t.length-1;for(let o=0;o<r;o++){let a=s(t[o],t[o+1]);if(e){const l=Array.isArray(e)?e[o]||Ye:e;a=Nn(l,a)}i.push(a)}return i}function Qf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const r=t.length;if(Us(r===e.length),r===1)return()=>e[0];if(r===2&&e[0]===e[1])return()=>e[1];const o=t[0]===t[1];t[0]>t[r-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Zf(e,i,s),l=a.length,c=u=>{if(o&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const f=On(t[d],t[d+1],u);return a[d](f)};return n?u=>c(wt(t[0],t[r-1],u)):c}function ep(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=On(0,e,i);t.push(be(n,1,s))}}function tp(t){const e=[0];return ep(e,t.length-1),e}function np(t,e){return t.map(n=>n*e)}function ip(t,e){return t.map(()=>e||Ha).splice(0,t.length-1)}function $n({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=pf(i)?i.map(Wa):Wa(i),r={done:!1,value:e[0]},o=np(n&&n.length===e.length?n:tp(e),t),a=Qf(o,e,{ease:Array.isArray(s)?s:ip(e,s)});return{calculatedDuration:t,next:l=>(r.value=a(l),r.done=l>=t,r)}}const sp=t=>t!==null;function ro(t,{repeat:e,repeatType:n="loop"},i,s=1){const r=t.filter(sp),a=s<0||e&&n!=="loop"&&e%2===1?0:r.length-1;return!a||i===void 0?r[a]:i}const op={decay:oo,inertia:oo,tween:$n,keyframes:$n,spring:Ni};function cl(t){typeof t.type=="string"&&(t.type=op[t.type])}class ao{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const rp=t=>t/100;class lo extends ao{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,s;const{motionValue:n}=this.options;n&&n.updatedAt!==$e.now()&&this.tick($e.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;cl(e);const{type:n=$n,repeat:i=0,repeatDelay:s=0,repeatType:r,velocity:o=0}=e;let{keyframes:a}=e;const l=n||$n;l!==$n&&typeof a[0]!="number"&&(this.mixKeyframes=Nn(rp,ol(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});r==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-o})),c.calculatedDuration===null&&(c.calculatedDuration=no(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:r,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:f,repeatDelay:m,type:v,onUpdate:y,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const _=this.currentTime-c*(this.playbackSpeed>=0?1:-1),T=this.playbackSpeed>=0?_<0:_>s;this.currentTime=Math.max(_,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let x=this.currentTime,I=i;if(d){const C=Math.min(this.currentTime,s)/a;let p=Math.floor(C),g=C%1;!g&&C>=1&&(g=1),g===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(f==="reverse"?(g=1-g,m&&(g-=m/a)):f==="mirror"&&(I=o)),x=wt(0,1,g)*a}const A=T?{done:!1,value:u[0]}:I.next(x);r&&(A.value=r(A.value));let{done:M}=A;!T&&l!==null&&(M=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return S&&v!==oo&&(A.value=ro(u,this.options,w,this.speed)),y&&y(A.value),S&&this.finish(),A}then(e,n){return this.finished.then(e,n)}get duration(){return ut(this.calculatedDuration)}get time(){return ut(this.currentTime)}set time(e){var n;e=dt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime($e.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=ut(this.currentTime))}play(){var s,r;if(this.isStopped)return;const{driver:e=Hf,startTime:n}=this.options;this.driver||(this.driver=e(o=>this.tick(o))),(r=(s=this.options).onPlay)==null||r.call(s);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime($e.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function ap(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Gt=t=>t*180/Math.PI,co=t=>{const e=Gt(Math.atan2(t[1],t[0]));return uo(e)},lp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:co,rotateZ:co,skewX:t=>Gt(Math.atan(t[1])),skewY:t=>Gt(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),dl=co,ul=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),hl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),cp={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ul,scaleY:hl,scale:t=>(ul(t)+hl(t))/2,rotateX:t=>uo(Gt(Math.atan2(t[6],t[5]))),rotateY:t=>uo(Gt(Math.atan2(-t[2],t[0]))),rotateZ:dl,rotate:dl,skewX:t=>Gt(Math.atan(t[4])),skewY:t=>Gt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ho(t){return t.includes("scale")?1:0}function fo(t,e){if(!t||t==="none")return ho(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=cp,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=lp,s=a}if(!s)return ho(e);const r=i[e],o=s[1].split(",").map(up);return typeof r=="function"?r(o):o[r]}const dp=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return fo(n,e)};function up(t){return parseFloat(t.trim())}const cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dn=new Set(cn),fl=t=>t===an||t===W,hp=new Set(["x","y","z"]),fp=cn.filter(t=>!hp.has(t));function pp(t){const e=[];return fp.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Wt={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>fo(e,"x"),y:(t,{transform:e})=>fo(e,"y")};Wt.translateX=Wt.x,Wt.translateY=Wt.y;const zt=new Set;let po=!1,go=!1,mo=!1;function pl(){if(go){const t=Array.from(zt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=pp(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([r,o])=>{var a;(a=i.getValue(r))==null||a.set(o)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}go=!1,po=!1,zt.forEach(t=>t.complete(mo)),zt.clear()}function gl(){zt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(go=!0)})}function gp(){mo=!0,gl(),pl(),mo=!1}class vo{constructor(e,n,i,s,r,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=r,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(zt.add(this),po||(po=!0,ve.read(gl),ve.resolveKeyframes(pl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const r=s==null?void 0:s.get(),o=e[e.length-1];if(r!==void 0)e[0]=r;else if(i&&n){const a=i.readValue(n,o);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=o),s&&r===void 0&&s.set(e[0])}ap(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),zt.delete(this)}cancel(){this.state==="scheduled"&&(zt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const mp=t=>t.startsWith("--");function vp(t,e,n){mp(e)?t.style.setProperty(e,n):t.style[e]=n}const _p=js(()=>window.ScrollTimeline!==void 0),yp={};function bp(t,e){const n=js(t);return()=>yp[e]??n()}const ml=bp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Hn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,vl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Hn([0,.65,.55,1]),circOut:Hn([.55,0,1,.45]),backIn:Hn([.31,.01,.66,-.59]),backOut:Hn([.33,1.53,.69,.99])};function _l(t,e){if(t)return typeof t=="function"?ml()?rl(t,e):"ease-out":Ga(t)?Hn(t):Array.isArray(t)?t.map(n=>_l(n,e)||vl.easeOut):vl[t]}function wp(t,e,n,{delay:i=0,duration:s=300,repeat:r=0,repeatType:o="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=_l(a,s);Array.isArray(d)&&(u.easing=d);const f={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:r+1,direction:o==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(u,f)}function yl(t){return typeof t=="function"&&"applyToOptions"in t}function Sp({type:t,...e}){return yl(t)&&ml()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Cp extends ao{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:r,allowFlatten:o=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!r,this.allowFlatten=o,this.options=e,Us(typeof e.type!="string");const c=Sp(e);this.animation=wp(n,i,s,c,r),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=ro(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):vp(n,i,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return ut(Number(e))}get time(){return ut(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=dt(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&_p()?(this.animation.timeline=e,Ye):n(this)}}const bl={anticipate:Ua,backInOut:Ba,circInOut:$a};function Tp(t){return t in bl}function kp(t){typeof t.ease=="string"&&Tp(t.ease)&&(t.ease=bl[t.ease])}const wl=10;class xp extends Cp{constructor(e){kp(e),cl(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:r,...o}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new lo({...o,autoplay:!1}),l=dt(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-wl).value,a.sample(l).value,wl),a.stop()}}const Sl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Lt.test(t)||t==="0")&&!t.startsWith("url("));function Ep(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function Ip(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const r=t[t.length-1],o=Sl(s,e),a=Sl(r,e);return!o||!a?!1:Ep(t)||(n==="spring"||yl(n))&&i}function _o(t){return Pa(t)&&"offsetHeight"in t}const Ap=new Set(["opacity","clipPath","filter","transform"]),Rp=js(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Lp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:r,type:o}=t;if(!_o((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return Rp()&&n&&Ap.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&r!==0&&o!=="inertia"}const Pp=40;class Dp extends ao{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:r=0,repeatType:o="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var v;super(),this.stop=()=>{var y,w;this._animation&&(this._animation.stop(),(y=this.stopTimeline)==null||y.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=$e.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:r,repeatType:o,name:l,motionValue:c,element:u,...d},m=(u==null?void 0:u.KeyframeResolver)||vo;this.keyframeResolver=new m(a,(y,w,_)=>this.onKeyframesResolved(y,w,f,!_),l,c,u),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:r,type:o,velocity:a,delay:l,isHandoff:c,onUpdate:u}=i;this.resolvedAt=$e.now(),Ip(e,r,o,a)||((St.instantAnimations||!l)&&(u==null||u(ro(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Pp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},m=!c&&Lp(f)?new xp({...f,element:f.motionValue.owner.current}):new lo(f);m.finished.then(()=>this.notifyFinished()).catch(Ye),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),gp()),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 Mp=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Np(t){const e=Mp.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function Cl(t,e,n=1){const[i,s]=Np(t);if(!i)return;const r=window.getComputedStyle(e).getPropertyValue(i);if(r){const o=r.trim();return La(o)?parseFloat(o):o}return qs(s)?Cl(s,e,n+1):s}function yo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Tl=new Set(["width","height","top","left","right","bottom",...cn]),Op={test:t=>t==="auto",parse:t=>t},kl=t=>e=>e.test(t),xl=[an,W,ht,Rt,Ef,xf,Op],El=t=>xl.find(kl(t));function Fp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Da(t):!0}const Vp=new Set(["brightness","contrast","saturate","opacity"]);function Bp(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Ks)||[];if(!i)return t;const s=n.replace(i,"");let r=Vp.has(e)?1:0;return i!==n&&(r*=100),e+"("+r+s+")"}const Up=/\b([a-z-]*)\(.*?\)/gu,bo={...Lt,getAnimatableNone:t=>{const e=t.match(Up);return e?e.map(Bp).join(" "):t}},Il={...an,transform:Math.round},wo={borderWidth:W,borderTopWidth:W,borderRightWidth:W,borderBottomWidth:W,borderLeftWidth:W,borderRadius:W,radius:W,borderTopLeftRadius:W,borderTopRightRadius:W,borderBottomRightRadius:W,borderBottomLeftRadius:W,width:W,maxWidth:W,height:W,maxHeight:W,top:W,right:W,bottom:W,left:W,padding:W,paddingTop:W,paddingRight:W,paddingBottom:W,paddingLeft:W,margin:W,marginTop:W,marginRight:W,marginBottom:W,marginLeft:W,backgroundPositionX:W,backgroundPositionY:W,...{rotate:Rt,rotateX:Rt,rotateY:Rt,rotateZ:Rt,scale:Pi,scaleX:Pi,scaleY:Pi,scaleZ:Pi,skew:Rt,skewX:Rt,skewY:Rt,distance:W,translateX:W,translateY:W,translateZ:W,x:W,y:W,z:W,perspective:W,transformPerspective:W,opacity:Vn,originX:Ya,originY:Ya,originZ:W},zIndex:Il,fillOpacity:Vn,strokeOpacity:Vn,numOctaves:Il},jp={...wo,color:ke,backgroundColor:ke,outlineColor:ke,fill:ke,stroke:ke,borderColor:ke,borderTopColor:ke,borderRightColor:ke,borderBottomColor:ke,borderLeftColor:ke,filter:bo,WebkitFilter:bo},Al=t=>jp[t];function Rl(t,e){let n=Al(t);return n!==bo&&(n=Lt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const $p=new Set(["auto","none","0"]);function Hp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const r=t[i];typeof r=="string"&&!$p.has(r)&&jn(r).values.length&&(s=t[i]),i++}if(s&&n)for(const r of e)t[r]=Rl(n,s)}class Gp extends vo{constructor(e,n,i,s,r){super(e,n,i,s,r,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),qs(c))){const u=Cl(c,n.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Tl.has(i)||e.length!==2)return;const[s,r]=e,o=El(s),a=El(r);if(o!==a)if(fl(o)&&fl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Wt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Fp(e[s]))&&i.push(s);i.length&&Hp(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Wt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const r=i.length-1,o=i[r];i[r]=Wt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function Wp(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const s=(n==null?void 0:n[t])??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Ll=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Pl=30,zp=t=>!isNaN(parseFloat(t));class qp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var o,a;const r=$e.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((o=this.events.change)==null||o.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=$e.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=zp(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new $s);const i=this.events[e].add(n);return e==="change"?()=>{i(),ve.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e,n=!0){!n||!this.passiveEffect?this.updateAndNotify(e,n):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=$e.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Pl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Pl);return Ma(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function un(t,e){return new qp(t,e)}const{schedule:So}=qa(queueMicrotask,!1),st={x:!1,y:!1};function Dl(){return st.x||st.y}function Kp(t){return t==="x"||t==="y"?st[t]?null:(st[t]=!0,()=>{st[t]=!1}):st.x||st.y?null:(st.x=st.y=!0,()=>{st.x=st.y=!1})}function Ml(t,e){const n=Wp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Nl(t){return!(t.pointerType==="touch"||Dl())}function Xp(t,e,n={}){const[i,s,r]=Ml(t,n),o=a=>{if(!Nl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Nl(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",o,s)}),r}const Ol=(t,e)=>e?t===e?!0:Ol(t,e.parentElement):!1,Co=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Yp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Jp(t){return Yp.has(t.tagName)||t.tabIndex!==-1}const Oi=new WeakSet;function Fl(t){return e=>{e.key==="Enter"&&t(e)}}function To(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Zp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Fl(()=>{if(Oi.has(n))return;To(n,"down");const s=Fl(()=>{To(n,"up")}),r=()=>To(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",r,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function Vl(t){return Co(t)&&!Dl()}function Qp(t,e,n={}){const[i,s,r]=Ml(t,n),o=a=>{const l=a.currentTarget;if(!Vl(a))return;Oi.add(l);const c=e(l,a),u=(m,v)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),Oi.has(l)&&Oi.delete(l),Vl(m)&&typeof c=="function"&&c(m,{success:v})},d=m=>{u(m,l===window||l===document||n.useGlobalTarget||Ol(l,m.target))},f=m=>{u(m,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,s),_o(a)&&(a.addEventListener("focus",c=>Zp(c,s)),!Jp(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),r}function Bl(t){return Pa(t)&&"ownerSVGElement"in t}function eg(t){return Bl(t)&&t.tagName==="svg"}const Oe=t=>!!(t&&t.getVelocity),tg=[...xl,ke,Lt],ng=t=>tg.find(kl(t)),Gn=bt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class ig extends it{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=_o(i)&&i.offsetWidth||0,r=this.props.sizeRef.current;r.height=n.offsetHeight||0,r.width=n.offsetWidth||0,r.top=n.offsetTop,r.left=n.offsetLeft,r.right=s-r.width-r.left}return null}componentDidUpdate(){}render(){return this.props.children}}function sg({children:t,isPresent:e,anchorX:n,root:i}){const s=Ts(),r=de(null),o=de({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Re(Gn);return ua(()=>{const{width:l,height:c,top:u,left:d,right:f}=o.current;if(e||!r.current||!l||!c)return;const m=n==="left"?`left: ${d}`:`right: ${f}`;r.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const y=i??document.head;return y.appendChild(v),v.sheet&&v.sheet.insertRule(`
1
+ var vb=Object.defineProperty;var yb=(nt,G,jt)=>G in nt?vb(nt,G,{enumerable:!0,configurable:!0,writable:!0,value:jt}):nt[G]=jt;var Y=(nt,G,jt)=>yb(nt,typeof G!="symbol"?G+"":G,jt);(function(){"use strict";var nt,G,jt,$t,kr,xr,Er,Ir,ps,gs,ms,Ar,An={},Rr=[],_h=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Rn=Array.isArray;function at(t,e){for(var n in e)t[n]=e[n];return t}function vs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ke(t,e,n){var i,s,r,o={};for(r in e)r=="key"?i=e[r]:r=="ref"?s=e[r]:o[r]=e[r];if(arguments.length>2&&(o.children=arguments.length>3?nt.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(r in t.defaultProps)o[r]===void 0&&(o[r]=t.defaultProps[r]);return Ln(t,o,i,s,null)}function Ln(t,e,n,i,s){var r={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++jt,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(r),r}function lt(t){return t.children}function it(t,e){this.props=t,this.context=e}function on(t,e){if(e==null)return t.__?on(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?on(t):null}function Lr(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Lr(t)}}function ys(t){(!t.__d&&(t.__d=!0)&&$t.push(t)&&!yi.__r++||kr!=G.debounceRendering)&&((kr=G.debounceRendering)||xr)(yi)}function yi(){for(var t,e,n,i,s,r,o,a=1;$t.length;)$t.length>a&&$t.sort(Er),t=$t.shift(),a=$t.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,r=[],o=[],e.__P&&((n=at({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),_s(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,r,s??on(i),!!(32&i.__u),o),n.__v=i.__v,n.__.__k[n.__i]=n,Or(r,n,o),n.__e!=s&&Lr(n)));yi.__r=0}function Pr(t,e,n,i,s,r,o,a,l,c,u){var d,f,m,v,_,w,y=i&&i.__k||Rr,T=e.length;for(l=bh(n,e,y,l,T),d=0;d<T;d++)(m=n.__k[d])!=null&&(f=m.__i==-1?An:y[m.__i]||An,m.__i=d,w=_s(t,m,f,s,r,o,a,l,c,u),v=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&bs(f.ref,null,m),u.push(m.ref,m.__c||v,m)),_==null&&v!=null&&(_=v),4&m.__u||f.__k===m.__k?l=Dr(m,l,t):typeof m.type=="function"&&w!==void 0?l=w:v&&(l=v.nextSibling),m.__u&=-7);return n.__e=_,l}function bh(t,e,n,i,s){var r,o,a,l,c,u=n.length,d=u,f=0;for(t.__k=new Array(s),r=0;r<s;r++)(o=e[r])!=null&&typeof o!="boolean"&&typeof o!="function"?(l=r+f,(o=t.__k[r]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Ln(null,o,null,null,null):Rn(o)?Ln(lt,{children:o},null,null,null):o.constructor==null&&o.__b>0?Ln(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,a=null,(c=o.__i=wh(o,n,l,d))!=-1&&(d--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?f--:s<u&&f++),typeof o.type!="function"&&(o.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,o.__u|=4))):t.__k[r]=null;if(d)for(r=0;r<u;r++)(a=n[r])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=on(a)),Vr(a,a));return i}function Dr(t,e,n){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Dr(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=on(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ct(t,e){return e=e||[],t==null||typeof t=="boolean"||(Rn(t)?t.some(function(n){ct(n,e)}):e.push(t)),e}function wh(t,e,n,i){var s,r,o=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&o==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,r=n+1;s>=0||r<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&o==l.key&&a==l.type)return s;s--}if(r<e.length){if((l=e[r])&&(2&l.__u)==0&&o==l.key&&a==l.type)return r;r++}}return-1}function Mr(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||_h.test(e)?n:n+"px"}function _i(t,e,n,i,s){var r,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Mr(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Mr(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(Ir,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+r]=n,n?i?n.u=i.u:(n.u=ps,t.addEventListener(e,r?ms:gs,r)):t.removeEventListener(e,r?ms:gs,r);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Nr(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=ps++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function _s(t,e,n,i,s,r,o,a,l,c){var u,d,f,m,v,_,w,y,T,x,I,A,M,S,C,p,g,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),r=[a=e.__e=n.__e]),(u=G.__b)&&u(e);e:if(typeof h=="function")try{if(y=e.props,T="prototype"in h&&h.prototype.render,x=(u=h.contextType)&&i[u.__c],I=u?x?x.props.value:u.__:i,n.__c?w=(d=e.__c=n.__c).__=d.__E:(T?e.__c=d=new h(y,I):(e.__c=d=new it(y,I),d.constructor=h,d.render=Ch),x&&x.sub(d),d.props=y,d.state||(d.state={}),d.context=I,d.__n=i,f=d.__d=!0,d.__h=[],d._sb=[]),T&&d.__s==null&&(d.__s=d.state),T&&h.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=at({},d.__s)),at(d.__s,h.getDerivedStateFromProps(y,d.__s))),m=d.props,v=d.state,d.__v=e,f)T&&h.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),T&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(T&&h.getDerivedStateFromProps==null&&y!==m&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,I),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,I)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),A=0;A<d._sb.length;A++)d.__h.push(d._sb[A]);d._sb=[],d.__h.length&&o.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,I),T&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(m,v,_)})}if(d.context=I,d.props=y,d.__P=t,d.__e=!1,M=G.__r,S=0,T){for(d.state=d.__s,d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),C=0;C<d._sb.length;C++)d.__h.push(d._sb[C]);d._sb=[]}else do d.__d=!1,M&&M(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++S<25);d.state=d.__s,d.getChildContext!=null&&(i=at(at({},i),d.getChildContext())),T&&!f&&d.getSnapshotBeforeUpdate!=null&&(_=d.getSnapshotBeforeUpdate(m,v)),p=u,u!=null&&u.type===lt&&u.key==null&&(p=Fr(u.props.children)),a=Pr(t,Rn(p)?p:[p],e,n,i,s,r,o,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&o.push(d),w&&(d.__E=d.__=null)}catch(b){if(e.__v=null,l||r!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;r[r.indexOf(a)]=null,e.__e=a}else for(g=r.length;g--;)vs(r[g]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,e,n)}else r==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Sh(n.__e,e,n,i,s,r,o,l,c);return(u=G.diffed)&&u(e),128&e.__u?void 0:a}function Or(t,e,n){for(var i=0;i<n.length;i++)bs(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(r){r.call(s)})}catch(r){G.__e(r,s.__v)}})}function Fr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Rn(t)?t.map(Fr):at({},t)}function Sh(t,e,n,i,s,r,o,a,l){var c,u,d,f,m,v,_,w=n.props,y=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"),r!=null){for(c=0;c<r.length;c++)if((m=r[c])&&"setAttribute"in m==!!T&&(T?m.localName==T:m.nodeType==3)){t=m,r[c]=null;break}}if(t==null){if(T==null)return document.createTextNode(y);t=document.createElementNS(s,T,y.is&&y),a&&(G.__m&&G.__m(e,r),a=!1),r=null}if(T==null)w===y||a&&t.data==y||(t.data=y);else{if(r=r&&nt.call(t.childNodes),w=n.props||An,!a&&r!=null)for(w={},c=0;c<t.attributes.length;c++)w[(m=t.attributes[c]).name]=m.value;for(c in w)if(m=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=m;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;_i(t,c,null,m,s)}}for(c in y)m=y[c],c=="children"?f=m:c=="dangerouslySetInnerHTML"?u=m:c=="value"?v=m:c=="checked"?_=m:a&&typeof m!="function"||w[c]===m||_i(t,c,m,w[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=""),Pr(e.type=="template"?t.content:t,Rn(f)?f:[f],e,n,i,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,r,o,r?r[0]:n.__k&&on(n,0),a,l),r!=null)for(c=r.length;c--;)vs(r[c]);a||(c="value",T=="progress"&&v==null?t.removeAttribute("value"):v!=null&&(v!==t[c]||T=="progress"&&!v||T=="option"&&v!=w[c])&&_i(t,c,v,w[c],s),c="checked",_!=null&&_!=t[c]&&_i(t,c,_,w[c],s))}return t}function bs(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){G.__e(s,n)}}function Vr(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||bs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(r){G.__e(r,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Vr(i[s],e,n||typeof t.type!="function");n||vs(t.__e),t.__c=t.__=t.__e=void 0}function Ch(t,e,n){return this.constructor(t,n)}function bi(t,e,n){var i,s,r,o;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,r=[],o=[],_s(e,t=(!i&&n||e).__k=Ke(lt,null,[t]),s||An,An,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?nt.call(e.childNodes):null,r,!i&&n?n:s?s.__e:e.firstChild,i,o),Or(r,t,o)}function Br(t,e){bi(t,e,Br)}function ws(t,e,n){var i,s,r,o,a=at({},t.props);for(r in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)r=="key"?i=e[r]:r=="ref"?s=e[r]:a[r]=e[r]===void 0&&o!=null?o[r]:e[r];return arguments.length>2&&(a.children=arguments.length>3?nt.call(arguments,2):n),Ln(t.type,a,i||t.key,s||t.ref,null)}function bt(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&i.forEach(function(o){o.__e=!0,ys(o)})},this.sub=function(r){i.add(r);var o=r.componentWillUnmount;r.componentWillUnmount=function(){i&&i.delete(r),o&&o.call(r)}}),n.children}return e.__c="__cC"+Ar++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}nt=Rr.slice,G={__e:function(t,e,n,i){for(var s,r,o;e=e.__;)if((s=e.__c)&&!s.__)try{if((r=s.constructor)&&r.getDerivedStateFromError!=null&&(s.setState(r.getDerivedStateFromError(t)),o=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),o=s.__d),o)return s.__E=s}catch(a){t=a}throw t}},jt=0,it.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=at({},this.state),typeof t=="function"&&(t=t(at({},n),this.props)),t&&at(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),ys(this))},it.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),ys(this))},it.prototype.render=lt,$t=[],xr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Er=function(t,e){return t.__v.__b-e.__v.__b},yi.__r=0,Ir=/(PointerCapture)$|Capture$/i,ps=0,gs=Nr(!1),ms=Nr(!0),Ar=0;var Th=0;function R(t,e,n,i,s,r){e||(e={});var o,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?o=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Th,__i:-1,__u:0,__source:s,__self:r};if(typeof t=="function"&&(o=t.defaultProps))for(a in o)l[a]===void 0&&(l[a]=o[a]);return G.vnode&&G.vnode(c),c}function Ss(){return(Ss=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var kh=["context","children"];function xh(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var r,o,a={},l=Object.keys(i);for(o=0;o<l.length;o++)s.indexOf(r=l[o])>=0||(a[r]=i[r]);return a}(t,kh);return ws(e,n)}function Eh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ke(xh,Ss({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],r={},o=0,a=n.attributes,l=n.childNodes;for(o=a.length;o--;)a[o].name!=="slot"&&(r[a[o].name]=a[o].value,r[Ur(a[o].name)]=a[o].value);for(o=l.length;o--;){var c=e(l[o],null),u=l[o].slot;u?r[u]=Ke(jr,{name:u},c):s[o]=c}var d=i?Ke(jr,null,s):s;return Ke(i||n.nodeName.toLowerCase(),r,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Br:bi)(this._vdom,this._root)}function Ur(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Ih(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ur(t)]=n,this._vdom=ws(this._vdom,i),bi(this._vdom,this._root)}}function Ah(){bi(this._vdom=null,this._root)}function jr(t,e){var n=this;return Ke("slot",Ss({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function Rh(t,e,n,i){function s(){var r=Reflect.construct(HTMLElement,[],s);return r._vdomComponent=t,r._root=i&&i.shadow?r.attachShadow({mode:i.mode||"open"}):r,r}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=Eh,s.prototype.attributeChangedCallback=Ih,s.prototype.disconnectedCallback=Ah,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=n,n.forEach(function(r){Object.defineProperty(s.prototype,r,{get:function(){return this._vdom.props[r]},set:function(o){this._vdom?this.attributeChangedCallback(r,null,o):(this._props||(this._props={}),this._props[r]=o,this.connectedCallback());var a=typeof o;o!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(r,o)}})}),customElements.define(e,s)}var Rt,pe,Cs,$r,Pn=0,Hr=[],_e=G,Gr=_e.__b,Wr=_e.__r,zr=_e.diffed,qr=_e.__c,Kr=_e.unmount,Xr=_e.__;function rn(t,e){_e.__h&&_e.__h(pe,t,Pn||e),Pn=0;var n=pe.__H||(pe.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ee(t){return Pn=1,Yr(Qr,t)}function Yr(t,e,n){var i=rn(Rt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Qr(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=pe,!pe.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(f){return!!f.__c});if(u.every(function(f){return!f.__N}))return!r||r.call(this,a,l,c);var d=i.__c.props!==a;return u.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(d=!0)}}),r&&r.call(this,a,l,c)||d};pe.__f=!0;var r=pe.shouldComponentUpdate,o=pe.componentWillUpdate;pe.componentWillUpdate=function(a,l,c){if(this.__e){var u=r;r=void 0,s(a,l,c),r=u}o&&o.call(this,a,l,c)},pe.shouldComponentUpdate=s}return i.__N||i.__}function Ae(t,e){var n=rn(Rt++,3);!_e.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,pe.__H.__h.push(n))}function Jr(t,e){var n=rn(Rt++,4);!_e.__s&&xs(n.__H,e)&&(n.__=t,n.u=e,pe.__h.push(n))}function de(t){return Pn=5,Xe(function(){return{current:t}},[])}function Xe(t,e){var n=rn(Rt++,7);return xs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function We(t,e){return Pn=8,Xe(function(){return t},e)}function Re(t){var e=pe.context[t.__c],n=rn(Rt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(pe)),e.props.value):t.__}function Lh(t,e){_e.useDebugValue&&_e.useDebugValue(e?e(t):t)}function Ts(){var t=rn(Rt++,11);if(!t.__){for(var e=pe.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function Ph(){for(var t;t=Hr.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(wi),t.__H.__h.forEach(ks),t.__H.__h=[]}catch(e){t.__H.__h=[],_e.__e(e,t.__v)}}_e.__b=function(t){pe=null,Gr&&Gr(t)},_e.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Xr&&Xr(t,e)},_e.__r=function(t){Wr&&Wr(t),Rt=0;var e=(pe=t.__c).__H;e&&(Cs===pe?(e.__h=[],pe.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(wi),e.__h.forEach(ks),e.__h=[],Rt=0)),Cs=pe},_e.diffed=function(t){zr&&zr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Hr.push(e)!==1&&$r===_e.requestAnimationFrame||(($r=_e.requestAnimationFrame)||Dh)(Ph)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Cs=pe=null},_e.__c=function(t,e){e.some(function(n){try{n.__h.forEach(wi),n.__h=n.__h.filter(function(i){return!i.__||ks(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],_e.__e(i,n.__v)}}),qr&&qr(t,e)},_e.unmount=function(t){Kr&&Kr(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{wi(i)}catch(s){e=s}}),n.__H=void 0,e&&_e.__e(e,n.__v))};var Zr=typeof requestAnimationFrame=="function";function Dh(t){var e,n=function(){clearTimeout(i),Zr&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Zr&&(e=requestAnimationFrame(n))}function wi(t){var e=pe,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),pe=e}function ks(t){var e=pe;t.__c=t.__(),pe=e}function xs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Qr(t,e){return typeof e=="function"?e(t):e}const Dn={},ea=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ta=t=>"init"in t,Es=t=>!!t.write,na=t=>"v"in t||"e"in t,Si=t=>{if("e"in t)throw t.e;if((Dn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Ci=new WeakMap,ia=t=>{var e;return Ti(t)&&!!((e=Ci.get(t))!=null&&e[0])},Mh=t=>{const e=Ci.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},sa=(t,e)=>{let n=Ci.get(t);if(!n){n=[!0,new Set],Ci.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},Ti=t=>typeof(t==null?void 0:t.then)=="function",oa=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Is=(t,e,n)=>{const i=n(t),s="v"in i,r=i.v;if(Ti(e))for(const o of i.d.keys())oa(t,e,n(o));i.v=e,delete i.e,(!s||!Object.is(r,i.v))&&(++i.n,Ti(r)&&Mh(r))},ra=(t,e,n)=>{var i;const s=new Set;for(const r of((i=n.get(t))==null?void 0:i.t)||[])n.has(r)&&s.add(r);for(const r of e.p)s.add(r);return s},Nh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},As=()=>{const t={},e=new WeakMap,n=i=>{var s,r;(s=e.get(t))==null||s.forEach(o=>o(i)),(r=e.get(i))==null||r.forEach(o=>o())};return n.add=(i,s)=>{const r=i||t,o=(e.has(r)?e:e.set(r,new Set)).get(r);return o.add(s),()=>{o==null||o.delete(s),o.size||e.delete(r)}},n},Oh=t=>(t.c||(t.c=As()),t.m||(t.m=As()),t.u||(t.u=As()),t.f||(t.f=Nh()),t),Fh=Symbol(),aa=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,r=new Set,o={},a=(f,...m)=>f.read(...m),l=(f,...m)=>f.write(...m),c=(f,m)=>{var v;return(v=f.unstable_onInit)==null?void 0:v.call(f,m)},u=(f,m)=>{var v;return(v=f.onMount)==null?void 0:v.call(f,m)},...d)=>{const f=d[0]||(S=>{if((Dn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let C=t.get(S);return C||(C={d:new Map,p:new Set,n:0},t.set(S,C),c==null||c(S,M)),C}),m=d[1]||(()=>{const S=[],C=p=>{try{p()}catch(g){S.push(g)}};do{o.f&&C(o.f);const p=new Set,g=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(g)}),i.clear(),r.forEach(g),r.clear(),s.forEach(g),s.clear(),p.forEach(C),i.size&&v()}while(i.size||r.size||s.size);if(S.length)throw new AggregateError(S)}),v=d[2]||(()=>{const S=[],C=new WeakSet,p=new WeakSet,g=Array.from(i);for(;g.length;){const h=g[g.length-1],b=f(h);if(p.has(h)){g.pop();continue}if(C.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Dn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),g.pop();continue}C.add(h);for(const E of ra(h,b,e))C.has(E)||g.push(E)}for(let h=S.length-1;h>=0;--h){const[b,E]=S[h];let P=!1;for(const L of E.d.keys())if(L!==b&&i.has(L)){P=!0;break}P&&(_(b),T(b)),n.delete(b)}}),_=d[3]||(S=>{var C;const p=f(S);if(na(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([D,F])=>_(D).n===F)))return p;p.d.clear();let g=!0;const h=()=>{e.has(S)&&(T(S),v(),m())},b=D=>{var F;if(ea(S,D)){const j=f(D);if(!na(j))if(ta(D))Is(D,D.init,f);else throw new Error("no atom init");return Si(j)}const z=_(D);try{return Si(z)}finally{p.d.set(D,z.n),ia(p.v)&&oa(S,p.v,z),(F=e.get(D))==null||F.t.add(S),g||h()}};let E,P;const L={get signal(){return E||(E=new AbortController),E.signal},get setSelf(){return(Dn?"production":void 0)!=="production"&&!Es(S)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&Es(S)&&(P=(...D)=>{if((Dn?"production":void 0)!=="production"&&g&&console.warn("setSelf function cannot be called in sync"),!g)try{return y(S,...D)}finally{v(),m()}}),P}},N=p.n;try{const D=a(S,b,L);return Is(S,D,f),Ti(D)&&(sa(D,()=>E==null?void 0:E.abort()),D.then(h,h)),p}catch(D){return delete p.v,p.e=D,++p.n,p}finally{g=!1,N!==p.n&&n.get(S)===N&&(n.set(S,p.n),i.add(S),(C=o.c)==null||C.call(o,S))}}),w=d[4]||(S=>{const C=[S];for(;C.length;){const p=C.pop(),g=f(p);for(const h of ra(p,g,e)){const b=f(h);n.set(h,b.n),C.push(h)}}}),y=d[5]||((S,...C)=>{let p=!0;const g=b=>Si(_(b)),h=(b,...E)=>{var P;const L=f(b);try{if(ea(S,b)){if(!ta(b))throw new Error("atom not writable");const N=L.n,D=E[0];Is(b,D,f),T(b),N!==L.n&&(i.add(b),(P=o.c)==null||P.call(o,b),w(b));return}else return y(b,...E)}finally{p||(v(),m())}};try{return l(S,g,h,...C)}finally{p=!1}}),T=d[6]||(S=>{var C;const p=f(S),g=e.get(S);if(g&&!ia(p.v)){for(const[h,b]of p.d)if(!g.d.has(h)){const E=f(h);x(h).t.add(S),g.d.add(h),b!==E.n&&(i.add(h),(C=o.c)==null||C.call(o,h),w(h))}for(const h of g.d||[])if(!p.d.has(h)){g.d.delete(h);const b=I(h);b==null||b.t.delete(S)}}}),x=d[7]||(S=>{var C;const p=f(S);let g=e.get(S);if(!g){_(S);for(const h of p.d.keys())x(h).t.add(S);if(g={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,g),(C=o.m)==null||C.call(o,S),Es(S)){const h=()=>{let b=!0;const E=(...P)=>{try{return y(S,...P)}finally{b||(v(),m())}};try{const P=u(S,E);P&&(g.u=()=>{b=!0;try{P()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return g}),I=d[8]||(S=>{var C;const p=f(S);let g=e.get(S);if(g&&!g.l.size&&!Array.from(g.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){g.u&&r.add(g.u),g=void 0,e.delete(S),(C=o.u)==null||C.call(o,S);for(const h of p.d.keys()){const b=I(h);b==null||b.t.delete(S)}return}return g}),A=[t,e,n,i,s,r,o,a,l,c,u,f,m,v,_,w,y,T,x,I],M={get:S=>Si(_(S)),set:(S,...C)=>{try{return y(S,...C)}finally{v(),m()}},sub:(S,C)=>{const g=x(S).l;return g.add(C),m(),()=>{g.delete(C),I(S),m()}}};return Object.defineProperty(M,Fh,{value:A}),M},Vh=Oh,la=sa,Rs={};let Bh=0;function ki(t,e){const n=`atom${++Bh}`,i={toString(){return(Rs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=Uh,i.write=jh),i}function Uh(t){return t(this)}function jh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const $h=()=>{let t=0;const e=Vh({}),n=new WeakMap,i=new WeakMap,s=aa(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),r=new Set;return e.m.add(void 0,a=>{r.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{r.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>r,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,f]of a)"init"in d&&u(d,f)}finally{--t}}};s.set(l)}})};function Hh(){return(Rs?"production":void 0)!=="production"?$h():aa()}let Mn;function Gh(){return Mn||(Mn=Hh(),(Rs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Mn),globalThis.__JOTAI_DEFAULT_STORE__!==Mn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Mn}function ca(t,e){for(var n in e)t[n]=e[n];return t}function da(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var i in e)if(i!=="__source"&&t[i]!==e[i])return!0;return!1}var ua=Jr;function ha(t,e){this.props=t,this.context=e}(ha.prototype=new it).isPureReactComponent=!0,ha.prototype.shouldComponentUpdate=function(t,e){return da(this.props,t)||da(this.state,e)};var fa=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),fa&&fa(t)};var Wh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function zh(t){function e(n){var i=ca({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Wh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var pa=function(t,e){return t==null?null:ct(ct(t).map(e))},qh={map:pa,forEach:pa,count:function(t){return t?ct(t).length:0},only:function(t){var e=ct(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ct},Kh=G.__e;G.__e=function(t,e,n,i){if(t.then){for(var s,r=e;r=r.__;)if((s=r.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}Kh(t,e,n,i)};var ga=G.unmount;function ma(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(i){typeof i.__c=="function"&&i.__c()}),t.__c.__H=null),(t=ca({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(i){return ma(i,e,n)})),t}function va(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return va(i,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function Ls(){this.__u=0,this.o=null,this.__b=null}function ya(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function xi(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),ga&&ga(t)},(Ls.prototype=new it).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=ya(i.__v),r=!1,o=function(){r||(r=!0,n.__R=null,s?s(a):a())};n.__R=o;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=va(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(o,o)},Ls.prototype.componentWillUnmount=function(){this.o=[]},Ls.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),i=this.__v.__k[0].__c;this.__v.__k[0]=ma(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&Ke(lt,null,t.fallback);return s&&(s.__u&=-33),[Ke(lt,null,e.__a?null:t.children),s]};var _a=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};(xi.prototype=new it).__a=function(t){var e=this,n=ya(e.__v),i=e.l.get(t);return i[0]++,function(s){var r=function(){e.props.revealOrder?(i.push(s),_a(e,t,i)):s()};n?n(r):r()}},xi.prototype.render=function(t){this.i=null,this.l=new Map;var e=ct(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},xi.prototype.componentDidUpdate=xi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){_a(t,n,e)})};var ba=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Xh=/^(?: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]/,Yh=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Jh=/[A-Z0-9]/g,Zh=typeof document<"u",Qh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};it.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(it.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var wa=G.event;function ef(){}function tf(){return this.cancelBubble}function nf(){return this.defaultPrevented}G.event=function(t){return wa&&(t=wa(t)),t.persist=ef,t.isPropagationStopped=tf,t.isDefaultPrevented=nf,t.nativeEvent=t};var sf={enumerable:!1,configurable:!0,get:function(){return this.class}},Sa=G.vnode;G.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},r=i.indexOf("-")===-1;for(var o in n){var a=n[o];if(!(o==="value"&&"defaultValue"in n&&a==null||Zh&&o==="children"&&i==="noscript"||o==="class"||o==="className")){var l=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?o="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Qh(n.type)?l==="onfocus"?o="onfocusin":l==="onblur"?o="onfocusout":Yh.test(o)&&(o=l):l=o="oninput":r&&Xh.test(o)?o=o.replace(Jh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[o=l]&&(o="oninputCapture"),s[o]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ct(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",sf)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ba,Sa&&Sa(t)};var Ca=G.__r;G.__r=function(t){Ca&&Ca(t),t.__c};var Ta=G.diffed;G.diffed=function(t){Ta&&Ta(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value)};function ka(t){return!!t&&t.$$typeof===ba}function of(t){return ka(t)?ws.apply(null,arguments):t}var xa={};const rf={},af=bt(void 0);function Ea(t){return Re(af)||Gh()}const Ps=t=>typeof(t==null?void 0:t.then)=="function",Ds=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},lf=xa.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ds(t),t)}),Ms=new WeakMap,Ia=(t,e)=>{let n=Ms.get(t);return n||(n=new Promise((i,s)=>{let r=t;const o=c=>u=>{r===c&&i(u)},a=c=>u=>{r===c&&s(u)},l=()=>{try{const c=e();Ps(c)?(Ms.set(c,n),r=c,c.then(o(c),a(c)),la(c,l)):i(c)}catch(c){s(c)}};t.then(o(t),a(t)),la(t,l)}),Ms.set(t,n)),n};function Ns(t,e){const{delay:n,unstable_promiseStatus:i=!xa.use}={},s=Ea(),[[r,o,a],l]=Yr(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=r;if((o!==s||a!==t)&&(l(),c=s.get(t)),Ae(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);Ps(d)&&Ds(Ia(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),u},[s,t,n,i]),Lh(c),Ps(c)){const u=Ia(c,()=>s.get(t));return i&&Ds(u),lf(u)}return c}function Ei(t,e){const n=Ea();return We((...s)=>{if((rf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function Aa(t,e){return[Ns(t),Ei(t)]}const Os=bt({});function Ii(t){const e=de(null);return e.current===null&&(e.current=t()),e.current}const Fs=typeof window<"u",Ra=Fs?Jr:Ae,Ai=bt(null);function Vs(t,e){t.indexOf(e)===-1&&t.push(e)}function Bs(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const wt=(t,e,n)=>n>e?e:n<t?t:n;let Us=()=>{};const St={},La=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Pa(t){return typeof t=="object"&&t!==null}const Da=t=>/^0[^.\s]+$/u.test(t);function js(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ye=t=>t,cf=(t,e)=>n=>e(t(n)),Nn=(...t)=>t.reduce(cf),On=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class $s{constructor(){this.subscriptions=[]}add(e){return Vs(this.subscriptions,e),()=>Bs(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let r=0;r<s;r++){const o=this.subscriptions[r];o&&o(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const dt=t=>t*1e3,ut=t=>t/1e3;function Ma(t,e){return e?t*(1e3/e):0}const Na=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,df=1e-7,uf=12;function hf(t,e,n,i,s){let r,o,a=0;do o=e+(n-e)/2,r=Na(o,i,s)-t,r>0?n=o:e=o;while(Math.abs(r)>df&&++a<uf);return o}function Fn(t,e,n,i){if(t===e&&n===i)return Ye;const s=r=>hf(r,0,1,t,n);return r=>r===0||r===1?r:Na(s(r),e,i)}const Oa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Fa=t=>e=>1-t(1-e),Va=Fn(.33,1.53,.69,.99),Hs=Fa(Va),Ba=Oa(Hs),Ua=t=>(t*=2)<1?.5*Hs(t):.5*(2-Math.pow(2,-10*(t-1))),Gs=t=>1-Math.sin(Math.acos(t)),ja=Fa(Gs),$a=Oa(Gs),ff=Fn(.42,0,1,1),pf=Fn(0,0,.58,1),Ha=Fn(.42,0,.58,1),gf=t=>Array.isArray(t)&&typeof t[0]!="number",Ga=t=>Array.isArray(t)&&typeof t[0]=="number",mf={linear:Ye,easeIn:ff,easeInOut:Ha,easeOut:pf,circIn:Gs,circInOut:$a,circOut:ja,backIn:Hs,backInOut:Ba,backOut:Va,anticipate:Ua},vf=t=>typeof t=="string",Wa=t=>{if(Ga(t)){Us(t.length===4);const[e,n,i,s]=t;return Fn(e,n,i,s)}else if(vf(t))return mf[t];return t},Ri=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],za={value:null};function yf(t,e){let n=new Set,i=new Set,s=!1,r=!1;const o=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){o.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,f=!1,m=!1)=>{const _=m&&s?n:i;return f&&o.add(d),_.has(d)||_.add(d),d},cancel:d=>{i.delete(d),o.delete(d)},process:d=>{if(a=d,s){r=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&za.value&&za.value.frameloop[e].push(l),l=0,n.clear(),s=!1,r&&(r=!1,u.process(d))}};return u}const _f=40;function qa(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,o=Ri.reduce((x,I)=>(x[I]=yf(r,e?I:void 0),x),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:f,render:m,postRender:v}=o,_=()=>{const x=St.useManualTiming?s.timestamp:performance.now();n=!1,St.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(x-s.timestamp,_f),1)),s.timestamp=x,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),f.process(s),m.process(s),v.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(_))},w=()=>{n=!0,i=!0,s.isProcessing||t(_)};return{schedule:Ri.reduce((x,I)=>{const A=o[I];return x[I]=(M,S=!1,C=!1)=>(n||w(),A.schedule(M,S,C)),x},{}),cancel:x=>{for(let I=0;I<Ri.length;I++)o[Ri[I]].cancel(x)},state:s,steps:o}}const{schedule:ve,cancel:Lt,state:Pe,steps:Ws}=qa(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ye,!0);let Li;function bf(){Li=void 0}const $e={now:()=>(Li===void 0&&$e.set(Pe.isProcessing||St.useManualTiming?Pe.timestamp:performance.now()),Li),set:t=>{Li=t,queueMicrotask(bf)}},Ka=t=>e=>typeof e=="string"&&e.startsWith(t),zs=Ka("--"),wf=Ka("var(--"),qs=t=>wf(t)?Sf.test(t.split("/*")[0].trim()):!1,Sf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,an={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Vn={...an,transform:t=>wt(0,1,t)},Pi={...an,default:1},Bn=t=>Math.round(t*1e5)/1e5,Ks=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Cf(t){return t==null}const Tf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Xs=(t,e)=>n=>!!(typeof n=="string"&&Tf.test(n)&&n.startsWith(t)||e&&!Cf(n)&&Object.prototype.hasOwnProperty.call(n,e)),Xa=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,r,o,a]=i.match(Ks);return{[t]:parseFloat(s),[e]:parseFloat(r),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},kf=t=>wt(0,255,t),Ys={...an,transform:t=>Math.round(kf(t))},Ht={test:Xs("rgb","red"),parse:Xa("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Ys.transform(t)+", "+Ys.transform(e)+", "+Ys.transform(n)+", "+Bn(Vn.transform(i))+")"};function xf(t){let e="",n="",i="",s="";return t.length>5?(e=t.substring(1,3),n=t.substring(3,5),i=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),n=t.substring(2,3),i=t.substring(3,4),s=t.substring(4,5),e+=e,n+=n,i+=i,s+=s),{red:parseInt(e,16),green:parseInt(n,16),blue:parseInt(i,16),alpha:s?parseInt(s,16)/255:1}}const Js={test:Xs("#"),parse:xf,transform:Ht.transform},Un=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Pt=Un("deg"),ht=Un("%"),W=Un("px"),Ef=Un("vh"),If=Un("vw"),Ya={...ht,parse:t=>ht.parse(t)/100,transform:t=>ht.transform(t*100)},ln={test:Xs("hsl","hue"),parse:Xa("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ht.transform(Bn(e))+", "+ht.transform(Bn(n))+", "+Bn(Vn.transform(i))+")"},ke={test:t=>Ht.test(t)||Js.test(t)||ln.test(t),parse:t=>Ht.test(t)?Ht.parse(t):ln.test(t)?ln.parse(t):Js.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ht.transform(t):ln.transform(t),getAnimatableNone:t=>{const e=ke.parse(t);return e.alpha=0,ke.transform(e)}},Af=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Rf(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Ks))==null?void 0:e.length)||0)+(((n=t.match(Af))==null?void 0:n.length)||0)>0}const Ja="number",Za="color",Lf="var",Pf="var(",Qa="${}",Df=/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 jn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let r=0;const a=e.replace(Df,l=>(ke.test(l)?(i.color.push(r),s.push(Za),n.push(ke.parse(l))):l.startsWith(Pf)?(i.var.push(r),s.push(Lf),n.push(l)):(i.number.push(r),s.push(Ja),n.push(parseFloat(l))),++r,Qa)).split(Qa);return{values:n,split:a,indexes:i,types:s}}function el(t){return jn(t).values}function tl(t){const{split:e,types:n}=jn(t),i=e.length;return s=>{let r="";for(let o=0;o<i;o++)if(r+=e[o],s[o]!==void 0){const a=n[o];a===Ja?r+=Bn(s[o]):a===Za?r+=ke.transform(s[o]):r+=s[o]}return r}}const Mf=t=>typeof t=="number"?0:ke.test(t)?ke.getAnimatableNone(t):t;function Nf(t){const e=el(t);return tl(t)(e.map(Mf))}const Dt={test:Rf,parse:el,createTransformer:tl,getAnimatableNone:Nf};function Zs(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+(e-t)*6*n:n<1/2?e:n<2/3?t+(e-t)*(2/3-n)*6:t}function Of({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,r=0,o=0;if(!e)s=r=o=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Zs(l,a,t+1/3),r=Zs(l,a,t),o=Zs(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(r*255),blue:Math.round(o*255),alpha:i}}function Di(t,e){return n=>n>0?e:t}const be=(t,e,n)=>t+(e-t)*n,Qs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Ff=[Js,Ht,ln],Vf=t=>Ff.find(e=>e.test(t));function nl(t){const e=Vf(t);if(!e)return!1;let n=e.parse(t);return e===ln&&(n=Of(n)),n}const il=(t,e)=>{const n=nl(t),i=nl(e);if(!n||!i)return Di(t,e);const s={...n};return r=>(s.red=Qs(n.red,i.red,r),s.green=Qs(n.green,i.green,r),s.blue=Qs(n.blue,i.blue,r),s.alpha=be(n.alpha,i.alpha,r),Ht.transform(s))},eo=new Set(["none","hidden"]);function Bf(t,e){return eo.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function Uf(t,e){return n=>be(t,e,n)}function to(t){return typeof t=="number"?Uf:typeof t=="string"?qs(t)?Di:ke.test(t)?il:Hf:Array.isArray(t)?sl:typeof t=="object"?ke.test(t)?il:jf:Di}function sl(t,e){const n=[...t],i=n.length,s=t.map((r,o)=>to(r)(r,e[o]));return r=>{for(let o=0;o<i;o++)n[o]=s[o](r);return n}}function jf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=to(t[s])(t[s],e[s]));return s=>{for(const r in i)n[r]=i[r](s);return n}}function $f(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const r=e.types[s],o=t.indexes[r][i[r]],a=t.values[o]??0;n[s]=a,i[r]++}return n}const Hf=(t,e)=>{const n=Dt.createTransformer(e),i=jn(t),s=jn(e);return i.indexes.var.length===s.indexes.var.length&&i.indexes.color.length===s.indexes.color.length&&i.indexes.number.length>=s.indexes.number.length?eo.has(t)&&!s.values.length||eo.has(e)&&!i.values.length?Bf(t,e):Nn(sl($f(i,s),s.values),n):Di(t,e)};function ol(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?be(t,e,n):to(t)(t,e)}const Gf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ve.update(e,n),stop:()=>Lt(e),now:()=>Pe.isProcessing?Pe.timestamp:$e.now()}},rl=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let r=0;r<s;r++)i+=Math.round(t(r/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Mi=2e4;function no(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Mi;)e+=n,i=t.next(e);return e>=Mi?1/0:e}function Wf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(no(i),Mi);return{type:"keyframes",ease:r=>i.next(s*r).value/e,duration:ut(s)}}const zf=5;function al(t,e,n){const i=Math.max(e-zf,0);return Ma(n-t(i),e-i)}const we={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},io=.001;function qf({duration:t=we.duration,bounce:e=we.bounce,velocity:n=we.velocity,mass:i=we.mass}){let s,r,o=1-e;o=wt(we.minDamping,we.maxDamping,o),t=wt(we.minDuration,we.maxDuration,ut(t)),o<1?(s=c=>{const u=c*o,d=u*t,f=u-n,m=so(c,o),v=Math.exp(-d);return io-f/m*v},r=c=>{const d=c*o*t,f=d*n+n,m=Math.pow(o,2)*Math.pow(c,2)*t,v=Math.exp(-d),_=so(Math.pow(c,2),o);return(-s(c)+io>0?-1:1)*((f-m)*v)/_}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-io+u*d},r=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const a=5/t,l=Xf(s,r,a);if(t=dt(t),isNaN(l))return{stiffness:we.stiffness,damping:we.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:o*2*Math.sqrt(i*c),duration:t}}}const Kf=12;function Xf(t,e,n){let i=n;for(let s=1;s<Kf;s++)i=i-t(i)/e(i);return i}function so(t,e){return t*Math.sqrt(1-e*e)}const Yf=["duration","bounce"],Jf=["stiffness","damping","mass"];function ll(t,e){return e.some(n=>t[n]!==void 0)}function Zf(t){let e={velocity:we.velocity,stiffness:we.stiffness,damping:we.damping,mass:we.mass,isResolvedFromDuration:!1,...t};if(!ll(t,Jf)&&ll(t,Yf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,r=2*wt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:we.mass,stiffness:s,damping:r}}else{const n=qf(t);e={...e,...n,mass:we.mass},e.isResolvedFromDuration=!0}return e}function Ni(t=we.visualDuration,e=we.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const r=n.keyframes[0],o=n.keyframes[n.keyframes.length-1],a={done:!1,value:r},{stiffness:l,damping:c,mass:u,duration:d,velocity:f,isResolvedFromDuration:m}=Zf({...n,velocity:-ut(n.velocity||0)}),v=f||0,_=c/(2*Math.sqrt(l*u)),w=o-r,y=ut(Math.sqrt(l/u)),T=Math.abs(w)<5;i||(i=T?we.restSpeed.granular:we.restSpeed.default),s||(s=T?we.restDelta.granular:we.restDelta.default);let x;if(_<1){const A=so(y,_);x=M=>{const S=Math.exp(-_*y*M);return o-S*((v+_*y*w)/A*Math.sin(A*M)+w*Math.cos(A*M))}}else if(_===1)x=A=>o-Math.exp(-y*A)*(w+(v+y*w)*A);else{const A=y*Math.sqrt(_*_-1);x=M=>{const S=Math.exp(-_*y*M),C=Math.min(A*M,300);return o-S*((v+_*y*w)*Math.sinh(C)+A*w*Math.cosh(C))/A}}const I={calculatedDuration:m&&d||null,next:A=>{const M=x(A);if(m)a.done=A>=d;else{let S=A===0?v:0;_<1&&(S=A===0?dt(v):al(x,A,M));const C=Math.abs(S)<=i,p=Math.abs(o-M)<=s;a.done=C&&p}return a.value=a.done?o:M,a},toString:()=>{const A=Math.min(no(I),Mi),M=rl(S=>I.next(A*S).value,A,30);return A+"ms "+M},toTransition:()=>{}};return I}Ni.applyToOptions=t=>{const e=Wf(t,100,Ni);return t.ease=e.ease,t.duration=dt(e.duration),t.type="keyframes",t};function oo({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:r=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],f={done:!1,value:d},m=C=>a!==void 0&&C<a||l!==void 0&&C>l,v=C=>a===void 0?l:l===void 0||Math.abs(a-C)<Math.abs(l-C)?a:l;let _=n*e;const w=d+_,y=o===void 0?w:o(w);y!==w&&(_=y-d);const T=C=>-_*Math.exp(-C/i),x=C=>y+T(C),I=C=>{const p=T(C),g=x(C);f.done=Math.abs(p)<=c,f.value=f.done?y:g};let A,M;const S=C=>{m(f.value)&&(A=C,M=Ni({keyframes:[f.value,v(f.value)],velocity:al(x,C,f.value),damping:s,stiffness:r,restDelta:c,restSpeed:u}))};return S(0),{calculatedDuration:null,next:C=>{let p=!1;return!M&&A===void 0&&(p=!0,I(C),S(C)),A!==void 0&&C>=A?M.next(C-A):(!p&&I(C),f)}}}function Qf(t,e,n){const i=[],s=n||St.mix||ol,r=t.length-1;for(let o=0;o<r;o++){let a=s(t[o],t[o+1]);if(e){const l=Array.isArray(e)?e[o]||Ye:e;a=Nn(l,a)}i.push(a)}return i}function ep(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const r=t.length;if(Us(r===e.length),r===1)return()=>e[0];if(r===2&&e[0]===e[1])return()=>e[1];const o=t[0]===t[1];t[0]>t[r-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=Qf(e,i,s),l=a.length,c=u=>{if(o&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const f=On(t[d],t[d+1],u);return a[d](f)};return n?u=>c(wt(t[0],t[r-1],u)):c}function tp(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=On(0,e,i);t.push(be(n,1,s))}}function np(t){const e=[0];return tp(e,t.length-1),e}function ip(t,e){return t.map(n=>n*e)}function sp(t,e){return t.map(()=>e||Ha).splice(0,t.length-1)}function $n({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=gf(i)?i.map(Wa):Wa(i),r={done:!1,value:e[0]},o=ip(n&&n.length===e.length?n:np(e),t),a=ep(o,e,{ease:Array.isArray(s)?s:sp(e,s)});return{calculatedDuration:t,next:l=>(r.value=a(l),r.done=l>=t,r)}}const op=t=>t!==null;function ro(t,{repeat:e,repeatType:n="loop"},i,s=1){const r=t.filter(op),a=s<0||e&&n!=="loop"&&e%2===1?0:r.length-1;return!a||i===void 0?r[a]:i}const rp={decay:oo,inertia:oo,tween:$n,keyframes:$n,spring:Ni};function cl(t){typeof t.type=="string"&&(t.type=rp[t.type])}class ao{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,n){return this.finished.then(e,n)}}const ap=t=>t/100;class lo extends ao{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var i,s;const{motionValue:n}=this.options;n&&n.updatedAt!==$e.now()&&this.tick($e.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(i=this.options).onStop)==null||s.call(i))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;cl(e);const{type:n=$n,repeat:i=0,repeatDelay:s=0,repeatType:r,velocity:o=0}=e;let{keyframes:a}=e;const l=n||$n;l!==$n&&typeof a[0]!="number"&&(this.mixKeyframes=Nn(ap,ol(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});r==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-o})),c.calculatedDuration===null&&(c.calculatedDuration=no(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:r,mirroredGenerator:o,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:f,repeatDelay:m,type:v,onUpdate:_,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),T=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let x=this.currentTime,I=i;if(d){const C=Math.min(this.currentTime,s)/a;let p=Math.floor(C),g=C%1;!g&&C>=1&&(g=1),g===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(f==="reverse"?(g=1-g,m&&(g-=m/a)):f==="mirror"&&(I=o)),x=wt(0,1,g)*a}const A=T?{done:!1,value:u[0]}:I.next(x);r&&(A.value=r(A.value));let{done:M}=A;!T&&l!==null&&(M=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return S&&v!==oo&&(A.value=ro(u,this.options,w,this.speed)),_&&_(A.value),S&&this.finish(),A}then(e,n){return this.finished.then(e,n)}get duration(){return ut(this.calculatedDuration)}get time(){return ut(this.currentTime)}set time(e){var n;e=dt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(n=this.driver)==null||n.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime($e.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=ut(this.currentTime))}play(){var s,r;if(this.isStopped)return;const{driver:e=Gf,startTime:n}=this.options;this.driver||(this.driver=e(o=>this.tick(o))),(r=(s=this.options).onPlay)==null||r.call(s);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime($e.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(e=this.options).onComplete)==null||n.call(e)}cancel(){var e,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(e=this.options).onCancel)==null||n.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),e.observe(this)}}function lp(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Gt=t=>t*180/Math.PI,co=t=>{const e=Gt(Math.atan2(t[1],t[0]));return uo(e)},cp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:co,rotateZ:co,skewX:t=>Gt(Math.atan(t[1])),skewY:t=>Gt(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),dl=co,ul=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),hl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),dp={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ul,scaleY:hl,scale:t=>(ul(t)+hl(t))/2,rotateX:t=>uo(Gt(Math.atan2(t[6],t[5]))),rotateY:t=>uo(Gt(Math.atan2(-t[2],t[0]))),rotateZ:dl,rotate:dl,skewX:t=>Gt(Math.atan(t[4])),skewY:t=>Gt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ho(t){return t.includes("scale")?1:0}function fo(t,e){if(!t||t==="none")return ho(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=dp,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=cp,s=a}if(!s)return ho(e);const r=i[e],o=s[1].split(",").map(hp);return typeof r=="function"?r(o):o[r]}const up=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return fo(n,e)};function hp(t){return parseFloat(t.trim())}const cn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dn=new Set(cn),fl=t=>t===an||t===W,fp=new Set(["x","y","z"]),pp=cn.filter(t=>!fp.has(t));function gp(t){const e=[];return pp.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Wt={width:({x:t},{paddingLeft:e="0",paddingRight:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),height:({y:t},{paddingTop:e="0",paddingBottom:n="0"})=>t.max-t.min-parseFloat(e)-parseFloat(n),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>fo(e,"x"),y:(t,{transform:e})=>fo(e,"y")};Wt.translateX=Wt.x,Wt.translateY=Wt.y;const zt=new Set;let po=!1,go=!1,mo=!1;function pl(){if(go){const t=Array.from(zt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=gp(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([r,o])=>{var a;(a=i.getValue(r))==null||a.set(o)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}go=!1,po=!1,zt.forEach(t=>t.complete(mo)),zt.clear()}function gl(){zt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(go=!0)})}function mp(){mo=!0,gl(),pl(),mo=!1}class vo{constructor(e,n,i,s,r,o=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=r,this.isAsync=o}scheduleResolve(){this.state="scheduled",this.isAsync?(zt.add(this),po||(po=!0,ve.read(gl),ve.resolveKeyframes(pl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const r=s==null?void 0:s.get(),o=e[e.length-1];if(r!==void 0)e[0]=r;else if(i&&n){const a=i.readValue(n,o);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=o),s&&r===void 0&&s.set(e[0])}lp(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),zt.delete(this)}cancel(){this.state==="scheduled"&&(zt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const vp=t=>t.startsWith("--");function yp(t,e,n){vp(e)?t.style.setProperty(e,n):t.style[e]=n}const _p=js(()=>window.ScrollTimeline!==void 0),bp={};function wp(t,e){const n=js(t);return()=>bp[e]??n()}const ml=wp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Hn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,vl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Hn([0,.65,.55,1]),circOut:Hn([.55,0,1,.45]),backIn:Hn([.31,.01,.66,-.59]),backOut:Hn([.33,1.53,.69,.99])};function yl(t,e){if(t)return typeof t=="function"?ml()?rl(t,e):"ease-out":Ga(t)?Hn(t):Array.isArray(t)?t.map(n=>yl(n,e)||vl.easeOut):vl[t]}function Sp(t,e,n,{delay:i=0,duration:s=300,repeat:r=0,repeatType:o="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=yl(a,s);Array.isArray(d)&&(u.easing=d);const f={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:r+1,direction:o==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(u,f)}function _l(t){return typeof t=="function"&&"applyToOptions"in t}function Cp({type:t,...e}){return _l(t)&&ml()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Tp extends ao{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:r,allowFlatten:o=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!r,this.allowFlatten=o,this.options=e,Us(typeof e.type!="string");const c=Cp(e);this.animation=Sp(n,i,s,c,r),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=ro(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):yp(n,i,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return ut(Number(e))}get time(){return ut(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=dt(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:n}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&_p()?(this.animation.timeline=e,Ye):n(this)}}const bl={anticipate:Ua,backInOut:Ba,circInOut:$a};function kp(t){return t in bl}function xp(t){typeof t.ease=="string"&&kp(t.ease)&&(t.ease=bl[t.ease])}const wl=10;class Ep extends Tp{constructor(e){xp(e),cl(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:r,...o}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new lo({...o,autoplay:!1}),l=dt(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-wl).value,a.sample(l).value,wl),a.stop()}}const Sl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Dt.test(t)||t==="0")&&!t.startsWith("url("));function Ip(t){const e=t[0];if(t.length===1)return!0;for(let n=0;n<t.length;n++)if(t[n]!==e)return!0}function Ap(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const r=t[t.length-1],o=Sl(s,e),a=Sl(r,e);return!o||!a?!1:Ip(t)||(n==="spring"||_l(n))&&i}function yo(t){return Pa(t)&&"offsetHeight"in t}const Rp=new Set(["opacity","clipPath","filter","transform"]),Lp=js(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Pp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:r,type:o}=t;if(!yo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return Lp()&&n&&Rp.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&r!==0&&o!=="inertia"}const Dp=40;class Mp extends ao{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:r=0,repeatType:o="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var v;super(),this.stop=()=>{var _,w;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=$e.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:r,repeatType:o,name:l,motionValue:c,element:u,...d},m=(u==null?void 0:u.KeyframeResolver)||vo;this.keyframeResolver=new m(a,(_,w,y)=>this.onKeyframesResolved(_,w,f,!y),l,c,u),(v=this.keyframeResolver)==null||v.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:r,type:o,velocity:a,delay:l,isHandoff:c,onUpdate:u}=i;this.resolvedAt=$e.now(),Ap(e,r,o,a)||((St.instantAnimations||!l)&&(u==null||u(ro(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Dp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},m=!c&&Pp(f)?new Ep({...f,element:f.motionValue.owner.current}):new lo(f);m.finished.then(()=>this.notifyFinished()).catch(Ye),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),mp()),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 Np=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Op(t){const e=Np.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function Cl(t,e,n=1){const[i,s]=Op(t);if(!i)return;const r=window.getComputedStyle(e).getPropertyValue(i);if(r){const o=r.trim();return La(o)?parseFloat(o):o}return qs(s)?Cl(s,e,n+1):s}function _o(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Tl=new Set(["width","height","top","left","right","bottom",...cn]),Fp={test:t=>t==="auto",parse:t=>t},kl=t=>e=>e.test(t),xl=[an,W,ht,Pt,If,Ef,Fp],El=t=>xl.find(kl(t));function Vp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Da(t):!0}const Bp=new Set(["brightness","contrast","saturate","opacity"]);function Up(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Ks)||[];if(!i)return t;const s=n.replace(i,"");let r=Bp.has(e)?1:0;return i!==n&&(r*=100),e+"("+r+s+")"}const jp=/\b([a-z-]*)\(.*?\)/gu,bo={...Dt,getAnimatableNone:t=>{const e=t.match(jp);return e?e.map(Up).join(" "):t}},Il={...an,transform:Math.round},wo={borderWidth:W,borderTopWidth:W,borderRightWidth:W,borderBottomWidth:W,borderLeftWidth:W,borderRadius:W,radius:W,borderTopLeftRadius:W,borderTopRightRadius:W,borderBottomRightRadius:W,borderBottomLeftRadius:W,width:W,maxWidth:W,height:W,maxHeight:W,top:W,right:W,bottom:W,left:W,padding:W,paddingTop:W,paddingRight:W,paddingBottom:W,paddingLeft:W,margin:W,marginTop:W,marginRight:W,marginBottom:W,marginLeft:W,backgroundPositionX:W,backgroundPositionY:W,...{rotate:Pt,rotateX:Pt,rotateY:Pt,rotateZ:Pt,scale:Pi,scaleX:Pi,scaleY:Pi,scaleZ:Pi,skew:Pt,skewX:Pt,skewY:Pt,distance:W,translateX:W,translateY:W,translateZ:W,x:W,y:W,z:W,perspective:W,transformPerspective:W,opacity:Vn,originX:Ya,originY:Ya,originZ:W},zIndex:Il,fillOpacity:Vn,strokeOpacity:Vn,numOctaves:Il},$p={...wo,color:ke,backgroundColor:ke,outlineColor:ke,fill:ke,stroke:ke,borderColor:ke,borderTopColor:ke,borderRightColor:ke,borderBottomColor:ke,borderLeftColor:ke,filter:bo,WebkitFilter:bo},Al=t=>$p[t];function Rl(t,e){let n=Al(t);return n!==bo&&(n=Dt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Hp=new Set(["auto","none","0"]);function Gp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const r=t[i];typeof r=="string"&&!Hp.has(r)&&jn(r).values.length&&(s=t[i]),i++}if(s&&n)for(const r of e)t[r]=Rl(n,s)}class Wp extends vo{constructor(e,n,i,s,r){super(e,n,i,s,r,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),qs(c))){const u=Cl(c,n.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Tl.has(i)||e.length!==2)return;const[s,r]=e,o=El(s),a=El(r);if(o!==a)if(fl(o)&&fl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Wt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Vp(e[s]))&&i.push(s);i.length&&Gp(e,i,n)}measureInitialState(){const{element:e,unresolvedKeyframes:n,name:i}=this;if(!e||!e.current)return;i==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Wt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const r=i.length-1,o=i[r];i[r]=Wt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),o!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=o),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function zp(t,e,n){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let i=document;const s=(n==null?void 0:n[t])??i.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Ll=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Pl=30,qp=t=>!isNaN(parseFloat(t));class Kp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var o,a;const r=$e.now();if(this.updatedAt!==r&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((o=this.events.change)==null||o.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=$e.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=qp(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,n){this.events[e]||(this.events[e]=new $s);const i=this.events[e].add(n);return e==="change"?()=>{i(),ve.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,n){this.passiveEffect=e,this.stopPassiveEffect=n}set(e,n=!0){!n||!this.passiveEffect?this.updateAndNotify(e,n):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,n,i){this.set(n),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,n=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=$e.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Pl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Pl);return Ma(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(e){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=e(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,n;(e=this.dependents)==null||e.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function un(t,e){return new Kp(t,e)}const{schedule:So}=qa(queueMicrotask,!1),st={x:!1,y:!1};function Dl(){return st.x||st.y}function Xp(t){return t==="x"||t==="y"?st[t]?null:(st[t]=!0,()=>{st[t]=!1}):st.x||st.y?null:(st.x=st.y=!0,()=>{st.x=st.y=!1})}function Ml(t,e){const n=zp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Nl(t){return!(t.pointerType==="touch"||Dl())}function Yp(t,e,n={}){const[i,s,r]=Ml(t,n),o=a=>{if(!Nl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Nl(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",o,s)}),r}const Ol=(t,e)=>e?t===e?!0:Ol(t,e.parentElement):!1,Co=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Jp=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Zp(t){return Jp.has(t.tagName)||t.tabIndex!==-1}const Oi=new WeakSet;function Fl(t){return e=>{e.key==="Enter"&&t(e)}}function To(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Qp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Fl(()=>{if(Oi.has(n))return;To(n,"down");const s=Fl(()=>{To(n,"up")}),r=()=>To(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",r,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function Vl(t){return Co(t)&&!Dl()}function eg(t,e,n={}){const[i,s,r]=Ml(t,n),o=a=>{const l=a.currentTarget;if(!Vl(a))return;Oi.add(l);const c=e(l,a),u=(m,v)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),Oi.has(l)&&Oi.delete(l),Vl(m)&&typeof c=="function"&&c(m,{success:v})},d=m=>{u(m,l===window||l===document||n.useGlobalTarget||Ol(l,m.target))},f=m=>{u(m,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",o,s),yo(a)&&(a.addEventListener("focus",c=>Qp(c,s)),!Zp(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),r}function Bl(t){return Pa(t)&&"ownerSVGElement"in t}function tg(t){return Bl(t)&&t.tagName==="svg"}const Oe=t=>!!(t&&t.getVelocity),ng=[...xl,ke,Dt],ig=t=>ng.find(kl(t)),Gn=bt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class sg extends it{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=yo(i)&&i.offsetWidth||0,r=this.props.sizeRef.current;r.height=n.offsetHeight||0,r.width=n.offsetWidth||0,r.top=n.offsetTop,r.left=n.offsetLeft,r.right=s-r.width-r.left}return null}componentDidUpdate(){}render(){return this.props.children}}function og({children:t,isPresent:e,anchorX:n,root:i}){const s=Ts(),r=de(null),o=de({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Re(Gn);return ua(()=>{const{width:l,height:c,top:u,left:d,right:f}=o.current;if(e||!r.current||!l||!c)return;const m=n==="left"?`left: ${d}`:`right: ${f}`;r.current.dataset.motionPopId=s;const v=document.createElement("style");a&&(v.nonce=a);const _=i??document.head;return _.appendChild(v),v.sheet&&v.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
@@ -6,34 +6,34 @@ var vb=Object.defineProperty;var _b=(nt,G,jt)=>G in nt?vb(nt,G,{enumerable:!0,co
6
6
  ${m}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{y.removeChild(v),y.contains(v)&&y.removeChild(v)}},[e]),R(ig,{isPresent:e,childRef:r,sizeRef:o,children:sf(t,{ref:r})})}const og=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:r,mode:o,anchorX:a,root:l})=>{const c=Ii(rg),u=Ts();let d=!0,f=Xe(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:m=>{c.set(m,!0);for(const v of c.values())if(!v)return;i&&i()},register:m=>(c.set(m,!1),()=>c.delete(m))}),[n,c,i]);return r&&d&&(f={...f}),Xe(()=>{c.forEach((m,v)=>c.set(v,!1))},[n]),Ae(()=>{!n&&!c.size&&i&&i()},[n]),o==="popLayout"&&(t=R(sg,{isPresent:n,anchorX:a,root:l,children:t})),R(Ai.Provider,{value:f,children:t})};function rg(){return new Map}function Ul(t=!0){const e=Re(Ai);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,r=Ts();Ae(()=>{if(t)return s(r)},[t]);const o=We(()=>t&&i&&i(r),[r,i,t]);return!n&&i?[!1,o]:[!0]}const Fi=t=>t.key||"";function jl(t){const e=[];return zh.forEach(t,n=>{ka(n)&&e.push(n)}),e}const ag=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:r="sync",propagate:o=!1,anchorX:a="left",root:l})=>{const[c,u]=Ul(o),d=Xe(()=>jl(t),[t]),f=o&&!c?[]:d.map(Fi),m=de(!0),v=de(d),y=Ii(()=>new Map),[w,_]=Ee(d),[T,x]=Ee(d);Ra(()=>{m.current=!1,v.current=d;for(let M=0;M<T.length;M++){const S=Fi(T[M]);f.includes(S)?y.delete(S):y.get(S)!==!0&&y.set(S,!1)}},[T,f.length,f.join("-")]);const I=[];if(d!==w){let M=[...d];for(let S=0;S<T.length;S++){const C=T[S],p=Fi(C);f.includes(p)||(M.splice(S,0,C),I.push(C))}return r==="wait"&&I.length&&(M=I),x(jl(M)),_(d),null}const{forceRender:A}=Re(Os);return R(lt,{children:T.map(M=>{const S=Fi(M),C=o&&!c?!1:d===T||f.includes(S),p=()=>{if(y.has(S))y.set(S,!0);else return;let g=!0;y.forEach(h=>{h||(g=!1)}),g&&(A==null||A(),x(v.current),o&&(u==null||u()),i&&i())};return R(og,{isPresent:C,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:r,root:l,onExitComplete:C?void 0:p,anchorX:a,children:M},S)})})},$l=bt({strict:!1}),Hl={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"]},hn={};for(const t in Hl)hn[t]={isEnabled:e=>Hl[t].some(n=>!!e[n])};function lg(t){for(const e in t)hn[e]={...hn[e],...t[e]}}const cg=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 Vi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||cg.has(t)}let Gl=t=>!Vi(t);function Wl(t){typeof t=="function"&&(Gl=e=>e.startsWith("on")?!Vi(e):t(e))}try{Wl(require("@emotion/is-prop-valid").default)}catch{}function dg(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Gl(s)||n===!0&&Vi(s)||!e&&!Vi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function ug({children:t,isValidProp:e,...n}){e&&Wl(e),n={...Re(Gn),...n},n.isStatic=Ii(()=>n.isStatic);const i=Xe(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return R(Gn.Provider,{value:i,children:t})}function hg(t){if(typeof Proxy>"u")return t;const e=new Map,n=(...i)=>t(...i);return new Proxy(n,{get:(i,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const Bi=bt({});function Ui(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Wn(t){return typeof t=="string"||Array.isArray(t)}const ko=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],xo=["initial",...ko];function ji(t){return Ui(t.animate)||xo.some(e=>Wn(t[e]))}function zl(t){return!!(ji(t)||t.variants)}function fg(t,e){if(ji(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Wn(n)?n:void 0,animate:Wn(i)?i:void 0}}return t.inherit!==!1?e:{}}function pg(t){const{initial:e,animate:n}=fg(t,Re(Bi));return Xe(()=>({initial:e,animate:n}),[ql(e),ql(n)])}function ql(t){return Array.isArray(t)?t.join(" "):t}const gg=Symbol.for("motionComponentSymbol");function fn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function mg(t,e,n){return We(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):fn(n)&&(n.current=i))},[e])}const Eo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Kl="data-"+Eo("framerAppearId"),Xl=bt({});function vg(t,e,n,i,s){var y,w;const{visualElement:r}=Re(Bi),o=Re($l),a=Re(Ai),l=Re(Gn).reducedMotion,c=de(null);i=i||o.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:r,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Re(Xl);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&_g(c.current,n,s,d);const f=de(!1);ua(()=>{u&&f.current&&u.update(n,a)});const m=n[Kl],v=de(!!m&&!((y=window.MotionHandoffIsComplete)!=null&&y.call(window,m))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,m)));return Ra(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),So.render(u.render),v.current&&u.animationState&&u.animationState.animateChanges())}),Ae(()=>{u&&(!v.current&&u.animationState&&u.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var _;(_=window.MotionHandoffMarkAsComplete)==null||_.call(window,m)}),v.current=!1))}),u}function _g(t,e,n,i){const{layoutId:s,layout:r,drag:o,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Yl(t.parent)),t.projection.setOptions({layoutId:s,layout:r,alwaysMeasureLayout:!!o||a&&fn(a),visualElement:t,animationType:typeof r=="string"?r:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:c})}function Yl(t){if(t)return t.options.allowProjection!==!1?t.projection:Yl(t.parent)}function yg({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&lg(t);function r(a,l){let c;const u={...Re(Gn),...a,layoutId:bg(a)},{isStatic:d}=u,f=pg(a),m=i(a,d);if(!d&&Fs){wg();const v=Sg(u);c=v.MeasureLayout,f.visualElement=vg(s,m,u,e,v.ProjectionNode)}return R(Bi.Provider,{value:f,children:[c&&f.visualElement?R(c,{visualElement:f.visualElement,...u}):null,n(s,a,mg(m,f.visualElement,l),m,d,f.visualElement)]})}r.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const o=Wh(r);return o[gg]=s,o}function bg({layoutId:t}){const e=Re(Os).id;return e&&t!==void 0?e+"-"+t:t}function wg(t,e){Re($l).strict}function Sg(t){const{drag:e,layout:n}=hn;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e!=null&&e.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const zn={};function Cg(t){for(const e in t)zn[e]=t[e],zs(e)&&(zn[e].isCSSVariable=!0)}function Jl(t,{layout:e,layoutId:n}){return dn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!zn[t]||t==="opacity")}const Tg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},kg=cn.length;function xg(t,e,n){let i="",s=!0;for(let r=0;r<kg;r++){const o=cn[r],a=t[o];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(o.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Ll(a,wo[o]);if(!l){s=!1;const u=Tg[o]||o;i+=`${u}(${c}) `}n&&(e[o]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function Io(t,e,n){const{style:i,vars:s,transformOrigin:r}=t;let o=!1,a=!1;for(const l in e){const c=e[l];if(dn.has(l)){o=!0;continue}else if(zs(l)){s[l]=c;continue}else{const u=Ll(c,wo[l]);l.startsWith("origin")?(a=!0,r[l]=u):i[l]=u}}if(e.transform||(o||n?i.transform=xg(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=r;i.transformOrigin=`${l} ${c} ${u}`}}const Ao=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zl(t,e,n){for(const i in e)!Oe(e[i])&&!Jl(i,n)&&(t[i]=e[i])}function Eg({transformTemplate:t},e){return Xe(()=>{const n=Ao();return Io(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Ig(t,e){const n=t.style||{},i={};return Zl(i,n,t),Object.assign(i,Eg(t,e)),i}function Ag(t,e){const n={},i=Ig(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const Rg={offset:"stroke-dashoffset",array:"stroke-dasharray"},Lg={offset:"strokeDashoffset",array:"strokeDasharray"};function Pg(t,e,n=1,i=0,s=!0){t.pathLength=1;const r=s?Rg:Lg;t[r.offset]=W.transform(-i);const o=W.transform(e),a=W.transform(n);t[r.array]=`${o} ${a}`}function Ql(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:r=1,pathOffset:o=0,...a},l,c,u){if(Io(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:f}=t;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),s!==void 0&&Pg(d,s,r,o,!1)}const ec=()=>({...Ao(),attrs:{}}),tc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Dg(t,e,n,i){const s=Xe(()=>{const r=ec();return Ql(r,e,tc(i),t.transformTemplate,t.style),{...r.attrs,style:{...r.style}}},[e]);if(t.style){const r={};Zl(r,t.style,t),s.style={...r,...s.style}}return s}const Mg=["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 Ro(t){return typeof t!="string"||t.includes("-")?!1:!!(Mg.indexOf(t)>-1||/[A-Z]/u.test(t))}function Ng(t=!1){return(n,i,s,{latestValues:r},o)=>{const l=(Ro(n)?Dg:Ag)(i,r,o,n),c=dg(i,typeof n=="string",t),u=n!==lt?{...c,...l,ref:s}:{},{children:d}=i,f=Xe(()=>Oe(d)?d.get():d,[d]);return Ke(n,{...u,children:f})}}function nc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Lo(t,e,n,i){if(typeof e=="function"){const[s,r]=nc(i);e=e(n!==void 0?n:t.custom,s,r)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,r]=nc(i);e=e(n!==void 0?n:t.custom,s,r)}return e}function $i(t){return Oe(t)?t.get():t}function Og({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Fg(n,i,s,t),renderState:e()}}const ic=t=>(e,n)=>{const i=Re(Bi),s=Re(Ai),r=()=>Og(t,e,i,s);return n?r():Ii(r)};function Fg(t,e,n,i){const s={},r=i(t,{});for(const f in r)s[f]=$i(r[f]);let{initial:o,animate:a}=t;const l=ji(t),c=zl(t);e&&c&&!l&&t.inherit!==!1&&(o===void 0&&(o=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!Ui(d)){const f=Array.isArray(d)?d:[d];for(let m=0;m<f.length;m++){const v=Lo(t,f[m]);if(v){const{transitionEnd:y,transition:w,..._}=v;for(const T in _){let x=_[T];if(Array.isArray(x)){const I=u?x.length-1:0;x=x[I]}x!==null&&(s[T]=x)}for(const T in y)s[T]=y[T]}}}return s}function Po(t,e,n){var r;const{style:i}=t,s={};for(const o in i)(Oe(i[o])||e.style&&Oe(e.style[o])||Jl(o,t)||((r=n==null?void 0:n.getValue(o))==null?void 0:r.liveStyle)!==void 0)&&(s[o]=i[o]);return s}const Vg={useVisualState:ic({scrapeMotionValuesFromProps:Po,createRenderState:Ao})};function sc(t,e,n){const i=Po(t,e,n);for(const s in t)if(Oe(t[s])||Oe(e[s])){const r=cn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[r]=t[s]}return i}const Bg={useVisualState:ic({scrapeMotionValuesFromProps:sc,createRenderState:ec})};function Ug(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const o={...Ro(i)?Bg:Vg,preloadedFeatures:t,useRender:Ng(s),createVisualElement:e,Component:i};return yg(o)}}function qn(t,e,n){const i=t.getProps();return Lo(i,e,n!==void 0?n:i.custom,t)}const Do=t=>Array.isArray(t);function jg(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,un(n))}function $g(t){return Do(t)?t[t.length-1]||0:t}function Hg(t,e){const n=qn(t,e);let{transitionEnd:i={},transition:s={},...r}=n||{};r={...r,...i};for(const o in r){const a=$g(r[o]);jg(t,o,a)}}function Gg(t){return!!(Oe(t)&&t.add)}function Mo(t,e){const n=t.getValue("willChange");if(Gg(n))return n.add(e);if(!n&&St.WillChange){const i=new St.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function oc(t){return t.props[Kl]}const Wg=t=>t!==null;function zg(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Wg),r=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[r]}const qg={type:"spring",stiffness:500,damping:25,restSpeed:10},Kg=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Xg={type:"keyframes",duration:.8},Yg={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Jg=(t,{keyframes:e})=>e.length>2?Xg:dn.has(t)?t.startsWith("scale")?Kg(e[1]):qg:Yg;function Zg({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:r,repeatType:o,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const No=(t,e,n,i={},s,r)=>o=>{const a=yo(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-dt(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:r?void 0:s};Zg(a)||Object.assign(u,Jg(t,u)),u.duration&&(u.duration=dt(u.duration)),u.repeatDelay&&(u.repeatDelay=dt(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)),(St.instantAnimations||St.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!r&&e.get()!==void 0){const f=zg(u.keyframes,a);if(f!==void 0){ve.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new lo(u):new Dp(u)};function Qg({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function rc(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:o,...a}=e;i&&(r=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),f=a[u];if(f===void 0||c&&Qg(c,u))continue;const m={delay:n,...yo(r||{},u)},v=d.get();if(v!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===v&&!m.velocity)continue;let y=!1;if(window.MotionHandoffAnimation){const _=oc(t);if(_){const T=window.MotionHandoffAnimation(_,u,ve);T!==null&&(m.startTime=T,y=!0)}}Mo(t,u),d.start(No(u,d,f,t.shouldReduceMotion&&Tl.has(u)?{type:!1}:m,t,y));const w=d.animation;w&&l.push(w)}return o&&Promise.all(l).then(()=>{ve.update(()=>{o&&Hg(t,o)})}),l}function Oo(t,e,n={}){var l;const i=qn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const r=i?()=>Promise.all(rc(t,i,n)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=s;return em(t,e,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[r,o]:[o,r];return c().then(()=>u())}else return Promise.all([r(),o(n.delay)])}function em(t,e,n=0,i=0,s=0,r=1,o){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof i=="function",d=u?f=>i(f,l):r===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(tm).forEach((f,m)=>{f.notify("AnimationStart",e),a.push(Oo(f,e,{...o,delay:n+(u?0:i)+d(m)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function tm(t,e){return t.sortNodePosition(e)}function nm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(r=>Oo(t,r,n));i=Promise.all(s)}else if(typeof e=="string")i=Oo(t,e,n);else{const s=typeof e=="function"?qn(t,e,n.custom):e;i=Promise.all(rc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function ac(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const im=xo.length;function lc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?lc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<im;n++){const i=xo[n],s=t.props[i];(Wn(s)||s===!1)&&(e[i]=s)}return e}const sm=[...ko].reverse(),om=ko.length;function rm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>nm(t,n,i)))}function am(t){let e=rm(t),n=cc(),i=!0;const s=l=>(c,u)=>{var f;const d=qn(t,u,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:m,transitionEnd:v,...y}=d;c={...c,...y,...v}}return c};function r(l){e=l(t)}function o(l){const{props:c}=t,u=lc(t.parent)||{},d=[],f=new Set;let m={},v=1/0;for(let w=0;w<om;w++){const _=sm[w],T=n[_],x=c[_]!==void 0?c[_]:u[_],I=Wn(x),A=_===l?T.isActive:null;A===!1&&(v=w);let M=x===u[_]&&x!==c[_]&&I;if(M&&i&&t.manuallyAnimateOnMount&&(M=!1),T.protectedKeys={...m},!T.isActive&&A===null||!x&&!T.prevProp||Ui(x)||typeof x=="boolean")continue;const S=lm(T.prevProp,x);let C=S||_===l&&T.isActive&&!M&&I||w>v&&I,p=!1;const g=Array.isArray(x)?x:[x];let h=g.reduce(s(_),{});A===!1&&(h={});const{prevResolvedValues:b={}}=T,E={...b,...h},P=D=>{C=!0,f.has(D)&&(p=!0,f.delete(D)),T.needsAnimating[D]=!0;const U=t.getValue(D);U&&(U.liveStyle=!1)};for(const D in E){const U=h[D],Y=b[D];if(m.hasOwnProperty(D))continue;let j=!1;Do(U)&&Do(Y)?j=!ac(U,Y):j=U!==Y,j?U!=null?P(D):f.add(D):U!==void 0&&f.has(D)?P(D):T.protectedKeys[D]=!0}T.prevProp=x,T.prevResolvedValues=h,T.isActive&&(m={...m,...h}),i&&t.blockInitialAnimation&&(C=!1),C&&(!(M&&S)||p)&&d.push(...g.map(D=>({animation:D,options:{type:_}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const _=qn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);_&&_.transition&&(w.transition=_.transition)}f.forEach(_=>{const T=t.getBaseTarget(_),x=t.getValue(_);x&&(x.liveStyle=!0),w[_]=T??null}),d.push({animation:w})}let y=!!d.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(y=!1),i=!1,y?e(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(f=>{var m;return(m=f.animationState)==null?void 0:m.setActive(l,c)}),n[l].isActive=c;const u=o(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:r,getState:()=>n,reset:()=>{n=cc(),i=!0}}}function lm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!ac(e,t):!1}function qt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function cc(){return{animate:qt(!0),whileInView:qt(),whileHover:qt(),whileTap:qt(),whileDrag:qt(),whileFocus:qt(),exit:qt()}}class Pt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class cm extends Pt{constructor(e){super(e),e.animationState||(e.animationState=am(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ui(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let dm=0;class um extends Pt{constructor(){super(...arguments),this.id=dm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const hm={animation:{Feature:cm},exit:{Feature:um}};function Kn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Xn(t){return{point:{x:t.pageX,y:t.pageY}}}const fm=t=>e=>Co(e)&&t(e,Xn(e));function Yn(t,e,n,i){return Kn(t,e,fm(n),i)}function dc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function pm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function gm(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const uc=1e-4,mm=1-uc,vm=1+uc,hc=.01,_m=0-hc,ym=0+hc;function Ve(t){return t.max-t.min}function bm(t,e,n){return Math.abs(t-e)<=n}function fc(t,e,n,i=.5){t.origin=i,t.originPoint=be(e.min,e.max,t.origin),t.scale=Ve(n)/Ve(e),t.translate=be(n.min,n.max,t.origin)-t.originPoint,(t.scale>=mm&&t.scale<=vm||isNaN(t.scale))&&(t.scale=1),(t.translate>=_m&&t.translate<=ym||isNaN(t.translate))&&(t.translate=0)}function Jn(t,e,n,i){fc(t.x,e.x,n.x,i?i.originX:void 0),fc(t.y,e.y,n.y,i?i.originY:void 0)}function pc(t,e,n){t.min=n.min+e.min,t.max=t.min+Ve(e)}function wm(t,e,n){pc(t.x,e.x,n.x),pc(t.y,e.y,n.y)}function gc(t,e,n){t.min=e.min-n.min,t.max=t.min+Ve(e)}function Zn(t,e,n){gc(t.x,e.x,n.x),gc(t.y,e.y,n.y)}const mc=()=>({translate:0,scale:1,origin:0,originPoint:0}),pn=()=>({x:mc(),y:mc()}),vc=()=>({min:0,max:0}),Ce=()=>({x:vc(),y:vc()});function Je(t){return[t("x"),t("y")]}function Fo(t){return t===void 0||t===1}function Vo({scale:t,scaleX:e,scaleY:n}){return!Fo(t)||!Fo(e)||!Fo(n)}function Kt(t){return Vo(t)||_c(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function _c(t){return yc(t.x)||yc(t.y)}function yc(t){return t&&t!=="0%"}function Hi(t,e,n){const i=t-n,s=e*i;return n+s}function bc(t,e,n,i,s){return s!==void 0&&(t=Hi(t,s,i)),Hi(t,n,i)+e}function Bo(t,e=0,n=1,i,s){t.min=bc(t.min,e,n,i,s),t.max=bc(t.max,e,n,i,s)}function wc(t,{x:e,y:n}){Bo(t.x,e.translate,e.scale,e.originPoint),Bo(t.y,n.translate,n.scale,n.originPoint)}const Sc=.999999999999,Cc=1.0000000000001;function Sm(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let r,o;for(let a=0;a<s;a++){r=n[a],o=r.projectionDelta;const{visualElement:l}=r.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&r.options.layoutScroll&&r.scroll&&r!==r.root&&mn(t,{x:-r.scroll.offset.x,y:-r.scroll.offset.y}),o&&(e.x*=o.x.scale,e.y*=o.y.scale,wc(t,o)),i&&Kt(r.latestValues)&&mn(t,r.latestValues))}e.x<Cc&&e.x>Sc&&(e.x=1),e.y<Cc&&e.y>Sc&&(e.y=1)}function gn(t,e){t.min=t.min+e,t.max=t.max+e}function Tc(t,e,n,i,s=.5){const r=be(t.min,t.max,s);Bo(t,e,n,r,i)}function mn(t,e){Tc(t.x,e.x,e.scaleX,e.scale,e.originX),Tc(t.y,e.y,e.scaleY,e.scale,e.originY)}function kc(t,e){return dc(gm(t.getBoundingClientRect(),e))}function Cm(t,e,n){const i=kc(t,n),{scroll:s}=e;return s&&(gn(i.x,s.offset.x),gn(i.y,s.offset.y)),i}const xc=({current:t})=>t?t.ownerDocument.defaultView:null,Ec=(t,e)=>Math.abs(t-e);function Tm(t,e){const n=Ec(t.x,e.x),i=Ec(t.y,e.y);return Math.sqrt(n**2+i**2)}class Ic{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:r=!1,distanceThreshold:o=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 f=jo(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,v=Tm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!v)return;const{point:y}=f,{timestamp:w}=Pe;this.history.push({...y,timestamp:w});const{onStart:_,onMove:T}=this.handlers;m||(_&&_(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Uo(m,this.transformPagePoint),ve.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=jo(f.type==="pointercancel"?this.lastMoveEventInfo:Uo(m,this.transformPagePoint),this.history);this.startEvent&&v&&v(f,_),y&&y(f,_)},!Co(e))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=s||window;const a=Xn(e),l=Uo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,jo(l,this.history)),this.removeListeners=Nn(Yn(this.contextWindow,"pointermove",this.handlePointerMove),Yn(this.contextWindow,"pointerup",this.handlePointerUp),Yn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),At(this.updatePoint)}}function Uo(t,e){return e?{point:e(t.point)}:t}function Ac(t,e){return{x:t.x-e.x,y:t.y-e.y}}function jo({point:t},e){return{point:t,delta:Ac(t,Rc(e)),offset:Ac(t,km(e)),velocity:xm(e,.1)}}function km(t){return t[0]}function Rc(t){return t[t.length-1]}function xm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=Rc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>dt(e)));)n--;if(!i)return{x:0,y:0};const r=ut(s.timestamp-i.timestamp);if(r===0)return{x:0,y:0};const o={x:(s.x-i.x)/r,y:(s.y-i.y)/r};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Em(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?be(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?be(n,t,i.max):Math.min(t,n)),t}function Lc(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function Im(t,{top:e,left:n,bottom:i,right:s}){return{x:Lc(t.x,n,s),y:Lc(t.y,e,i)}}function Pc(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function Am(t,e){return{x:Pc(t.x,e.x),y:Pc(t.y,e.y)}}function Rm(t,e){let n=.5;const i=Ve(t),s=Ve(e);return s>i?n=On(e.min,e.max-i,t.min):i>s&&(n=On(t.min,t.max-s,e.min)),wt(0,1,n)}function Lm(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const $o=.35;function Pm(t=$o){return t===!1?t=0:t===!0&&(t=$o),{x:Dc(t,"left","right"),y:Dc(t,"top","bottom")}}function Dc(t,e,n){return{min:Mc(t,e),max:Mc(t,n)}}function Mc(t,e){return typeof t=="number"?t:t[e]||0}const Dm=new WeakMap;class Mm{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=Ce(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const r=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Xn(d).point)},o=(d,f)=>{const{drag:m,dragPropagation:v,onDragStart:y}=this.getProps();if(m&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Kp(m),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Je(_=>{let T=this.getAxisMotionValue(_).get()||0;if(ht.test(T)){const{projection:x}=this.visualElement;if(x&&x.layout){const I=x.layout.layoutBox[_];I&&(T=Ve(I)*(parseFloat(T)/100))}}this.originPoint[_]=T}),y&&ve.postRender(()=>y(d,f)),Mo(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:m,dragDirectionLock:v,onDirectionLock:y,onDrag:w}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:_}=f;if(v&&this.currentDirection===null){this.currentDirection=Nm(_),this.currentDirection!==null&&y&&y(this.currentDirection);return}this.updateAxis("x",f.point,_),this.updateAxis("y",f.point,_),this.visualElement.render(),w&&w(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Je(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)==null?void 0:f.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Ic(e,{onSessionStart:r,onStart:o,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:xc(this.visualElement)})}stop(e,n){const i=e||this.latestPointerEvent,s=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!s||!i)return;const{velocity:o}=s;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&ve.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,i){const{drag:s}=this.getProps();if(!i||!Gi(e,s,this.currentDirection))return;const r=this.getAxisMotionValue(e);let o=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(o=Em(o,this.constraints[e],this.elastic[e])),r.set(o)}resolveConstraints(){var r;const{dragConstraints:e,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(r=this.visualElement.projection)==null?void 0:r.layout,s=this.constraints;e&&fn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Im(i.layoutBox,e):this.constraints=!1,this.elastic=Pm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Je(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Lm(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!fn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const r=Cm(i,s.root,this.visualElement.getTransformPagePoint());let o=Am(s.layout.layoutBox,r);if(n){const a=n(pm(o));this.hasMutatedConstraints=!!a,a&&(o=dc(a))}return o}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:r,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Je(u=>{if(!Gi(u,n,this.currentDirection))return;let d=l&&l[u]||{};o&&(d={min:0,max:0});const f=s?200:1e6,m=s?40:1e7,v={type:"inertia",velocity:i?e[u]:0,bounceStiffness:f,bounceDamping:m,timeConstant:750,restDelta:1,restSpeed:10,...r,...d};return this.startAxisValueAnimation(u,v)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Mo(this.visualElement,e),i.start(No(e,i,0,n,this.visualElement,!1))}stopAnimation(){Je(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Je(e=>{var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.pause()})}getAnimationState(e){var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){Je(n=>{const{drag:i}=this.getProps();if(!Gi(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,r=this.getAxisMotionValue(n);if(s&&s.layout){const{min:o,max:a}=s.layout.layoutBox[n];r.set(e[n]-be(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!fn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Je(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const l=a.get();s[o]=Rm({min:l,max:l},this.constraints[o])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Je(o=>{if(!Gi(o,e,null))return;const a=this.getAxisMotionValue(o),{min:l,max:c}=this.constraints[o];a.set(be(l,c,s[o]))})}addListeners(){if(!this.visualElement.current)return;Dm.set(this.visualElement,this);const e=this.visualElement.current,n=Yn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();fn(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,r=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ve.read(i);const o=Kn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Je(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{o(),n(),r(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:r=!1,dragElastic:o=$o,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:r,dragElastic:o,dragMomentum:a}}}function Gi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Nm(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Om extends Pt{constructor(e){super(e),this.removeGroupControls=Ye,this.removeListeners=Ye,this.controls=new Mm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ye}unmount(){this.removeGroupControls(),this.removeListeners()}}const Nc=t=>(e,n)=>{t&&ve.postRender(()=>t(e,n))};class Fm extends Pt{constructor(){super(...arguments),this.removePointerDownListener=Ye}onPointerDown(e){this.session=new Ic(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Nc(e),onStart:Nc(n),onMove:i,onEnd:(r,o)=>{delete this.session,s&&ve.postRender(()=>s(r,o))}}}mount(){this.removePointerDownListener=Yn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Wi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Oc(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Qn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(W.test(t))t=parseFloat(t);else return t;const n=Oc(t,e.target.x),i=Oc(t,e.target.y);return`${n}% ${i}%`}},Vm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Lt.parse(t);if(s.length>5)return i;const r=Lt.createTransformer(t),o=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+o]/=a,s[1+o]/=l;const c=be(a,l,.5);return typeof s[2+o]=="number"&&(s[2+o]/=c),typeof s[3+o]=="number"&&(s[3+o]/=c),r(s)}};let Fc=!1;class Bm extends it{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:r}=e;Cg(Um),r&&(n.group&&n.group.add(r),i&&i.register&&s&&i.register(r),Fc&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),Wi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:r}=this.props,{projection:o}=i;return o&&(o.isPresent=r,Fc=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==r?o.willUpdate():this.safeToRemove(),e.isPresent!==r&&(r?o.promote():o.relegate()||ve.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),So.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Vc(t){const[e,n]=Ul(),i=Re(Os);return R(Bm,{...t,layoutGroup:i,switchLayoutGroup:Re(Xl),isPresent:e,safeToRemove:n})}const Um={borderRadius:{...Qn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Qn,borderTopRightRadius:Qn,borderBottomLeftRadius:Qn,borderBottomRightRadius:Qn,boxShadow:Vm};function jm(t,e,n){const i=Oe(t)?t:un(t);return i.start(No("",i,e,n)),i.animation}const $m=(t,e)=>t.depth-e.depth;class Hm{constructor(){this.children=[],this.isDirty=!1}add(e){Vs(this.children,e),this.isDirty=!0}remove(e){Bs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort($m),this.isDirty=!1,this.children.forEach(e)}}function Gm(t,e){const n=$e.now(),i=({timestamp:s})=>{const r=s-n;r>=e&&(At(i),t(r-e))};return ve.setup(i,!0),()=>At(i)}const Bc=["TopLeft","TopRight","BottomLeft","BottomRight"],Wm=Bc.length,Uc=t=>typeof t=="string"?parseFloat(t):t,jc=t=>typeof t=="number"||W.test(t);function zm(t,e,n,i,s,r){s?(t.opacity=be(0,n.opacity??1,qm(i)),t.opacityExit=be(e.opacity??1,0,Km(i))):r&&(t.opacity=be(e.opacity??1,n.opacity??1,i));for(let o=0;o<Wm;o++){const a=`border${Bc[o]}Radius`;let l=$c(e,a),c=$c(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||jc(l)===jc(c)?(t[a]=Math.max(be(Uc(l),Uc(c),i),0),(ht.test(c)||ht.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=be(e.rotate||0,n.rotate||0,i))}function $c(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const qm=Hc(0,.5,ja),Km=Hc(.5,.95,Ye);function Hc(t,e,n){return i=>i<t?0:i>e?1:n(On(t,e,i))}function Gc(t,e){t.min=e.min,t.max=e.max}function Ze(t,e){Gc(t.x,e.x),Gc(t.y,e.y)}function Wc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function zc(t,e,n,i,s){return t-=e,t=Hi(t,1/n,i),s!==void 0&&(t=Hi(t,1/s,i)),t}function Xm(t,e=0,n=1,i=.5,s,r=t,o=t){if(ht.test(e)&&(e=parseFloat(e),e=be(o.min,o.max,e/100)-o.min),typeof e!="number")return;let a=be(r.min,r.max,i);t===r&&(a-=e),t.min=zc(t.min,e,n,a,s),t.max=zc(t.max,e,n,a,s)}function qc(t,e,[n,i,s],r,o){Xm(t,e[n],e[i],e[s],e.scale,r,o)}const Ym=["x","scaleX","originX"],Jm=["y","scaleY","originY"];function Kc(t,e,n,i){qc(t.x,e,Ym,n?n.x:void 0,i?i.x:void 0),qc(t.y,e,Jm,n?n.y:void 0,i?i.y:void 0)}function Xc(t){return t.translate===0&&t.scale===1}function Yc(t){return Xc(t.x)&&Xc(t.y)}function Jc(t,e){return t.min===e.min&&t.max===e.max}function Zm(t,e){return Jc(t.x,e.x)&&Jc(t.y,e.y)}function Zc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Qc(t,e){return Zc(t.x,e.x)&&Zc(t.y,e.y)}function ed(t){return Ve(t.x)/Ve(t.y)}function td(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Qm{constructor(){this.members=[]}add(e){Vs(this.members,e),e.scheduleRender()}remove(e){if(Bs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===s);if(n===0)return!1;let i;for(let s=n;s>=0;s--){const r=this.members[s];if(r.isPresent!==!1){i=r;break}}return i?(this.promote(i),!0):!1}promote(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function ev(t,e,n){let i="";const s=t.x.translate/e.x,r=t.y.translate/e.y,o=(n==null?void 0:n.z)||0;if((s||r||o)&&(i=`translate3d(${s}px, ${r}px, ${o}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:m,skewY:v}=n;c&&(i=`perspective(${c}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),f&&(i+=`rotateY(${f}deg) `),m&&(i+=`skewX(${m}deg) `),v&&(i+=`skewY(${v}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Ho=["","X","Y","Z"],tv=1e3;let nv=0;function Go(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function nd(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=oc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:r}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ve,!(s||r))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&nd(i)}function id({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(o={},a=e==null?void 0:e()){this.id=nv++,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(ov),this.nodes.forEach(cv),this.nodes.forEach(dv),this.nodes.forEach(rv)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,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 Hm)}addEventListener(o,a){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new $s),this.eventHandlers.get(o).add(a)}notifyListeners(o,...a){const l=this.eventHandlers.get(o);l&&l.notify(...a)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=Bl(o)&&!eg(o),this.instance=o;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(o),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 f=()=>this.root.updateBlockedByResize=!1;ve.read(()=>{d=window.innerWidth}),t(o,()=>{const m=window.innerWidth;m!==d&&(d=m,this.root.updateBlockedByResize=!0,u&&u(),u=Gm(f,250),Wi.hasAnimatedSinceResize&&(Wi.hasAnimatedSinceResize=!1,this.nodes.forEach(rd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:m})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||gv,{onLayoutAnimationStart:y,onLayoutAnimationComplete:w}=c.getProps(),_=!this.targetLayout||!Qc(this.targetLayout,m),T=!d&&f;if(this.options.layoutRoot||this.resumeFrom||T||d&&(_||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const x={...yo(v,"layout"),onPlay:y,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(x.delay=0,x.type=!1),this.startAnimation(x),this.setAnimationOrigin(u,T)}else d||rd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=m})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),At(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(uv),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&nd(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(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(sd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(od);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(lv),this.nodes.forEach(iv),this.nodes.forEach(sv)):this.nodes.forEach(od),this.clearAllSnapshots();const a=$e.now();Pe.delta=wt(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,Ws.update.process(Pe),Ws.preRender.process(Pe),Ws.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,So.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(av),this.sharedNodes.forEach(hv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ve.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ve.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ve(this.snapshot.measuredBox.x)&&!Ve(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 o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Ce(),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,o?o.layoutBox:void 0)}updateScroll(o="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Yc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;o&&this.instance&&(a||Kt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return o&&(l=this.removeTransform(l)),mv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:o}=this.options;if(!o)return Ce();const a=o.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(vv))){const{scroll:u}=this.root;u&&(gn(a.x,u.offset.x),gn(a.y,u.offset.y))}return a}removeElementScroll(o){var l;const a=Ce();if(Ze(a,o),(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:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Ze(a,o),gn(a.x,d.offset.x),gn(a.y,d.offset.y))}return a}applyTransform(o,a=!1){const l=Ce();Ze(l,o);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&mn(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Kt(u.latestValues)&&mn(l,u.latestValues)}return Kt(this.latestValues)&&mn(l,this.latestValues),l}removeTransform(o){const a=Ce();Ze(a,o);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Kt(c.latestValues))continue;Vo(c.latestValues)&&c.updateSnapshot();const u=Ce(),d=c.measurePageBox();Ze(u,d),Kc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Kt(this.latestValues)&&Kc(a,this.latestValues),a}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.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(o=!1){var f;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(!(o||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.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 m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ce(),this.relativeTargetOrigin=Ce(),Zn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Ce(),this.targetWithTransforms=Ce()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),wm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ze(this.target,this.layout.layoutBox),wc(this.target,this.targetDelta)):Ze(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ce(),this.relativeTargetOrigin=Ce(),Zn(this.relativeTargetOrigin,this.target,m.target),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Vo(this.parent.latestValues)||_c(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 o=this.getLead(),a=!!this.resumingFrom||this!==o;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;Ze(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;Sm(this.layoutCorrected,this.treeScale,this.path,a),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=Ce());const{target:m}=o;if(!m){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Wc(this.prevProjectionDelta.x,this.projectionDelta.x),Wc(this.prevProjectionDelta.y,this.projectionDelta.y)),Jn(this.projectionDelta,this.layoutCorrected,m,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!td(this.projectionDelta.x,this.prevProjectionDelta.x)||!td(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",m))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),o){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=pn(),this.projectionDelta=pn(),this.projectionDeltaWithTransform=pn()}setAnimationOrigin(o,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=pn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=Ce(),m=l?l.source:void 0,v=this.layout?this.layout.source:void 0,y=m!==v,w=this.getStack(),_=!w||w.members.length<=1,T=!!(y&&!_&&this.options.crossfade===!0&&!this.path.some(pv));this.animationProgress=0;let x;this.mixTargetDelta=I=>{const A=I/1e3;ad(d.x,o.x,A),ad(d.y,o.y,A),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Zn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),fv(this.relativeTarget,this.relativeTargetOrigin,f,A),x&&Zm(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=Ce()),Ze(x,this.relativeTarget)),y&&(this.animationValues=u,zm(u,c,this.latestValues,A,T,_)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){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&&(At(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ve.update(()=>{Wi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=un(0)),this.currentAnimation=jm(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),o.onUpdate&&o.onUpdate(u)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.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 o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(tv),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=o;if(!(!a||!l||!c)){if(this!==o&&this.layout&&c&&hd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||Ce();const d=Ve(this.layout.layoutBox.x);l.x.min=o.target.x.min,l.x.max=l.x.min+d;const f=Ve(this.layout.layoutBox.y);l.y.min=o.target.y.min,l.y.max=l.y.min+f}Ze(a,l),mn(a,u),Jn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new Qm),this.sharedNodes.get(o).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 o=this.getStack();return o?o.lead===this:!0}getLead(){var a;const{layoutId:o}=this.options;return o?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:o}=this.options;return o?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:l}=o;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Go("z",o,c,this.animationValues);for(let u=0;u<Ho.length;u++)Go(`rotate${Ho[u]}`,o,c,this.animationValues),Go(`skew${Ho[u]}`,o,c,this.animationValues);o.render();for(const u in c)o.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);o.scheduleRender()}applyProjectionStyles(o,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||"",o.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Kt(this.latestValues)&&(o.transform=l?l({},""):"none",this.hasProjected=!1);return}o.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=ev(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),o.transform=d;const{x:f,y:m}=this.projectionDelta;o.transformOrigin=`${f.origin*100}% ${m.origin*100}% 0`,c.animationValues?o.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:o.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const v in zn){if(u[v]===void 0)continue;const{correct:y,applyTo:w,isCSSVariable:_}=zn[v],T=d==="none"?u[v]:y(u[v],c);if(w){const x=w.length;for(let I=0;I<x;I++)o[w[I]]=T}else _?this.options.visualElement.renderState.vars[v]=T:o[v]=T}this.options.layoutId&&(o.pointerEvents=c===this?$i(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var a;return(a=o.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(sd),this.root.sharedNodes.clear()}}}function iv(t){t.updateLayout()}function sv(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:r}=t.options,o=e.source!==t.layout.source;r==="size"?Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],m=Ve(f);f.min=i[d].min,f.max=f.min+m}):hd(r,e.layoutBox,i)&&Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],m=Ve(i[d]);f.max=f.min+m,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+m)});const a=pn();Jn(a,i,e.layoutBox);const l=pn();o?Jn(l,t.applyTransform(s,!0),e.measuredBox):Jn(l,i,e.layoutBox);const c=!Yc(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:m}=d;if(f&&m){const v=Ce();Zn(v,e.layoutBox,f.layoutBox);const y=Ce();Zn(y,i,m.layoutBox),Qc(v,y)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=y,t.relativeTargetOrigin=v,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function ov(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 rv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function av(t){t.clearSnapshot()}function sd(t){t.clearMeasurements()}function od(t){t.isLayoutDirty=!1}function lv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function rd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function cv(t){t.resolveTargetDelta()}function dv(t){t.calcProjection()}function uv(t){t.resetSkewAndRotation()}function hv(t){t.removeLeadSnapshot()}function ad(t,e,n){t.translate=be(e.translate,0,n),t.scale=be(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function ld(t,e,n,i){t.min=be(e.min,n.min,i),t.max=be(e.max,n.max,i)}function fv(t,e,n,i){ld(t.x,e.x,n.x,i),ld(t.y,e.y,n.y,i)}function pv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const gv={duration:.45,ease:[.4,0,.1,1]},cd=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),dd=cd("applewebkit/")&&!cd("chrome/")?Math.round:Ye;function ud(t){t.min=dd(t.min),t.max=dd(t.max)}function mv(t){ud(t.x),ud(t.y)}function hd(t,e,n){return t==="position"||t==="preserve-aspect"&&!bm(ed(e),ed(n),.2)}function vv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const _v=id({attachResizeListener:(t,e)=>Kn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Wo={current:void 0},fd=id({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Wo.current){const t=new _v({});t.mount(window),t.setOptions({layoutScroll:!0}),Wo.current=t}return Wo.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),yv={pan:{Feature:Fm},drag:{Feature:Om,ProjectionNode:fd,MeasureLayout:Vc}};function pd(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,r=i[s];r&&ve.postRender(()=>r(e,Xn(e)))}class bv extends Pt{mount(){const{current:e}=this.node;e&&(this.unmount=Xp(e,(n,i)=>(pd(this.node,i,"Start"),s=>pd(this.node,s,"End"))))}unmount(){}}class wv extends Pt{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=Nn(Kn(this.node.current,"focus",()=>this.onFocus()),Kn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function gd(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),r=i[s];r&&ve.postRender(()=>r(e,Xn(e)))}class Sv extends Pt{mount(){const{current:e}=this.node;e&&(this.unmount=Qp(e,(n,i)=>(gd(this.node,i,"Start"),(s,{success:r})=>gd(this.node,s,r?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const zo=new WeakMap,qo=new WeakMap,Cv=t=>{const e=zo.get(t.target);e&&e(t)},Tv=t=>{t.forEach(Cv)};function kv({root:t,...e}){const n=t||document;qo.has(n)||qo.set(n,{});const i=qo.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Tv,{root:t,...e})),i[s]}function xv(t,e,n){const i=kv(e);return zo.set(t,n),i.observe(t),()=>{zo.delete(t),i.unobserve(t)}}const Ev={some:0,all:1};class Iv extends Pt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:r}=e,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Ev[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,r&&!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(),f=c?u:d;f&&f(l)};return xv(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(Av(e,n))&&this.startObserver()}unmount(){}}function Av({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Rv={inView:{Feature:Iv},tap:{Feature:Sv},focus:{Feature:wv},hover:{Feature:bv}},Lv={layout:{ProjectionNode:fd,MeasureLayout:Vc}},Ko={current:null},md={current:!1};function Pv(){if(md.current=!0,!!Fs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Ko.current=t.matches;t.addEventListener("change",e),e()}else Ko.current=!1}const Dv=new WeakMap;function Mv(t,e,n){for(const i in e){const s=e[i],r=n[i];if(Oe(s))t.addValue(i,s);else if(Oe(r))t.addValue(i,un(s,{owner:t}));else if(r!==s)if(t.hasValue(i)){const o=t.getValue(i);o.liveStyle===!0?o.jump(s):o.hasAnimated||o.set(s)}else{const o=t.getStaticValue(i);t.addValue(i,un(o!==void 0?o:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const vd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Nv{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:r,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=vo,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 f=$e.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ve.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=o;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!r,this.isControllingVariants=ji(n),this.isVariantNode=zl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const m=d[f];l[f]!==void 0&&Oe(m)&&m.set(l[f],!1)}}mount(e){this.current=e,Dv.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),md.current||Pv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ko.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),At(this.notifyUpdate),At(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=dn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ve.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),r=n.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in hn){const n=hn[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const r=this.features[e];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Ce()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<vd.length;i++){const s=vd[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const r="on"+s,o=e[r];o&&(this.propEventSubscriptions[s]=this.on(s,o))}this.prevMotionValues=Mv(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=un(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(La(i)||Da(i))?i=parseFloat(i):!ng(i)&&Lt.test(n)&&(i=Rl(e,n)),this.setBaseTarget(e,Oe(i)?i.get():i)),Oe(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var r;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const o=Lo(this.props,n,(r=this.presenceContext)==null?void 0:r.custom);o&&(i=o[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Oe(s)?s:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new $s),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class _d extends Nv{constructor(){super(...arguments),this.KeyframeResolver=Gp}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Oe(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function yd(t,{style:e,vars:n},i,s){const r=t.style;let o;for(o in e)r[o]=e[o];s==null||s.applyProjectionStyles(r,i);for(o in n)r.setProperty(o,n[o])}function Ov(t){return window.getComputedStyle(t)}class Fv extends _d{constructor(){super(...arguments),this.type="html",this.renderInstance=yd}readValueFromInstance(e,n){var i;if(dn.has(n))return(i=this.projection)!=null&&i.isProjecting?ho(n):dp(e,n);{const s=Ov(e),r=(zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return kc(e,n)}build(e,n,i){Io(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return Po(e,n,i)}}const bd=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 Vv(t,e,n,i){yd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(bd.has(s)?s:Eo(s),e.attrs[s])}class Bv extends _d{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ce}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(dn.has(n)){const i=Al(n);return i&&i.default||0}return n=bd.has(n)?n:Eo(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return sc(e,n,i)}build(e,n,i){Ql(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){Vv(e,n,i,s)}mount(e){this.isSVGTag=tc(e.tagName),super.mount(e)}}const Uv=(t,e)=>Ro(t)?new Bv(e):new Fv(e,{allowProjection:t!==lt}),jv=Ug({...hm,...Rv,...yv,...Lv},Uv),vn=hg(jv),$v=["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"],ei="widget-layout-id";function wd(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=wd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function Ct(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=wd(t))&&(i&&(i+=" "),i+=e);return i}const Hv=ki("listening"),Xo=()=>Aa(Hv);function Gv(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const zi={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},Sd=ki(zi),Wv=()=>{const t=Ei(Sd);return We(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=zi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=zi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=zi.speak_to_interrupt_text),n}),[t])},Xt=()=>Ns(Sd),Cd=({size:t="large",className:e})=>{const n=Xt(),[i]=Xo();return R("h1",{className:Ct({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},Td=({stream:t,chatMode:e})=>{const n=de(null);return Ae(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:R("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
9
+ `),()=>{_.removeChild(v),_.contains(v)&&_.removeChild(v)}},[e]),R(sg,{isPresent:e,childRef:r,sizeRef:o,children:of(t,{ref:r})})}const rg=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:r,mode:o,anchorX:a,root:l})=>{const c=Ii(ag),u=Ts();let d=!0,f=Xe(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:m=>{c.set(m,!0);for(const v of c.values())if(!v)return;i&&i()},register:m=>(c.set(m,!1),()=>c.delete(m))}),[n,c,i]);return r&&d&&(f={...f}),Xe(()=>{c.forEach((m,v)=>c.set(v,!1))},[n]),Ae(()=>{!n&&!c.size&&i&&i()},[n]),o==="popLayout"&&(t=R(og,{isPresent:n,anchorX:a,root:l,children:t})),R(Ai.Provider,{value:f,children:t})};function ag(){return new Map}function Ul(t=!0){const e=Re(Ai);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,r=Ts();Ae(()=>{if(t)return s(r)},[t]);const o=We(()=>t&&i&&i(r),[r,i,t]);return!n&&i?[!1,o]:[!0]}const Fi=t=>t.key||"";function jl(t){const e=[];return qh.forEach(t,n=>{ka(n)&&e.push(n)}),e}const lg=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:r="sync",propagate:o=!1,anchorX:a="left",root:l})=>{const[c,u]=Ul(o),d=Xe(()=>jl(t),[t]),f=o&&!c?[]:d.map(Fi),m=de(!0),v=de(d),_=Ii(()=>new Map),[w,y]=Ee(d),[T,x]=Ee(d);Ra(()=>{m.current=!1,v.current=d;for(let M=0;M<T.length;M++){const S=Fi(T[M]);f.includes(S)?_.delete(S):_.get(S)!==!0&&_.set(S,!1)}},[T,f.length,f.join("-")]);const I=[];if(d!==w){let M=[...d];for(let S=0;S<T.length;S++){const C=T[S],p=Fi(C);f.includes(p)||(M.splice(S,0,C),I.push(C))}return r==="wait"&&I.length&&(M=I),x(jl(M)),y(d),null}const{forceRender:A}=Re(Os);return R(lt,{children:T.map(M=>{const S=Fi(M),C=o&&!c?!1:d===T||f.includes(S),p=()=>{if(_.has(S))_.set(S,!0);else return;let g=!0;_.forEach(h=>{h||(g=!1)}),g&&(A==null||A(),x(v.current),o&&(u==null||u()),i&&i())};return R(rg,{isPresent:C,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:r,root:l,onExitComplete:C?void 0:p,anchorX:a,children:M},S)})})},$l=bt({strict:!1}),Hl={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"]},hn={};for(const t in Hl)hn[t]={isEnabled:e=>Hl[t].some(n=>!!e[n])};function cg(t){for(const e in t)hn[e]={...hn[e],...t[e]}}const dg=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 Vi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||dg.has(t)}let Gl=t=>!Vi(t);function Wl(t){typeof t=="function"&&(Gl=e=>e.startsWith("on")?!Vi(e):t(e))}try{Wl(require("@emotion/is-prop-valid").default)}catch{}function ug(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Gl(s)||n===!0&&Vi(s)||!e&&!Vi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function hg({children:t,isValidProp:e,...n}){e&&Wl(e),n={...Re(Gn),...n},n.isStatic=Ii(()=>n.isStatic);const i=Xe(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return R(Gn.Provider,{value:i,children:t})}function fg(t){if(typeof Proxy>"u")return t;const e=new Map,n=(...i)=>t(...i);return new Proxy(n,{get:(i,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const Bi=bt({});function Ui(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Wn(t){return typeof t=="string"||Array.isArray(t)}const ko=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],xo=["initial",...ko];function ji(t){return Ui(t.animate)||xo.some(e=>Wn(t[e]))}function zl(t){return!!(ji(t)||t.variants)}function pg(t,e){if(ji(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Wn(n)?n:void 0,animate:Wn(i)?i:void 0}}return t.inherit!==!1?e:{}}function gg(t){const{initial:e,animate:n}=pg(t,Re(Bi));return Xe(()=>({initial:e,animate:n}),[ql(e),ql(n)])}function ql(t){return Array.isArray(t)?t.join(" "):t}const mg=Symbol.for("motionComponentSymbol");function fn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function vg(t,e,n){return We(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):fn(n)&&(n.current=i))},[e])}const Eo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Kl="data-"+Eo("framerAppearId"),Xl=bt({});function yg(t,e,n,i,s){var _,w;const{visualElement:r}=Re(Bi),o=Re($l),a=Re(Ai),l=Re(Gn).reducedMotion,c=de(null);i=i||o.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:r,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Re(Xl);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&_g(c.current,n,s,d);const f=de(!1);ua(()=>{u&&f.current&&u.update(n,a)});const m=n[Kl],v=de(!!m&&!((_=window.MotionHandoffIsComplete)!=null&&_.call(window,m))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,m)));return Ra(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),So.render(u.render),v.current&&u.animationState&&u.animationState.animateChanges())}),Ae(()=>{u&&(!v.current&&u.animationState&&u.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,m)}),v.current=!1))}),u}function _g(t,e,n,i){const{layoutId:s,layout:r,drag:o,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Yl(t.parent)),t.projection.setOptions({layoutId:s,layout:r,alwaysMeasureLayout:!!o||a&&fn(a),visualElement:t,animationType:typeof r=="string"?r:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:c})}function Yl(t){if(t)return t.options.allowProjection!==!1?t.projection:Yl(t.parent)}function bg({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&cg(t);function r(a,l){let c;const u={...Re(Gn),...a,layoutId:wg(a)},{isStatic:d}=u,f=gg(a),m=i(a,d);if(!d&&Fs){Sg();const v=Cg(u);c=v.MeasureLayout,f.visualElement=yg(s,m,u,e,v.ProjectionNode)}return R(Bi.Provider,{value:f,children:[c&&f.visualElement?R(c,{visualElement:f.visualElement,...u}):null,n(s,a,vg(m,f.visualElement,l),m,d,f.visualElement)]})}r.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const o=zh(r);return o[mg]=s,o}function wg({layoutId:t}){const e=Re(Os).id;return e&&t!==void 0?e+"-"+t:t}function Sg(t,e){Re($l).strict}function Cg(t){const{drag:e,layout:n}=hn;if(!e&&!n)return{};const i={...e,...n};return{MeasureLayout:e!=null&&e.isEnabled(t)||n!=null&&n.isEnabled(t)?i.MeasureLayout:void 0,ProjectionNode:i.ProjectionNode}}const zn={};function Tg(t){for(const e in t)zn[e]=t[e],zs(e)&&(zn[e].isCSSVariable=!0)}function Jl(t,{layout:e,layoutId:n}){return dn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!zn[t]||t==="opacity")}const kg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},xg=cn.length;function Eg(t,e,n){let i="",s=!0;for(let r=0;r<xg;r++){const o=cn[r],a=t[o];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(o.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Ll(a,wo[o]);if(!l){s=!1;const u=kg[o]||o;i+=`${u}(${c}) `}n&&(e[o]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function Io(t,e,n){const{style:i,vars:s,transformOrigin:r}=t;let o=!1,a=!1;for(const l in e){const c=e[l];if(dn.has(l)){o=!0;continue}else if(zs(l)){s[l]=c;continue}else{const u=Ll(c,wo[l]);l.startsWith("origin")?(a=!0,r[l]=u):i[l]=u}}if(e.transform||(o||n?i.transform=Eg(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=r;i.transformOrigin=`${l} ${c} ${u}`}}const Ao=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Zl(t,e,n){for(const i in e)!Oe(e[i])&&!Jl(i,n)&&(t[i]=e[i])}function Ig({transformTemplate:t},e){return Xe(()=>{const n=Ao();return Io(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Ag(t,e){const n=t.style||{},i={};return Zl(i,n,t),Object.assign(i,Ig(t,e)),i}function Rg(t,e){const n={},i=Ag(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const Lg={offset:"stroke-dashoffset",array:"stroke-dasharray"},Pg={offset:"strokeDashoffset",array:"strokeDasharray"};function Dg(t,e,n=1,i=0,s=!0){t.pathLength=1;const r=s?Lg:Pg;t[r.offset]=W.transform(-i);const o=W.transform(e),a=W.transform(n);t[r.array]=`${o} ${a}`}function Ql(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:r=1,pathOffset:o=0,...a},l,c,u){if(Io(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:f}=t;d.transform&&(f.transform=d.transform,delete d.transform),(f.transform||d.transformOrigin)&&(f.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),f.transform&&(f.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),n!==void 0&&(d.y=n),i!==void 0&&(d.scale=i),s!==void 0&&Dg(d,s,r,o,!1)}const ec=()=>({...Ao(),attrs:{}}),tc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Mg(t,e,n,i){const s=Xe(()=>{const r=ec();return Ql(r,e,tc(i),t.transformTemplate,t.style),{...r.attrs,style:{...r.style}}},[e]);if(t.style){const r={};Zl(r,t.style,t),s.style={...r,...s.style}}return s}const Ng=["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 Ro(t){return typeof t!="string"||t.includes("-")?!1:!!(Ng.indexOf(t)>-1||/[A-Z]/u.test(t))}function Og(t=!1){return(n,i,s,{latestValues:r},o)=>{const l=(Ro(n)?Mg:Rg)(i,r,o,n),c=ug(i,typeof n=="string",t),u=n!==lt?{...c,...l,ref:s}:{},{children:d}=i,f=Xe(()=>Oe(d)?d.get():d,[d]);return Ke(n,{...u,children:f})}}function nc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Lo(t,e,n,i){if(typeof e=="function"){const[s,r]=nc(i);e=e(n!==void 0?n:t.custom,s,r)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,r]=nc(i);e=e(n!==void 0?n:t.custom,s,r)}return e}function $i(t){return Oe(t)?t.get():t}function Fg({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Vg(n,i,s,t),renderState:e()}}const ic=t=>(e,n)=>{const i=Re(Bi),s=Re(Ai),r=()=>Fg(t,e,i,s);return n?r():Ii(r)};function Vg(t,e,n,i){const s={},r=i(t,{});for(const f in r)s[f]=$i(r[f]);let{initial:o,animate:a}=t;const l=ji(t),c=zl(t);e&&c&&!l&&t.inherit!==!1&&(o===void 0&&(o=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||o===!1;const d=u?a:o;if(d&&typeof d!="boolean"&&!Ui(d)){const f=Array.isArray(d)?d:[d];for(let m=0;m<f.length;m++){const v=Lo(t,f[m]);if(v){const{transitionEnd:_,transition:w,...y}=v;for(const T in y){let x=y[T];if(Array.isArray(x)){const I=u?x.length-1:0;x=x[I]}x!==null&&(s[T]=x)}for(const T in _)s[T]=_[T]}}}return s}function Po(t,e,n){var r;const{style:i}=t,s={};for(const o in i)(Oe(i[o])||e.style&&Oe(e.style[o])||Jl(o,t)||((r=n==null?void 0:n.getValue(o))==null?void 0:r.liveStyle)!==void 0)&&(s[o]=i[o]);return s}const Bg={useVisualState:ic({scrapeMotionValuesFromProps:Po,createRenderState:Ao})};function sc(t,e,n){const i=Po(t,e,n);for(const s in t)if(Oe(t[s])||Oe(e[s])){const r=cn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[r]=t[s]}return i}const Ug={useVisualState:ic({scrapeMotionValuesFromProps:sc,createRenderState:ec})};function jg(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const o={...Ro(i)?Ug:Bg,preloadedFeatures:t,useRender:Og(s),createVisualElement:e,Component:i};return bg(o)}}function qn(t,e,n){const i=t.getProps();return Lo(i,e,n!==void 0?n:i.custom,t)}const Do=t=>Array.isArray(t);function $g(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,un(n))}function Hg(t){return Do(t)?t[t.length-1]||0:t}function Gg(t,e){const n=qn(t,e);let{transitionEnd:i={},transition:s={},...r}=n||{};r={...r,...i};for(const o in r){const a=Hg(r[o]);$g(t,o,a)}}function Wg(t){return!!(Oe(t)&&t.add)}function Mo(t,e){const n=t.getValue("willChange");if(Wg(n))return n.add(e);if(!n&&St.WillChange){const i=new St.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function oc(t){return t.props[Kl]}const zg=t=>t!==null;function qg(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(zg),r=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[r]}const Kg={type:"spring",stiffness:500,damping:25,restSpeed:10},Xg=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Yg={type:"keyframes",duration:.8},Jg={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Zg=(t,{keyframes:e})=>e.length>2?Yg:dn.has(t)?t.startsWith("scale")?Xg(e[1]):Kg:Jg;function Qg({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:r,repeatType:o,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const No=(t,e,n,i={},s,r)=>o=>{const a=_o(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-dt(l);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:r?void 0:s};Qg(a)||Object.assign(u,Zg(t,u)),u.duration&&(u.duration=dt(u.duration)),u.repeatDelay&&(u.repeatDelay=dt(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)),(St.instantAnimations||St.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!r&&e.get()!==void 0){const f=qg(u.keyframes,a);if(f!==void 0){ve.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new lo(u):new Mp(u)};function em({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function rc(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:r=t.getDefaultTransition(),transitionEnd:o,...a}=e;i&&(r=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),f=a[u];if(f===void 0||c&&em(c,u))continue;const m={delay:n,..._o(r||{},u)},v=d.get();if(v!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===v&&!m.velocity)continue;let _=!1;if(window.MotionHandoffAnimation){const y=oc(t);if(y){const T=window.MotionHandoffAnimation(y,u,ve);T!==null&&(m.startTime=T,_=!0)}}Mo(t,u),d.start(No(u,d,f,t.shouldReduceMotion&&Tl.has(u)?{type:!1}:m,t,_));const w=d.animation;w&&l.push(w)}return o&&Promise.all(l).then(()=>{ve.update(()=>{o&&Gg(t,o)})}),l}function Oo(t,e,n={}){var l;const i=qn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const r=i?()=>Promise.all(rc(t,i,n)):()=>Promise.resolve(),o=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=s;return tm(t,e,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[r,o]:[o,r];return c().then(()=>u())}else return Promise.all([r(),o(n.delay)])}function tm(t,e,n=0,i=0,s=0,r=1,o){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof i=="function",d=u?f=>i(f,l):r===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(nm).forEach((f,m)=>{f.notify("AnimationStart",e),a.push(Oo(f,e,{...o,delay:n+(u?0:i)+d(m)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function nm(t,e){return t.sortNodePosition(e)}function im(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(r=>Oo(t,r,n));i=Promise.all(s)}else if(typeof e=="string")i=Oo(t,e,n);else{const s=typeof e=="function"?qn(t,e,n.custom):e;i=Promise.all(rc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function ac(t,e){if(!Array.isArray(e))return!1;const n=e.length;if(n!==t.length)return!1;for(let i=0;i<n;i++)if(e[i]!==t[i])return!1;return!0}const sm=xo.length;function lc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?lc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<sm;n++){const i=xo[n],s=t.props[i];(Wn(s)||s===!1)&&(e[i]=s)}return e}const om=[...ko].reverse(),rm=ko.length;function am(t){return e=>Promise.all(e.map(({animation:n,options:i})=>im(t,n,i)))}function lm(t){let e=am(t),n=cc(),i=!0;const s=l=>(c,u)=>{var f;const d=qn(t,u,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:m,transitionEnd:v,..._}=d;c={...c,..._,...v}}return c};function r(l){e=l(t)}function o(l){const{props:c}=t,u=lc(t.parent)||{},d=[],f=new Set;let m={},v=1/0;for(let w=0;w<rm;w++){const y=om[w],T=n[y],x=c[y]!==void 0?c[y]:u[y],I=Wn(x),A=y===l?T.isActive:null;A===!1&&(v=w);let M=x===u[y]&&x!==c[y]&&I;if(M&&i&&t.manuallyAnimateOnMount&&(M=!1),T.protectedKeys={...m},!T.isActive&&A===null||!x&&!T.prevProp||Ui(x)||typeof x=="boolean")continue;const S=cm(T.prevProp,x);let C=S||y===l&&T.isActive&&!M&&I||w>v&&I,p=!1;const g=Array.isArray(x)?x:[x];let h=g.reduce(s(y),{});A===!1&&(h={});const{prevResolvedValues:b={}}=T,E={...b,...h},P=D=>{C=!0,f.has(D)&&(p=!0,f.delete(D)),T.needsAnimating[D]=!0;const F=t.getValue(D);F&&(F.liveStyle=!1)};for(const D in E){const F=h[D],z=b[D];if(m.hasOwnProperty(D))continue;let j=!1;Do(F)&&Do(z)?j=!ac(F,z):j=F!==z,j?F!=null?P(D):f.add(D):F!==void 0&&f.has(D)?P(D):T.protectedKeys[D]=!0}T.prevProp=x,T.prevResolvedValues=h,T.isActive&&(m={...m,...h}),i&&t.blockInitialAnimation&&(C=!1),C&&(!(M&&S)||p)&&d.push(...g.map(D=>({animation:D,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=qn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const T=t.getBaseTarget(y),x=t.getValue(y);x&&(x.liveStyle=!0),w[y]=T??null}),d.push({animation:w})}let _=!!d.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(_=!1),i=!1,_?e(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(f=>{var m;return(m=f.animationState)==null?void 0:m.setActive(l,c)}),n[l].isActive=c;const u=o(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:r,getState:()=>n,reset:()=>{n=cc(),i=!0}}}function cm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!ac(e,t):!1}function qt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function cc(){return{animate:qt(!0),whileInView:qt(),whileHover:qt(),whileTap:qt(),whileDrag:qt(),whileFocus:qt(),exit:qt()}}class Mt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class dm extends Mt{constructor(e){super(e),e.animationState||(e.animationState=lm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Ui(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:n}=this.node.prevProps||{};e!==n&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let um=0;class hm extends Mt{constructor(){super(...arguments),this.id=um++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:n}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;const s=this.node.animationState.setActive("exit",!e);n&&!e&&s.then(()=>{n(this.id)})}mount(){const{register:e,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const fm={animation:{Feature:dm},exit:{Feature:hm}};function Kn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Xn(t){return{point:{x:t.pageX,y:t.pageY}}}const pm=t=>e=>Co(e)&&t(e,Xn(e));function Yn(t,e,n,i){return Kn(t,e,pm(n),i)}function dc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function gm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function mm(t,e){if(!e)return t;const n=e({x:t.left,y:t.top}),i=e({x:t.right,y:t.bottom});return{top:n.y,left:n.x,bottom:i.y,right:i.x}}const uc=1e-4,vm=1-uc,ym=1+uc,hc=.01,_m=0-hc,bm=0+hc;function Ve(t){return t.max-t.min}function wm(t,e,n){return Math.abs(t-e)<=n}function fc(t,e,n,i=.5){t.origin=i,t.originPoint=be(e.min,e.max,t.origin),t.scale=Ve(n)/Ve(e),t.translate=be(n.min,n.max,t.origin)-t.originPoint,(t.scale>=vm&&t.scale<=ym||isNaN(t.scale))&&(t.scale=1),(t.translate>=_m&&t.translate<=bm||isNaN(t.translate))&&(t.translate=0)}function Jn(t,e,n,i){fc(t.x,e.x,n.x,i?i.originX:void 0),fc(t.y,e.y,n.y,i?i.originY:void 0)}function pc(t,e,n){t.min=n.min+e.min,t.max=t.min+Ve(e)}function Sm(t,e,n){pc(t.x,e.x,n.x),pc(t.y,e.y,n.y)}function gc(t,e,n){t.min=e.min-n.min,t.max=t.min+Ve(e)}function Zn(t,e,n){gc(t.x,e.x,n.x),gc(t.y,e.y,n.y)}const mc=()=>({translate:0,scale:1,origin:0,originPoint:0}),pn=()=>({x:mc(),y:mc()}),vc=()=>({min:0,max:0}),Ce=()=>({x:vc(),y:vc()});function Je(t){return[t("x"),t("y")]}function Fo(t){return t===void 0||t===1}function Vo({scale:t,scaleX:e,scaleY:n}){return!Fo(t)||!Fo(e)||!Fo(n)}function Kt(t){return Vo(t)||yc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function yc(t){return _c(t.x)||_c(t.y)}function _c(t){return t&&t!=="0%"}function Hi(t,e,n){const i=t-n,s=e*i;return n+s}function bc(t,e,n,i,s){return s!==void 0&&(t=Hi(t,s,i)),Hi(t,n,i)+e}function Bo(t,e=0,n=1,i,s){t.min=bc(t.min,e,n,i,s),t.max=bc(t.max,e,n,i,s)}function wc(t,{x:e,y:n}){Bo(t.x,e.translate,e.scale,e.originPoint),Bo(t.y,n.translate,n.scale,n.originPoint)}const Sc=.999999999999,Cc=1.0000000000001;function Cm(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let r,o;for(let a=0;a<s;a++){r=n[a],o=r.projectionDelta;const{visualElement:l}=r.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&r.options.layoutScroll&&r.scroll&&r!==r.root&&mn(t,{x:-r.scroll.offset.x,y:-r.scroll.offset.y}),o&&(e.x*=o.x.scale,e.y*=o.y.scale,wc(t,o)),i&&Kt(r.latestValues)&&mn(t,r.latestValues))}e.x<Cc&&e.x>Sc&&(e.x=1),e.y<Cc&&e.y>Sc&&(e.y=1)}function gn(t,e){t.min=t.min+e,t.max=t.max+e}function Tc(t,e,n,i,s=.5){const r=be(t.min,t.max,s);Bo(t,e,n,r,i)}function mn(t,e){Tc(t.x,e.x,e.scaleX,e.scale,e.originX),Tc(t.y,e.y,e.scaleY,e.scale,e.originY)}function kc(t,e){return dc(mm(t.getBoundingClientRect(),e))}function Tm(t,e,n){const i=kc(t,n),{scroll:s}=e;return s&&(gn(i.x,s.offset.x),gn(i.y,s.offset.y)),i}const xc=({current:t})=>t?t.ownerDocument.defaultView:null,Ec=(t,e)=>Math.abs(t-e);function km(t,e){const n=Ec(t.x,e.x),i=Ec(t.y,e.y);return Math.sqrt(n**2+i**2)}class Ic{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:r=!1,distanceThreshold:o=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 f=jo(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,v=km(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!v)return;const{point:_}=f,{timestamp:w}=Pe;this.history.push({..._,timestamp:w});const{onStart:y,onMove:T}=this.handlers;m||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Uo(m,this.transformPagePoint),ve.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:v,onSessionEnd:_,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=jo(f.type==="pointercancel"?this.lastMoveEventInfo:Uo(m,this.transformPagePoint),this.history);this.startEvent&&v&&v(f,y),_&&_(f,y)},!Co(e))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=o,this.contextWindow=s||window;const a=Xn(e),l=Uo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,jo(l,this.history)),this.removeListeners=Nn(Yn(this.contextWindow,"pointermove",this.handlePointerMove),Yn(this.contextWindow,"pointerup",this.handlePointerUp),Yn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Lt(this.updatePoint)}}function Uo(t,e){return e?{point:e(t.point)}:t}function Ac(t,e){return{x:t.x-e.x,y:t.y-e.y}}function jo({point:t},e){return{point:t,delta:Ac(t,Rc(e)),offset:Ac(t,xm(e)),velocity:Em(e,.1)}}function xm(t){return t[0]}function Rc(t){return t[t.length-1]}function Em(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=Rc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>dt(e)));)n--;if(!i)return{x:0,y:0};const r=ut(s.timestamp-i.timestamp);if(r===0)return{x:0,y:0};const o={x:(s.x-i.x)/r,y:(s.y-i.y)/r};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Im(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?be(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?be(n,t,i.max):Math.min(t,n)),t}function Lc(t,e,n){return{min:e!==void 0?t.min+e:void 0,max:n!==void 0?t.max+n-(t.max-t.min):void 0}}function Am(t,{top:e,left:n,bottom:i,right:s}){return{x:Lc(t.x,n,s),y:Lc(t.y,e,i)}}function Pc(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function Rm(t,e){return{x:Pc(t.x,e.x),y:Pc(t.y,e.y)}}function Lm(t,e){let n=.5;const i=Ve(t),s=Ve(e);return s>i?n=On(e.min,e.max-i,t.min):i>s&&(n=On(t.min,t.max-s,e.min)),wt(0,1,n)}function Pm(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const $o=.35;function Dm(t=$o){return t===!1?t=0:t===!0&&(t=$o),{x:Dc(t,"left","right"),y:Dc(t,"top","bottom")}}function Dc(t,e,n){return{min:Mc(t,e),max:Mc(t,n)}}function Mc(t,e){return typeof t=="number"?t:t[e]||0}const Mm=new WeakMap;class Nm{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=Ce(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const r=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Xn(d).point)},o=(d,f)=>{const{drag:m,dragPropagation:v,onDragStart:_}=this.getProps();if(m&&!v&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Xp(m),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Je(y=>{let T=this.getAxisMotionValue(y).get()||0;if(ht.test(T)){const{projection:x}=this.visualElement;if(x&&x.layout){const I=x.layout.layoutBox[y];I&&(T=Ve(I)*(parseFloat(T)/100))}}this.originPoint[y]=T}),_&&ve.postRender(()=>_(d,f)),Mo(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:m,dragDirectionLock:v,onDirectionLock:_,onDrag:w}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:y}=f;if(v&&this.currentDirection===null){this.currentDirection=Om(y),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Je(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)==null?void 0:f.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Ic(e,{onSessionStart:r,onStart:o,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:xc(this.visualElement)})}stop(e,n){const i=e||this.latestPointerEvent,s=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!s||!i)return;const{velocity:o}=s;this.startAnimation(o);const{onDragEnd:a}=this.getProps();a&&ve.postRender(()=>a(i,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:n}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(e,n,i){const{drag:s}=this.getProps();if(!i||!Gi(e,s,this.currentDirection))return;const r=this.getAxisMotionValue(e);let o=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(o=Im(o,this.constraints[e],this.elastic[e])),r.set(o)}resolveConstraints(){var r;const{dragConstraints:e,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(r=this.visualElement.projection)==null?void 0:r.layout,s=this.constraints;e&&fn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Am(i.layoutBox,e):this.constraints=!1,this.elastic=Dm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Je(o=>{this.constraints!==!1&&this.getAxisMotionValue(o)&&(this.constraints[o]=Pm(i.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!fn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const r=Tm(i,s.root,this.visualElement.getTransformPagePoint());let o=Rm(s.layout.layoutBox,r);if(n){const a=n(gm(o));this.hasMutatedConstraints=!!a,a&&(o=dc(a))}return o}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:r,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Je(u=>{if(!Gi(u,n,this.currentDirection))return;let d=l&&l[u]||{};o&&(d={min:0,max:0});const f=s?200:1e6,m=s?40:1e7,v={type:"inertia",velocity:i?e[u]:0,bounceStiffness:f,bounceDamping:m,timeConstant:750,restDelta:1,restSpeed:10,...r,...d};return this.startAxisValueAnimation(u,v)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Mo(this.visualElement,e),i.start(No(e,i,0,n,this.visualElement,!1))}stopAnimation(){Je(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Je(e=>{var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.pause()})}getAnimationState(e){var n;return(n=this.getAxisMotionValue(e).animation)==null?void 0:n.state}getAxisMotionValue(e){const n=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps(),s=i[n];return s||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){Je(n=>{const{drag:i}=this.getProps();if(!Gi(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,r=this.getAxisMotionValue(n);if(s&&s.layout){const{min:o,max:a}=s.layout.layoutBox[n];r.set(e[n]-be(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!fn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Je(o=>{const a=this.getAxisMotionValue(o);if(a&&this.constraints!==!1){const l=a.get();s[o]=Lm({min:l,max:l},this.constraints[o])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Je(o=>{if(!Gi(o,e,null))return;const a=this.getAxisMotionValue(o),{min:l,max:c}=this.constraints[o];a.set(be(l,c,s[o]))})}addListeners(){if(!this.visualElement.current)return;Mm.set(this.visualElement,this);const e=this.visualElement.current,n=Yn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();fn(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,r=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ve.read(i);const o=Kn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Je(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{o(),n(),r(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:r=!1,dragElastic:o=$o,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:r,dragElastic:o,dragMomentum:a}}}function Gi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Om(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Fm extends Mt{constructor(e){super(e),this.removeGroupControls=Ye,this.removeListeners=Ye,this.controls=new Nm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ye}unmount(){this.removeGroupControls(),this.removeListeners()}}const Nc=t=>(e,n)=>{t&&ve.postRender(()=>t(e,n))};class Vm extends Mt{constructor(){super(...arguments),this.removePointerDownListener=Ye}onPointerDown(e){this.session=new Ic(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Nc(e),onStart:Nc(n),onMove:i,onEnd:(r,o)=>{delete this.session,s&&ve.postRender(()=>s(r,o))}}}mount(){this.removePointerDownListener=Yn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Wi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Oc(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Qn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(W.test(t))t=parseFloat(t);else return t;const n=Oc(t,e.target.x),i=Oc(t,e.target.y);return`${n}% ${i}%`}},Bm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Dt.parse(t);if(s.length>5)return i;const r=Dt.createTransformer(t),o=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+o]/=a,s[1+o]/=l;const c=be(a,l,.5);return typeof s[2+o]=="number"&&(s[2+o]/=c),typeof s[3+o]=="number"&&(s[3+o]/=c),r(s)}};let Fc=!1;class Um extends it{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:r}=e;Tg(jm),r&&(n.group&&n.group.add(r),i&&i.register&&s&&i.register(r),Fc&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),Wi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:r}=this.props,{projection:o}=i;return o&&(o.isPresent=r,Fc=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==r?o.willUpdate():this.safeToRemove(),e.isPresent!==r&&(r?o.promote():o.relegate()||ve.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),So.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),i&&i.deregister&&i.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Vc(t){const[e,n]=Ul(),i=Re(Os);return R(Um,{...t,layoutGroup:i,switchLayoutGroup:Re(Xl),isPresent:e,safeToRemove:n})}const jm={borderRadius:{...Qn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Qn,borderTopRightRadius:Qn,borderBottomLeftRadius:Qn,borderBottomRightRadius:Qn,boxShadow:Bm};function $m(t,e,n){const i=Oe(t)?t:un(t);return i.start(No("",i,e,n)),i.animation}const Hm=(t,e)=>t.depth-e.depth;class Gm{constructor(){this.children=[],this.isDirty=!1}add(e){Vs(this.children,e),this.isDirty=!0}remove(e){Bs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Hm),this.isDirty=!1,this.children.forEach(e)}}function Wm(t,e){const n=$e.now(),i=({timestamp:s})=>{const r=s-n;r>=e&&(Lt(i),t(r-e))};return ve.setup(i,!0),()=>Lt(i)}const Bc=["TopLeft","TopRight","BottomLeft","BottomRight"],zm=Bc.length,Uc=t=>typeof t=="string"?parseFloat(t):t,jc=t=>typeof t=="number"||W.test(t);function qm(t,e,n,i,s,r){s?(t.opacity=be(0,n.opacity??1,Km(i)),t.opacityExit=be(e.opacity??1,0,Xm(i))):r&&(t.opacity=be(e.opacity??1,n.opacity??1,i));for(let o=0;o<zm;o++){const a=`border${Bc[o]}Radius`;let l=$c(e,a),c=$c(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||jc(l)===jc(c)?(t[a]=Math.max(be(Uc(l),Uc(c),i),0),(ht.test(c)||ht.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=be(e.rotate||0,n.rotate||0,i))}function $c(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Km=Hc(0,.5,ja),Xm=Hc(.5,.95,Ye);function Hc(t,e,n){return i=>i<t?0:i>e?1:n(On(t,e,i))}function Gc(t,e){t.min=e.min,t.max=e.max}function Ze(t,e){Gc(t.x,e.x),Gc(t.y,e.y)}function Wc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function zc(t,e,n,i,s){return t-=e,t=Hi(t,1/n,i),s!==void 0&&(t=Hi(t,1/s,i)),t}function Ym(t,e=0,n=1,i=.5,s,r=t,o=t){if(ht.test(e)&&(e=parseFloat(e),e=be(o.min,o.max,e/100)-o.min),typeof e!="number")return;let a=be(r.min,r.max,i);t===r&&(a-=e),t.min=zc(t.min,e,n,a,s),t.max=zc(t.max,e,n,a,s)}function qc(t,e,[n,i,s],r,o){Ym(t,e[n],e[i],e[s],e.scale,r,o)}const Jm=["x","scaleX","originX"],Zm=["y","scaleY","originY"];function Kc(t,e,n,i){qc(t.x,e,Jm,n?n.x:void 0,i?i.x:void 0),qc(t.y,e,Zm,n?n.y:void 0,i?i.y:void 0)}function Xc(t){return t.translate===0&&t.scale===1}function Yc(t){return Xc(t.x)&&Xc(t.y)}function Jc(t,e){return t.min===e.min&&t.max===e.max}function Qm(t,e){return Jc(t.x,e.x)&&Jc(t.y,e.y)}function Zc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Qc(t,e){return Zc(t.x,e.x)&&Zc(t.y,e.y)}function ed(t){return Ve(t.x)/Ve(t.y)}function td(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class ev{constructor(){this.members=[]}add(e){Vs(this.members,e),e.scheduleRender()}remove(e){if(Bs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===s);if(n===0)return!1;let i;for(let s=n;s>=0;s--){const r=this.members[s];if(r.isPresent!==!1){i=r;break}}return i?(this.promote(i),!0):!1}promote(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function tv(t,e,n){let i="";const s=t.x.translate/e.x,r=t.y.translate/e.y,o=(n==null?void 0:n.z)||0;if((s||r||o)&&(i=`translate3d(${s}px, ${r}px, ${o}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:m,skewY:v}=n;c&&(i=`perspective(${c}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),f&&(i+=`rotateY(${f}deg) `),m&&(i+=`skewX(${m}deg) `),v&&(i+=`skewY(${v}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Ho=["","X","Y","Z"],nv=1e3;let iv=0;function Go(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function nd(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=oc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:r}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ve,!(s||r))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&nd(i)}function id({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(o={},a=e==null?void 0:e()){this.id=iv++,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(rv),this.nodes.forEach(dv),this.nodes.forEach(uv),this.nodes.forEach(av)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,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 Gm)}addEventListener(o,a){return this.eventHandlers.has(o)||this.eventHandlers.set(o,new $s),this.eventHandlers.get(o).add(a)}notifyListeners(o,...a){const l=this.eventHandlers.get(o);l&&l.notify(...a)}hasListeners(o){return this.eventHandlers.has(o)}mount(o){if(this.instance)return;this.isSVG=Bl(o)&&!tg(o),this.instance=o;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(o),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 f=()=>this.root.updateBlockedByResize=!1;ve.read(()=>{d=window.innerWidth}),t(o,()=>{const m=window.innerWidth;m!==d&&(d=m,this.root.updateBlockedByResize=!0,u&&u(),u=Wm(f,250),Wi.hasAnimatedSinceResize&&(Wi.hasAnimatedSinceResize=!1,this.nodes.forEach(rd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:m})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const v=this.options.transition||c.getDefaultTransition()||mv,{onLayoutAnimationStart:_,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Qc(this.targetLayout,m),T=!d&&f;if(this.options.layoutRoot||this.resumeFrom||T||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const x={..._o(v,"layout"),onPlay:_,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(x.delay=0,x.type=!1),this.startAnimation(x),this.setAnimationOrigin(u,T)}else d||rd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=m})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Lt(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(hv),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&nd(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(),o&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(sd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(od);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(cv),this.nodes.forEach(sv),this.nodes.forEach(ov)):this.nodes.forEach(od),this.clearAllSnapshots();const a=$e.now();Pe.delta=wt(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,Ws.update.process(Pe),Ws.preRender.process(Pe),Ws.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,So.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(lv),this.sharedNodes.forEach(fv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ve.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ve.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ve(this.snapshot.measuredBox.x)&&!Ve(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 o=this.layout;this.layout=this.measure(!1),this.layoutCorrected=Ce(),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,o?o.layoutBox:void 0)}updateScroll(o="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===o&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:o,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const o=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Yc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;o&&this.instance&&(a||Kt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(o=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return o&&(l=this.removeTransform(l)),vv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:o}=this.options;if(!o)return Ce();const a=o.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(yv))){const{scroll:u}=this.root;u&&(gn(a.x,u.offset.x),gn(a.y,u.offset.y))}return a}removeElementScroll(o){var l;const a=Ce();if(Ze(a,o),(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:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Ze(a,o),gn(a.x,d.offset.x),gn(a.y,d.offset.y))}return a}applyTransform(o,a=!1){const l=Ce();Ze(l,o);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&mn(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Kt(u.latestValues)&&mn(l,u.latestValues)}return Kt(this.latestValues)&&mn(l,this.latestValues),l}removeTransform(o){const a=Ce();Ze(a,o);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Kt(c.latestValues))continue;Vo(c.latestValues)&&c.updateSnapshot();const u=Ce(),d=c.measurePageBox();Ze(u,d),Kc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Kt(this.latestValues)&&Kc(a,this.latestValues),a}setTargetDelta(o){this.targetDelta=o,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(o){this.options={...this.options,...o,crossfade:o.crossfade!==void 0?o.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(o=!1){var f;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(!(o||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.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 m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ce(),this.relativeTargetOrigin=Ce(),Zn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Ce(),this.targetWithTransforms=Ce()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Sm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Ze(this.target,this.layout.layoutBox),wc(this.target,this.targetDelta)):Ze(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ce(),this.relativeTargetOrigin=Ce(),Zn(this.relativeTargetOrigin,this.target,m.target),Ze(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Vo(this.parent.latestValues)||yc(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 o=this.getLead(),a=!!this.resumingFrom||this!==o;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;Ze(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;Cm(this.layoutCorrected,this.treeScale,this.path,a),o.layout&&!o.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(o.target=o.layout.layoutBox,o.targetWithTransforms=Ce());const{target:m}=o;if(!m){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Wc(this.prevProjectionDelta.x,this.projectionDelta.x),Wc(this.prevProjectionDelta.y,this.projectionDelta.y)),Jn(this.projectionDelta,this.layoutCorrected,m,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!td(this.projectionDelta.x,this.prevProjectionDelta.x)||!td(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",m))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(o=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),o){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=pn(),this.projectionDelta=pn(),this.projectionDeltaWithTransform=pn()}setAnimationOrigin(o,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=pn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=Ce(),m=l?l.source:void 0,v=this.layout?this.layout.source:void 0,_=m!==v,w=this.getStack(),y=!w||w.members.length<=1,T=!!(_&&!y&&this.options.crossfade===!0&&!this.path.some(gv));this.animationProgress=0;let x;this.mixTargetDelta=I=>{const A=I/1e3;ad(d.x,o.x,A),ad(d.y,o.y,A),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Zn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),pv(this.relativeTarget,this.relativeTargetOrigin,f,A),x&&Qm(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=Ce()),Ze(x,this.relativeTarget)),_&&(this.animationValues=u,qm(u,c,this.latestValues,A,T,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=A},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){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&&(Lt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ve.update(()=>{Wi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=un(0)),this.currentAnimation=$m(this.motionValue,[0,1e3],{...o,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),o.onUpdate&&o.onUpdate(u)},onStop:()=>{},onComplete:()=>{o.onComplete&&o.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 o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(nv),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=o;if(!(!a||!l||!c)){if(this!==o&&this.layout&&c&&hd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||Ce();const d=Ve(this.layout.layoutBox.x);l.x.min=o.target.x.min,l.x.max=l.x.min+d;const f=Ve(this.layout.layoutBox.y);l.y.min=o.target.y.min,l.y.max=l.y.min+f}Ze(a,l),mn(a,u),Jn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new ev),this.sharedNodes.get(o).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 o=this.getStack();return o?o.lead===this:!0}getLead(){var a;const{layoutId:o}=this.options;return o?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:o}=this.options;return o?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetSkewAndRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:l}=o;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Go("z",o,c,this.animationValues);for(let u=0;u<Ho.length;u++)Go(`rotate${Ho[u]}`,o,c,this.animationValues),Go(`skew${Ho[u]}`,o,c,this.animationValues);o.render();for(const u in c)o.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);o.scheduleRender()}applyProjectionStyles(o,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){o.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,o.visibility="",o.opacity="",o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||"",o.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(o.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,o.pointerEvents=$i(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Kt(this.latestValues)&&(o.transform=l?l({},""):"none",this.hasProjected=!1);return}o.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=tv(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),o.transform=d;const{x:f,y:m}=this.projectionDelta;o.transformOrigin=`${f.origin*100}% ${m.origin*100}% 0`,c.animationValues?o.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:o.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const v in zn){if(u[v]===void 0)continue;const{correct:_,applyTo:w,isCSSVariable:y}=zn[v],T=d==="none"?u[v]:_(u[v],c);if(w){const x=w.length;for(let I=0;I<x;I++)o[w[I]]=T}else y?this.options.visualElement.renderState.vars[v]=T:o[v]=T}this.options.layoutId&&(o.pointerEvents=c===this?$i(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(o=>{var a;return(a=o.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(sd),this.root.sharedNodes.clear()}}}function sv(t){t.updateLayout()}function ov(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:r}=t.options,o=e.source!==t.layout.source;r==="size"?Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],m=Ve(f);f.min=i[d].min,f.max=f.min+m}):hd(r,e.layoutBox,i)&&Je(d=>{const f=o?e.measuredBox[d]:e.layoutBox[d],m=Ve(i[d]);f.max=f.min+m,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+m)});const a=pn();Jn(a,i,e.layoutBox);const l=pn();o?Jn(l,t.applyTransform(s,!0),e.measuredBox):Jn(l,i,e.layoutBox);const c=!Yc(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:m}=d;if(f&&m){const v=Ce();Zn(v,e.layoutBox,f.layoutBox);const _=Ce();Zn(_,i,m.layoutBox),Qc(v,_)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=_,t.relativeTargetOrigin=v,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function rv(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 av(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function lv(t){t.clearSnapshot()}function sd(t){t.clearMeasurements()}function od(t){t.isLayoutDirty=!1}function cv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function rd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function dv(t){t.resolveTargetDelta()}function uv(t){t.calcProjection()}function hv(t){t.resetSkewAndRotation()}function fv(t){t.removeLeadSnapshot()}function ad(t,e,n){t.translate=be(e.translate,0,n),t.scale=be(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function ld(t,e,n,i){t.min=be(e.min,n.min,i),t.max=be(e.max,n.max,i)}function pv(t,e,n,i){ld(t.x,e.x,n.x,i),ld(t.y,e.y,n.y,i)}function gv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const mv={duration:.45,ease:[.4,0,.1,1]},cd=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),dd=cd("applewebkit/")&&!cd("chrome/")?Math.round:Ye;function ud(t){t.min=dd(t.min),t.max=dd(t.max)}function vv(t){ud(t.x),ud(t.y)}function hd(t,e,n){return t==="position"||t==="preserve-aspect"&&!wm(ed(e),ed(n),.2)}function yv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const _v=id({attachResizeListener:(t,e)=>Kn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Wo={current:void 0},fd=id({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Wo.current){const t=new _v({});t.mount(window),t.setOptions({layoutScroll:!0}),Wo.current=t}return Wo.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),bv={pan:{Feature:Vm},drag:{Feature:Fm,ProjectionNode:fd,MeasureLayout:Vc}};function pd(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,r=i[s];r&&ve.postRender(()=>r(e,Xn(e)))}class wv extends Mt{mount(){const{current:e}=this.node;e&&(this.unmount=Yp(e,(n,i)=>(pd(this.node,i,"Start"),s=>pd(this.node,s,"End"))))}unmount(){}}class Sv extends Mt{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=Nn(Kn(this.node.current,"focus",()=>this.onFocus()),Kn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function gd(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),r=i[s];r&&ve.postRender(()=>r(e,Xn(e)))}class Cv extends Mt{mount(){const{current:e}=this.node;e&&(this.unmount=eg(e,(n,i)=>(gd(this.node,i,"Start"),(s,{success:r})=>gd(this.node,s,r?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const zo=new WeakMap,qo=new WeakMap,Tv=t=>{const e=zo.get(t.target);e&&e(t)},kv=t=>{t.forEach(Tv)};function xv({root:t,...e}){const n=t||document;qo.has(n)||qo.set(n,{});const i=qo.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(kv,{root:t,...e})),i[s]}function Ev(t,e,n){const i=xv(e);return zo.set(t,n),i.observe(t),()=>{zo.delete(t),i.unobserve(t)}}const Iv={some:0,all:1};class Av extends Mt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:r}=e,o={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Iv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,r&&!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(),f=c?u:d;f&&f(l)};return Ev(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(Rv(e,n))&&this.startObserver()}unmount(){}}function Rv({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Lv={inView:{Feature:Av},tap:{Feature:Cv},focus:{Feature:Sv},hover:{Feature:wv}},Pv={layout:{ProjectionNode:fd,MeasureLayout:Vc}},Ko={current:null},md={current:!1};function Dv(){if(md.current=!0,!!Fs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Ko.current=t.matches;t.addEventListener("change",e),e()}else Ko.current=!1}const Mv=new WeakMap;function Nv(t,e,n){for(const i in e){const s=e[i],r=n[i];if(Oe(s))t.addValue(i,s);else if(Oe(r))t.addValue(i,un(s,{owner:t}));else if(r!==s)if(t.hasValue(i)){const o=t.getValue(i);o.liveStyle===!0?o.jump(s):o.hasAnimated||o.set(s)}else{const o=t.getStaticValue(i);t.addValue(i,un(o!==void 0?o:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const vd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Ov{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:r,visualState:o},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=vo,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 f=$e.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ve.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=o;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!r,this.isControllingVariants=ji(n),this.isVariantNode=zl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in d){const m=d[f];l[f]!==void 0&&Oe(m)&&m.set(l[f],!1)}}mount(e){this.current=e,Mv.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),md.current||Dv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Ko.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Lt(this.notifyUpdate),Lt(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=dn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ve.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),r=n.on("renderRequest",this.scheduleRender);let o;window.MotionCheckAppearSync&&(o=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),r(),o&&o(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in hn){const n=hn[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const r=this.features[e];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Ce()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,n){this.latestValues[e]=n}update(e,n){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let i=0;i<vd.length;i++){const s=vd[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const r="on"+s,o=e[r];o&&(this.propEventSubscriptions[s]=this.on(s,o))}this.prevMotionValues=Nv(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(e),()=>n.variantChildren.delete(e)}addValue(e,n){const i=this.values.get(e);n!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,n),this.values.set(e,n),this.latestValues[e]=n.get())}removeValue(e){this.values.delete(e);const n=this.valueSubscriptions.get(e);n&&(n(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,n){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return i===void 0&&n!==void 0&&(i=un(n===null?void 0:n,{owner:this}),this.addValue(e,i)),i}readValue(e,n){let i=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return i!=null&&(typeof i=="string"&&(La(i)||Da(i))?i=parseFloat(i):!ig(i)&&Dt.test(n)&&(i=Rl(e,n)),this.setBaseTarget(e,Oe(i)?i.get():i)),Oe(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var r;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const o=Lo(this.props,n,(r=this.presenceContext)==null?void 0:r.custom);o&&(i=o[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Oe(s)?s:this.initialValues[e]!==void 0&&i===void 0?void 0:this.baseTarget[e]}on(e,n){return this.events[e]||(this.events[e]=new $s),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class yd extends Ov{constructor(){super(...arguments),this.KeyframeResolver=Wp}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Oe(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function _d(t,{style:e,vars:n},i,s){const r=t.style;let o;for(o in e)r[o]=e[o];s==null||s.applyProjectionStyles(r,i);for(o in n)r.setProperty(o,n[o])}function Fv(t){return window.getComputedStyle(t)}class Vv extends yd{constructor(){super(...arguments),this.type="html",this.renderInstance=_d}readValueFromInstance(e,n){var i;if(dn.has(n))return(i=this.projection)!=null&&i.isProjecting?ho(n):up(e,n);{const s=Fv(e),r=(zs(n)?s.getPropertyValue(n):s[n])||0;return typeof r=="string"?r.trim():r}}measureInstanceViewportBox(e,{transformPagePoint:n}){return kc(e,n)}build(e,n,i){Io(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return Po(e,n,i)}}const bd=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 Bv(t,e,n,i){_d(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(bd.has(s)?s:Eo(s),e.attrs[s])}class Uv extends yd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ce}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(dn.has(n)){const i=Al(n);return i&&i.default||0}return n=bd.has(n)?n:Eo(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return sc(e,n,i)}build(e,n,i){Ql(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){Bv(e,n,i,s)}mount(e){this.isSVGTag=tc(e.tagName),super.mount(e)}}const jv=(t,e)=>Ro(t)?new Uv(e):new Vv(e,{allowProjection:t!==lt}),$v=jg({...fm,...Lv,...bv,...Pv},jv),vn=fg($v),Hv=["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"],ei="widget-layout-id";function wd(t){var e,n,i="";if(typeof t=="string"||typeof t=="number")i+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=wd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function Ct(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=wd(t))&&(i&&(i+=" "),i+=e);return i}const Gv=ki("listening"),Xo=()=>Aa(Gv);function Wv(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const zi={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},Sd=ki(zi),zv=()=>{const t=Ei(Sd);return We(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=zi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=zi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=zi.speak_to_interrupt_text),n}),[t])},Xt=()=>Ns(Sd),Cd=({size:t="large",className:e})=>{const n=Xt(),[i]=Xo();return R("h1",{className:Ct({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},Td=({stream:t,chatMode:e})=>{const n=de(null);return Ae(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:R("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const zv="4.5.1",Yo=Math.PI,_n=2*Yo,Jo=Yo/2,kd=8.17579892,xd="dual-combined",qi="dual-horizontal",Tt="single",ft="dual-vertical",Ed="bar-index",Id="bar-level",Ki="gradient",Ad=60,Rd="click",qv="fullscreenchange",Ld="resize",Kv="#111",Pd="",Dd="A",Md="B",Nd="C",Od="D",Fd="468",Xi="sans-serif",Xv="#0f0",Yv="#7f7f7f22",yn=10,Vd="create",Bd="fschange",Jv="lores",Zv=Ld,Zo="user",Qv="#000c",Ud="#fff",e_="#4f4",jd="#888",t_="#555",Qo="bark",ti="linear",bn="log",er="mel",$d=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Hd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:$d}],["rainbow",{dir:"h",colorStops:["#817",...$d,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],ni={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Tt,colorMode:Ki,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:bn,gradient:Hd[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:Pd,width:void 0},n_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],i_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],s_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],tr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],o_=["ERR_INVALID_MODE","Invalid mode"],r_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],a_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],l_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],c_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],d_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Qe extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Gd=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Wd=t=>{for(const e in t)return!1;return!0},Yi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],u_=(t,e,n,i,s)=>e+(i-e)*(s-t)/(n-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class h_{constructor(e,n={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(Wd(n)&&!Wd(e)&&(n=e),e=null),this._ownCanvas=!(n.canvas instanceof HTMLCanvasElement);const i=this._ownCanvas?document.createElement("canvas"):n.canvas;i.style="max-width: 100%;",this._ctx=i.getContext("2d");for(const[d,f]of Hd)this.registerGradient(d,f);this._container=e||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Qe(n_)}}if(!s.createGain)throw new Qe(i_);const r=this._analyzer=[s.createAnalyser(),s.createAnalyser()],o=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const d of[0,1])o.connect(r[d],d);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Zv),this._fsTimeout=0)},Ad))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Ld,l,{signal:c}),i.addEventListener(qv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Bd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ad)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Rd,u))};window.addEventListener(Rd,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Vd)}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=Yi(e,[Tt,qi,ft,xd]),this._input.disconnect(),this._input.connect(this._chLayout!=Tt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Tt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Yi(e,[Ki,Ed,Id])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const i of[0,1])this._analyzer[i].fftSize=e;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=Yi(e,[bn,Qo,er,ti]),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||ni.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Zo)}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(Jv)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const n of[0,1])this._analyzer[n].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new Qe(tr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const n of[0,1])this._analyzer[n].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new Qe(tr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const n=e|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new Qe(o_,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||ni.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 Qe(r_);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const n of[0,1])this._analyzer[n].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Jo),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Gd("stereo","channelLayout"),this._chLayout!=Tt}set stereo(e){Gd("stereo","channelLayout"),this.channelLayout=e?ft:Tt}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=Yi(e,[Pd,Dd,Md,Nd,Od,Fd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Zo)}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 zv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Qe(a_);const i=n?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==Tt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:r,_observer:o,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),o&&o.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),r.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const r of i.mediaStream.getAudioTracks())r.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:r,peak:o,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:r,peak:o,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,r=this._chLayout==Tt?1:2;let o=0;for(let a=0;a<r;a++)for(let l=i;l<=s;l++)o+=this._normalizedB(this._fftData[a][l]);return o/(s-i+1)/r}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(ni))e.includes(i)||(i=="gradient"&&this.gradientLeft!=this.gradientRight?(n.gradientLeft=this.gradientLeft,n.gradientRight=this.gradientRight):i!="start"&&(n[i]=this[i]));return n}registerGradient(e,n){if(typeof e!="string"||e.trim().length==0)throw new Qe(l_);if(typeof n!="object")throw new Qe(c_);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Qe(d_);const s=i.length,r=o=>+o!=o||o<0||o>1;i.forEach((o,a)=>{const l=a/Math.max(1,s-1);typeof o!="object"?i[a]={pos:l,color:o}:r(o.pos)&&(o.pos=l),r(o.level)&&(i[a].level=1-a/s)}),i.sort((o,a)=>o.level<a.level?1:o.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||Kv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Zo)}setFreqRange(e,n){if(e<1||n<1)throw new Qe(tr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:r,_maxFreq:o,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:f}=this,m=s.width>>1,v=s.height>>1,y=r==ft&&!u,w=r==qi,_=c%10!=0,T=_&&this._frequencyScale==bn,x=this._showLeds&&_&&!u,I=this._lumiBars&&_&&!u,A=this._alphaBars&&!I&&c!=yn,M=this._outlineBars&&_&&!I&&!x,S=this._roundBars&&_&&!I&&!x,C=r!=ft||f>0&&!I,p=s.height-(y&&!x?.5:0)>>y,g=p*(I||u?1:1-f)|0,h=s.width-m*(w||l!=0),b=y?s.height-p*2:0,E=m*(l==-1&&!w&&!u);let P=Math.min(s.width,s.height)*.375*(r==ft?1:this._radius)|0,L=Math.min(m,v);d&&r!=ft&&([P,L]=[L,P]);const N=K=>e.push({...K,peak:[0,0],hold:[0],alpha:[0],value:[0]}),D=K=>{const Z=this._freqToBin(K,"floor"),Q=this._binToFreq(Z),ne=this._binToFreq(Z+1),ge=Math.log2(K/Q)/Math.log2(ne/Q);return[Z,ge]};let U,Y,j;if(T){const K=(ce,_e,le)=>+ce.toPrecision(le?Math.max(_e,1+Math.log10(ce)|0):_e),Z=ce=>{const _e=[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],le=Math.log10(ce)|0,mt=ce/10**le;let ot=1;for(;ot<_e.length&&mt>_e[ot];)ot++;return mt-_e[ot-1]<_e[ot]-mt&&ot--,(_e[ot]*10**(le+5)|0)/1e5},Q=[0,24,12,8,6,4,3,2,1][c],ne=n?10**(3/(Q*10)):2**(1/Q),ge=ne**.5;let re=n?7.94328235/(Q%2?1:ge):kd;do{let ce=re;const _e=K(ce/ge,4,!0),le=K(ce*ge,4,!0),[mt,ot]=D(_e),[pi,vt]=D(le);n?ce=Q<4?Z(ce):K(ce,ce.toString()[0]<5?3:2):ce=K(ce,4,!0),ce>=a&&N({posX:0,freq:ce,freqLo:_e,freqHi:le,binLo:mt,binHi:pi,ratioLo:ot,ratioHi:vt}),re*=ne}while(re<=o);U=h/e.length,e.forEach((ce,_e)=>ce.posX=E+_e*U);const ie=e[0],Ie=e[e.length-1];Y=this._freqScaling(ie.freqLo),j=h/(this._freqScaling(Ie.freqHi)-Y),ie.freqLo<a&&(ie.freqLo=a,[ie.binLo,ie.ratioLo]=D(a)),Ie.freqHi>o&&(Ie.freqHi=o,[Ie.binHi,Ie.ratioHi]=D(o))}else if(_){const K=[0,24,12,8,6,4,3,2,1][c]*10,Z=Q=>{switch(this._frequencyScale){case Qo:return 1960/(26.81/(Q+.53)-1);case er:return 700*(2**Q-1);case ti:return Q}};U=h/K,Y=this._freqScaling(a),j=h/(this._freqScaling(o)-Y);for(let Q=0,ne=0;Q<K;Q++,ne+=U){const ge=Z(Y+ne/j),re=Z(Y+(ne+U/2)/j),ie=Z(Y+(ne+U)/j),[Ie,ce]=D(ge),[_e,le]=D(ie);N({posX:E+ne,freq:re,freqLo:ge,freqHi:ie,binLo:Ie,binHi:_e,ratioLo:ce,ratioHi:le})}}else{U=1,Y=this._freqScaling(a),j=h/(this._freqScaling(o)-Y);const K=this._freqToBin(a,"floor"),Z=this._freqToBin(o);let Q=-999;for(let ne=K;ne<=Z;ne++){const ge=this._binToFreq(ne),re=E+Math.round(j*(this._freqScaling(ge)-Y));if(re>Q)N({posX:re,freq:ge,freqLo:ge,freqHi:ge,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),Q=re;else if(e.length){const ie=e[e.length-1];ie.binHi=ne,ie.freqHi=ge,ie.freq=(ie.freqLo*ge)**.5}}}let ae=0,ee=0;if(x){const K=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Z=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Q=this._ledParams,[ne,ge,re]=Q||Z[c];let ie,Ie=g;if(Q){const ce=2*K;let _e;ie=ne+1;do ie--,_e=Ie/ie/(1+ge),ee=_e*ge;while((_e<ce||ee<ce)&&ie>1)}else{const ce=540/ge;ee=Math.min(ge*K,Math.max(2,Ie/ce+.1|0))}C&&(Ie+=ee),Q||(ie=Math.min(ne,Ie/(ee*2)|0)),ae=re>=1?re:U*re,this._leds=[ie,ae,ee,Ie/ie-ee]}const $=Math.min(U-1,i*(i>0&&i<1?U:1));_&&(U-=Math.max(x?ae:0,$)),e.forEach((K,Z)=>{let Q=K.posX,ne=U;_&&(i==0&&!x?(Q|=0,ne|=0,Z>0&&Q>e[Z-1].posX+e[Z-1].width&&(Q--,ne++)):Q+=Math.max(x?ae:0,$)/2,K.posX=Q),K.barCenter=Q+(U==1?0:ne/2),K.width=ne});const ue=[];for(const K of[0,1]){const Z=r==ft?(p+b)*K:0,Q=Z+p,ne=Z+g-(!x||C?0:ee);ue.push({channelTop:Z,channelBottom:Q,analyzerBottom:ne})}this._aux={analyzerHeight:g,analyzerWidth:h,centerX:m,centerY:v,channelCoords:ue,channelHeight:p,channelGap:b,initialX:E,innerRadius:P,outerRadius:L,scaleMin:Y,unitWidth:j},this._flg={isAlpha:A,isBands:_,isLeds:x,isLumi:I,isOctaves:T,isOutline:M,isRound:S,noLedGap:C},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:r}=this._aux,{canvas:o,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:f}=this,m=d.canvas,v=f.canvas,y=[],w=this._chLayout==qi,_=this._chLayout==ft,T=Math.min(o.width,o.height),x=["C",,"D",,"E","F",,"G",,"A",,"B"],I=T/34|0,A=m.height>>1,M=I>>1,S=A*(c?.7:1.5),C=M*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=bn))y.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ti?y.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):y.push(8e3,16e3);else{let L=kd;for(let N=-1;N<11;N++)for(let D=0;D<12;D++){if(L>=this._minFreq&&L<=this._maxFreq){const U=x[D],Y=U=="C";(U&&c&&!l&&!w||Y)&&y.push(c?[L,U+(Y?N:"")]:L)}L*=p}}v.width=v.height=Math.max(T*.15,(i<<1)+_*I);const g=v.width>>1,h=g-I*.7,b=(L,N)=>{const D=_n*(L/o.width),U=D-Jo,Y=h*Math.cos(U),j=h*Math.sin(U);f.save(),f.translate(g+Y,g+j),f.rotate(D),f.fillText(N,0,0),f.restore()};m.width|=0,d.fillStyle=f.strokeStyle=Qv,d.fillRect(0,0,m.width,m.height),f.arc(g,g,g-I/2,0,_n),f.lineWidth=I,f.stroke(),d.fillStyle=f.fillStyle=Ud,d.font=`${A}px ${Xi}`,f.font=`${M}px ${Xi}`,d.textAlign=f.textAlign="center";let E=-S/4,P=-C;for(const L of y){const[N,D]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],U=r*(this._freqScaling(N)-s),Y=m.height*.75,j=D[0]=="C",ae=A*(c&&!l&&!w?j?1.2:.6:3);if(d.fillStyle=f.fillStyle=j&&!l&&!w?e_:Ud,c){const ee=a==bn,$=a==ti;let ue=["C"];if((ee||N>2e3||!$&&N>250||(!u||_)&&(!$&&N>125||N>1e3))&&ue.push("G"),(ee||N>4e3||!$&&N>500||(!u||_)&&(!$&&N>250||N>2e3))&&ue.push("E"),($&&N>4e3||(!u||_)&&(ee||N>2e3||!$&&N>500))&&ue.push("D","F","A","B"),!ue.includes(D[0]))continue}U>=E+S/2&&U<=e&&(d.fillText(D,w&&l==-1?e-U:n+U,Y,ae),(w||l&&(U>S||l==1))&&d.fillText(D,w&&l!=1?e+U:(n||o.width)-U,Y,ae),E=U+Math.min(ae,d.measureText(D).width)/2),U>=P+C&&U<e-C&&(b(w&&l==1?e-U:U,D),(w||l&&(U>C||l==1))&&b(w&&l!=-1?e+U:-U,D),P=U)}}_draw(e){this._runId=requestAnimationFrame(V=>this._draw(V));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:r,isBands:o,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:f}=this._flg,{analyzerHeight:m,centerX:v,centerY:y,channelCoords:w,channelHeight:_,channelGap:T,initialX:x,innerRadius:I,outerRadius:A}=this._aux,{_bars:M,canvas:S,_canvasGradients:C,_chLayout:p,_colorMode:g,_ctx:h,_energy:b,_fadePeaks:E,fillAlpha:P,_fps:L,_linearAmplitude:N,_lineWidth:D,maxDecibels:U,minDecibels:Y,_mirror:j,_mode:ae,overlay:ee,_radial:$,showBgColor:ue,showPeaks:K,useCanvas:Z,_weightingFilter:Q}=this,ne=this._scaleX.canvas,ge=this._scaleR.canvas,re=L*this._peakFadeTime/1e3,ie=L**2,Ie=this._gravity*1e3,ce=L*this._peakHoldTime/1e3,_e=p==xd,le=p==qi,mt=p==ft,ot=p==Tt,pi=a&&this._trueLeds&&g==Ki,vt=$?S.width:this._aux.analyzerWidth,vr=x+vt,gi=K&&this._peakLine&&ae==yn,Ft=$?A-I:m,ub=Ft/this._pixelRatio,[hb,Sb,mi,_r]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*_n/60/L);const fb=V=>{if(this._reflexRatio>0&&!l&&!$){let se,_t;this.reflexFit||mt?(se=mt&&V==0?_+T:0,_t=_-m):(se=S.height-m*2,_t=m),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[V].channelTop,S.width,m,0,se,S.width,_t),h.restore()}},pb=()=>{this.showScaleX&&($?(h.save(),h.translate(v,y),this._spinSpeed&&h.rotate(this._spinAngle+Jo),h.drawImage(ge,-ge.width>>1,-ge.width>>1),h.restore()):h.drawImage(ne,0,S.height-ne.height))},gb=V=>{const se=V**2,_t=424.36,Ne=11599.29,us=25122.25,Vt=544496.41,Et=148693636,Qt=en=>20*Math.log10(en);switch(Q){case Dd:const en=Et*se**2/((se+_t)*Math.sqrt((se+Ne)*(se+Vt))*(se+Et));return 2+Qt(en);case Md:const tn=Et*se*V/((se+_t)*Math.sqrt(se+us)*(se+Et));return .17+Qt(tn);case Nd:const wr=Et*se/((se+_t)*(se+Et));return .06+Qt(wr);case Od:const hs=((103791848e-2-se)**2+108076816e-2*se)/((9837328-se)**2+11723776*se),Sr=V/68966888496476e-18*Math.sqrt(hs/((se+79919.29)*(se+1345600)));return Qt(Sr);case Fd:const fs=-4737338981378384e-39*V**6+2043828333606125e-30*V**4-1363894795463638e-22*se+1,nn=1306612257412824e-34*V**5-2118150887518656e-26*V**3+.0005559488023498642*V,qe=.0001246332637532143*V/Math.hypot(fs,nn);return 18.2+Qt(qe)}return 0},yr=(V,se,_t)=>{h.beginPath(),h.moveTo(V,se),h.lineTo(V,_t),h.stroke()},br=V=>{if(V&&D){const se=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=se}},Zt=V=>Math.max(0,(V*hb|0)*(_r+mi)-mi),mb=V=>{b.val=V,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*Ie/ie/S.height*this._pixelRatio)),V>=b.peak&&(b.peak=V,b.hold=ce)};ee&&h.clearRect(0,0,S.width,S.height);let fh=0;const ph=M.length,gh=ot?1:2;for(let V=0;V<gh;V++){const{channelTop:se,channelBottom:_t,analyzerBottom:Ne}=w[V],us=this._gradients[this._selectedGrads[V]],Vt=us.colorStops,Et=Vt.length,Qt=!ue||a&&!ee?"#000":us.bgColor,en=mt&&$&&V?-1:1,tn=!V&&j==-1||V&&j==1,wr=!le||V&&j!=1?0:vt>>(V||!tn),hs=le&&tn?-1:1,Sr=()=>{const H=ne.height,q=H>>1,J=N?100:U,me=N?0:Y,xe=N?20:5,Ge=m/(J-me),yt=j!=-1&&(!le||V==0||j==1),Bt=j!=1&&(!le||V!=j);h.save(),h.fillStyle=jd,h.font=`${q}px ${Xi}`,h.textAlign="right",h.lineWidth=1;for(let Ut=J;Ut>me;Ut-=xe){const En=se+(J-Ut)*Ge,Le=Ut%2==0|0;if(Le){const je=En+q*(En==se?.8:.35);yt&&h.fillText(Ut,H*.85,je),Bt&&h.fillText(Ut,(le?vt:S.width)-H*.1,je),h.strokeStyle=jd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=t_,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(x+H*Le*yt,~~En+.5),h.lineTo(vr-H*Le*Bt,~~En+.5),h.stroke()}h.restore()},fs=(H,q)=>{const J=rt[H]+(H<rt.length-1?(rt[H+1]-rt[H])*q:0);return isNaN(J)?-1/0:J},nn=(H,q=hs)=>q*_n*((H+wr)/S.width)+this._spinAngle,qe=(H,q,J)=>{const me=I+q*en,xe=nn(H,J);return[v+me*Math.cos(xe),y+me*Math.sin(xe)]},Cr=(H,q,J,me,xe)=>{h.beginPath();for(const Ge of j&&!le?[1,-1]:[hs]){const[yt,Bt]=d?[nn(H,Ge),nn(H+J,Ge)]:[];h.moveTo(...qe(H,q,Ge)),h.lineTo(...qe(H,q+me,Ge)),d?h.arc(v,y,I+(q+me)*en,yt,Bt,Ge!=1):h.lineTo(...qe(H+J,q+me,Ge)),h.lineTo(...qe(H+J,q,Ge)),d&&!xe&&h.arc(v,y,I+q*en,Bt,yt,Ge==1)}br(xe),h.fill()},Tr=(H=0,q=0)=>{let J;if(g==Ki&&!pi||ae==yn)J=C[V];else{const me=g==Ed?q%Et:Vt.findLastIndex(xe=>a?Zt(H)<=Zt(xe.level):H<=xe.level);J=Vt[me].color}h.fillStyle=h.strokeStyle=J};if(Z){if(le&&!$){const H=vt*(V+tn),q=tn?-1:1;h.setTransform(q,0,0,1,H,0)}if((!ee||ue)&&(ee&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Qt,(V==0||!$&&!_e)&&h.fillRect(x,se-T,vt,(ee&&this.reflexAlpha==1?m:_)+T),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(V==0||!_e)&&Sr(),a?(h.setLineDash([_r,mi]),h.lineWidth=M[0].width):h.lineWidth=u?Math.min(D,M[0].width/2):D,h.save(),!$){const H=new Path2D;H.rect(0,se,S.width,m),h.clip(H)}}let rt=this._fftData[V];this._analyzer[V].getFloatFrequencyData(rt),Q&&(rt=rt.map((H,q)=>H+gb(this._binToFreq(q)))),h.beginPath();let vi=[];for(let H=0;H<ph;H++){const q=M[H],{posX:J,barCenter:me,width:xe,freq:Ge,binLo:yt,binHi:Bt,ratioLo:Ut,ratioHi:En}=q;let Le=Math.max(fs(yt,Ut),fs(Bt,En));for(let fe=yt+1;fe<Bt;fe++)rt[fe]>Le&&(Le=rt[fe]);if(Le=this._normalizedB(Le),q.value[V]=Le,fh+=Le,q.peak[V]>0&&q.alpha[V]>0&&(q.hold[V]--,q.hold[V]<0)){if(E&&!gi){const fe=!r||u&&D>0?1:r?q.peak[V]:P;q.alpha[V]=fe*(1+q.hold[V]/re)}else q.peak[V]+=q.hold[V]*Ie/ie/ub;q.alpha[V]<=0&&(q.peak[V]=0)}if(Le>=q.peak[V]&&(q.peak[V]=Le,q.hold[V]=ce,q.alpha[V]=!r||u&&D>0?1:r?Le:P),!Z)continue;h.globalAlpha=l||r?Le:u?P:1,Tr(Le,H);const je=l?Ft:a?Zt(Le):Le*Ft|0;if(ae==yn){const fe=H?0:(this._normalizedB(rt[M[1].binLo])*Ft+je)/2;if($){if(H==0&&(le&&h.moveTo(...qe(0,0)),h.lineTo(...qe(0,J<0?fe:je))),J>=0){const tt=[J,je];h.lineTo(...qe(...tt)),vi.push(tt)}}else{if(H==0)if(j==-1&&!le)h.moveTo(x,Ne-(J<x?fe:je));else{const tt=yt?this._normalizedB(rt[yt-1])*Ft:je;h.moveTo(x-D,Ne-tt)}(le||j!=-1||J>=x)&&h.lineTo(J,Ne-je)}}else if(a){if(ue&&!ee&&(V==0||!_e)){const fe=h.globalAlpha;h.strokeStyle=Yv,h.globalAlpha=1,yr(me,se,Ne),h.strokeStyle=h.fillStyle,h.globalAlpha=fe}if(pi){const fe=l?0:Vt.findLastIndex(sn=>Zt(Le)<=Zt(sn.level));let tt=Ne;for(let sn=Et-1;sn>=fe;sn--){h.strokeStyle=Vt[sn].color;let vh=Ne-(sn==fe?je:Zt(Vt[sn].level));yr(me,tt,vh),tt=vh-mi}}else yr(me,Ne,Ne-je)}else if(J>=x)if($)Cr(J,0,xe,je,u);else if(d){const fe=xe/2,tt=Ne+fe;h.beginPath(),h.moveTo(J,tt),h.lineTo(J,tt-je),h.arc(me,tt-je,fe,Yo,_n),h.lineTo(J+xe,tt),br(u),h.fill()}else{const fe=u?h.lineWidth:0;h.beginPath(),h.rect(J,Ne+fe,xe,-je-fe),br(u),h.fill()}const In=q.peak[V],mh=q.alpha[V];if(In>0&&mh>0&&K&&!gi&&!l&&J>=x&&J<vr){if(E?h.globalAlpha=mh:u&&D>0?h.globalAlpha=1:r&&(h.globalAlpha=In),(g==Id||pi)&&Tr(In),a){const fe=Zt(In);fe>=mi&&h.fillRect(J,Ne-fe,xe,_r)}else if(!$)h.fillRect(J,Ne-In*Ft,xe,2);else if(ae!=yn){const fe=In*Ft;Cr(J,fe,xe,!this._radialInvert||mt||fe+I>=2?-2:2)}}}if(Z){if(h.globalAlpha=1,ae==yn){if(Tr(),$&&!le){if(j){let H;for(;H=vi.pop();)h.lineTo(...qe(...H,-1))}h.closePath()}if(D>0&&h.stroke(),P>0){if($){const H=le?nn(vt>>1):0,q=le?nn(vt):_n;h.moveTo(...qe(le?vt>>1:0,0)),h.arc(v,y,I,H,q,le?!tn:!0)}else h.lineTo(vr,Ne),h.lineTo(x,Ne);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((gi||$&&K)&&(vi=[],h.beginPath(),M.forEach((H,q)=>{let J=H.posX,me=H.peak[V],xe=q?"lineTo":"moveTo";if($&&J<0){const Ge=M[q+1];me=u_(J,me,Ge.posX,Ge.peak[V],0),J=0}me*=Ft,gi?(h[xe](...$?qe(J,me):[J,Ne-me]),$&&j&&!le&&vi.push([J,me])):me>0&&Cr(J,me,1,-2)}),gi)){let H;for(;H=vi.pop();)h.lineTo(...qe(...H,-1));h.lineWidth=1,h.stroke()}}h.restore(),le&&!$&&h.setTransform(1,0,0,1,0,0),(!le&&!_e||V)&&fb(V)}}if(mb(fh/(ph<<gh-1)),Z&&(j&&!$&&!le&&(h.setTransform(-1,0,0,1,S.width-x,0),h.drawImage(S,x,0,v,S.height,0,0,v,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),pb()),this.showFPS){const V=ne.height;h.font=`bold ${V}px ${Xi}`,h.fillStyle=Xv,h.textAlign="right",h.fillText(Math.round(L),S.width-V,V*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=C[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:C}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case bn:return Math.log2(e);case Qo:return 26.81*e/(1960+e)-.53;case er:return Math.log2(1+e/700);case ti:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:r,centerX:o,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,f=this._chLayout==ft,m=1-s,v=d?e.height:e.height*(1-s*!f)|0;for(const y of[0,1]){const w=this._gradients[this._selectedGrads[y]],_=w.colorStops,T=w.dir=="h";let x;if(i?x=n.createRadialGradient(o,a,u,o,a,c-(u-c)*f):x=n.createLinearGradient(...T?[l,0,l+r,0]:[0,0,0,v]),_){const I=f&&!this._splitGradient&&(!T||i);for(let A=0;A<1+I;A++){const M=_.length-1;_.forEach((S,C)=>{let p=S.pos;if(I&&(p/=2),f&&!d&&!i&&!T&&(p*=m,!I&&p>.5*m&&(p+=.5*s)),A==1)if(i||d){const g=M-C;S=_[g],p=1-S.pos/2}else C==0&&p>0&&x.addColorStop(.5,S.color),p+=.5;x.addColorStop(p,S.color),f&&C==M&&p<.5&&x.addColorStop(.5,S.color)})}}this._canvasGradients[y]=x}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,r=l=>10**(l/20);let o=this.maxDecibels,a=this.minDecibels;return n&&(o=r(o),a=r(a),e=r(e)**i),s((e-a)/(o-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,r=window.devicePixelRatio/(this._loRes+1);let o=window.screen.width*r,a=window.screen.height*r;Math.abs(window.orientation)==90&&o<a&&([o,a]=[a,o]);const l=this.isFullscreen,c=l&&this._fsEl==n,u=c?o:(this._width||this._container.clientWidth||this._defaultWidth)*r|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*r|0;this._pixelRatio=r,this._fsWidth=o,this._fsHeight=a,!(e!=Vd&&n.width==u&&n.height==d)&&(n.width=u,n.height=d,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,u,d)),i.lineJoin="bevel",s.width=u,s.height=Math.max(20*r,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Bd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Qe(s_,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],r=Object.keys(ni).filter(o=>o!="start").concat(i,s);(n||e===void 0)&&(e={...ni,...e});for(const o of Object.keys(e))i.includes(o)&&typeof e[o]!="function"?this[o]=void 0:r.includes(o)&&(this[o]=e[o]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const f_={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}]}},zd=({stream:t,className:e,onClick:n})=>{var r;const i=de(null),s=Xt();return Ae(()=>{var c;if(!i.current||!t)return;const o=new AudioContext,a=o.createMediaStreamSource(t),l=new h_(i.current,{source:a,audioCtx:o,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",f_[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(r=s.audio_visualizer_config)==null?void 0:r.color,t]),R("div",{onClick:n,className:Ct("w-full",e),ref:i})},qd=ki(null),Kd=({className:t,debug:e=!1})=>{const n=Ns(qd);return!e||!n||!(n.region||n.dc)?null:R("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[n.region&&R("span",{"data-testid":"connection-info-region",children:["region: ",n.region]}),n.region&&n.dc&&R("span",{children:" · "}),n.dc&&R("span",{"data-testid":"connection-info-dc",children:["dc: ",n.dc]})]})};/**
16
+ */const qv="4.5.1",Yo=Math.PI,yn=2*Yo,Jo=Yo/2,kd=8.17579892,xd="dual-combined",qi="dual-horizontal",Tt="single",ft="dual-vertical",Ed="bar-index",Id="bar-level",Ki="gradient",Ad=60,Rd="click",Kv="fullscreenchange",Ld="resize",Xv="#111",Pd="",Dd="A",Md="B",Nd="C",Od="D",Fd="468",Xi="sans-serif",Yv="#0f0",Jv="#7f7f7f22",_n=10,Vd="create",Bd="fschange",Zv="lores",Qv=Ld,Zo="user",ey="#000c",Ud="#fff",ty="#4f4",jd="#888",ny="#555",Qo="bark",ti="linear",bn="log",er="mel",$d=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Hd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:$d}],["rainbow",{dir:"h",colorStops:["#817",...$d,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],ni={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Tt,colorMode:Ki,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:bn,gradient:Hd[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:Pd,width:void 0},iy=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],sy=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],oy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],tr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],ry=["ERR_INVALID_MODE","Invalid mode"],ay=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],ly=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],cy=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],dy=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],uy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Qe extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Gd=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Wd=t=>{for(const e in t)return!1;return!0},Yi=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],hy=(t,e,n,i,s)=>e+(i-e)*(s-t)/(n-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class fy{constructor(e,n={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(Wd(n)&&!Wd(e)&&(n=e),e=null),this._ownCanvas=!(n.canvas instanceof HTMLCanvasElement);const i=this._ownCanvas?document.createElement("canvas"):n.canvas;i.style="max-width: 100%;",this._ctx=i.getContext("2d");for(const[d,f]of Hd)this.registerGradient(d,f);this._container=e||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Qe(iy)}}if(!s.createGain)throw new Qe(sy);const r=this._analyzer=[s.createAnalyser(),s.createAnalyser()],o=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const d of[0,1])o.connect(r[d],d);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Qv),this._fsTimeout=0)},Ad))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Ld,l,{signal:c}),i.addEventListener(Kv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Bd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ad)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Rd,u))};window.addEventListener(Rd,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Vd)}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=Yi(e,[Tt,qi,ft,xd]),this._input.disconnect(),this._input.connect(this._chLayout!=Tt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Tt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Yi(e,[Ki,Ed,Id])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const i of[0,1])this._analyzer[i].fftSize=e;const n=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(n),new Float32Array(n)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=Yi(e,[bn,Qo,er,ti]),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||ni.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Zo)}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(Zv)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const n of[0,1])this._analyzer[n].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new Qe(tr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const n of[0,1])this._analyzer[n].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new Qe(tr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const n=e|0;if(n>=0&&n<=10&&n!=9)this._mode=n,this._calcBars(),this._makeGrad();else throw new Qe(ry,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||ni.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 Qe(ay);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const n of[0,1])this._analyzer[n].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-Jo),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Gd("stereo","channelLayout"),this._chLayout!=Tt}set stereo(e){Gd("stereo","channelLayout"),this.channelLayout=e?ft:Tt}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=Yi(e,[Pd,Dd,Md,Nd,Od,Fd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Zo)}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 qv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Qe(ly);const i=n?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(i)||(i.connect(this._input),this._sources.push(i)),i}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const n of[0,1])this._analyzer[n].connect(this._chLayout==Tt&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:r,_observer:o,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),o&&o.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),r.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const r of i.mediaStream.getAudioTracks())r.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:r,peak:o,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:r,peak:o,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,r=this._chLayout==Tt?1:2;let o=0;for(let a=0;a<r;a++)for(let l=i;l<=s;l++)o+=this._normalizedB(this._fftData[a][l]);return o/(s-i+1)/r}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(ni))e.includes(i)||(i=="gradient"&&this.gradientLeft!=this.gradientRight?(n.gradientLeft=this.gradientLeft,n.gradientRight=this.gradientRight):i!="start"&&(n[i]=this[i]));return n}registerGradient(e,n){if(typeof e!="string"||e.trim().length==0)throw new Qe(cy);if(typeof n!="object")throw new Qe(dy);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Qe(uy);const s=i.length,r=o=>+o!=o||o<0||o>1;i.forEach((o,a)=>{const l=a/Math.max(1,s-1);typeof o!="object"?i[a]={pos:l,color:o}:r(o.pos)&&(o.pos=l),r(o.level)&&(i[a].level=1-a/s)}),i.sort((o,a)=>o.level<a.level?1:o.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||Xv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Zo)}setFreqRange(e,n){if(e<1||n<1)throw new Qe(tr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:r,_maxFreq:o,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:f}=this,m=s.width>>1,v=s.height>>1,_=r==ft&&!u,w=r==qi,y=c%10!=0,T=y&&this._frequencyScale==bn,x=this._showLeds&&y&&!u,I=this._lumiBars&&y&&!u,A=this._alphaBars&&!I&&c!=_n,M=this._outlineBars&&y&&!I&&!x,S=this._roundBars&&y&&!I&&!x,C=r!=ft||f>0&&!I,p=s.height-(_&&!x?.5:0)>>_,g=p*(I||u?1:1-f)|0,h=s.width-m*(w||l!=0),b=_?s.height-p*2:0,E=m*(l==-1&&!w&&!u);let P=Math.min(s.width,s.height)*.375*(r==ft?1:this._radius)|0,L=Math.min(m,v);d&&r!=ft&&([P,L]=[L,P]);const N=X=>e.push({...X,peak:[0,0],hold:[0],alpha:[0],value:[0]}),D=X=>{const Z=this._freqToBin(X,"floor"),Q=this._binToFreq(Z),ne=this._binToFreq(Z+1),ge=Math.log2(X/Q)/Math.log2(ne/Q);return[Z,ge]};let F,z,j;if(T){const X=(ue,ye,ce)=>+ue.toPrecision(ce?Math.max(ye,1+Math.log10(ue)|0):ye),Z=ue=>{const ye=[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],ce=Math.log10(ue)|0,mt=ue/10**ce;let ot=1;for(;ot<ye.length&&mt>ye[ot];)ot++;return mt-ye[ot-1]<ye[ot]-mt&&ot--,(ye[ot]*10**(ce+5)|0)/1e5},Q=[0,24,12,8,6,4,3,2,1][c],ne=n?10**(3/(Q*10)):2**(1/Q),ge=ne**.5;let re=n?7.94328235/(Q%2?1:ge):kd;do{let ue=re;const ye=X(ue/ge,4,!0),ce=X(ue*ge,4,!0),[mt,ot]=D(ye),[pi,vt]=D(ce);n?ue=Q<4?Z(ue):X(ue,ue.toString()[0]<5?3:2):ue=X(ue,4,!0),ue>=a&&N({posX:0,freq:ue,freqLo:ye,freqHi:ce,binLo:mt,binHi:pi,ratioLo:ot,ratioHi:vt}),re*=ne}while(re<=o);F=h/e.length,e.forEach((ue,ye)=>ue.posX=E+ye*F);const ie=e[0],Ie=e[e.length-1];z=this._freqScaling(ie.freqLo),j=h/(this._freqScaling(Ie.freqHi)-z),ie.freqLo<a&&(ie.freqLo=a,[ie.binLo,ie.ratioLo]=D(a)),Ie.freqHi>o&&(Ie.freqHi=o,[Ie.binHi,Ie.ratioHi]=D(o))}else if(y){const X=[0,24,12,8,6,4,3,2,1][c]*10,Z=Q=>{switch(this._frequencyScale){case Qo:return 1960/(26.81/(Q+.53)-1);case er:return 700*(2**Q-1);case ti:return Q}};F=h/X,z=this._freqScaling(a),j=h/(this._freqScaling(o)-z);for(let Q=0,ne=0;Q<X;Q++,ne+=F){const ge=Z(z+ne/j),re=Z(z+(ne+F/2)/j),ie=Z(z+(ne+F)/j),[Ie,ue]=D(ge),[ye,ce]=D(ie);N({posX:E+ne,freq:re,freqLo:ge,freqHi:ie,binLo:Ie,binHi:ye,ratioLo:ue,ratioHi:ce})}}else{F=1,z=this._freqScaling(a),j=h/(this._freqScaling(o)-z);const X=this._freqToBin(a,"floor"),Z=this._freqToBin(o);let Q=-999;for(let ne=X;ne<=Z;ne++){const ge=this._binToFreq(ne),re=E+Math.round(j*(this._freqScaling(ge)-z));if(re>Q)N({posX:re,freq:ge,freqLo:ge,freqHi:ge,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),Q=re;else if(e.length){const ie=e[e.length-1];ie.binHi=ne,ie.freqHi=ge,ie.freq=(ie.freqLo*ge)**.5}}}let le=0,ee=0;if(x){const X=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Z=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Q=this._ledParams,[ne,ge,re]=Q||Z[c];let ie,Ie=g;if(Q){const ue=2*X;let ye;ie=ne+1;do ie--,ye=Ie/ie/(1+ge),ee=ye*ge;while((ye<ue||ee<ue)&&ie>1)}else{const ue=540/ge;ee=Math.min(ge*X,Math.max(2,Ie/ue+.1|0))}C&&(Ie+=ee),Q||(ie=Math.min(ne,Ie/(ee*2)|0)),le=re>=1?re:F*re,this._leds=[ie,le,ee,Ie/ie-ee]}const $=Math.min(F-1,i*(i>0&&i<1?F:1));y&&(F-=Math.max(x?le:0,$)),e.forEach((X,Z)=>{let Q=X.posX,ne=F;y&&(i==0&&!x?(Q|=0,ne|=0,Z>0&&Q>e[Z-1].posX+e[Z-1].width&&(Q--,ne++)):Q+=Math.max(x?le:0,$)/2,X.posX=Q),X.barCenter=Q+(F==1?0:ne/2),X.width=ne});const he=[];for(const X of[0,1]){const Z=r==ft?(p+b)*X:0,Q=Z+p,ne=Z+g-(!x||C?0:ee);he.push({channelTop:Z,channelBottom:Q,analyzerBottom:ne})}this._aux={analyzerHeight:g,analyzerWidth:h,centerX:m,centerY:v,channelCoords:he,channelHeight:p,channelGap:b,initialX:E,innerRadius:P,outerRadius:L,scaleMin:z,unitWidth:j},this._flg={isAlpha:A,isBands:y,isLeds:x,isLumi:I,isOctaves:T,isOutline:M,isRound:S,noLedGap:C},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:r}=this._aux,{canvas:o,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:f}=this,m=d.canvas,v=f.canvas,_=[],w=this._chLayout==qi,y=this._chLayout==ft,T=Math.min(o.width,o.height),x=["C",,"D",,"E","F",,"G",,"A",,"B"],I=T/34|0,A=m.height>>1,M=I>>1,S=A*(c?.7:1.5),C=M*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=bn))_.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ti?_.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):_.push(8e3,16e3);else{let L=kd;for(let N=-1;N<11;N++)for(let D=0;D<12;D++){if(L>=this._minFreq&&L<=this._maxFreq){const F=x[D],z=F=="C";(F&&c&&!l&&!w||z)&&_.push(c?[L,F+(z?N:"")]:L)}L*=p}}v.width=v.height=Math.max(T*.15,(i<<1)+y*I);const g=v.width>>1,h=g-I*.7,b=(L,N)=>{const D=yn*(L/o.width),F=D-Jo,z=h*Math.cos(F),j=h*Math.sin(F);f.save(),f.translate(g+z,g+j),f.rotate(D),f.fillText(N,0,0),f.restore()};m.width|=0,d.fillStyle=f.strokeStyle=ey,d.fillRect(0,0,m.width,m.height),f.arc(g,g,g-I/2,0,yn),f.lineWidth=I,f.stroke(),d.fillStyle=f.fillStyle=Ud,d.font=`${A}px ${Xi}`,f.font=`${M}px ${Xi}`,d.textAlign=f.textAlign="center";let E=-S/4,P=-C;for(const L of _){const[N,D]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],F=r*(this._freqScaling(N)-s),z=m.height*.75,j=D[0]=="C",le=A*(c&&!l&&!w?j?1.2:.6:3);if(d.fillStyle=f.fillStyle=j&&!l&&!w?ty:Ud,c){const ee=a==bn,$=a==ti;let he=["C"];if((ee||N>2e3||!$&&N>250||(!u||y)&&(!$&&N>125||N>1e3))&&he.push("G"),(ee||N>4e3||!$&&N>500||(!u||y)&&(!$&&N>250||N>2e3))&&he.push("E"),($&&N>4e3||(!u||y)&&(ee||N>2e3||!$&&N>500))&&he.push("D","F","A","B"),!he.includes(D[0]))continue}F>=E+S/2&&F<=e&&(d.fillText(D,w&&l==-1?e-F:n+F,z,le),(w||l&&(F>S||l==1))&&d.fillText(D,w&&l!=1?e+F:(n||o.width)-F,z,le),E=F+Math.min(le,d.measureText(D).width)/2),F>=P+C&&F<e-C&&(b(w&&l==1?e-F:F,D),(w||l&&(F>C||l==1))&&b(w&&l!=-1?e+F:-F,D),P=F)}}_draw(e){this._runId=requestAnimationFrame(B=>this._draw(B));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:r,isBands:o,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:f}=this._flg,{analyzerHeight:m,centerX:v,centerY:_,channelCoords:w,channelHeight:y,channelGap:T,initialX:x,innerRadius:I,outerRadius:A}=this._aux,{_bars:M,canvas:S,_canvasGradients:C,_chLayout:p,_colorMode:g,_ctx:h,_energy:b,_fadePeaks:E,fillAlpha:P,_fps:L,_linearAmplitude:N,_lineWidth:D,maxDecibels:F,minDecibels:z,_mirror:j,_mode:le,overlay:ee,_radial:$,showBgColor:he,showPeaks:X,useCanvas:Z,_weightingFilter:Q}=this,ne=this._scaleX.canvas,ge=this._scaleR.canvas,re=L*this._peakFadeTime/1e3,ie=L**2,Ie=this._gravity*1e3,ue=L*this._peakHoldTime/1e3,ye=p==xd,ce=p==qi,mt=p==ft,ot=p==Tt,pi=a&&this._trueLeds&&g==Ki,vt=$?S.width:this._aux.analyzerWidth,vr=x+vt,gi=X&&this._peakLine&&le==_n,Ft=$?A-I:m,ub=Ft/this._pixelRatio,[hb,Sb,mi,yr]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*yn/60/L);const fb=B=>{if(this._reflexRatio>0&&!l&&!$){let se,yt;this.reflexFit||mt?(se=mt&&B==0?y+T:0,yt=y-m):(se=S.height-m*2,yt=m),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[B].channelTop,S.width,m,0,se,S.width,yt),h.restore()}},pb=()=>{this.showScaleX&&($?(h.save(),h.translate(v,_),this._spinSpeed&&h.rotate(this._spinAngle+Jo),h.drawImage(ge,-ge.width>>1,-ge.width>>1),h.restore()):h.drawImage(ne,0,S.height-ne.height))},gb=B=>{const se=B**2,yt=424.36,Ne=11599.29,us=25122.25,Vt=544496.41,At=148693636,Qt=en=>20*Math.log10(en);switch(Q){case Dd:const en=At*se**2/((se+yt)*Math.sqrt((se+Ne)*(se+Vt))*(se+At));return 2+Qt(en);case Md:const tn=At*se*B/((se+yt)*Math.sqrt(se+us)*(se+At));return .17+Qt(tn);case Nd:const wr=At*se/((se+yt)*(se+At));return .06+Qt(wr);case Od:const hs=((103791848e-2-se)**2+108076816e-2*se)/((9837328-se)**2+11723776*se),Sr=B/68966888496476e-18*Math.sqrt(hs/((se+79919.29)*(se+1345600)));return Qt(Sr);case Fd:const fs=-4737338981378384e-39*B**6+2043828333606125e-30*B**4-1363894795463638e-22*se+1,nn=1306612257412824e-34*B**5-2118150887518656e-26*B**3+.0005559488023498642*B,qe=.0001246332637532143*B/Math.hypot(fs,nn);return 18.2+Qt(qe)}return 0},_r=(B,se,yt)=>{h.beginPath(),h.moveTo(B,se),h.lineTo(B,yt),h.stroke()},br=B=>{if(B&&D){const se=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=se}},Zt=B=>Math.max(0,(B*hb|0)*(yr+mi)-mi),mb=B=>{b.val=B,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*Ie/ie/S.height*this._pixelRatio)),B>=b.peak&&(b.peak=B,b.hold=ue)};ee&&h.clearRect(0,0,S.width,S.height);let ph=0;const gh=M.length,mh=ot?1:2;for(let B=0;B<mh;B++){const{channelTop:se,channelBottom:yt,analyzerBottom:Ne}=w[B],us=this._gradients[this._selectedGrads[B]],Vt=us.colorStops,At=Vt.length,Qt=!he||a&&!ee?"#000":us.bgColor,en=mt&&$&&B?-1:1,tn=!B&&j==-1||B&&j==1,wr=!ce||B&&j!=1?0:vt>>(B||!tn),hs=ce&&tn?-1:1,Sr=()=>{const H=ne.height,K=H>>1,J=N?100:F,me=N?0:z,xe=N?20:5,Ge=m/(J-me),_t=j!=-1&&(!ce||B==0||j==1),Bt=j!=1&&(!ce||B!=j);h.save(),h.fillStyle=jd,h.font=`${K}px ${Xi}`,h.textAlign="right",h.lineWidth=1;for(let Ut=J;Ut>me;Ut-=xe){const En=se+(J-Ut)*Ge,Le=Ut%2==0|0;if(Le){const je=En+K*(En==se?.8:.35);_t&&h.fillText(Ut,H*.85,je),Bt&&h.fillText(Ut,(ce?vt:S.width)-H*.1,je),h.strokeStyle=jd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=ny,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(x+H*Le*_t,~~En+.5),h.lineTo(vr-H*Le*Bt,~~En+.5),h.stroke()}h.restore()},fs=(H,K)=>{const J=rt[H]+(H<rt.length-1?(rt[H+1]-rt[H])*K:0);return isNaN(J)?-1/0:J},nn=(H,K=hs)=>K*yn*((H+wr)/S.width)+this._spinAngle,qe=(H,K,J)=>{const me=I+K*en,xe=nn(H,J);return[v+me*Math.cos(xe),_+me*Math.sin(xe)]},Cr=(H,K,J,me,xe)=>{h.beginPath();for(const Ge of j&&!ce?[1,-1]:[hs]){const[_t,Bt]=d?[nn(H,Ge),nn(H+J,Ge)]:[];h.moveTo(...qe(H,K,Ge)),h.lineTo(...qe(H,K+me,Ge)),d?h.arc(v,_,I+(K+me)*en,_t,Bt,Ge!=1):h.lineTo(...qe(H+J,K+me,Ge)),h.lineTo(...qe(H+J,K,Ge)),d&&!xe&&h.arc(v,_,I+K*en,Bt,_t,Ge==1)}br(xe),h.fill()},Tr=(H=0,K=0)=>{let J;if(g==Ki&&!pi||le==_n)J=C[B];else{const me=g==Ed?K%At:Vt.findLastIndex(xe=>a?Zt(H)<=Zt(xe.level):H<=xe.level);J=Vt[me].color}h.fillStyle=h.strokeStyle=J};if(Z){if(ce&&!$){const H=vt*(B+tn),K=tn?-1:1;h.setTransform(K,0,0,1,H,0)}if((!ee||he)&&(ee&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Qt,(B==0||!$&&!ye)&&h.fillRect(x,se-T,vt,(ee&&this.reflexAlpha==1?m:y)+T),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(B==0||!ye)&&Sr(),a?(h.setLineDash([yr,mi]),h.lineWidth=M[0].width):h.lineWidth=u?Math.min(D,M[0].width/2):D,h.save(),!$){const H=new Path2D;H.rect(0,se,S.width,m),h.clip(H)}}let rt=this._fftData[B];this._analyzer[B].getFloatFrequencyData(rt),Q&&(rt=rt.map((H,K)=>H+gb(this._binToFreq(K)))),h.beginPath();let vi=[];for(let H=0;H<gh;H++){const K=M[H],{posX:J,barCenter:me,width:xe,freq:Ge,binLo:_t,binHi:Bt,ratioLo:Ut,ratioHi:En}=K;let Le=Math.max(fs(_t,Ut),fs(Bt,En));for(let fe=_t+1;fe<Bt;fe++)rt[fe]>Le&&(Le=rt[fe]);if(Le=this._normalizedB(Le),K.value[B]=Le,ph+=Le,K.peak[B]>0&&K.alpha[B]>0&&(K.hold[B]--,K.hold[B]<0)){if(E&&!gi){const fe=!r||u&&D>0?1:r?K.peak[B]:P;K.alpha[B]=fe*(1+K.hold[B]/re)}else K.peak[B]+=K.hold[B]*Ie/ie/ub;K.alpha[B]<=0&&(K.peak[B]=0)}if(Le>=K.peak[B]&&(K.peak[B]=Le,K.hold[B]=ue,K.alpha[B]=!r||u&&D>0?1:r?Le:P),!Z)continue;h.globalAlpha=l||r?Le:u?P:1,Tr(Le,H);const je=l?Ft:a?Zt(Le):Le*Ft|0;if(le==_n){const fe=H?0:(this._normalizedB(rt[M[1].binLo])*Ft+je)/2;if($){if(H==0&&(ce&&h.moveTo(...qe(0,0)),h.lineTo(...qe(0,J<0?fe:je))),J>=0){const tt=[J,je];h.lineTo(...qe(...tt)),vi.push(tt)}}else{if(H==0)if(j==-1&&!ce)h.moveTo(x,Ne-(J<x?fe:je));else{const tt=_t?this._normalizedB(rt[_t-1])*Ft:je;h.moveTo(x-D,Ne-tt)}(ce||j!=-1||J>=x)&&h.lineTo(J,Ne-je)}}else if(a){if(he&&!ee&&(B==0||!ye)){const fe=h.globalAlpha;h.strokeStyle=Jv,h.globalAlpha=1,_r(me,se,Ne),h.strokeStyle=h.fillStyle,h.globalAlpha=fe}if(pi){const fe=l?0:Vt.findLastIndex(sn=>Zt(Le)<=Zt(sn.level));let tt=Ne;for(let sn=At-1;sn>=fe;sn--){h.strokeStyle=Vt[sn].color;let yh=Ne-(sn==fe?je:Zt(Vt[sn].level));_r(me,tt,yh),tt=yh-mi}}else _r(me,Ne,Ne-je)}else if(J>=x)if($)Cr(J,0,xe,je,u);else if(d){const fe=xe/2,tt=Ne+fe;h.beginPath(),h.moveTo(J,tt),h.lineTo(J,tt-je),h.arc(me,tt-je,fe,Yo,yn),h.lineTo(J+xe,tt),br(u),h.fill()}else{const fe=u?h.lineWidth:0;h.beginPath(),h.rect(J,Ne+fe,xe,-je-fe),br(u),h.fill()}const In=K.peak[B],vh=K.alpha[B];if(In>0&&vh>0&&X&&!gi&&!l&&J>=x&&J<vr){if(E?h.globalAlpha=vh:u&&D>0?h.globalAlpha=1:r&&(h.globalAlpha=In),(g==Id||pi)&&Tr(In),a){const fe=Zt(In);fe>=mi&&h.fillRect(J,Ne-fe,xe,yr)}else if(!$)h.fillRect(J,Ne-In*Ft,xe,2);else if(le!=_n){const fe=In*Ft;Cr(J,fe,xe,!this._radialInvert||mt||fe+I>=2?-2:2)}}}if(Z){if(h.globalAlpha=1,le==_n){if(Tr(),$&&!ce){if(j){let H;for(;H=vi.pop();)h.lineTo(...qe(...H,-1))}h.closePath()}if(D>0&&h.stroke(),P>0){if($){const H=ce?nn(vt>>1):0,K=ce?nn(vt):yn;h.moveTo(...qe(ce?vt>>1:0,0)),h.arc(v,_,I,H,K,ce?!tn:!0)}else h.lineTo(vr,Ne),h.lineTo(x,Ne);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((gi||$&&X)&&(vi=[],h.beginPath(),M.forEach((H,K)=>{let J=H.posX,me=H.peak[B],xe=K?"lineTo":"moveTo";if($&&J<0){const Ge=M[K+1];me=hy(J,me,Ge.posX,Ge.peak[B],0),J=0}me*=Ft,gi?(h[xe](...$?qe(J,me):[J,Ne-me]),$&&j&&!ce&&vi.push([J,me])):me>0&&Cr(J,me,1,-2)}),gi)){let H;for(;H=vi.pop();)h.lineTo(...qe(...H,-1));h.lineWidth=1,h.stroke()}}h.restore(),ce&&!$&&h.setTransform(1,0,0,1,0,0),(!ce&&!ye||B)&&fb(B)}}if(mb(ph/(gh<<mh-1)),Z&&(j&&!$&&!ce&&(h.setTransform(-1,0,0,1,S.width-x,0),h.drawImage(S,x,0,v,S.height,0,0,v,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),pb()),this.showFPS){const B=ne.height;h.font=`bold ${B}px ${Xi}`,h.fillStyle=Yv,h.textAlign="right",h.fillText(Math.round(L),S.width-B,B*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=C[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:C}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case bn:return Math.log2(e);case Qo:return 26.81*e/(1960+e)-.53;case er:return Math.log2(1+e/700);case ti:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:r,centerX:o,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,f=this._chLayout==ft,m=1-s,v=d?e.height:e.height*(1-s*!f)|0;for(const _ of[0,1]){const w=this._gradients[this._selectedGrads[_]],y=w.colorStops,T=w.dir=="h";let x;if(i?x=n.createRadialGradient(o,a,u,o,a,c-(u-c)*f):x=n.createLinearGradient(...T?[l,0,l+r,0]:[0,0,0,v]),y){const I=f&&!this._splitGradient&&(!T||i);for(let A=0;A<1+I;A++){const M=y.length-1;y.forEach((S,C)=>{let p=S.pos;if(I&&(p/=2),f&&!d&&!i&&!T&&(p*=m,!I&&p>.5*m&&(p+=.5*s)),A==1)if(i||d){const g=M-C;S=y[g],p=1-S.pos/2}else C==0&&p>0&&x.addColorStop(.5,S.color),p+=.5;x.addColorStop(p,S.color),f&&C==M&&p<.5&&x.addColorStop(.5,S.color)})}}this._canvasGradients[_]=x}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,r=l=>10**(l/20);let o=this.maxDecibels,a=this.minDecibels;return n&&(o=r(o),a=r(a),e=r(e)**i),s((e-a)/(o-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,r=window.devicePixelRatio/(this._loRes+1);let o=window.screen.width*r,a=window.screen.height*r;Math.abs(window.orientation)==90&&o<a&&([o,a]=[a,o]);const l=this.isFullscreen,c=l&&this._fsEl==n,u=c?o:(this._width||this._container.clientWidth||this._defaultWidth)*r|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*r|0;this._pixelRatio=r,this._fsWidth=o,this._fsHeight=a,!(e!=Vd&&n.width==u&&n.height==d)&&(n.width=u,n.height=d,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,u,d)),i.lineJoin="bevel",s.width=u,s.height=Math.max(20*r,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Bd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Qe(oy,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],r=Object.keys(ni).filter(o=>o!="start").concat(i,s);(n||e===void 0)&&(e={...ni,...e});for(const o of Object.keys(e))i.includes(o)&&typeof e[o]!="function"?this[o]=void 0:r.includes(o)&&(this[o]=e[o]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const py={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}]}},zd=({stream:t,className:e,onClick:n})=>{var r;const i=de(null),s=Xt();return Ae(()=>{var c;if(!i.current||!t)return;const o=new AudioContext,a=o.createMediaStreamSource(t),l=new fy(i.current,{source:a,audioCtx:o,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",py[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(r=s.audio_visualizer_config)==null?void 0:r.color,t]),R("div",{onClick:n,className:Ct("w-full",e),ref:i})},qd=ki(null),Kd=({className:t,debug:e=!1})=>{const n=Ns(qd);return!e||!n||!(n.region||n.dc)?null:R("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[n.region&&R("span",{"data-testid":"connection-info-region",children:["region: ",n.region]}),n.region&&n.dc&&R("span",{children:" · "}),n.dc&&R("span",{"data-testid":"connection-info-dc",children:["dc: ",n.dc]})]})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Xd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),p_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Yd=t=>{const e=p_(t);return e.charAt(0).toUpperCase()+e.slice(1)},g_=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
21
+ */const Xd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),gy=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Yd=t=>{const e=gy(t);return e.charAt(0).toUpperCase()+e.slice(1)},my=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var m_={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 vy={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 v_=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:r,class:o="",...a})=>Ke("svg",{...m_,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",o].join(" "),...a},[...r.map(([l,c])=>Ke(l,c)),...ct(s)]);/**
31
+ */const yy=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:r,class:o="",...a})=>Ke("svg",{...vy,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",o].join(" "),...a},[...r.map(([l,c])=>Ke(l,c)),...ct(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 Be=(t,e)=>{const n=({class:i="",children:s,...r})=>Ke(v_,{...r,iconNode:e,class:g_(`lucide-${Xd(Yd(t))}`,`lucide-${Xd(t)}`,i)},s);return n.displayName=Yd(t),n};/**
36
+ */const Be=(t,e)=>{const n=({class:i="",children:s,...r})=>Ke(yy,{...r,iconNode:e,class:my(`lucide-${Xd(Yd(t))}`,`lucide-${Xd(t)}`,i)},s);return n.displayName=Yd(t),n};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
@@ -43,7 +43,7 @@ var vb=Object.defineProperty;var _b=(nt,G,jt)=>G in nt?vb(nt,G,{enumerable:!0,co
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 __=Be("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 _y=Be("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.
@@ -53,67 +53,67 @@ var vb=Object.defineProperty;var _b=(nt,G,jt)=>G in nt?vb(nt,G,{enumerable:!0,co
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 y_=Be("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 by=Be("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 b_=Be("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const wy=Be("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 w_=Be("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 Sy=Be("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 S_=Be("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 Cy=Be("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 C_=Be("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 Ty=Be("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 T_=Be("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 ky=Be("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 k_=Be("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 xy=Be("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 x_=Be("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 Ey=Be("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 E_=Be("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 Iy=Be("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 I_=Be("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 Ay=Be("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 A_=Be("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 Ry=Be("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 nr=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Qd=ki(!1),R_=()=>Aa(Qd),kt=({children:t,className:e,onClick:n,tooltip:i})=>R("button",{title:i,onClick:n,className:Ct("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),eu=({call:t,chatMode:e})=>{const[n,i]=R_(),s=()=>{i(o=>{const a=!o;return a?t.muteAudio():t.unmuteAudio(),a})},r=()=>{t.hangup()};return R("div",{className:"flex items-center justify-center gap-2",children:[!e&&R(kt,{tooltip:n?"Unmute":"Mute",onClick:s,className:Ct(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?R(w_,{className:"w-5 h-5 text-black dark:text-white"}):R(S_,{className:"w-5 h-5 text-black dark:text-white"})}),R(kt,{tooltip:"End Call",onClick:r,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:R(T_,{className:"w-4 h-4 text-black dark:text-white"})})]})},tu=({call:t,onExpand:e,chatMode:n,debug:i=!1})=>R(vn.div,{layoutId:ei,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!n&&R(zd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),R(Td,{stream:t.remoteStream,chatMode:n}),R(Cd,{size:"small"}),R(eu,{call:t,chatMode:n}),R(Kd,{debug:i})]});function L_(){const[t,e]=Ee(!1),n=Xt();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},r=()=>{i(n.report_issue_url)},o=()=>{i(n.view_history_url)};return R("div",{children:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Zd,{className:"text-black dark:text-white"})}),t&&R("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:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Zd,{className:"text-black dark:text-white"})}),R("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&R("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",R(I_,{className:"w-4 h-4"})]}),n.report_issue_url&&R("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",R(A_,{className:"w-4 h-4"})]}),n.view_history_url&&R("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",R(y_,{className:"w-4 h-4"})]})]})]})]})}function P_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ji={exports:{}},D_=Ji.exports,nu;function M_(){return nu||(nu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(D_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(y,w){var _=y[w];if(typeof _.bind=="function")return _.bind(y);try{return Function.prototype.bind.call(_,y)}catch{return function(){return Function.prototype.apply.apply(_,[y,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(y){return y==="debug"&&(y="log"),typeof console===n?!1:y==="trace"&&i?l:console[y]!==void 0?a(console,y):console.log!==void 0?a(console,"log"):e}function u(){for(var y=this.getLevel(),w=0;w<s.length;w++){var _=s[w];this[_]=w<y?e:this.methodFactory(_,y,this.name)}if(this.log=this.debug,typeof console===n&&y<this.levels.SILENT)return"No console available for logging"}function d(y){return function(){typeof console!==n&&(u.call(this),this[y].apply(this,arguments))}}function f(y,w,_){return c(y)||d.apply(this,arguments)}function m(y,w){var _=this,T,x,I,A="loglevel";typeof y=="string"?A+=":"+y:typeof y=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),P=b.indexOf(E+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+E.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&_.levels[b.toUpperCase()]!==void 0&&(b=_.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=_.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=y,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=w||f,_.getLevel=function(){return I??x??T},_.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(_)},_.setDefaultLevel=function(h){x=p(h),S()||_.setLevel(h,!1)},_.resetLevel=function(){I=null,C(),u.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(o!==_&&(T=p(o.getLevel())),u.call(_),o===_)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var g=S();g!=null&&(I=p(g)),u.call(_)}o=new m,o.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var _=r[w];return _||(_=r[w]=new m(w,o.methodFactory)),_};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(Ji)),Ji.exports}var N_=M_();const O_=P_(N_),F_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),V_="[ai-agent-widget]",he=O_.getLogger("telnyx-ai-agent-widget"),B_=he.methodFactory;he.methodFactory=(t,e,n)=>{const i=B_(t,e,n);return function(...s){i(F_(),V_,...s)}},he.setLevel("info");function U_({onCapture:t,onClose:e}){const n=de(null),i=de(null),s=de(null),[r,o]=Ee(null),[a,l]=Ee(!0);Ae(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){he.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?o("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?o("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?o("Camera is already in use by another application."):o("Unable to access camera. Please try again."):o("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const d=n.current,f=i.current,m=f.getContext("2d");if(!m)return;f.width=d.videoWidth,f.height=d.videoHeight,m.drawImage(d,0,0,f.width,f.height);const v=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(y=>y.stop()),t(v),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return R("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:[R("div",{className:"absolute top-2 right-2 z-10",children:R(kt,{tooltip:"Close",onClick:u,children:R(nr,{className:"text-white w-5 h-5"})})}),R("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!r&&R("div",{className:"absolute text-white text-center",children:R("p",{className:"text-sm",children:"Loading camera..."})}),r&&R("div",{className:"text-white text-center max-w-xs",children:[R("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),R("p",{className:"text-xs",children:r}),R("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"})]}),!r&&R(lt,{children:[R("video",{ref:n,autoPlay:!0,playsInline:!0,className:Ct("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),R("canvas",{ref:i,className:"hidden"})]})]}),!r&&!a&&R("div",{className:"p-3 flex justify-center",children:R("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:[R(Jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const ir=["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"],j_=["audio","lang","mark","p","s","sub","w"],iu=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function su(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`</?(?:${n})(?:\\s+[^<>]*)?\\s*/?>`,e)}function ou(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`<\\/?(?:${n})(?:\\s+[^<>]*)?$`,e)}const ru=ir.filter(t=>!j_.includes(t)),$_=su(ir,"gi"),au=su(ru,"gi"),H_=ou(ir,"i"),G_=ou(ru,"i"),W_=new RegExp(`${au.source}|${iu.source}`,"i");function z_(t){const e=W_.test(t),n=e?$_:au,i=e?H_:G_;return t.replace(n,"").replace(i,"").replace(iu,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function q_({item:t,containerRef:e}){const n=de(null),i=t.role==="assistant"?z_(t.content):t.content;return Ae(()=>{var s;n.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),R("li",{className:Ct("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[R("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),R("div",{className:Ct("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&R("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,r)=>s.type==="image"&&R("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},r))}),i&&R("p",{className:Ct("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:i})]})]})}const K_=({transcript:t,call:e})=>{const n=de(null),i=de(null),s=de(null),[r,o]=Ee([]),[a,l]=Ee(!1),[c,u]=Ee([]),[,d]=Xo();Ae(()=>()=>{r.forEach(S=>URL.revokeObjectURL(S.preview))},[r]),Ae(()=>{if(c.length===0)return;const S=t.filter(C=>C.role==="user"&&!C.id.startsWith("optimistic-"));if(S.length>0){const C=S[S.length-1];u(p=>p.filter(g=>g.timestamp>C.timestamp))}},[t,c]);const f=S=>new Promise((C,p)=>{const g=new FileReader;g.onload=()=>C(g.result),g.onerror=p,g.readAsDataURL(S)}),m=async S=>{if(S.type.startsWith("image/"))try{const C=await f(S),p=URL.createObjectURL(S),g={id:Date.now().toString(),file:S,base64:C,preview:p};o(h=>[...h,g])}catch(C){he.error("Error processing image:",C)}},v=S=>{o(C=>{const p=C.find(g=>g.id===S);return p&&URL.revokeObjectURL(p.preview),C.filter(g=>g.id!==S)})},y=S=>{const C=S.target,p=C.files;p&&p.length>0&&(Array.from(p).forEach(m),C.value="")},w=S=>{var p;const C=(p=S.clipboardData)==null?void 0:p.items;C&&Array.from(C).forEach(g=>{if(g.type.startsWith("image/")){const h=g.getAsFile();h&&m(h)}})},_=()=>{var S;(S=i.current)==null||S.click()},T=()=>{l(!0)},x=S=>{fetch(S).then(C=>C.blob()).then(C=>{const p=new File([C],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});m(p)}).catch(C=>{he.error("Error processing camera capture:",C)})},I=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",C=r.length>0;if(S||C){const g=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:g,timestamp:h,attachments:r.map(E=>({type:"image",url:E.base64}))};u(E=>[...E,b]),C&&d("processing_image"),e.sendConversationMessage(g,r.map(E=>E.base64)),n.current&&(n.current.value=""),r.forEach(E=>URL.revokeObjectURL(E.preview)),o([])}},A=S=>{S.key==="Enter"&&(S.preventDefault(),I())},M=[...t,...c];return R("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:[R("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:M.map((S,C)=>R(q_,{item:S,containerRef:s},S.id+C))}),r.length>0&&R("div",{className:"flex flex-wrap gap-2 mb-2",children:r.map(S=>R("div",{className:"relative",children:[R("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),R("button",{onClick:()=>v(S.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:R(nr,{className:"w-3 h-3"})})]},S.id))}),R("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:[R("input",{ref:n,type:"text",onKeyDown:A,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),R("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:y,className:"hidden"}),R(kt,{tooltip:"Attach image",onClick:_,children:R(C_,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Take photo",onClick:T,children:R(Jd,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Send",children:R(x_,{onClick:I,className:"text-[#969696] w-4 h-4"})})]}),a&&R(U_,{onCapture:x,onClose:()=>l(!1)})]})};function X_({onCollapse:t}){return R("div",{className:"flex items-center justify-between w-full",children:[R(L_,{}),R(kt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:R(nr,{className:"text-black dark:text-white"})})]})}const Y_=({call:t,onCollapse:e,transcript:n,chatMode:i,debug:s=!1})=>R(ag,{children:R(vn.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:[R("div",{className:"p-4 text-center",children:[R(X_,{onCollapse:e}),!i&&R(zd,{className:"h-[144px]",stream:t.remoteStream}),R(Cd,{size:"large",className:"mb-4"}),R(eu,{call:t,chatMode:i}),R(Kd,{className:"mt-2",debug:s})]}),R(Td,{stream:t.remoteStream,chatMode:i}),R(K_,{call:t,transcript:n})]})});function Zi(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function F(t,e,n,i){return new(n||(n=Promise))(function(s,r){function o(c){try{l(i.next(c))}catch(u){r(u)}}function a(c){try{l(i.throw(c))}catch(u){r(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof n?u:new n(function(d){d(u)})).then(o,a)}l((i=i.apply(t,[])).next())})}var lu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),J_=new Uint8Array(16);function Z_(){if(!lu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return lu(J_)}for(var cu=[],Qi=0;Qi<256;++Qi)cu[Qi]=(Qi+256).toString(16).substr(1);function wn(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||Z_)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var r=0;r<16;++r)e[i+r]=s[r];return e||function(o,a){var l=0,c=cu;return[c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]]].join("")}(s)}const Q_={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,NETWORK_OFFLINE:48001,UNEXPECTED_ERROR:49001},ey={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,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,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001},{SDP_CREATE_OFFER_FAILED:ty,SDP_CREATE_ANSWER_FAILED:ny,SDP_SET_LOCAL_DESCRIPTION_FAILED:iy,SDP_SET_REMOTE_DESCRIPTION_FAILED:du,SDP_SEND_FAILED:uu,MEDIA_MICROPHONE_PERMISSION_DENIED:sy,MEDIA_DEVICE_NOT_FOUND:oy,MEDIA_GET_USER_MEDIA_FAILED:hu,HOLD_FAILED:ry,INVALID_CALL_PARAMETERS:ay,BYE_SEND_FAILED:ly,SUBSCRIBE_FAILED:cy,PEER_CLOSED_DURING_INIT:sr,WEBSOCKET_CONNECTION_FAILED:dy,WEBSOCKET_ERROR:uy,RECONNECTION_EXHAUSTED:hy,GATEWAY_FAILED:fy,LOGIN_FAILED:fu,INVALID_CREDENTIALS:py,AUTHENTICATION_REQUIRED:gy,NETWORK_OFFLINE:my,UNEXPECTED_ERROR:pu}=Q_,{HIGH_RTT:vy,HIGH_JITTER:_y,HIGH_PACKET_LOSS:yy,LOW_MOS:gu,LOW_BYTES_RECEIVED:by,LOW_BYTES_SENT:wy,ICE_CONNECTIVITY_LOST:Sy,ICE_GATHERING_TIMEOUT:Cy,ICE_GATHERING_EMPTY:Ty,PEER_CONNECTION_FAILED:ky,ONLY_HOST_ICE_CANDIDATES:xy,ANSWER_WHILE_PEER_ACTIVE:Ey,TOKEN_EXPIRING_SOON:Iy,SESSION_NOT_REATTACHED:Ay}=ey,Ry=/^a=candidate:.+typ (srflx|prflx|relay)/m,mu="wss://rtc.telnyx.com",Ly=1006,vu={urls:"stun:stun.l.google.com:19302"},Py=[{urls:"stun:stun.telnyx.com:3478"},vu,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Dy=[{urls:"stun:stundev.telnyx.com:3478"},vu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var O;(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.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"})(O||(O={}));const My={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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED or FAIL_WAIT 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"]},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"]},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)"]},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"]},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"]},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"]}},Ny={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"]},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"]},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 but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",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"]},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"]},35001:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server returned an empty reattached_sessions list while the SDK still has an active call. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST.",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"]}};function xt(t,e){const n=Ny[t];return{code:t,name:n.name,message:n.message,description:n.description,causes:[...n.causes],solutions:[...n.solutions]}}class ii 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,Object.setPrototypeOf(this,ii.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function si(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return sy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return oy}return hu}function oe(t,e,n){const i=My[t],s=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new ii({code:t,name:i.name,description:i.description,message:n||i.message,causes:[...i.causes],solutions:[...i.solutions],originalError:s})}var Oy=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function _u(t,e){return t(e={exports:{}},e.exports),e.exports}var Fy=_u(function(t){var e,n;e=Oy,n=function(){var i=function(){},s="undefined",r=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function a(w,_){var T=w[_];if(typeof T.bind=="function")return T.bind(w);try{return Function.prototype.bind.call(T,w)}catch{return function(){return Function.prototype.apply.apply(T,[w,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(w,_){for(var T=0;T<o.length;T++){var x=o[T];this[x]=T<w?i:this.methodFactory(x,w,_)}this.log=this.debug}function u(w,_,T){return function(){typeof console!==s&&(c.call(this,_,T),this[w].apply(this,arguments))}}function d(w,_,T){return function(x){return x==="debug"&&(x="log"),typeof console!==s&&(x==="trace"&&r?l:console[x]!==void 0?a(console,x):console.log!==void 0?a(console,"log"):i)}(w)||u.apply(this,arguments)}function f(w,_,T){var x,I=this;_=_??"WARN";var A="loglevel";function M(){var C;if(typeof window!==s&&A){try{C=window.localStorage[A]}catch{}if(typeof C===s)try{var p=window.document.cookie,g=p.indexOf(encodeURIComponent(A)+"=");g!==-1&&(C=/^([^;]+)/.exec(p.slice(g))[1])}catch{}return I.levels[C]===void 0&&(C=void 0),C}}typeof w=="string"?A+=":"+w:typeof w=="symbol"&&(A=void 0),I.name=w,I.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},I.methodFactory=T||d,I.getLevel=function(){return x},I.setLevel=function(C,p){if(typeof C=="string"&&I.levels[C.toUpperCase()]!==void 0&&(C=I.levels[C.toUpperCase()]),!(typeof C=="number"&&C>=0&&C<=I.levels.SILENT))throw"log.setLevel() called with invalid level: "+C;if(x=C,p!==!1&&function(g){var h=(o[g]||"silent").toUpperCase();if(typeof window!==s&&A){try{return void(window.localStorage[A]=h)}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+h+";"}catch{}}}(C),c.call(I,C,w),typeof console===s&&C<I.levels.SILENT)return"No console available for logging"},I.setDefaultLevel=function(C){_=C,M()||I.setLevel(C,!1)},I.resetLevel=function(){I.setLevel(_,!1),function(){if(typeof window!==s&&A){try{return void window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},I.enableAll=function(C){I.setLevel(I.levels.TRACE,C)},I.disableAll=function(C){I.setLevel(I.levels.SILENT,C)};var S=M();S==null&&(S=_),I.setLevel(S,!1)}var m=new f,v={};m.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var _=v[w];return _||(_=v[w]=new f(w,m.getLevel(),m.methodFactory)),_};var y=typeof window!==s?window.log:void 0;return m.noConflict=function(){return typeof window!==s&&window.log===m&&(window.log=y),m},m.getLoggers=function(){return v},m.default=m,m},t.exports?t.exports=n():e.log=n()});const yu={debug:0,info:1,warn:2,error:3};class Vy{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||yu[e]<yu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let bu=null;const k=Fy.getLogger("telnyx"),es={trace:0,debug:1,info:2,warn:3,error:4};let wu=es.info;function Su(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const By=k.methodFactory;k.methodFactory=(t,e,n)=>{const i=By(t,e,n);return function(...s){if(es[t]>=wu){const o=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)o.push(a);i(...o)}const r=bu;if(r!=null&&r.isActive()){const[o,...a]=s,l=typeof o=="string"?o:JSON.stringify(o);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Su(a[0]):{args:a.map(Su)}),r.addEntry(t,l,c)}}},k.setLevel("debug",!1);const ts=t=>{const[e,n,i,s,r,o]=t;let a={};try{a=JSON.parse(r.replace(/ID"/g,'Id"'))}catch{k.warn("Verto LA invalid media JSON string:",r)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:o}},Cu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Sn=t=>t instanceof Function||typeof t=="function",ns=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Uy=/^(ws|wss):\/\//,Tu=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:r=null,node_id:o=null,result:a=null}=s;return r&&r!=="200"?{error:s}:a?Tu(a,o):{result:s}},ku=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),is=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),oi=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,or=t=>{var e,n,i,s,r,o;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((r=t==null?void 0:t.params)===null||r===void 0)&&r.state&&(l=(o=t==null?void 0:t.params)===null||o===void 0?void 0:o.state),a||l};function xu({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?jy(i,t):i,n=s}),resolve:e,reject:n}}const jy=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},rr="telnyx-voice-sdk-id";function Yt(){return sessionStorage.getItem(rr)}function Eu(){sessionStorage.removeItem(rr)}var De,pt,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{Eu()}),function(t){t.Offer="offer",t.Answer="answer"}(De||(De={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(pt||(pt={})),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"}(te||(te={}));const et={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},$y={invalidCredentialsOptions:"InvalidCredentialsOptions"},Hy={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 z,ar,ze,gt,Ue;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(ar||(ar={})),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"}(ze||(ze={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(gt||(gt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Ue||(Ue={}));const Cn="GLOBAL",He={},ri=(t,e)=>`${t}|${e}`,Iu=(t,e=Cn)=>ri(t,e)in He,Dt=(t,e,n=Cn)=>{const i=ri(t,n);i in He||(He[i]=[]),He[i].push(e)},Au=(t,e,n=Cn)=>{const i=function(s){Mt(t,i,n),e(s)};return i.prototype.targetRef=e,Dt(t,i,n)},Mt=(t,e,n=Cn)=>{if(!Iu(t,n))return!1;const i=ri(t,n);if(Sn(e))for(let s=He[i].length-1;s>=0;s--){const r=He[i][s];(e===r||r.prototype&&e===r.prototype.targetRef)&&He[i].splice(s,1)}else He[i]=[];return He[i].length===0&&delete He[i],!0},B=(t,e,n=Cn,i=!0)=>{const s=i&&n!==Cn;if(!Iu(t,n))return s&&B(t,e),!1;const r=ri(t,n),o=He[r].length;if(!o)return s&&B(t,e),!1;for(let a=o-1;a>=0;a--)He[r][a](e);return s&&B(t,e),!0},lr=t=>{const e=ri(t,"");Object.keys(He).filter(n=>n.indexOf(e)===0).forEach(n=>delete He[n])};let Gy=typeof WebSocket<"u"?WebSocket:null;const Wy=0,zy=1,qy=2,Ru=3;class Lu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=mu,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":mu),n&&(this._host=(o=>`${Uy.test(o)?"":"wss://"}${o}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),r&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===zy}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Wy}get closing(){return!!this._wsClient&&this._wsClient.readyState===qy}get closed(){return!!this._wsClient&&this._wsClient.readyState===Ru}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=Yt();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),k.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true");try{this._wsClient=new Gy(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){k.error("WebSocket connection failed:",i);const s=oe(dy,i);B(O.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((r,o)=>{if(i.hasOwnProperty("result"))return r();Au(i.id,a=>{const{result:l,error:c}=Tu(a);return c?o(c):r(l)})});return k.debug(`SEND:
111
+ */const nr=Be("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Qd=ki(!1),Ly=()=>Aa(Qd),kt=({children:t,className:e,onClick:n,tooltip:i})=>R("button",{title:i,onClick:n,className:Ct("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),eu=({call:t,chatMode:e})=>{const[n,i]=Ly(),s=()=>{i(o=>{const a=!o;return a?t.muteAudio():t.unmuteAudio(),a})},r=()=>{t.hangup()};return R("div",{className:"flex items-center justify-center gap-2",children:[!e&&R(kt,{tooltip:n?"Unmute":"Mute",onClick:s,className:Ct(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?R(Sy,{className:"w-5 h-5 text-black dark:text-white"}):R(Cy,{className:"w-5 h-5 text-black dark:text-white"})}),R(kt,{tooltip:"End Call",onClick:r,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:R(ky,{className:"w-4 h-4 text-black dark:text-white"})})]})},tu=({call:t,onExpand:e,chatMode:n,debug:i=!1})=>R(vn.div,{layoutId:ei,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!n&&R(zd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),R(Td,{stream:t.remoteStream,chatMode:n}),R(Cd,{size:"small"}),R(eu,{call:t,chatMode:n}),R(Kd,{debug:i})]});function Py(){const[t,e]=Ee(!1),n=Xt();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},r=()=>{i(n.report_issue_url)},o=()=>{i(n.view_history_url)};return R("div",{children:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Zd,{className:"text-black dark:text-white"})}),t&&R("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:[R(kt,{tooltip:"More",onClick:()=>e(!t),children:R(Zd,{className:"text-black dark:text-white"})}),R("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&R("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",R(Ay,{className:"w-4 h-4"})]}),n.report_issue_url&&R("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",R(Ry,{className:"w-4 h-4"})]}),n.view_history_url&&R("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",R(by,{className:"w-4 h-4"})]})]})]})]})}function Dy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ji={exports:{}},My=Ji.exports,nu;function Ny(){return nu||(nu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(My,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,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===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function m(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),P=b.indexOf(E+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var g=S();g!=null&&(I=p(g)),u.call(y)}o=new m,o.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=r[w];return y||(y=r[w]=new m(w,o.methodFactory)),y};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(Ji)),Ji.exports}var Oy=Ny();const Fy=Dy(Oy),Vy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),By="[ai-agent-widget]",ae=Fy.getLogger("telnyx-ai-agent-widget"),Uy=ae.methodFactory;ae.methodFactory=(t,e,n)=>{const i=Uy(t,e,n);return function(...s){i(Vy(),By,...s)}},ae.setLevel("info");function jy({onCapture:t,onClose:e}){const n=de(null),i=de(null),s=de(null),[r,o]=Ee(null),[a,l]=Ee(!0);Ae(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){ae.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?o("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?o("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?o("Camera is already in use by another application."):o("Unable to access camera. Please try again."):o("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const d=n.current,f=i.current,m=f.getContext("2d");if(!m)return;f.width=d.videoWidth,f.height=d.videoHeight,m.drawImage(d,0,0,f.width,f.height);const v=f.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 R("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:[R("div",{className:"absolute top-2 right-2 z-10",children:R(kt,{tooltip:"Close",onClick:u,children:R(nr,{className:"text-white w-5 h-5"})})}),R("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!r&&R("div",{className:"absolute text-white text-center",children:R("p",{className:"text-sm",children:"Loading camera..."})}),r&&R("div",{className:"text-white text-center max-w-xs",children:[R("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),R("p",{className:"text-xs",children:r}),R("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"})]}),!r&&R(lt,{children:[R("video",{ref:n,autoPlay:!0,playsInline:!0,className:Ct("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),R("canvas",{ref:i,className:"hidden"})]})]}),!r&&!a&&R("div",{className:"p-3 flex justify-center",children:R("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:[R(Jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const ir=["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"],$y=["audio","lang","mark","p","s","sub","w"],iu=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function su(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`</?(?:${n})(?:\\s+[^<>]*)?\\s*/?>`,e)}function ou(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`<\\/?(?:${n})(?:\\s+[^<>]*)?$`,e)}const ru=ir.filter(t=>!$y.includes(t)),Hy=su(ir,"gi"),au=su(ru,"gi"),Gy=ou(ir,"i"),Wy=ou(ru,"i"),zy=new RegExp(`${au.source}|${iu.source}`,"i");function qy(t){const e=zy.test(t),n=e?Hy:au,i=e?Gy:Wy;return t.replace(n,"").replace(i,"").replace(iu,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function Ky({item:t,containerRef:e}){const n=de(null),i=t.role==="assistant"?qy(t.content):t.content;return Ae(()=>{var s;n.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),R("li",{className:Ct("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[R("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),R("div",{className:Ct("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&R("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,r)=>s.type==="image"&&R("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},r))}),i&&R("p",{className:Ct("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:i})]})]})}const Xy=({transcript:t,call:e})=>{const n=de(null),i=de(null),s=de(null),[r,o]=Ee([]),[a,l]=Ee(!1),[c,u]=Ee([]),[,d]=Xo();Ae(()=>()=>{r.forEach(S=>URL.revokeObjectURL(S.preview))},[r]),Ae(()=>{if(c.length===0)return;const S=t.filter(C=>C.role==="user"&&!C.id.startsWith("optimistic-"));if(S.length>0){const C=S[S.length-1];u(p=>p.filter(g=>g.timestamp>C.timestamp))}},[t,c]);const f=S=>new Promise((C,p)=>{const g=new FileReader;g.onload=()=>C(g.result),g.onerror=p,g.readAsDataURL(S)}),m=async S=>{if(S.type.startsWith("image/"))try{const C=await f(S),p=URL.createObjectURL(S),g={id:Date.now().toString(),file:S,base64:C,preview:p};o(h=>[...h,g])}catch(C){ae.error("Error processing image:",C)}},v=S=>{o(C=>{const p=C.find(g=>g.id===S);return p&&URL.revokeObjectURL(p.preview),C.filter(g=>g.id!==S)})},_=S=>{const C=S.target,p=C.files;p&&p.length>0&&(Array.from(p).forEach(m),C.value="")},w=S=>{var p;const C=(p=S.clipboardData)==null?void 0:p.items;C&&Array.from(C).forEach(g=>{if(g.type.startsWith("image/")){const h=g.getAsFile();h&&m(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},T=()=>{l(!0)},x=S=>{fetch(S).then(C=>C.blob()).then(C=>{const p=new File([C],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});m(p)}).catch(C=>{ae.error("Error processing camera capture:",C)})},I=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",C=r.length>0;if(S||C){const g=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:g,timestamp:h,attachments:r.map(E=>({type:"image",url:E.base64}))};u(E=>[...E,b]),C&&d("processing_image"),e.sendConversationMessage(g,r.map(E=>E.base64)),n.current&&(n.current.value=""),r.forEach(E=>URL.revokeObjectURL(E.preview)),o([])}},A=S=>{S.key==="Enter"&&(S.preventDefault(),I())},M=[...t,...c];return R("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:[R("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:M.map((S,C)=>R(Ky,{item:S,containerRef:s},S.id+C))}),r.length>0&&R("div",{className:"flex flex-wrap gap-2 mb-2",children:r.map(S=>R("div",{className:"relative",children:[R("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),R("button",{onClick:()=>v(S.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:R(nr,{className:"w-3 h-3"})})]},S.id))}),R("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:[R("input",{ref:n,type:"text",onKeyDown:A,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),R("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:_,className:"hidden"}),R(kt,{tooltip:"Attach image",onClick:y,children:R(Ty,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Take photo",onClick:T,children:R(Jd,{className:"text-[#969696] w-4 h-4"})}),R(kt,{tooltip:"Send",children:R(Ey,{onClick:I,className:"text-[#969696] w-4 h-4"})})]}),a&&R(jy,{onCapture:x,onClose:()=>l(!1)})]})};function Yy({onCollapse:t}){return R("div",{className:"flex items-center justify-between w-full",children:[R(Py,{}),R(kt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:R(nr,{className:"text-black dark:text-white"})})]})}const Jy=({call:t,onCollapse:e,transcript:n,chatMode:i,debug:s=!1})=>R(lg,{children:R(vn.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:[R("div",{className:"p-4 text-center",children:[R(Yy,{onCollapse:e}),!i&&R(zd,{className:"h-[144px]",stream:t.remoteStream}),R(Cd,{size:"large",className:"mb-4"}),R(eu,{call:t,chatMode:i}),R(Kd,{className:"mt-2",debug:s})]}),R(Td,{stream:t.remoteStream,chatMode:i}),R(Xy,{call:t,transcript:n})]})});function Zi(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function V(t,e,n,i){return new(n||(n=Promise))(function(s,r){function o(c){try{l(i.next(c))}catch(u){r(u)}}function a(c){try{l(i.throw(c))}catch(u){r(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof n?u:new n(function(d){d(u)})).then(o,a)}l((i=i.apply(t,[])).next())})}var lu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Zy=new Uint8Array(16);function Qy(){if(!lu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return lu(Zy)}for(var cu=[],Qi=0;Qi<256;++Qi)cu[Qi]=(Qi+256).toString(16).substr(1);function wn(t,e,n){var i=e&&n||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||Qy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var r=0;r<16;++r)e[i+r]=s[r];return e||function(o,a){var l=0,c=cu;return[c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],"-",c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]],c[o[l++]]].join("")}(s)}const e_={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,NETWORK_OFFLINE:48001,UNEXPECTED_ERROR:49001},t_={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,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,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001},{SDP_CREATE_OFFER_FAILED:n_,SDP_CREATE_ANSWER_FAILED:i_,SDP_SET_LOCAL_DESCRIPTION_FAILED:s_,SDP_SET_REMOTE_DESCRIPTION_FAILED:du,SDP_SEND_FAILED:uu,MEDIA_MICROPHONE_PERMISSION_DENIED:o_,MEDIA_DEVICE_NOT_FOUND:r_,MEDIA_GET_USER_MEDIA_FAILED:hu,HOLD_FAILED:a_,INVALID_CALL_PARAMETERS:l_,BYE_SEND_FAILED:c_,SUBSCRIBE_FAILED:d_,PEER_CLOSED_DURING_INIT:sr,WEBSOCKET_CONNECTION_FAILED:u_,WEBSOCKET_ERROR:h_,RECONNECTION_EXHAUSTED:f_,GATEWAY_FAILED:p_,LOGIN_FAILED:fu,INVALID_CREDENTIALS:g_,AUTHENTICATION_REQUIRED:m_,NETWORK_OFFLINE:v_,UNEXPECTED_ERROR:pu}=e_,{HIGH_RTT:y_,HIGH_JITTER:__,HIGH_PACKET_LOSS:b_,LOW_MOS:gu,LOW_BYTES_RECEIVED:w_,LOW_BYTES_SENT:S_,ICE_CONNECTIVITY_LOST:C_,ICE_GATHERING_TIMEOUT:T_,ICE_GATHERING_EMPTY:k_,PEER_CONNECTION_FAILED:x_,ONLY_HOST_ICE_CANDIDATES:E_,ANSWER_WHILE_PEER_ACTIVE:I_,TOKEN_EXPIRING_SOON:A_,SESSION_NOT_REATTACHED:R_}=t_,L_=/^a=candidate:.+typ (srflx|prflx|relay)/m,mu="wss://rtc.telnyx.com",P_=1006,vu={urls:"stun:stun.l.google.com:19302"},D_=[{urls:"stun:stun.telnyx.com:3478"},vu,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],M_=[{urls:"stun:stundev.telnyx.com:3478"},vu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var O;(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.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"})(O||(O={}));const N_={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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},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"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED or FAIL_WAIT 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"]},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"]},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)"]},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"]},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"]},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"]}},O_={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"]},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"]},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 but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",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"]},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"]},35001:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server returned an empty reattached_sessions list while the SDK still has an active call. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST.",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"]}};function xt(t,e){const n=O_[t];return{code:t,name:n.name,message:n.message,description:n.description,causes:[...n.causes],solutions:[...n.solutions]}}class ii 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,Object.setPrototypeOf(this,ii.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function si(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return o_;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return r_}return hu}function oe(t,e,n){const i=N_[t],s=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new ii({code:t,name:i.name,description:i.description,message:n||i.message,causes:[...i.causes],solutions:[...i.solutions],originalError:s})}var F_=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function yu(t,e){return t(e={exports:{}},e.exports),e.exports}var V_=yu(function(t){var e,n;e=F_,n=function(){var i=function(){},s="undefined",r=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),o=["trace","debug","info","warn","error"];function a(w,y){var T=w[y];if(typeof T.bind=="function")return T.bind(w);try{return Function.prototype.bind.call(T,w)}catch{return function(){return Function.prototype.apply.apply(T,[w,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(w,y){for(var T=0;T<o.length;T++){var x=o[T];this[x]=T<w?i:this.methodFactory(x,w,y)}this.log=this.debug}function u(w,y,T){return function(){typeof console!==s&&(c.call(this,y,T),this[w].apply(this,arguments))}}function d(w,y,T){return function(x){return x==="debug"&&(x="log"),typeof console!==s&&(x==="trace"&&r?l:console[x]!==void 0?a(console,x):console.log!==void 0?a(console,"log"):i)}(w)||u.apply(this,arguments)}function f(w,y,T){var x,I=this;y=y??"WARN";var A="loglevel";function M(){var C;if(typeof window!==s&&A){try{C=window.localStorage[A]}catch{}if(typeof C===s)try{var p=window.document.cookie,g=p.indexOf(encodeURIComponent(A)+"=");g!==-1&&(C=/^([^;]+)/.exec(p.slice(g))[1])}catch{}return I.levels[C]===void 0&&(C=void 0),C}}typeof w=="string"?A+=":"+w:typeof w=="symbol"&&(A=void 0),I.name=w,I.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},I.methodFactory=T||d,I.getLevel=function(){return x},I.setLevel=function(C,p){if(typeof C=="string"&&I.levels[C.toUpperCase()]!==void 0&&(C=I.levels[C.toUpperCase()]),!(typeof C=="number"&&C>=0&&C<=I.levels.SILENT))throw"log.setLevel() called with invalid level: "+C;if(x=C,p!==!1&&function(g){var h=(o[g]||"silent").toUpperCase();if(typeof window!==s&&A){try{return void(window.localStorage[A]=h)}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+h+";"}catch{}}}(C),c.call(I,C,w),typeof console===s&&C<I.levels.SILENT)return"No console available for logging"},I.setDefaultLevel=function(C){y=C,M()||I.setLevel(C,!1)},I.resetLevel=function(){I.setLevel(y,!1),function(){if(typeof window!==s&&A){try{return void window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},I.enableAll=function(C){I.setLevel(I.levels.TRACE,C)},I.disableAll=function(C){I.setLevel(I.levels.SILENT,C)};var S=M();S==null&&(S=y),I.setLevel(S,!1)}var m=new f,v={};m.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=v[w];return y||(y=v[w]=new f(w,m.getLevel(),m.methodFactory)),y};var _=typeof window!==s?window.log:void 0;return m.noConflict=function(){return typeof window!==s&&window.log===m&&(window.log=_),m},m.getLoggers=function(){return v},m.default=m,m},t.exports?t.exports=n():e.log=n()});const _u={debug:0,info:1,warn:2,error:3};class B_{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||_u[e]<_u[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let bu=null;const k=V_.getLogger("telnyx"),es={trace:0,debug:1,info:2,warn:3,error:4};let wu=es.info;function Su(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const U_=k.methodFactory;k.methodFactory=(t,e,n)=>{const i=U_(t,e,n);return function(...s){if(es[t]>=wu){const o=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)o.push(a);i(...o)}const r=bu;if(r!=null&&r.isActive()){const[o,...a]=s,l=typeof o=="string"?o:JSON.stringify(o);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Su(a[0]):{args:a.map(Su)}),r.addEntry(t,l,c)}}},k.setLevel("debug",!1);const ts=t=>{const[e,n,i,s,r,o]=t;let a={};try{a=JSON.parse(r.replace(/ID"/g,'Id"'))}catch{k.warn("Verto LA invalid media JSON string:",r)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:o}},Cu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Sn=t=>t instanceof Function||typeof t=="function",ns=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,j_=/^(ws|wss):\/\//,Tu=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:r=null,node_id:o=null,result:a=null}=s;return r&&r!=="200"?{error:s}:a?Tu(a,o):{result:s}},ku=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),is=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),oi=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,or=t=>{var e,n,i,s,r,o;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((r=t==null?void 0:t.params)===null||r===void 0)&&r.state&&(l=(o=t==null?void 0:t.params)===null||o===void 0?void 0:o.state),a||l};function xu({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?$_(i,t):i,n=s}),resolve:e,reject:n}}const $_=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},rr="telnyx-voice-sdk-id";function Yt(){return sessionStorage.getItem(rr)}function Eu(){sessionStorage.removeItem(rr)}var De,pt,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{Eu()}),function(t){t.Offer="offer",t.Answer="answer"}(De||(De={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(pt||(pt={})),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"}(te||(te={}));const et={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},H_={invalidCredentialsOptions:"InvalidCredentialsOptions"},G_={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 q,ar,ze,gt,Ue;(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"})(q||(q={})),function(t){t.Participant="participant",t.Moderator="moderator"}(ar||(ar={})),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"}(ze||(ze={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(gt||(gt={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(Ue||(Ue={}));const Cn="GLOBAL",He={},ri=(t,e)=>`${t}|${e}`,Iu=(t,e=Cn)=>ri(t,e)in He,Nt=(t,e,n=Cn)=>{const i=ri(t,n);i in He||(He[i]=[]),He[i].push(e)},Au=(t,e,n=Cn)=>{const i=function(s){Ot(t,i,n),e(s)};return i.prototype.targetRef=e,Nt(t,i,n)},Ot=(t,e,n=Cn)=>{if(!Iu(t,n))return!1;const i=ri(t,n);if(Sn(e))for(let s=He[i].length-1;s>=0;s--){const r=He[i][s];(e===r||r.prototype&&e===r.prototype.targetRef)&&He[i].splice(s,1)}else He[i]=[];return He[i].length===0&&delete He[i],!0},U=(t,e,n=Cn,i=!0)=>{const s=i&&n!==Cn;if(!Iu(t,n))return s&&U(t,e),!1;const r=ri(t,n),o=He[r].length;if(!o)return s&&U(t,e),!1;for(let a=o-1;a>=0;a--)He[r][a](e);return s&&U(t,e),!0},lr=t=>{const e=ri(t,"");Object.keys(He).filter(n=>n.indexOf(e)===0).forEach(n=>delete He[n])};let W_=typeof WebSocket<"u"?WebSocket:null;const z_=0,q_=1,K_=2,Ru=3;class Lu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=mu,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:r}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":mu),n&&(this._host=(o=>`${j_.test(o)?"":"wss://"}${o}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),r&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===q_}get connecting(){return!!this._wsClient&&this._wsClient.readyState===z_}get closing(){return!!this._wsClient&&this._wsClient.readyState===K_}get closed(){return!!this._wsClient&&this._wsClient.readyState===Ru}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=Yt();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),k.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true");try{this._wsClient=new W_(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){k.error("WebSocket connection failed:",i);const s=oe(u_,i);U(O.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((r,o)=>{if(i.hasOwnProperty("result"))return r();Au(i.id,a=>{const{result:l,error:c}=Tu(a);return c?o(c):r(l)})});return k.debug(`SEND:
112
112
  `,JSON.stringify(i,null,2),`
113
- `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;Sn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>B(O.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),B(O.SocketClose,n,this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=oe(uy);return B(O.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),B(O.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=n=>{var i,s;const r=Cu(n.data);var o;if(typeof r!="string"){if(r.voice_sdk_id&&(o=r.voice_sdk_id,sessionStorage.setItem(rr,o)),this._unsetTimer(r.id),k.debug(`RECV:
113
+ `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;Sn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>U(O.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),U(O.SocketClose,n,this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=oe(h_);return U(O.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),U(O.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=n=>{var i,s;const r=Cu(n.data);var o;if(typeof r!="string"){if(r.voice_sdk_id&&(o=r.voice_sdk_id,sessionStorage.setItem(rr,o)),this._unsetTimer(r.id),k.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Ue[`${(s=(i=r==null?void 0:r.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!B(r.id,r)){const a=or(r);B(O.SocketMessage,r,this.session.uuid),a&&(this.previousGatewayState=a)}}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!==Ru?(k.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||B(O.SocketClose,{code:Ly,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):k.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(k.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(k.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):k.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_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)),B(O.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else k.warn("Unknown message from socket",e)}}class ai{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:wn()},e)}}const Pu={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 Fe extends ai{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Zi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in Pu)i&&n.hasOwnProperty(i)&&(n[Pu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class Du extends Fe{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ky{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>F(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(or(n))}),this.getIsRegistered=()=>F(this,void 0,void 0,function*(){const n=new Du(Yt());this.pendingRequestId=n.request.id,this.gatewayStateTask=xu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ue.REGISTER,Ue.REGED].includes(i)}),this.session=e,this.gatewayStateTask=xu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Mu extends Fe{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var Nu="2.26.4",cr=Nu;class Xy extends Fe{constructor(e,n,i,s,r={},o){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:r,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:cr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class Yy extends Fe{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Ou extends Fe{toString(){return te.Invite}}class Fu extends Fe{toString(){return te.Answer}}class Vu extends Fe{toString(){return te.Attach}}class Jy extends Fe{toString(){return te.Bye}}class Zy extends Fe{toString(){return te.Candidate}}class Qy extends Fe{toString(){return te.EndOfCandidates}}class dr extends Fe{toString(){return te.Modify}}class Bu extends Fe{toString(){return te.Info}}class e0 extends Fe{toString(){return te.Broadcast}}class t0 extends Fe{toString(){return te.Subscribe}}class n0 extends Fe{toString(){return te.Unsubscribe}}class i0 extends Fe{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:r,userVariables:o,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:l,"User-Agent":{sdkVersion:cr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),r&&(c.target_params=r),this.buildRequest({method:this.method,params:c})}}class li{constructor(e){if(this.options=e,this.uuid=wn(),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.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._tokenExpiryTimeout=null,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",wu=(i=es[n])!==null&&i!==void 0?i:es.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new Lu(this),this.registerAgent=new Ky(this)}get __logger(){return k}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return F(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*ku(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e).catch(n=>F(this,void 0,void 0,function*(){if((n==null?void 0:n.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const i=oe(gy,n);B(O.Error,{error:i,sessionId:this.sessionid},this.uuid)}yield this.login()}throw n})):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),k.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return is(this.options)||oi(this.options)}broadcast(e){}disconnect(){return F(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),k.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Dt(e,n,this.uuid),this}off(e,n){return Mt(e,n,this.uuid),this}connect(){return F(this,void 0,void 0,function*(){this.connection||(k.debug("No existing connection found, creating a new one."),this.connection=new Lu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(k.debug("Initiating connection to the server..."),this.connection.connect()),k.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){const n=oe(fu,e);B(O.Error,{error:n,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Eu()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const n=e.split(".");if(n.length!==3)return;const i=JSON.parse(atob(n[1])).exp;if(typeof i!="number")return;const s=i-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=li.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const r=1e3*(s-li.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},r)}}catch{k.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=xt(Iy);B(O.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:n,onError:i}={}){return F(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)),is(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(oi(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";k.error(s);const r=oe(py,void 0,s);return void B(O.Error,{error:r,type:$y.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return F(this,void 0,void 0,function*(){let s;s=e==="login"?new Xy(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Yt()):new i0({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:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Yt()});const r=yield this.execute(s).catch(o=>{this._handleLoginError(o),i&&i(o)});r&&(this.sessionid=r.sessid,this._checkTokenExpiry(),n&&n())})}_onSocketOpen(){return F(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&lr(this.relayProtocol);for(const e in this.subscriptions)lr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{k.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Mt(e,null,n)):(delete this.subscriptions[e],lr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Sn(n)&&Dt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(O.SocketOpen,this._onSocketOpen),this.on(O.SocketClose,this.onNetworkClose),this.on(O.SocketError,this.onNetworkClose),this.on(O.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(O.SocketOpen,this._onSocketOpen),this.off(O.SocketClose,this.onNetworkClose),this.off(O.SocketError,this.onNetworkClose),this.off(O.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(k.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Mu(Yt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){k.debug("Ping received"),this._pong=!0}static on(e,n){Dt(e,n)}static off(e){Mt(e)}static uuid(){return wn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}li.TOKEN_EXPIRY_WARNING_SECONDS=120;const ss=t=>navigator.mediaDevices.getUserMedia(t),Tn=t=>t&&t instanceof MediaStream,ci=(t,e)=>{const n=ns(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},Uu=(t,e)=>F(void 0,void 0,void 0,function*(){const n=ns(t);if(n===null)return k.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return k.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),s0=t=>{t&&t.readyState==="live"&&t.stop()},di=t=>{Tn(t)&&t.getTracks().forEach(s0),t=null},os=t=>F(void 0,void 0,void 0,function*(){k.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield ss(t)}catch(i){if(k.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(r=>{const{audio:o,video:a}=r;let l=!1,c=o,u=a;if(typeof o=="object"&&o!==null&&"deviceId"in o){l=!0;const d=Zi(o,["deviceId"]);c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Zi(a,["deviceId"]);u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){k.warn("Device not found or not readable, falling back to default device");try{return yield ss(s)}catch(r){throw k.error("Fallback getUserMedia also failed: ",r),i}}}throw i}}),ui=(t=null,e=!1)=>F(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===gt.AudioIn||s===gt.AudioOut,video:!s||s===gt.Video}))(t)).catch(s=>(k.error(s),null));if(i){if(di(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(r=>r.kind===t)),e===!0)return n;const s=[];n=n.filter(r=>{if(!r.groupId)return!0;const o=`${r.kind}-${r.groupId}`;return!s.includes(o)&&(s.push(o),!0)})}return n}),ju=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],rs=(t,e,n)=>F(void 0,void 0,void 0,function*(){const i=yield ui(n,!0);for(let s=0;s<i.length;s++){const{deviceId:r,label:o}=i[s];if(t===r||e===o)return r}return null}),o0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},ur=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=hr(t);return n.includes(e)||i.includes(e)},hr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},kn=(t,e=null,n=null)=>{if(!Tn(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},$u=t=>{kn(t,"audio",!0)},fr=t=>{kn(t,"audio",!1)},Hu=t=>{kn(t,"audio",null)},r0=t=>((e,n=null)=>{if(!Tn(e))return null;let i=[];switch(n){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some(s=>s.enabled)})(t,"audio");function a0(){try{const{browserInfo:t,name:e,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,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],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,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("/"),f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,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],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),r=window.RTCPeerConnection,o=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(r&&o&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!r,supportSessionDescription:!!o,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!os}}catch(t){return t.message}}var Se;function Gu(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Wu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{k.error("playAudio",e),t._playFulfilled=!0}))}function zu(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"})(Se||(Se={}));const qu=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class l0 extends ai{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:wn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class Te{constructor(e,n){var i;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=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._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new Vy(s)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,bu=i)}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,k.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return F(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),k.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,r=this.statsBuffer;this.statsBuffer=[];const o=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:r},o.length>0?{logs:o}:{}),{segment:s});return k.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:r.length,logEntries:o.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var r,o;return F(this,void 0,void 0,function*(){const a=(r=this.logCollector)===null||r===void 0?void 0:r.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void k.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void k.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:(o=this.callEndTime)===null||o===void 0?void 0:o.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,n,i,s)})}sendPayload(e,n,i,s){return F(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var r,o;return F(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";k.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(o=(r=e.logs)===null||r===void 0?void 0:r.length)!==null&&o!==void 0?o:0,callId:e.summary.callId,segment:e.segment});const u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:u,body:d}),m=yield f();if(m.ok)k.info(`CallReportCollector: Successfully posted ${c}`);else{const v=yield m.text();k.error(`CallReportCollector: Failed to post ${c}`,{status:m.status,error:v})}}catch(a){k.warn(`CallReportCollector: Network error posting call report, retrying in ${Te.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,Te.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=yield fetch(c,{method:"POST",headers:u,body:JSON.stringify(e)});if(d.ok)k.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield d.text();k.error("CallReportCollector: Failed to post call report on retry",{status:d.status,error:f})}}catch(l){k.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return F(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const r=yield this.peerConnection.getStats(),o=new Date;let a,l,c=null,u=null,d=null,f=null;if(r.forEach(v=>{switch(v.type){case"outbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(c=v);break;case"inbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(u=v);break;case"candidate-pair":(v.nominated||v.state==="succeeded")&&(d=v);break;case"transport":f=v}}),c){const v=this._getOutboundAudioLevel(r,c);if(v!==null&&this.intervalAudioLevels.outbound.push(v),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const y=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const _=8*y*1e3/w;this.intervalBitrates.outbound.push(_)}}this.previousStats.outboundBytes=c.bytesSent}if(u){const v=this._getInboundAudioLevel(r,u);if(v!==null&&this.intervalAudioLevels.inbound.push(v),u.jitter!==void 0&&this.intervalJitters.push(1e3*u.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const y=(u.bytesReceived||0)-this.previousStats.inboundBytes,w=(u.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const _=8*y*1e3/w;this.intervalBitrates.inbound.push(_)}}this.previousStats.inboundBytes=u.bytesReceived}d&&(d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),this.previousCandidatePairId!==null&&d.id!==this.previousCandidatePairId&&k.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:d.id}),this.previousCandidatePairId=(n=d.id)!==null&&n!==void 0?n:null),d&&(a=this._resolveCandidate(r,d.localCandidateId),l=this._resolveCandidate(r,d.remoteCandidateId)),this.previousStats.timestamp=o.getTime();const m=o.getTime()-this.intervalStartTime.getTime();if(e||m>=this.options.interval){const v=this._createStatsEntry(this.intervalStartTime,o,c,u,d,a,l,f);if(this.statsBuffer.push(v),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),k.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const y=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(y>=Te.STATS_FLUSH_THRESHOLD||w>=Te.LOGS_FLUSH_THRESHOLD){k.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:y,logEntries:w});try{this.onFlushNeeded()}catch(_){k.error("CallReportCollector: onFlushNeeded callback error",{error:_})}}}this._checkQualityWarnings(v,u),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(r){k.error("CallReportCollector: Error collecting stats",{error:r})}})}_checkQualityWarnings(e,n){var i,s,r,o,a,l,c,u,d,f,m,v,y,w,_,T,x;if(!this.onWarning)return;const I=(i=e.connection)===null||i===void 0?void 0:i.roundTripTimeAvg,A=(r=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||r===void 0?void 0:r.jitterAvg;let M;if(n){const S=(o=n.packetsReceived)!==null&&o!==void 0?o:0,C=(a=n.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const p=S-this._prevPacketsReceived,g=C-this._prevPacketsLost,h=p+g;h>0&&(M=g/h*100)}this._prevPacketsReceived=S,this._prevPacketsLost=C}if(this._trackBreach(vy,I!==void 0&&I>Te.THRESHOLD_RTT_MS),this._trackBreach(_y,A!==void 0&&A>Te.THRESHOLD_JITTER_MS),this._trackBreach(yy,M!==void 0&&M>Te.THRESHOLD_PACKET_LOSS_PCT),I!==void 0&&A!==void 0&&M!==void 0){const S=93.2-.11*A-2.5*M-.01*(1e3*I),C=Math.max(1,Math.min(4.5,1+.035*S+S*(S-60)*(100-S)*7e-6));this._trackBreach(gu,C<Te.THRESHOLD_MOS)}else this._trackBreach(gu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(f=(d=(u=S==null?void 0:S.audio)===null||u===void 0?void 0:u.inbound)===null||d===void 0?void 0:d.bytesReceived)!==null&&f!==void 0?f:0,p=(m=e.audio.inbound.bytesReceived)!==null&&m!==void 0?m:0;this._trackBreach(by,p-C==0)}if(((y=(v=e.audio)===null||v===void 0?void 0:v.outbound)===null||y===void 0?void 0:y.bytesSent)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(T=(_=(w=S==null?void 0:S.audio)===null||w===void 0?void 0:w.outbound)===null||_===void 0?void 0:_.bytesSent)!==null&&T!==void 0?T:0,p=(x=e.audio.outbound.bytesSent)!==null&&x!==void 0?x:0;this._trackBreach(wy,p-C==0)}}_trackBreach(e,n){var i,s,r;if(n){if(this._breachCounters[e]=((i=this._breachCounters[e])!==null&&i!==void 0?i:0)+1,this._breachCounters[e]>=Te.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();if(o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=Te.WARNING_THROTTLE_MS){this._lastWarningEmitted[e]=o;try{const a=xt(e);k.warn(`CallReportCollector: warning ${a.code}: ${a.message}`),(r=this.onWarning)===null||r===void 0||r.call(this,a)}catch(a){k.error(`CallReportCollector: Failed to emit warning ${e}`,{error:a})}}}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_createStatsEntry(e,n,i,s,r,o,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={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)}),r&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:r.packetsSent,packetsReceived:r.packetsReceived,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},c.ice=Object.assign(Object.assign({id:r.id,state:r.state,nominated:r.nominated,writable:r.writable,requestsSent:r.requestsSent,responsesReceived:r.responsesReceived},o?{local:o}:{}),a?{remote:a}:{})),l&&(c.transport=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}:{})),c}_resolveCandidate(e,n){if(!n)return void k.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void k.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;k.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",r=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",o=this.previousStats[s],a=this.previousStats[r];if(this.previousStats[s]=e,this.previousStats[r]=n,o===void 0||a===void 0)return null;const l=e-o,c=n-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}Te.STATS_FLUSH_THRESHOLD=300,Te.LOGS_FLUSH_THRESHOLD=800,Te.CONSECUTIVE_BREACHES_REQUIRED=3,Te.THRESHOLD_RTT_MS=.4,Te.THRESHOLD_JITTER_MS=30,Te.THRESHOLD_PACKET_LOSS_PCT=1,Te.THRESHOLD_MOS=3.5,Te.WARNING_THROTTLE_MS=15e3,Te.RETRY_DELAY_MS=500;var as,Ku=_u(function(t,e){var n;function i(){}function s(){s.init.call(this)}function r(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function o(p,g,h,b){var E,P,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=p._events)?(P.newListener&&(p.emit("newListener",g,h.listener?h.listener:h),P=p._events),L=P[g]):(P=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=P[g]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(E=r(p))&&0<E&&L.length>E){L.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+g+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=g,N.count=L.length,function(D){typeof console.warn=="function"?console.warn(D):console.log(D)}(N)}}else L=P[g]=h,++p._eventsCount;return p}function a(p,g,h){function b(){p.removeListener(g,b),E||(E=!0,h.apply(p,arguments))}var E=!1;return b.listener=h,b}function l(p){var g=this._events;if(g){var h=g[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,g){for(var h=Array(g);g--;)h[g]=p[g];return h}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(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 r(this)},s.prototype.emit=function(p){var g,h,b,E,P,L,N,D=p==="error";if(L=this._events)D=D&&L.error==null;else if(!D)return!1;if(N=this.domain,D){if(g=arguments[1],!N){if(g instanceof Error)throw g;var U=new Error('Uncaught, unspecified "error" event. ('+g+")");throw U.context=g,U}return g||(g=new Error('Uncaught, unspecified "error" event')),g.domainEmitter=this,g.domain=N,g.domainThrown=!1,N.emit("error",g),!1}if(!(h=L[p]))return!1;var Y=typeof h=="function";switch(b=arguments.length){case 1:(function(j,ae,ee){if(ae)j.call(ee);else for(var $=j.length,ue=c(j,$),K=0;K<$;++K)ue[K].call(ee)})(h,Y,this);break;case 2:(function(j,ae,ee,$){if(ae)j.call(ee,$);else for(var ue=j.length,K=c(j,ue),Z=0;Z<ue;++Z)K[Z].call(ee,$)})(h,Y,this,arguments[1]);break;case 3:(function(j,ae,ee,$,ue){if(ae)j.call(ee,$,ue);else for(var K=j.length,Z=c(j,K),Q=0;Q<K;++Q)Z[Q].call(ee,$,ue)})(h,Y,this,arguments[1],arguments[2]);break;case 4:(function(j,ae,ee,$,ue,K){if(ae)j.call(ee,$,ue,K);else for(var Z=j.length,Q=c(j,Z),ne=0;ne<Z;++ne)Q[ne].call(ee,$,ue,K)})(h,Y,this,arguments[1],arguments[2],arguments[3]);break;default:for(E=Array(b-1),P=1;P<b;P++)E[P-1]=arguments[P];(function(j,ae,ee,$){if(ae)j.apply(ee,$);else for(var ue=j.length,K=c(j,ue),Z=0;Z<ue;++Z)K[Z].apply(ee,$)})(h,Y,this,E)}return!0},s.prototype.addListener=function(p,g){return o(this,p,g,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,g){return o(this,p,g,!0)},s.prototype.once=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,g)),this},s.prototype.prependOnceListener=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,g)),this},s.prototype.removeListener=function(p,g){var h,b,E,P,L;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===g||h.listener&&h.listener===g)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||g));else if(typeof h!="function"){for(E=-1,P=h.length;0<P--;)if(h[P]===g||h[P].listener&&h[P].listener===g){L=h[P].listener,E=P;break}if(0>E)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(N,D){for(var U=D,Y=U+1,j=N.length;Y<j;U+=1,Y+=1)N[U]=N[Y];N.pop()})(h,E);b.removeListener&&this.emit("removeListener",p,L||g)}return this},s.prototype.removeAllListeners=function(p){var g,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,E=Object.keys(h),P=0;P<E.length;++P)(b=E[P])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(g=h[p])=="function")this.removeListener(p,g);else if(g)do this.removeListener(p,g[g.length-1]);while(g[0]);return this},s.prototype.listeners=function(p){var g,h,b=this._events;return b?h=(g=b[p])?typeof g=="function"?[g.listener||g]:function(E){for(var P=Array(E.length),L=0;L<P.length;++L)P[L]=E[L].listener||E[L];return P}(g):[]:h=[],h},s.listenerCount=function(p,g){return typeof p.listenerCount=="function"?p.listenerCount(g):l.call(p,g)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function f(){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 m=/^(?:[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=[],y=0;256>y;++y)v.push((y+256).toString(16).substr(1));function w(p){var g=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(v[p[g+0]]+v[p[g+1]]+v[p[g+2]]+v[p[g+3]]+"-"+v[p[g+4]]+v[p[g+5]]+"-"+v[p[g+6]]+v[p[g+7]]+"-"+v[p[g+8]]+v[p[g+9]]+"-"+v[p[g+10]]+v[p[g+11]]+v[p[g+12]]+v[p[g+13]]+v[p[g+14]]+v[p[g+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&m.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function _(p,g,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function T(p,g){if(!p||!g)return{};const h={...p};if(h.localCandidateId){const b=g.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=g.get(h.remoteCandidateId);h.remote={...b}}return h}function x(p,g,h){return 8*function(b,E,P){const L=b[P],N=E?E[P]:null;return L===null||N===null?null:(L-N)/(b.timestamp-E.timestamp)*1e3}(p,g,h)}function I(p){if(!p.entries)return p;const g={};return p.forEach(function(h,b){g[b]=h}),g}function A(p,g,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const E of p.values())switch(E.type){case"outbound-rtp":{const P=E.mediaType||E.kind,L={};let N={};if(!["audio","video"].includes(P))continue;if(E.codecId){const D=p.get(E.codecId);D&&(L.clockRate=D.clockRate,L.mimeType=D.mimeType,L.payloadType=D.payloadType)}N=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[P].outbound.push({...E,...L,track:{...N}});break}case"inbound-rtp":{let P=E.mediaType||E.kind,L={};const N={};if(!["audio","video"].includes(P))if(E.id.includes("Video"))P="video";else{if(!E.id.includes("Audio"))continue;P="audio"}if(E.codecId){const D=p.get(E.codecId);D&&(N.clockRate=D.clockRate,N.mimeType=D.mimeType,N.payloadType=D.payloadType)}if(!b.connection.id&&E.transportId){const D=p.get(E.transportId);if(D&&D.selectedCandidatePairId){const U=p.get(D.selectedCandidatePairId);b.connection=T(U,p)}}L=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[P].inbound.push({...E,...N,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=E.dataChannelsClosed,b.connection.dataChannelsOpened=E.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=E.mediaType||E.kind;const L={};if(!["audio","video"].includes(P))if(E.id.includes("Video"))P="video";else{if(!E.id.includes("Audio"))continue;P="audio"}if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}if(!b.connection.id&&E.transportId){const N=p.get(E.transportId);if(N&&N.selectedCandidatePairId){const D=p.get(N.selectedCandidatePairId);b.connection=T(D,p)}}b.remote[P].inbound.push({...E,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=E.mediaType||E.kind,L={};if(!["audio","video"].includes(P))continue;if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}b.remote[P].outbound.push({...E,...L});break}}if(!b.connection.id)for(const E of p.values())E.type==="candidate-pair"&&E.nominated&&E.state==="succeeded"&&(b.connection=T(E,p));return b=function(E,P){return P&&(E.audio.inbound.map(L=>{let N=P.audio.inbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.audio.outbound.map(L=>{let N=P.audio.outbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")}),E.video.inbound.map(L=>{let N=P.video.inbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.video.outbound.map(L=>{let N=P.video.outbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")})),E}(b,g),b}let M,S={},C=[];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 g={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=g.getStatsInterval||1e3,this.rawStats=!!g.rawStats,this.statsObject=!!g.statsObject,this.filteredStats=!!g.filteredStats,this.shouldWrapGetUserMedia=!!g.wrapGetUserMedia,typeof g.remote=="boolean"&&(this.remote=g.remote),this.debug=!!g.debug,this.logLevel=g.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,g){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:g})}async addConnection(p){const{pc:g,peerId:h}=p;let{connectionId:b,remote:E}=p;if(E=typeof E=="boolean"?E:this.remote,!(g&&g instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const N=this.peersToMonitor[h][L];if(N.pc===g)throw new Error(`We are already monitoring peer with id ${h}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const P=g.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(L){delete L.credential}),b||(b=_()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:b,pc:g,remote:E}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((g,h)=>g.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(g=>g.tag===p):this.timeline}get logger(){const p=g=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(g)>-1};return{error(...g){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...g)},warn(...g){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...g)},info(...g){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...g)},debug(...g){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...g)}}}removeConnection(p){let g,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let E in this.peersToMonitor)h in this.peersToMonitor[E]&&(b=this.peersToMonitor[E][h].pc,g=E)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let E in this.peersToMonitor)for(let P in this.peersToMonitor[E])this.peersToMonitor[E][P].pc===b&&(h=P,g=E)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[g][h],Object.values(this.peersToMonitor[g]).length===0&&delete this.peersToMonitor[g],{connectionId:h}}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 g in this.peersToMonitor[p]){let h=this.peersToMonitor[p][g].pc;this.removePeerConnectionEventListeners(g,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),C.forEach(p=>{this.removeTrackEventListeners(p)}),C=[],this.shouldWrapGetUserMedia&&M&&(navigator.mediaDevices.getUserMedia=M)}monitorPeer(p){let{peerId:g,connectionId:h,pc:b,remote:E}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:E}};if(this.peersToMonitor[g]){if(h in this.peersToMonitor[g])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[g][h]=P}else this.peersToMonitor[g]={[h]:P};this.addPeerConnectionEventListeners(g,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(g=>{this.emitEvent(g)})})},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 g={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);g[p]=this.peersToMonitor[p]}else g=this.peersToMonitor;let h=[];for(const b in g)for(const E in g[b]){const P=g[b][E],L=P.pc;if(L&&!this.checkIfConnectionIsClosed(b,E,L))try{const N=this.getTimestamp(),D=L.getStats(null);if(D){const U=await D,Y=this.getTimestamp(),j=I(U),ae={remote:P.options.remote},ee=A(U,P.stats.parsed,ae),$={event:"stats",tag:"stats",peerId:b,connectionId:E,timeTaken:Y-N,data:ee};this.rawStats===!0&&($.rawStats=U),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),P.stats.parsed=ee}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(N){this.logger.error(N)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const g in this.peersToMonitor[p]){const h=this.peersToMonitor[p][g].pc;this.checkIfConnectionIsClosed(p,g,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,g,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let E=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:E,peerId:p,connectionId:g,tag:"connection",data:"closed"})}return b}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."),M=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),M.apply(navigator.mediaDevices,arguments).then(g=>(p({stream:g}),g),g=>(p({error:g}),Promise.reject(g)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const g={...p};for(const b in g){var h=g[b];this.statsToMonitor.includes(h.type)||delete g[b]}return g}get peerConnectionListeners(){return{icecandidate:(p,g,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:g,data:b.candidate})},track:(p,g,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const E=b.track,P=b.streams[0];p in this.peersToMonitor&&g in this.peersToMonitor[p]&&(this.peersToMonitor[p][g].stream=P),this.addTrackEventListeners(E,g),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:g,data:{stream:P?this.getStreamDetails(P):null,track:E?this.getMediaTrackDetails(E):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:g,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceConnectionState})},icegatheringstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceGatheringState})},icecandidateerror:(p,g,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:g,error:{errorCode:b.errorCode}})},connectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.connectionState})},negotiationneeded:(p,g,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:g})},datachannel:(p,g,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:g,data:b.channel})}}}addPeerConnectionEventListeners(p,g,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${g}.`),S[g]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[g][b]=this.peerConnectionListeners[b].bind(this,p,g,h),h.addEventListener(b,S[g][b],!1)})}parseGetUserMedia(p){try{const g={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(g.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),C.push(h)})),this.emitEvent(g)}catch{}}parseStream(p){const g={audio:[],video:[]};return p.getTracks().forEach(h=>{g[h.kind].push(this.getMediaTrackDetails(h))}),g}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:g=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:g}})},unmute:g=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:g}})},overconstrained:g=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:g}})},ended:g=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:g}}),this.removeTrackEventListeners(g.target)}}}addTrackEventListeners(p,g){S[p.id]={};const h=this.getTrackEventObject(g);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const g=this.getTrackEventObject();Object.keys(g).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const g={...p,timestamp:new Date};this.addToTimeline(g),g.tag&&this.emit(g.tag,g)}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,g){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{g.removeEventListener(h,S[p][h],!1)}),delete S[p]),g.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),g.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const g=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),g.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(as=Ku)&&as.__esModule&&Object.prototype.hasOwnProperty.call(as,"default")&&as.default;var c0=Ku.WebRTCStats;function d0(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,r=function(c){const{jitter:u,rtt:d}=c,f=u+d/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),o=function(c){const{packetsLost:u,packetsReceived:d}=c,f=u/(d+u)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-r-o+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function u0(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 h0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class f0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class p0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function Xu(t,e){var n,i;return{errorCode:t.errorCode,errorText:t.errorText,url:t.url,address:t.address,port:t.port,connectionState:e.connectionState,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState,localDescriptionType:(n=e.localDescription)===null||n===void 0?void 0:n.type,remoteDescriptionType:(i=e.remoteDescription)===null||i===void 0?void 0:i.type}}function g0(t,e){const n=wn();let i=!1;const s=new c0({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=o=>F(this,void 0,void 0,function*(){o.event==="stats"&&B(O.StatsFrame,function({data:a}){var l,c,u,d,f,m,v,y;const{audio:w,remote:_}=a,{audio:T}=_,x=(c=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,I=(d=(u=T.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,A=(m=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&m!==void 0?m:-1,M=(y=(v=w.inbound[0])===null||v===void 0?void 0:v.packetsLost)!==null&&y!==void 0?y:-1,S=d0({jitter:1e3*x,rtt:1e3*I,packetsLost:M,packetsReceived:A});return{jitter:x,rtt:I,mos:S,quality:u0(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}}(o),t.uuid),yield t.execute(new p0(n,o))});return{get isRunning(){return i},start:(o,a,l)=>F(this,void 0,void 0,function*(){if(i)k.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new h0(n,e)),s.on("timeline",r);try{yield s.addConnection({pc:o,peerId:a,connectionId:l}),i=!0}catch(c){k.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:o=>F(this,void 0,void 0,function*(){const a=s.getTimeline();B(O.StatsReport,a,t.uuid),o==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),f=document.createElement("a");f.href=d,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new f0(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:o=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)},reportIceCandidateError:o=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)}}}const Yu=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:r=null,currentLayerIdx:o=-1}=e;r&&i!=="mcu-personal-canvas"&&delete r.memberID;const a={type:et.conferenceUpdate,call:t.calls[s],canvasInfo:m0(r),currentLayerIdx:o};switch(n){case"layer-info":{const l=Object.assign({action:ze.LayerInfo},a);B(O.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ze.LayoutInfo},a);B(O.Notification,l,t.uuid);break}}},m0=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Cu(e)},Ju=["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"],v0={"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 Zu(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}class hi{constructor(e,n,i,s,r){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,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.handleConnectionStateChange=()=>F(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(k.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${o}`),o==="failed"||o==="disconnected"){const a=()=>F(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,u){return F(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const m=f[0].sender,v=m==null?void 0:m.transport;v&&(d.dtlsState=v.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const m=yield c.getStats();m.forEach(v=>{v.type==="candidate-pair"&&v.state==="succeeded"&&(d.candidatePairState=v.state,m.forEach(y=>{y.type==="local-candidate"&&y.id===v.localCandidateId&&(d.localCandidateType=y.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:y.address,port:y.port,protocol:y.protocol,candidateType:y.candidateType}),y.type==="remote-candidate"&&y.id===v.remoteCandidateId&&(d.remoteCandidateType=y.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:y.address,port:y.port,protocol:y.protocol,candidateType:y.candidateType})})),v.type==="transport"&&(d.dtlsCipher=v.dtlsCipher,d.srtpCipher=v.srtpCipher,d.tlsVersion=v.tlsVersion,v.dtlsState&&(d.dtlsState=v.dtlsState))})}catch(m){k.error("Error gathering connection state details:",m)}return d})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}if(o==="disconnected"){const a=xt(Sy);B(O.Warning,{warning:a,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(o==="failed"){const a=xt(ky);B(O.PeerConnectionFailureError,{warning:a,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${o}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=o,o==="connected"&&(performance.mark("dtls-connected"),this.tryCollectTimings()),this._isTrickleIce()&&(o==="connecting"&&performance.mark("peer-connection-connecting"),o==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark("peer-connection-connected")))}),this._handleIceConnectionStateChange=()=>{const o=this.instance.iceConnectionState;k.debug(`[${new Date().toISOString()}] ICE Connection State`,o),o==="connected"&&performance.mark("ice-connected")},this._handleIceGatheringStateChange=()=>{const o=this.instance.iceGatheringState;k.debug(`[${new Date().toISOString()}] ICE Gathering State`,o),o==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):o==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(o,a)=>{if(o.setCodecPreferences)return o.setCodecPreferences(a)},k.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=r}get isOffer(){return this.type===De.Offer}get isAnswer(){return this.type===De.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("start-negotiation"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return F(this,void 0,void 0,function*(){performance.mark("start-negotiation"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){this.instance?(k.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{k.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),k.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):k.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(k.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(O.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(k.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){k.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?k.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark("first-remote-media-track"),this._firstMediaTrackMarked=!0);const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&ci(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName("call-active","mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=function(n,i){const s=Zu("new-call-start");if(s===void 0)return{mode:n,direction:i,steps:[]};const r=[];for(const l of Ju){if(l==="new-call-start")continue;const c=Zu(l);c!==void 0&&r.push({label:v0[l]||l,fromStart:c-s})}r.sort((l,c)=>l.fromStart-c.fromStart);const o=[];let a=0;for(const l of r)o.push({label:l.label,fromStart:l.fromStart,delta:l.fromStart-a}),a=l.fromStart;return{mode:n,direction:i,steps:o}}(this._isTrickleIce()?"trickle":"non-trickle",this.isOffer?"outbound":"inbound");(function(n){const{mode:i,direction:s,steps:r}=n,o=`[CallTimings][${s}][${i}]`;if(r.length===0)return void k.info(`${o} No timing data collected`);const a=Math.max(...r.map(f=>f.label.length),4)+2,l=(f,m)=>{for(;f.length<m;)f+=" ";return f},c=(f,m)=>{for(;f.length<m;)f=" "+f;return f},u=l("Step",a)+c("Delta",14)+c("From Start",14);let d="";for(let f=0;f<u.length;f++)d+="-";k.info(`${o} Call establishment timing breakdown:`),k.info(`${o} ${u}`),k.info(`${o} ${d}`),k.info(`${o} ${l("Call Start",a)}${c("-",14)}${c("0.00ms",14)}`);for(const f of r){const m=f.delta.toFixed(2)+"ms",v=f.fromStart.toFixed(2)+"ms";k.info(`${o} ${l(f.label,a)}${c(m,14)}${c(v,14)}`)}k.info(`${o} ${d}`)})(e),function(){for(const n of Ju)try{performance.clearMarks(n)}catch{k.warn("Clearing performance marks is failed")}}()}createPeerConnection(){return F(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:De.Offer}),performance.mark("set-remote-description"),!this.instance))throw oe(sr);const n=!!this.options.receiveOnlyAudio&&!this.options.audio;let i=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>F(this,void 0,void 0,function*(){const r=this._session.options.mediaPermissionsRecovery;if(r!=null&&r.enabled&&this._isAnswer()){let o=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),r.timeout),B(O.Error,{error:oe(si(s),s),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+r.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>F(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),o=yield this._retrieveLocalStream(),(l=r.onSuccess)===null||l===void 0||l.call(r)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),i=l,(c=r.onError)===null||c===void 0||c.call(r,l)}),o}return i=s,null})),!this.instance)throw oe(sr);if(!this.options.localStream&&!n)throw oe(i?si(i):hu,i??void 0);performance.mark("get-user-media"),this.options.mutedMicOnStart&&Tn(this.options.localStream)&&(k.info("Muting local audio tracks on start"),fr(this.options.localStream)),performance.mark("peer-creation-end")})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=xt(Ty);B(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=xt(Cy);B(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},hi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return F(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw oe(sr);this.isDebugEnabled&&(this.statsReporter=g0(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Tn(i)){const r=i.getAudioTracks();let o=[...r];if(k.info("Local audio tracks: ",r),typeof this.options.audio=="object"&&r.forEach(c=>{k.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();o=[...r,...c],k.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{k.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=qu(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};o.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"?(o.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&ci(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const r=this.instance.addTransceiver("audio",{direction:"recvonly"});k.info("Added recvonly audio transceiver for receive-only mode",r);const{audioCodecs:o}=qu(this.options.preferred_codecs);o.length>0&&this._setCodecs(r,o)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);k.info("Add transceiver",e,n)}}_createOffer(){return F(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,k.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark("create-offer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),this._isTrickleIce()||this._sdpReady(),e}catch(e){k.error("Peer _createOffer error:",e);const n=oe(ty,e);B(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setRemoteDescription(e){return F(this,void 0,void 0,function*(){k.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(n){k.error("Peer _setRemoteDescription error:",n);const i=oe(du,n);throw B(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_createAnswer(){return F(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return k.debug("Skipping negotiation, state:",this.instance.signalingState),k.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:De.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark("create-answer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),e}catch(e){k.error("Peer _createAnswer error:",e);const n=oe(ny,e);B(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setLocalDescription(e){return F(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(n){k.error("Peer _setLocalDescription error:",n);const i=oe(iy,n);throw B(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_sdpReady(){Sn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return F(this,void 0,void 0,function*(){if(Tn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,F(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:r=!1,camId:o}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield rs(s,a,gt.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),o&&(o=yield rs(o,l,gt.Video).catch(c=>null),o&&(typeof r=="boolean"&&(r={}),r.deviceId={exact:o})),{audio:i,video:r}}));var n;return os(e)})}_isOffer(){return this.type===De.Offer}_isAnswer(){return this.type===De.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return k.info("RTC config",s),s}restartStatsReporter(){return F(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?k.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(k.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):k.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return F(this,void 0,void 0,function*(){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)})}}hi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3;const ls=cr;class Qu{constructor(e,n){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=ar.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=w=>{const _=w<0||!this._lastSerno||this._lastSerno&&w===this._lastSerno+1;return _&&w>=0&&(this._lastSerno=w),_},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(w=>{w.forEach(_=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const x in T.constraints)if(T.constraints.hasOwnProperty(x)&&T.constraints[x]!==_[x])return}T.callback(_)}})})})};const{iceServers:i,speaker:s,micId:r,micLabel:o,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:f,video:m},ringtoneFile:v,ringbackFile:y}=e;this.options=Object.assign({},Hy,{audio:f,video:m,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:i,localElement:c,remoteElement:u,micId:r,micLabel:o,camId:a,camLabel:l,speakerId:s,ringtoneFile:v,ringbackFile:y,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=Gu(this.options.ringtoneFile,"_ringtone"),this._ringback=Gu(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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!r0(this.options.localStream)}invite(){return F(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=pt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new hi(De.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(e){k.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const n=e instanceof ii?e:oe(pu,e instanceof Error?e:void 0);return B(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({},!1)}this._creatingPeer=!1})}answer(e={}){var n,i;return F(this,void 0,void 0,function*(){if(!((n=this.peer)===null||n===void 0)&&n.instance&&this.peer.instance.signalingState!=="closed"){const s=xt(Ey);return B(O.Warning,{warning:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void k.warn(`[${this.id}] answer() ignored: peer connection already exists (signalingState: ${this.peer.instance.signalingState})`)}performance.mark("answer-called"),this._creatingPeer=!0,this.stopRingtone(),this.direction=pt.Inbound,((i=e==null?void 0:e.customHeaders)===null||i===void 0?void 0:i.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new hi(De.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(s){k.error("Peer init failed, aborting call",s),this._creatingPeer=!1;const r=s instanceof ii?s:oe(pu,s instanceof Error?s:void 0);return B(O.Error,{error:r,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup())}this._creatingPeer=!1})}playRingtone(){Wu(this._ringtone)}stopRingtone(){zu(this._ringtone)}playRingback(){Wu(this._ringback)}stopRingback(){zu(this._ringback)}hangup(e,n){var i,s,r,o;return F(this,void 0,void 0,function*(){const a=e||{},l=n!==!1,c=this._state<z.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=a.cause||c.cause,this.causeCode=a.causeCode||c.causeCode,this.sipCode=a.sipCode||null,this.sipReason=a.sipReason||null,this.sipCallId=a.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(r=(s=a==null?void 0:a.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&r!==void 0?r:[]],a.isRecovering)return this._isRecovering=!0,this.setState(z.Recovering),void this._finalize();if(this.setState(z.Hangup),this.stopRingtone(),this.stopRingback(),l){const u=new Jy({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});try{yield this._execute(u)}catch(d){k.error("telnyx_rtc.bye failed!",d);const f=oe(ly,d);B(O.Error,{error:f,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}k.debug(`[${this.id}] Closing peer from hangup`),(o=this.peer)===null||o===void 0||o.close(),this.setState(z.Destroy)})}hold(){const e=new dr({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new dr({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new dr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new Bu({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},s=new Bu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){fr(this.options.localStream)}unmuteAudio(){$u(this.options.localStream)}toggleAudioMute(){Hu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){var i;return F(this,void 0,void 0,function*(){const{instance:s}=this.peer,r=s.getSenders().find(({track:{kind:o}})=>o==="audio");if(r){let o;try{o=yield ss({audio:{deviceId:{exact:e}}})}catch(c){const u=oe(si(c),c);return void B(O.MediaError,u,((i=this.options)===null||i===void 0?void 0:i.id)||this.id)}const a=o.getAudioTracks()[0];a.enabled=!n,r.replaceTrack(a),this.options.micId=e;const{localStream:l}=this.options;l.getAudioTracks().forEach(c=>c.stop()),l.getVideoTracks().forEach(c=>o.addTrack(c)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,kn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,kn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,kn(e,"video",null)}setVideoDevice(e){return F(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield ss({video:{deviceId:{exact:e}}}),r=s.getVideoTracks()[0];i.replaceTrack(r);const{localElement:o,localStream:a}=this.options;ci(o,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){fr(this.options.remoteStream)}undeaf(){$u(this.options.remoteStream)}toggleDeaf(){Hu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return F(this,void 0,void 0,function*(){if(!this||!this.peer)return void k.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,s=i.getSenders();if(!s)return void k.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 r=s.find(({track:{kind:o}})=>o===n);if(r){const o=r.getParameters();o.encodings||(o.encodings=[{rid:"h"}]),k.info("Parameters: ",o),k.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),o.encodings[0].maxBitrate=e,yield r.setParameters(o).then(()=>{k.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",r.getParameters())}).catch(a=>k.error(a))}else k.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n,i;switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),k.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:et.callUpdate,call:this}),e){case z.Purge:k.info(`[${this.id}] Entering Purge state.`);break;case z.Active:performance.mark("call-active"),(n=this.peer)===null||n===void 0||n.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,k.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:s,speakerId:r}=this.options;s&&r&&Uu(s,r)},0),this._callReportCollector&&!((i=this.peer)===null||i===void 0)&&i.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(performance.mark("telnyx-rtc-answer"),this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(performance.mark("telnyx-rtc-media"),this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:{const{display_name:r,display_number:o,display_direction:a}=i;this.extension=o;const l=a===pt.Inbound?pt.Outbound:pt.Inbound,c={type:et[n],call:this,displayName:r,displayNumber:o,displayDirection:l};B(O.Notification,c,this.id)||B(O.Notification,c,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const r=Object.assign(Object.assign({},i),{type:et.generic,call:this});B(O.Notification,r,this.id)||B(O.Notification,r,this.session.uuid);break}case te.Ringing:performance.mark("ringing"),this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case te.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,n){return F(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return k.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:r=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:f}=n;this._dispatchConferenceUpdate({action:ze.Join,conferenceName:u,participantId:Number(d),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const m=[];for(const v in s)m.push(Object.assign({callId:s[v][0],index:Number(v)},ts(s[v][1])));this._dispatchConferenceUpdate({action:ze.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ze.Add,callId:r,index:o},ts(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ze.Modify,callId:r,index:o},ts(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ze.Delete,callId:r,index:o},ts(s)));break;case"clear":this._dispatchConferenceUpdate({action:ze.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:r,index:o})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return F(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:r,from:o,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ze.ChatMessage,direction:r,participantNumber:o,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfChat subscription error:",s)});ur(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,r)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:r}})}}}))})}_subscribeConferenceInfo(e){return F(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:r}=s;r.contentType==="layout-info"?(r.callID=this.id,Yu(this.session,r)):k.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfInfo subscription error:",s)});ur(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){k.error(`Failed to ${e.action} on call ${this.id}`);const n=oe(ry,e);return B(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_onRemoteSdp(e){return F(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:De.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{performance.mark("set-remote-description"),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(i=>F(this,void 0,void 0,function*(){k.error("Call setRemoteDescription Error: ",i);const s=oe(du,i);B(O.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(r){k.error("Error during hangup after setRemoteDescription failure:",r)}}))})}_requestAnotherLocalDescription(){Sn(this.peer.onSdpReadyTwice)?B(O.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0,!e)return void k.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:s,type:r}=e;if(s.indexOf("candidate")===-1)return k.info(`No candidate - retry
116
- `),void this._requestAnotherLocalDescription();if((i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),!Ry.test(s)){const l=xt(xy);k.warn(`[${this.id}] Warning ${l.code}: ${l.message}`),B(O.Warning,{warning:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark("ice-gathering-end");let o=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${ls}`};switch(r){case De.Offer:this.setState(z.Requesting),o=new Ou(a);break;case De.Answer:this._isRecovering||this.setState(z.Answering),o=this.options.attach===!0?new Vu(a):new Fu(a);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(o).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,r===De.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(l=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${r} error:`,l);const c=oe(uu,l);B(O.Error,{error:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(u){k.error("Error during hangup after SDP send failure:",u)}}))}_onTrickleIceSdp(e){if(!e)return k.error("No SDP data provided"),void this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ls}`};switch(i){case De.Offer:this.setState(z.Requesting),s=new Ou(r);break;case De.Answer:this._isRecovering||this.setState(z.Answering),s=this.options.attach===!0?new Vu(r):new Fu(r);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(s).then(o=>{const{node_id:a=null}=o;this._targetNodeId=a,i===De.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(o=>F(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${i} error:`,o);const a=oe(uu,o);B(O.Error,{error:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(l){k.error("Error during hangup after SDP send failure:",l)}}))}_onIce(e){var n;const{instance:i}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(i.localDescription),s)}e.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var n;e.candidate&&e.candidate.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new Zy({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return k.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{k.debug("Successfully added ICE candidate:",e)}).catch(i=>{k.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Qy({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark("first-candidate"),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark("first-non-host-candidate"),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.onicegatheringstatechange=()=>{e.iceGatheringState==="complete"&&performance.mark("ice-gathering-completed")},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Xu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:r}=this.options;r===!1&&ci(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{k.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(k.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Xu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:r}=this.options;r===!1&&ci(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:et.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),k.error(`Media error (${n}): ${i}`,e),B(O.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:et.peerConnectionFailureError,error:e.error}),k.error("Peer connection failure error"),e.warning&&B(O.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:et.signalingStateClosed},e)),k.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:et.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(O.Notification,e,this.id,!1)||B(O.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){var e,n;const{id:i,userVariables:s,remoteCallerNumber:r,onNotification:o,recoveredCallId:a}=this.options;var l;this.options.id=i?i.toString():wn(),this.id=this.options.id,a&&(this.recoveredCallId=a,this._isRecovering=!0),s&&(l=s,Object.keys(l).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Dt(O.MediaError,this._onMediaError,this.id),Dt(O.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Dt(O.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Sn(o)&&Dt(O.Notification,o.bind(this),this.id);const c=this.session.options.enableCallReports!==!1,u=this.session.options.callReportInterval||5e3,d=this.session.options.debugLogLevel||"debug",f=this.session.options.debugLogMaxEntries||1e3;c&&(this._callReportCollector=new Te({enabled:!0,interval:u},{enabled:!0,level:d,maxEntries:f}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=m=>{B(O.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(z.Recovering):this.setState(z.New),k.info(`New Call — region: ${(e=this.session.region)!==null&&e!==void 0?e:"unknown"}, dc: ${(n=this.session.dc)!==null&&n!==void 0?n:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),k.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;di(n),di(i),Mt(O.MediaError,null,this.id),Mt(O.PeerConnectionFailureError,null,this.id),Mt(O.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{k.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void k.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void k.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},r=this._callReportCollector.flush(s);if(!r)return;const o=Yt()||void 0;this._callReportCollector.sendPayload(r,n,i,o).catch(a=>{k.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return F(this,void 0,void 0,function*(){if(!this._callReportCollector)return void k.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return k.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void k.error("Cannot post call report: connection host not available");const r=Yt()||void 0;this._callReportCollector.postReport(i,n,s,r).catch(o=>{k.error("Failed to post call report",{error:o})}).finally(()=>{var o;(o=this._callReportCollector)===null||o===void 0||o.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),k.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),k.debug("Stats stopped")}}Qu.setStateTelnyx=t=>{if(t){switch(t._state){case z.Recovering:t.state="recovering";break;case z.Requesting:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class Jt extends Qu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new l0(e,n))}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return F(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>F(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup())}))});const{remoteCallerName:s,remoteCallerNumber:r,callerName:o,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${r}-screen`,callerName:`${o} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Jt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return F(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup())})}setAudioOutDevice(e){return F(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Uu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>F(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],r=["id","type","timestamp"];n.forEach(o=>{s.includes(o.type)||(i+=`
115
+ `),Ue[`${(s=(i=r==null?void 0:r.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!U(r.id,r)){const a=or(r);U(O.SocketMessage,r,this.session.uuid),a&&(this.previousGatewayState=a)}}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!==Ru?(k.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||U(O.SocketClose,{code:P_,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):k.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(k.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(k.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):k.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_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(O.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else k.warn("Unknown message from socket",e)}}class ai{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:wn()},e)}}const Pu={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 Fe extends ai{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Zi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in Pu)i&&n.hasOwnProperty(i)&&(n[Pu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class Du extends Fe{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class X_{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>V(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(or(n))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const n=new Du(Yt());this.pendingRequestId=n.request.id,this.gatewayStateTask=xu({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ue.REGISTER,Ue.REGED].includes(i)}),this.session=e,this.gatewayStateTask=xu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Mu extends Fe{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var Nu="2.26.4",cr=Nu;class Y_ extends Fe{constructor(e,n,i,s,r={},o){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:r,reconnection:o,loginParams:{},"User-Agent":{sdkVersion:cr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class J_ extends Fe{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Ou extends Fe{toString(){return te.Invite}}class Fu extends Fe{toString(){return te.Answer}}class Vu extends Fe{toString(){return te.Attach}}class Z_ extends Fe{toString(){return te.Bye}}class Q_ extends Fe{toString(){return te.Candidate}}class e0 extends Fe{toString(){return te.EndOfCandidates}}class dr extends Fe{toString(){return te.Modify}}class Bu extends Fe{toString(){return te.Info}}class t0 extends Fe{toString(){return te.Broadcast}}class n0 extends Fe{toString(){return te.Subscribe}}class i0 extends Fe{toString(){return te.Unsubscribe}}class s0 extends Fe{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:r,userVariables:o,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:l,"User-Agent":{sdkVersion:cr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),r&&(c.target_params=r),this.buildRequest({method:this.method,params:c})}}class li{constructor(e){if(this.options=e,this.uuid=wn(),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.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._tokenExpiryTimeout=null,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",wu=(i=es[n])!==null&&i!==void 0?i:es.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new Lu(this),this.registerAgent=new X_(this)}get __logger(){return k}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return V(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*ku(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e).catch(n=>V(this,void 0,void 0,function*(){if((n==null?void 0:n.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const i=oe(m_,n);U(O.Error,{error:i,sessionId:this.sessionid},this.uuid)}yield this.login()}throw n})):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),k.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return is(this.options)||oi(this.options)}broadcast(e){}disconnect(){return V(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),k.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Nt(e,n,this.uuid),this}off(e,n){return Ot(e,n,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(k.debug("No existing connection found, creating a new one."),this.connection=new Lu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(k.debug("Initiating connection to the server..."),this.connection.connect()),k.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){const n=oe(fu,e);U(O.Error,{error:n,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Eu()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const n=e.split(".");if(n.length!==3)return;const i=JSON.parse(atob(n[1])).exp;if(typeof i!="number")return;const s=i-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=li.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const r=1e3*(s-li.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},r)}}catch{k.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=xt(A_);U(O.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:n,onError:i}={}){return V(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)),is(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(oi(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";k.error(s);const r=oe(g_,void 0,s);return void U(O.Error,{error:r,type:H_.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return V(this,void 0,void 0,function*(){let s;s=e==="login"?new Y_(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Yt()):new s0({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:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Yt()});const r=yield this.execute(s).catch(o=>{this._handleLoginError(o),i&&i(o)});r&&(this.sessionid=r.sessid,this._checkTokenExpiry(),n&&n())})}_onSocketOpen(){return V(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&lr(this.relayProtocol);for(const e in this.subscriptions)lr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{k.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Ot(e,null,n)):(delete this.subscriptions[e],lr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},Sn(n)&&Nt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(O.SocketOpen,this._onSocketOpen),this.on(O.SocketClose,this.onNetworkClose),this.on(O.SocketError,this.onNetworkClose),this.on(O.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(O.SocketOpen,this._onSocketOpen),this.off(O.SocketClose,this.onNetworkClose),this.off(O.SocketError,this.onNetworkClose),this.off(O.SocketMessage,this._onSocketMessage)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:n})=>{typeof n=="string"?this.executeRaw(n):e(this.execute(n))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(k.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Mu(Yt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){k.debug("Ping received"),this._pong=!0}static on(e,n){Nt(e,n)}static off(e){Ot(e)}static uuid(){return wn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}li.TOKEN_EXPIRY_WARNING_SECONDS=120;const ss=t=>navigator.mediaDevices.getUserMedia(t),Tn=t=>t&&t instanceof MediaStream,ci=(t,e)=>{const n=ns(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},Uu=(t,e)=>V(void 0,void 0,void 0,function*(){const n=ns(t);if(n===null)return k.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return k.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),o0=t=>{t&&t.readyState==="live"&&t.stop()},di=t=>{Tn(t)&&t.getTracks().forEach(o0),t=null},os=t=>V(void 0,void 0,void 0,function*(){k.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield ss(t)}catch(i){if(k.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(r=>{const{audio:o,video:a}=r;let l=!1,c=o,u=a;if(typeof o=="object"&&o!==null&&"deviceId"in o){l=!0;const d=Zi(o,["deviceId"]);c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Zi(a,["deviceId"]);u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){k.warn("Device not found or not readable, falling back to default device");try{return yield ss(s)}catch(r){throw k.error("Fallback getUserMedia also failed: ",r),i}}}throw i}}),ui=(t=null,e=!1)=>V(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===gt.AudioIn||s===gt.AudioOut,video:!s||s===gt.Video}))(t)).catch(s=>(k.error(s),null));if(i){if(di(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(r=>r.kind===t)),e===!0)return n;const s=[];n=n.filter(r=>{if(!r.groupId)return!0;const o=`${r.kind}-${r.groupId}`;return!s.includes(o)&&(s.push(o),!0)})}return n}),ju=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],rs=(t,e,n)=>V(void 0,void 0,void 0,function*(){const i=yield ui(n,!0);for(let s=0;s<i.length;s++){const{deviceId:r,label:o}=i[s];if(t===r||e===o)return r}return null}),r0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},ur=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=hr(t);return n.includes(e)||i.includes(e)},hr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},kn=(t,e=null,n=null)=>{if(!Tn(t))return null;let i=[];switch(e){case"audio":i=t.getAudioTracks();break;case"video":i=t.getVideoTracks();break;default:i=t.getTracks()}i.forEach(s=>{switch(n){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},$u=t=>{kn(t,"audio",!0)},fr=t=>{kn(t,"audio",!1)},Hu=t=>{kn(t,"audio",null)},a0=t=>((e,n=null)=>{if(!Tn(e))return null;let i=[];switch(n){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some(s=>s.enabled)})(t,"audio");function l0(){try{const{browserInfo:t,name:e,version:n,supportAudio:i,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,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],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,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("/"),f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,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],f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),r=window.RTCPeerConnection,o=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(r&&o&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!r,supportSessionDescription:!!o,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!os}}catch(t){return t.message}}var Se;function Gu(t,e){const n=document.getElementById(e);if(n)return n;if(t&&e){const i=document.createElement("audio");return i.id=e,i.loop=!0,i.src=t,i.preload="auto",i.load(),document.body.appendChild(i),i}return null}function Wu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{k.error("playAudio",e),t._playFulfilled=!0}))}function zu(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"})(Se||(Se={}));const qu=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class c0 extends ai{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:wn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class Te{constructor(e,n){var i;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=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._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new B_(s)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,bu=i)}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,k.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return V(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),k.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,r=this.statsBuffer;this.statsBuffer=[];const o=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:r},o.length>0?{logs:o}:{}),{segment:s});return k.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:r.length,logEntries:o.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var r,o;return V(this,void 0,void 0,function*(){const a=(r=this.logCollector)===null||r===void 0?void 0:r.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void k.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void k.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:(o=this.callEndTime)===null||o===void 0?void 0:o.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,n,i,s)})}sendPayload(e,n,i,s){return V(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var r,o;return V(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";k.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(o=(r=e.logs)===null||r===void 0?void 0:r.length)!==null&&o!==void 0?o:0,callId:e.summary.callId,segment:e.segment});const u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:u,body:d}),m=yield f();if(m.ok)k.info(`CallReportCollector: Successfully posted ${c}`);else{const v=yield m.text();k.error(`CallReportCollector: Failed to post ${c}`,{status:m.status,error:v})}}catch(a){k.warn(`CallReportCollector: Network error posting call report, retrying in ${Te.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,Te.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,u={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(u["x-voice-sdk-id"]=s);const d=yield fetch(c,{method:"POST",headers:u,body:JSON.stringify(e)});if(d.ok)k.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield d.text();k.error("CallReportCollector: Failed to post call report on retry",{status:d.status,error:f})}}catch(l){k.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return V(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const r=yield this.peerConnection.getStats(),o=new Date;let a,l,c=null,u=null,d=null,f=null;if(r.forEach(v=>{switch(v.type){case"outbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(c=v);break;case"inbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(u=v);break;case"candidate-pair":(v.nominated||v.state==="succeeded")&&(d=v);break;case"transport":f=v}}),c){const v=this._getOutboundAudioLevel(r,c);if(v!==null&&this.intervalAudioLevels.outbound.push(v),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const y=8*_*1e3/w;this.intervalBitrates.outbound.push(y)}}this.previousStats.outboundBytes=c.bytesSent}if(u){const v=this._getInboundAudioLevel(r,u);if(v!==null&&this.intervalAudioLevels.inbound.push(v),u.jitter!==void 0&&this.intervalJitters.push(1e3*u.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(u.bytesReceived||0)-this.previousStats.inboundBytes,w=(u.timestamp||o.getTime())-this.previousStats.timestamp;if(w>0){const y=8*_*1e3/w;this.intervalBitrates.inbound.push(y)}}this.previousStats.inboundBytes=u.bytesReceived}d&&(d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),this.previousCandidatePairId!==null&&d.id!==this.previousCandidatePairId&&k.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:d.id}),this.previousCandidatePairId=(n=d.id)!==null&&n!==void 0?n:null),d&&(a=this._resolveCandidate(r,d.localCandidateId),l=this._resolveCandidate(r,d.remoteCandidateId)),this.previousStats.timestamp=o.getTime();const m=o.getTime()-this.intervalStartTime.getTime();if(e||m>=this.options.interval){const v=this._createStatsEntry(this.intervalStartTime,o,c,u,d,a,l,f);if(this.statsBuffer.push(v),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),k.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const _=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(_>=Te.STATS_FLUSH_THRESHOLD||w>=Te.LOGS_FLUSH_THRESHOLD){k.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:_,logEntries:w});try{this.onFlushNeeded()}catch(y){k.error("CallReportCollector: onFlushNeeded callback error",{error:y})}}}this._checkQualityWarnings(v,u),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(r){k.error("CallReportCollector: Error collecting stats",{error:r})}})}_checkQualityWarnings(e,n){var i,s,r,o,a,l,c,u,d,f,m,v,_,w,y,T,x;if(!this.onWarning)return;const I=(i=e.connection)===null||i===void 0?void 0:i.roundTripTimeAvg,A=(r=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||r===void 0?void 0:r.jitterAvg;let M;if(n){const S=(o=n.packetsReceived)!==null&&o!==void 0?o:0,C=(a=n.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const p=S-this._prevPacketsReceived,g=C-this._prevPacketsLost,h=p+g;h>0&&(M=g/h*100)}this._prevPacketsReceived=S,this._prevPacketsLost=C}if(this._trackBreach(y_,I!==void 0&&I>Te.THRESHOLD_RTT_MS),this._trackBreach(__,A!==void 0&&A>Te.THRESHOLD_JITTER_MS),this._trackBreach(b_,M!==void 0&&M>Te.THRESHOLD_PACKET_LOSS_PCT),I!==void 0&&A!==void 0&&M!==void 0){const S=93.2-.11*A-2.5*M-.01*(1e3*I),C=Math.max(1,Math.min(4.5,1+.035*S+S*(S-60)*(100-S)*7e-6));this._trackBreach(gu,C<Te.THRESHOLD_MOS)}else this._trackBreach(gu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(f=(d=(u=S==null?void 0:S.audio)===null||u===void 0?void 0:u.inbound)===null||d===void 0?void 0:d.bytesReceived)!==null&&f!==void 0?f:0,p=(m=e.audio.inbound.bytesReceived)!==null&&m!==void 0?m:0;this._trackBreach(w_,p-C==0)}if(((_=(v=e.audio)===null||v===void 0?void 0:v.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0&&this.statsBuffer.length>1){const S=this.statsBuffer[this.statsBuffer.length-2],C=(T=(y=(w=S==null?void 0:S.audio)===null||w===void 0?void 0:w.outbound)===null||y===void 0?void 0:y.bytesSent)!==null&&T!==void 0?T:0,p=(x=e.audio.outbound.bytesSent)!==null&&x!==void 0?x:0;this._trackBreach(S_,p-C==0)}}_trackBreach(e,n){var i,s,r;if(n){if(this._breachCounters[e]=((i=this._breachCounters[e])!==null&&i!==void 0?i:0)+1,this._breachCounters[e]>=Te.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();if(o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=Te.WARNING_THROTTLE_MS){this._lastWarningEmitted[e]=o;try{const a=xt(e);k.warn(`CallReportCollector: warning ${a.code}: ${a.message}`),(r=this.onWarning)===null||r===void 0||r.call(this,a)}catch(a){k.error(`CallReportCollector: Failed to emit warning ${e}`,{error:a})}}}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_createStatsEntry(e,n,i,s,r,o,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={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)}),r&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:r.packetsSent,packetsReceived:r.packetsReceived,bytesSent:r.bytesSent,bytesReceived:r.bytesReceived},c.ice=Object.assign(Object.assign({id:r.id,state:r.state,nominated:r.nominated,writable:r.writable,requestsSent:r.requestsSent,responsesReceived:r.responsesReceived},o?{local:o}:{}),a?{remote:a}:{})),l&&(c.transport=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}:{})),c}_resolveCandidate(e,n){if(!n)return void k.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void k.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;k.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",r=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",o=this.previousStats[s],a=this.previousStats[r];if(this.previousStats[s]=e,this.previousStats[r]=n,o===void 0||a===void 0)return null;const l=e-o,c=n-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}Te.STATS_FLUSH_THRESHOLD=300,Te.LOGS_FLUSH_THRESHOLD=800,Te.CONSECUTIVE_BREACHES_REQUIRED=3,Te.THRESHOLD_RTT_MS=.4,Te.THRESHOLD_JITTER_MS=30,Te.THRESHOLD_PACKET_LOSS_PCT=1,Te.THRESHOLD_MOS=3.5,Te.WARNING_THROTTLE_MS=15e3,Te.RETRY_DELAY_MS=500;var as,Ku=yu(function(t,e){var n;function i(){}function s(){s.init.call(this)}function r(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function o(p,g,h,b){var E,P,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=p._events)?(P.newListener&&(p.emit("newListener",g,h.listener?h.listener:h),P=p._events),L=P[g]):(P=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=P[g]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(E=r(p))&&0<E&&L.length>E){L.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+g+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=g,N.count=L.length,function(D){typeof console.warn=="function"?console.warn(D):console.log(D)}(N)}}else L=P[g]=h,++p._eventsCount;return p}function a(p,g,h){function b(){p.removeListener(g,b),E||(E=!0,h.apply(p,arguments))}var E=!1;return b.listener=h,b}function l(p){var g=this._events;if(g){var h=g[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,g){for(var h=Array(g);g--;)h[g]=p[g];return h}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(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 r(this)},s.prototype.emit=function(p){var g,h,b,E,P,L,N,D=p==="error";if(L=this._events)D=D&&L.error==null;else if(!D)return!1;if(N=this.domain,D){if(g=arguments[1],!N){if(g instanceof Error)throw g;var F=new Error('Uncaught, unspecified "error" event. ('+g+")");throw F.context=g,F}return g||(g=new Error('Uncaught, unspecified "error" event')),g.domainEmitter=this,g.domain=N,g.domainThrown=!1,N.emit("error",g),!1}if(!(h=L[p]))return!1;var z=typeof h=="function";switch(b=arguments.length){case 1:(function(j,le,ee){if(le)j.call(ee);else for(var $=j.length,he=c(j,$),X=0;X<$;++X)he[X].call(ee)})(h,z,this);break;case 2:(function(j,le,ee,$){if(le)j.call(ee,$);else for(var he=j.length,X=c(j,he),Z=0;Z<he;++Z)X[Z].call(ee,$)})(h,z,this,arguments[1]);break;case 3:(function(j,le,ee,$,he){if(le)j.call(ee,$,he);else for(var X=j.length,Z=c(j,X),Q=0;Q<X;++Q)Z[Q].call(ee,$,he)})(h,z,this,arguments[1],arguments[2]);break;case 4:(function(j,le,ee,$,he,X){if(le)j.call(ee,$,he,X);else for(var Z=j.length,Q=c(j,Z),ne=0;ne<Z;++ne)Q[ne].call(ee,$,he,X)})(h,z,this,arguments[1],arguments[2],arguments[3]);break;default:for(E=Array(b-1),P=1;P<b;P++)E[P-1]=arguments[P];(function(j,le,ee,$){if(le)j.apply(ee,$);else for(var he=j.length,X=c(j,he),Z=0;Z<he;++Z)X[Z].apply(ee,$)})(h,z,this,E)}return!0},s.prototype.addListener=function(p,g){return o(this,p,g,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,g){return o(this,p,g,!0)},s.prototype.once=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,g)),this},s.prototype.prependOnceListener=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,g)),this},s.prototype.removeListener=function(p,g){var h,b,E,P,L;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===g||h.listener&&h.listener===g)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||g));else if(typeof h!="function"){for(E=-1,P=h.length;0<P--;)if(h[P]===g||h[P].listener&&h[P].listener===g){L=h[P].listener,E=P;break}if(0>E)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(N,D){for(var F=D,z=F+1,j=N.length;z<j;F+=1,z+=1)N[F]=N[z];N.pop()})(h,E);b.removeListener&&this.emit("removeListener",p,L||g)}return this},s.prototype.removeAllListeners=function(p){var g,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,E=Object.keys(h),P=0;P<E.length;++P)(b=E[P])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(g=h[p])=="function")this.removeListener(p,g);else if(g)do this.removeListener(p,g[g.length-1]);while(g[0]);return this},s.prototype.listeners=function(p){var g,h,b=this._events;return b?h=(g=b[p])?typeof g=="function"?[g.listener||g]:function(E){for(var P=Array(E.length),L=0;L<P.length;++L)P[L]=E[L].listener||E[L];return P}(g):[]:h=[],h},s.listenerCount=function(p,g){return typeof p.listenerCount=="function"?p.listenerCount(g):l.call(p,g)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function f(){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 m=/^(?:[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 w(p){var g=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(v[p[g+0]]+v[p[g+1]]+v[p[g+2]]+v[p[g+3]]+"-"+v[p[g+4]]+v[p[g+5]]+"-"+v[p[g+6]]+v[p[g+7]]+"-"+v[p[g+8]]+v[p[g+9]]+"-"+v[p[g+10]]+v[p[g+11]]+v[p[g+12]]+v[p[g+13]]+v[p[g+14]]+v[p[g+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&m.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(p,g,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function T(p,g){if(!p||!g)return{};const h={...p};if(h.localCandidateId){const b=g.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=g.get(h.remoteCandidateId);h.remote={...b}}return h}function x(p,g,h){return 8*function(b,E,P){const L=b[P],N=E?E[P]:null;return L===null||N===null?null:(L-N)/(b.timestamp-E.timestamp)*1e3}(p,g,h)}function I(p){if(!p.entries)return p;const g={};return p.forEach(function(h,b){g[b]=h}),g}function A(p,g,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const E of p.values())switch(E.type){case"outbound-rtp":{const P=E.mediaType||E.kind,L={};let N={};if(!["audio","video"].includes(P))continue;if(E.codecId){const D=p.get(E.codecId);D&&(L.clockRate=D.clockRate,L.mimeType=D.mimeType,L.payloadType=D.payloadType)}N=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[P].outbound.push({...E,...L,track:{...N}});break}case"inbound-rtp":{let P=E.mediaType||E.kind,L={};const N={};if(!["audio","video"].includes(P))if(E.id.includes("Video"))P="video";else{if(!E.id.includes("Audio"))continue;P="audio"}if(E.codecId){const D=p.get(E.codecId);D&&(N.clockRate=D.clockRate,N.mimeType=D.mimeType,N.payloadType=D.payloadType)}if(!b.connection.id&&E.transportId){const D=p.get(E.transportId);if(D&&D.selectedCandidatePairId){const F=p.get(D.selectedCandidatePairId);b.connection=T(F,p)}}L=p.get(E.mediaSourceId)||p.get(E.trackId)||{},b[P].inbound.push({...E,...N,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=E.dataChannelsClosed,b.connection.dataChannelsOpened=E.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=E.mediaType||E.kind;const L={};if(!["audio","video"].includes(P))if(E.id.includes("Video"))P="video";else{if(!E.id.includes("Audio"))continue;P="audio"}if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}if(!b.connection.id&&E.transportId){const N=p.get(E.transportId);if(N&&N.selectedCandidatePairId){const D=p.get(N.selectedCandidatePairId);b.connection=T(D,p)}}b.remote[P].inbound.push({...E,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=E.mediaType||E.kind,L={};if(!["audio","video"].includes(P))continue;if(E.codecId){const N=p.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}b.remote[P].outbound.push({...E,...L});break}}if(!b.connection.id)for(const E of p.values())E.type==="candidate-pair"&&E.nominated&&E.state==="succeeded"&&(b.connection=T(E,p));return b=function(E,P){return P&&(E.audio.inbound.map(L=>{let N=P.audio.inbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.audio.outbound.map(L=>{let N=P.audio.outbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")}),E.video.inbound.map(L=>{let N=P.video.inbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesReceived"),L.packetRate=x(L,N,"packetsReceived")}),E.video.outbound.map(L=>{let N=P.video.outbound.find(D=>D.id===L.id);L.bitrate=x(L,N,"bytesSent"),L.packetRate=x(L,N,"packetsSent")})),E}(b,g),b}let M,S={},C=[];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 g={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=g.getStatsInterval||1e3,this.rawStats=!!g.rawStats,this.statsObject=!!g.statsObject,this.filteredStats=!!g.filteredStats,this.shouldWrapGetUserMedia=!!g.wrapGetUserMedia,typeof g.remote=="boolean"&&(this.remote=g.remote),this.debug=!!g.debug,this.logLevel=g.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,g){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:g})}async addConnection(p){const{pc:g,peerId:h}=p;let{connectionId:b,remote:E}=p;if(E=typeof E=="boolean"?E:this.remote,!(g&&g instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const N=this.peersToMonitor[h][L];if(N.pc===g)throw new Error(`We are already monitoring peer with id ${h}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const P=g.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(L){delete L.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:b,pc:g,remote:E}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((g,h)=>g.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(g=>g.tag===p):this.timeline}get logger(){const p=g=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(g)>-1};return{error(...g){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...g)},warn(...g){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...g)},info(...g){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...g)},debug(...g){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...g)}}}removeConnection(p){let g,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let E in this.peersToMonitor)h in this.peersToMonitor[E]&&(b=this.peersToMonitor[E][h].pc,g=E)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let E in this.peersToMonitor)for(let P in this.peersToMonitor[E])this.peersToMonitor[E][P].pc===b&&(h=P,g=E)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[g][h],Object.values(this.peersToMonitor[g]).length===0&&delete this.peersToMonitor[g],{connectionId:h}}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 g in this.peersToMonitor[p]){let h=this.peersToMonitor[p][g].pc;this.removePeerConnectionEventListeners(g,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),C.forEach(p=>{this.removeTrackEventListeners(p)}),C=[],this.shouldWrapGetUserMedia&&M&&(navigator.mediaDevices.getUserMedia=M)}monitorPeer(p){let{peerId:g,connectionId:h,pc:b,remote:E}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:E}};if(this.peersToMonitor[g]){if(h in this.peersToMonitor[g])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[g][h]=P}else this.peersToMonitor[g]={[h]:P};this.addPeerConnectionEventListeners(g,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(g=>{this.emitEvent(g)})})},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 g={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);g[p]=this.peersToMonitor[p]}else g=this.peersToMonitor;let h=[];for(const b in g)for(const E in g[b]){const P=g[b][E],L=P.pc;if(L&&!this.checkIfConnectionIsClosed(b,E,L))try{const N=this.getTimestamp(),D=L.getStats(null);if(D){const F=await D,z=this.getTimestamp(),j=I(F),le={remote:P.options.remote},ee=A(F,P.stats.parsed,le),$={event:"stats",tag:"stats",peerId:b,connectionId:E,timeTaken:z-N,data:ee};this.rawStats===!0&&($.rawStats=F),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),P.stats.parsed=ee}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(N){this.logger.error(N)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const g in this.peersToMonitor[p]){const h=this.peersToMonitor[p][g].pc;this.checkIfConnectionIsClosed(p,g,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,g,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let E=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:E,peerId:p,connectionId:g,tag:"connection",data:"closed"})}return b}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."),M=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),M.apply(navigator.mediaDevices,arguments).then(g=>(p({stream:g}),g),g=>(p({error:g}),Promise.reject(g)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const g={...p};for(const b in g){var h=g[b];this.statsToMonitor.includes(h.type)||delete g[b]}return g}get peerConnectionListeners(){return{icecandidate:(p,g,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:g,data:b.candidate})},track:(p,g,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const E=b.track,P=b.streams[0];p in this.peersToMonitor&&g in this.peersToMonitor[p]&&(this.peersToMonitor[p][g].stream=P),this.addTrackEventListeners(E,g),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:g,data:{stream:P?this.getStreamDetails(P):null,track:E?this.getMediaTrackDetails(E):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:g,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceConnectionState})},icegatheringstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceGatheringState})},icecandidateerror:(p,g,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:g,error:{errorCode:b.errorCode}})},connectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.connectionState})},negotiationneeded:(p,g,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:g})},datachannel:(p,g,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:g,data:b.channel})}}}addPeerConnectionEventListeners(p,g,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${g}.`),S[g]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[g][b]=this.peerConnectionListeners[b].bind(this,p,g,h),h.addEventListener(b,S[g][b],!1)})}parseGetUserMedia(p){try{const g={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(g.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),C.push(h)})),this.emitEvent(g)}catch{}}parseStream(p){const g={audio:[],video:[]};return p.getTracks().forEach(h=>{g[h.kind].push(this.getMediaTrackDetails(h))}),g}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:g=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:g}})},unmute:g=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:g}})},overconstrained:g=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:g}})},ended:g=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:g}}),this.removeTrackEventListeners(g.target)}}}addTrackEventListeners(p,g){S[p.id]={};const h=this.getTrackEventObject(g);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const g=this.getTrackEventObject();Object.keys(g).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const g={...p,timestamp:new Date};this.addToTimeline(g),g.tag&&this.emit(g.tag,g)}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,g){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{g.removeEventListener(h,S[p][h],!1)}),delete S[p]),g.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),g.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const g=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),g.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(as=Ku)&&as.__esModule&&Object.prototype.hasOwnProperty.call(as,"default")&&as.default;var d0=Ku.WebRTCStats;function u0(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,r=function(c){const{jitter:u,rtt:d}=c,f=u+d/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),o=function(c){const{packetsLost:u,packetsReceived:d}=c,f=u/(d+u)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-r-o+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function h0(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 f0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class p0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class g0 extends ai{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function Xu(t,e){var n,i;return{errorCode:t.errorCode,errorText:t.errorText,url:t.url,address:t.address,port:t.port,connectionState:e.connectionState,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState,localDescriptionType:(n=e.localDescription)===null||n===void 0?void 0:n.type,remoteDescriptionType:(i=e.remoteDescription)===null||i===void 0?void 0:i.type}}function m0(t,e){const n=wn();let i=!1;const s=new d0({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),r=o=>V(this,void 0,void 0,function*(){o.event==="stats"&&U(O.StatsFrame,function({data:a}){var l,c,u,d,f,m,v,_;const{audio:w,remote:y}=a,{audio:T}=y,x=(c=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,I=(d=(u=T.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,A=(m=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&m!==void 0?m:-1,M=(_=(v=w.inbound[0])===null||v===void 0?void 0:v.packetsLost)!==null&&_!==void 0?_:-1,S=u0({jitter:1e3*x,rtt:1e3*I,packetsLost:M,packetsReceived:A});return{jitter:x,rtt:I,mos:S,quality:h0(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}}(o),t.uuid),yield t.execute(new g0(n,o))});return{get isRunning(){return i},start:(o,a,l)=>V(this,void 0,void 0,function*(){if(i)k.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new f0(n,e)),s.on("timeline",r);try{yield s.addConnection({pc:o,peerId:a,connectionId:l}),i=!0}catch(c){k.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:o=>V(this,void 0,void 0,function*(){const a=s.getTimeline();U(O.StatsReport,a,t.uuid),o==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),f=document.createElement("a");f.href=d,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new p0(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:o=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)},reportIceCandidateError:o=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:o};r(a)}}}const Yu=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:r=null,currentLayerIdx:o=-1}=e;r&&i!=="mcu-personal-canvas"&&delete r.memberID;const a={type:et.conferenceUpdate,call:t.calls[s],canvasInfo:v0(r),currentLayerIdx:o};switch(n){case"layer-info":{const l=Object.assign({action:ze.LayerInfo},a);U(O.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ze.LayoutInfo},a);U(O.Notification,l,t.uuid);break}}},v0=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Cu(e)},Ju=["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"],y0={"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 Zu(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}class hi{constructor(e,n,i,s,r){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,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.handleConnectionStateChange=()=>V(this,void 0,void 0,function*(){const{connectionState:o}=this.instance;if(k.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${o}`),o==="failed"||o==="disconnected"){const a=()=>V(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,u){return V(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const m=f[0].sender,v=m==null?void 0:m.transport;v&&(d.dtlsState=v.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const m=yield c.getStats();m.forEach(v=>{v.type==="candidate-pair"&&v.state==="succeeded"&&(d.candidatePairState=v.state,m.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(m){k.error("Error gathering connection state details:",m)}return d})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}if(o==="disconnected"){const a=xt(C_);U(O.Warning,{warning:a,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(o==="failed"){const a=xt(x_);U(O.PeerConnectionFailureError,{warning:a,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${o}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=o,o==="connected"&&(performance.mark("dtls-connected"),this.tryCollectTimings()),this._isTrickleIce()&&(o==="connecting"&&performance.mark("peer-connection-connecting"),o==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark("peer-connection-connected")))}),this._handleIceConnectionStateChange=()=>{const o=this.instance.iceConnectionState;k.debug(`[${new Date().toISOString()}] ICE Connection State`,o),o==="connected"&&performance.mark("ice-connected")},this._handleIceGatheringStateChange=()=>{const o=this.instance.iceGatheringState;k.debug(`[${new Date().toISOString()}] ICE Gathering State`,o),o==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):o==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(o,a)=>{if(o.setCodecPreferences)return o.setCodecPreferences(a)},k.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=r}get isOffer(){return this.type===De.Offer}get isAnswer(){return this.type===De.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("start-negotiation"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return V(this,void 0,void 0,function*(){performance.mark("start-negotiation"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){this.instance?(k.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{k.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),k.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):k.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(k.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":U(O.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(k.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){k.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?k.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark("first-remote-media-track"),this._firstMediaTrackMarked=!0);const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&ci(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName("call-active","mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=function(n,i){const s=Zu("new-call-start");if(s===void 0)return{mode:n,direction:i,steps:[]};const r=[];for(const l of Ju){if(l==="new-call-start")continue;const c=Zu(l);c!==void 0&&r.push({label:y0[l]||l,fromStart:c-s})}r.sort((l,c)=>l.fromStart-c.fromStart);const o=[];let a=0;for(const l of r)o.push({label:l.label,fromStart:l.fromStart,delta:l.fromStart-a}),a=l.fromStart;return{mode:n,direction:i,steps:o}}(this._isTrickleIce()?"trickle":"non-trickle",this.isOffer?"outbound":"inbound");(function(n){const{mode:i,direction:s,steps:r}=n,o=`[CallTimings][${s}][${i}]`;if(r.length===0)return void k.info(`${o} No timing data collected`);const a=Math.max(...r.map(f=>f.label.length),4)+2,l=(f,m)=>{for(;f.length<m;)f+=" ";return f},c=(f,m)=>{for(;f.length<m;)f=" "+f;return f},u=l("Step",a)+c("Delta",14)+c("From Start",14);let d="";for(let f=0;f<u.length;f++)d+="-";k.info(`${o} Call establishment timing breakdown:`),k.info(`${o} ${u}`),k.info(`${o} ${d}`),k.info(`${o} ${l("Call Start",a)}${c("-",14)}${c("0.00ms",14)}`);for(const f of r){const m=f.delta.toFixed(2)+"ms",v=f.fromStart.toFixed(2)+"ms";k.info(`${o} ${l(f.label,a)}${c(m,14)}${c(v,14)}`)}k.info(`${o} ${d}`)})(e),function(){for(const n of Ju)try{performance.clearMarks(n)}catch{k.warn("Clearing performance marks is failed")}}()}createPeerConnection(){return V(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:De.Offer}),performance.mark("set-remote-description"),!this.instance))throw oe(sr);const n=!!this.options.receiveOnlyAudio&&!this.options.audio;let i=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>V(this,void 0,void 0,function*(){const r=this._session.options.mediaPermissionsRecovery;if(r!=null&&r.enabled&&this._isAnswer()){let o=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),r.timeout),U(O.Error,{error:oe(si(s),s),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+r.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>V(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),o=yield this._retrieveLocalStream(),(l=r.onSuccess)===null||l===void 0||l.call(r)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),i=l,(c=r.onError)===null||c===void 0||c.call(r,l)}),o}return i=s,null})),!this.instance)throw oe(sr);if(!this.options.localStream&&!n)throw oe(i?si(i):hu,i??void 0);performance.mark("get-user-media"),this.options.mutedMicOnStart&&Tn(this.options.localStream)&&(k.info("Muting local audio tracks on start"),fr(this.options.localStream)),performance.mark("peer-creation-end")})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=xt(k_);U(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=xt(T_);U(O.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},hi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return V(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw oe(sr);this.isDebugEnabled&&(this.statsReporter=m0(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Tn(i)){const r=i.getAudioTracks();let o=[...r];if(k.info("Local audio tracks: ",r),typeof this.options.audio=="object"&&r.forEach(c=>{k.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();o=[...r,...c],k.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{k.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=qu(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};o.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"?(o.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&ci(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const r=this.instance.addTransceiver("audio",{direction:"recvonly"});k.info("Added recvonly audio transceiver for receive-only mode",r);const{audioCodecs:o}=qu(this.options.preferred_codecs);o.length>0&&this._setCodecs(r,o)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);k.info("Add transceiver",e,n)}}_createOffer(){return V(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,k.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark("create-offer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),this._isTrickleIce()||this._sdpReady(),e}catch(e){k.error("Peer _createOffer error:",e);const n=oe(n_,e);U(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){k.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(n){k.error("Peer _setRemoteDescription error:",n);const i=oe(du,n);throw U(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_createAnswer(){return V(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return k.debug("Skipping negotiation, state:",this.instance.signalingState),k.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:De.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark("create-answer"),yield this._setLocalDescription(e),performance.mark("set-local-description"),performance.mark("ice-gathering-started"),e}catch(e){k.error("Peer _createAnswer error:",e);const n=oe(i_,e);U(O.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(n){k.error("Peer _setLocalDescription error:",n);const i=oe(s_,n);throw U(O.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_sdpReady(){Sn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(Tn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,V(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:r=!1,camId:o}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield rs(s,a,gt.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),o&&(o=yield rs(o,l,gt.Video).catch(c=>null),o&&(typeof r=="boolean"&&(r={}),r.deviceId={exact:o})),{audio:i,video:r}}));var n;return os(e)})}_isOffer(){return this.type===De.Offer}_isAnswer(){return this.type===De.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return k.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?k.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(k.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):k.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){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)})}}hi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3;const ls=cr;class Qu{constructor(e,n){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=q[q.New],this.prevState="",this.channels=[],this.role=ar.Participant,this.extension=null,this._state=q.New,this._prevState=q.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=w=>{const y=w<0||!this._lastSerno||this._lastSerno&&w===this._lastSerno+1;return y&&w>=0&&(this._lastSerno=w),y},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(w=>{w.forEach(y=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const x in T.constraints)if(T.constraints.hasOwnProperty(x)&&T.constraints[x]!==y[x])return}T.callback(y)}})})})};const{iceServers:i,speaker:s,micId:r,micLabel:o,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:f,video:m},ringtoneFile:v,ringbackFile:_}=e;this.options=Object.assign({},G_,{audio:f,video:m,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:i,localElement:c,remoteElement:u,micId:r,micLabel:o,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},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=Gu(this.options.ringtoneFile,"_ringtone"),this._ringback=Gu(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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!a0(this.options.localStream)}invite(){return V(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=pt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new hi(De.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(e){k.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const n=e instanceof ii?e:oe(pu,e instanceof Error?e:void 0);return U(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({},!1)}this._creatingPeer=!1})}answer(e={}){var n,i;return V(this,void 0,void 0,function*(){if(!((n=this.peer)===null||n===void 0)&&n.instance&&this.peer.instance.signalingState!=="closed"){const s=xt(I_);return U(O.Warning,{warning:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void k.warn(`[${this.id}] answer() ignored: peer connection already exists (signalingState: ${this.peer.instance.signalingState})`)}performance.mark("answer-called"),this._creatingPeer=!0,this.stopRingtone(),this.direction=pt.Inbound,((i=e==null?void 0:e.customHeaders)===null||i===void 0?void 0:i.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("new-peer"),this.peer=new hi(De.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents);try{yield this.peer.init()}catch(s){k.error("Peer init failed, aborting call",s),this._creatingPeer=!1;const r=s instanceof ii?s:oe(pu,s instanceof Error?s:void 0);return U(O.Error,{error:r,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup())}this._creatingPeer=!1})}playRingtone(){Wu(this._ringtone)}stopRingtone(){zu(this._ringtone)}playRingback(){Wu(this._ringback)}stopRingback(){zu(this._ringback)}hangup(e,n){var i,s,r,o;return V(this,void 0,void 0,function*(){const a=e||{},l=n!==!1,c=this._state<q.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=a.cause||c.cause,this.causeCode=a.causeCode||c.causeCode,this.sipCode=a.sipCode||null,this.sipReason=a.sipReason||null,this.sipCallId=a.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(r=(s=a==null?void 0:a.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&r!==void 0?r:[]],a.isRecovering)return this._isRecovering=!0,this.setState(q.Recovering),void this._finalize();if(this.setState(q.Hangup),this.stopRingtone(),this.stopRingback(),l){const u=new Z_({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});try{yield this._execute(u)}catch(d){k.error("telnyx_rtc.bye failed!",d);const f=oe(c_,d);U(O.Error,{error:f,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}k.debug(`[${this.id}] Closing peer from hangup`),(o=this.peer)===null||o===void 0||o.close(),this.setState(q.Destroy)})}hold(){const e=new dr({sessid:this.session.sessionid,action:"hold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new dr({sessid:this.session.sessionid,action:"unhold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new dr({sessid:this.session.sessionid,action:"toggleHold",dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new Bu({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(n)}message(e,n){const i={from:this.session.options.login,to:e,body:n},s=new Bu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){fr(this.options.localStream)}unmuteAudio(){$u(this.options.localStream)}toggleAudioMute(){Hu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){var i;return V(this,void 0,void 0,function*(){const{instance:s}=this.peer,r=s.getSenders().find(({track:{kind:o}})=>o==="audio");if(r){let o;try{o=yield ss({audio:{deviceId:{exact:e}}})}catch(c){const u=oe(si(c),c);return void U(O.MediaError,u,((i=this.options)===null||i===void 0?void 0:i.id)||this.id)}const a=o.getAudioTracks()[0];a.enabled=!n,r.replaceTrack(a),this.options.micId=e;const{localStream:l}=this.options;l.getAudioTracks().forEach(c=>c.stop()),l.getVideoTracks().forEach(c=>o.addTrack(c)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,kn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,kn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,kn(e,"video",null)}setVideoDevice(e){return V(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield ss({video:{deviceId:{exact:e}}}),r=s.getVideoTracks()[0];i.replaceTrack(r);const{localElement:o,localStream:a}=this.options;ci(o,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){fr(this.options.remoteStream)}undeaf(){$u(this.options.remoteStream)}toggleDeaf(){Hu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void k.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:i}=this.peer,s=i.getSenders();if(!s)return void k.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 r=s.find(({track:{kind:o}})=>o===n);if(r){const o=r.getParameters();o.encodings||(o.encodings=[{rid:"h"}]),k.info("Parameters: ",o),k.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),o.encodings[0].maxBitrate=e,yield r.setParameters(o).then(()=>{k.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",r.getParameters())}).catch(a=>k.error(a))}else k.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n,i;switch(this._prevState=this._state,this._state=e,this.state=q[this._state].toLowerCase(),this.prevState=q[this._prevState].toLowerCase(),k.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:et.callUpdate,call:this}),e){case q.Purge:k.info(`[${this.id}] Entering Purge state.`);break;case q.Active:performance.mark("call-active"),(n=this.peer)===null||n===void 0||n.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,k.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:s,speakerId:r}=this.options;s&&r&&Uu(s,r)},0),this._callReportCollector&&!((i=this.peer)===null||i===void 0)&&i.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case q.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(performance.mark("telnyx-rtc-answer"),this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=q.Active)return;this._state>=q.Early&&this.setState(q.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(performance.mark("telnyx-rtc-media"),this._state>=q.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:{const{display_name:r,display_number:o,display_direction:a}=i;this.extension=o;const l=a===pt.Inbound?pt.Outbound:pt.Inbound,c={type:et[n],call:this,displayName:r,displayNumber:o,displayDirection:l};U(O.Notification,c,this.id)||U(O.Notification,c,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const r=Object.assign(Object.assign({},i),{type:et.generic,call:this});U(O.Notification,r,this.id)||U(O.Notification,r,this.session.uuid);break}case te.Ringing:performance.mark("ringing"),this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case te.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(i,!1)}}handleConferenceUpdate(e,n){return V(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return k.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:r=String(this._lastSerno),arrIndex:o}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:f}=n;this._dispatchConferenceUpdate({action:ze.Join,conferenceName:u,participantId:Number(d),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const m=[];for(const v in s)m.push(Object.assign({callId:s[v][0],index:Number(v)},ts(s[v][1])));this._dispatchConferenceUpdate({action:ze.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ze.Add,callId:r,index:o},ts(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ze.Modify,callId:r,index:o},ts(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ze.Delete,callId:r,index:o},ts(s)));break;case"clear":this._dispatchConferenceUpdate({action:ze.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:r,index:o})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return V(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:r,from:o,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ze.ChatMessage,direction:r,participantNumber:o,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfChat subscription error:",s)});ur(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,r)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:r}})}}}))})}_subscribeConferenceInfo(e){return V(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:r}=s;r.contentType==="layout-info"?(r.callID=this.id,Yu(this.session,r)):k.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{k.error("ConfInfo subscription error:",s)});ur(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(q.Active):this.setState(q.Held),!0}_handleChangeHoldStateError(e){k.error(`Failed to ${e.action} on call ${this.id}`);const n=oe(a_,e);return U(O.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_onRemoteSdp(e){return V(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:De.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{performance.mark("set-remote-description"),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(q.Early),this.gotAnswer&&this.setState(q.Active)}).catch(i=>V(this,void 0,void 0,function*(){k.error("Call setRemoteDescription Error: ",i);const s=oe(du,i);U(O.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(r){k.error("Error during hangup after setRemoteDescription failure:",r)}}))})}_requestAnotherLocalDescription(){Sn(this.peer.onSdpReadyTwice)?U(O.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this._iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0,!e)return void k.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:s,type:r}=e;if(s.indexOf("candidate")===-1)return k.info(`No candidate - retry
116
+ `),void this._requestAnotherLocalDescription();if((i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),!L_.test(s)){const l=xt(E_);k.warn(`[${this.id}] Warning ${l.code}: ${l.message}`),U(O.Warning,{warning:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark("ice-gathering-end");let o=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${ls}`};switch(r){case De.Offer:this.setState(q.Requesting),o=new Ou(a);break;case De.Answer:this._isRecovering||this.setState(q.Answering),o=this.options.attach===!0?new Vu(a):new Fu(a);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(o).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,r===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(l=>V(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${r} error:`,l);const c=oe(uu,l);U(O.Error,{error:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(u){k.error("Error during hangup after SDP send failure:",u)}}))}_onTrickleIceSdp(e){if(!e)return k.error("No SDP data provided"),void this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ls}`};switch(i){case De.Offer:this.setState(q.Requesting),s=new Ou(r);break;case De.Answer:this._isRecovering||this.setState(q.Answering),s=this.options.attach===!0?new Vu(r):new Fu(r);break;default:return k.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({},!1)}performance.mark("send-sdp"),this._execute(s).then(o=>{const{node_id:a=null}=o;this._targetNodeId=a,i===De.Offer?this.setState(q.Trying):this.setState(q.Active)}).catch(o=>V(this,void 0,void 0,function*(){k.error(`${this.id} - Sending ${i} error:`,o);const a=oe(uu,o);U(O.Error,{error:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17},!0)}catch(l){k.error("Error during hangup after SDP send failure:",l)}}))}_onIce(e){var n;const{instance:i}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(i.localDescription),s)}e.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(i.localDescription)}_onTrickleIce(e){var n;e.candidate&&e.candidate.candidate?(k.debug("RTCPeer Candidate:",e.candidate),(n=this.peer)===null||n===void 0||n.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new Q_({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(n)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return k.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const n=this.peer.instance.addIceCandidate(e);Promise.resolve(n).then(()=>{k.debug("Successfully added ICE candidate:",e)}).catch(i=>{k.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new e0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark("first-candidate"),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark("first-non-host-candidate"),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){this._iceDone=!1,e.onicecandidate=n=>{this._iceDone||this._onIce(n)},e.onicegatheringstatechange=()=>{e.iceGatheringState==="complete"&&performance.mark("ice-gathering-completed")},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Xu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:r}=this.options;r===!1&&ci(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{k.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(k.debug("Finished gathering candidates"),performance.mark("ice-gathering-completed"))},e.onicecandidateerror=n=>{var i;if(k.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Xu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:r}=this.options;r===!1&&ci(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:et.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),k.error(`Media error (${n}): ${i}`,e),U(O.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:et.peerConnectionFailureError,error:e.error}),k.error("Peer connection failure error"),e.warning&&U(O.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:et.signalingStateClosed},e)),k.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:et.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(U(O.Notification,e,this.id,!1)||U(O.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){var e,n;const{id:i,userVariables:s,remoteCallerNumber:r,onNotification:o,recoveredCallId:a}=this.options;var l;this.options.id=i?i.toString():wn(),this.id=this.options.id,a&&(this.recoveredCallId=a,this._isRecovering=!0),s&&(l=s,Object.keys(l).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Nt(O.MediaError,this._onMediaError,this.id),Nt(O.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Nt(O.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Sn(o)&&Nt(O.Notification,o.bind(this),this.id);const c=this.session.options.enableCallReports!==!1,u=this.session.options.callReportInterval||5e3,d=this.session.options.debugLogLevel||"debug",f=this.session.options.debugLogMaxEntries||1e3;c&&(this._callReportCollector=new Te({enabled:!0,interval:u},{enabled:!0,level:d,maxEntries:f}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=m=>{U(O.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}),this._isRecovering?this.setState(q.Recovering):this.setState(q.New),k.info(`New Call — region: ${(e=this.session.region)!==null&&e!==void 0?e:"unknown"}, dc: ${(n=this.session.dc)!==null&&n!==void 0?n:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),k.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;di(n),di(i),Ot(O.MediaError,null,this.id),Ot(O.PeerConnectionFailureError,null,this.id),Ot(O.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{k.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void k.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void k.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},r=this._callReportCollector.flush(s);if(!r)return;const o=Yt()||void 0;this._callReportCollector.sendPayload(r,n,i,o).catch(a=>{k.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return V(this,void 0,void 0,function*(){if(!this._callReportCollector)return void k.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return k.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===pt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ls},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void k.error("Cannot post call report: connection host not available");const r=Yt()||void 0;this._callReportCollector.postReport(i,n,s,r).catch(o=>{k.error("Failed to post call report",{error:o})}).finally(()=>{var o;(o=this._callReportCollector)===null||o===void 0||o.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),k.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),k.debug("Stats stopped")}}Qu.setStateTelnyx=t=>{if(t){switch(t._state){case q.Recovering:t.state="recovering";break;case q.Requesting:case q.Trying:case q.Early:t.state="connecting";break;case q.Active:t.state="active";break;case q.Held:t.state="held";break;case q.Hangup:case q.Destroy:t.state="done";break;case q.Answering:t.state="ringing";break;case q.New:t.state="new"}return t}};class Jt extends Qu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new c0(e,n))}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return V(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return V(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>V(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup())}))});const{remoteCallerName:s,remoteCallerNumber:r,callerName:o,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${r}-screen`,callerName:`${o} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Jt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof Jt&&(yield this.screenShare.hangup())})}setAudioOutDevice(e){return V(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&Uu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>V(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],r=["id","type","timestamp"];n.forEach(o=>{s.includes(o.type)||(i+=`
117
117
  ${o.type}
118
118
  `,Object.keys(o).forEach(a=>{r.includes(a)||(i+=` ${a}: ${o[a]}
119
- `)}))}),k.info(i)}),2e3)}}class _0 extends li{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return F(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return F(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return F(this,void 0,void 0,function*(){try{const i=yield os({audio:e,video:n});return di(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(z.Purge),k.info("Start hangup for ",i),yield i.hangup({},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return F(this,void 0,void 0,function*(){k.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(z.Purge),i.hangup({},!1)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Au(O.SpeedTest,o=>{const{upDur:a,downDur:l}=o,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const r=".".repeat(1024);for(let o=0;o<s;o++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return ui().catch(e=>{const n=oe(si(e),e);return B(O.MediaError,n,this.uuid),[]})}getVideoDevices(){return ui(gt.Video).catch(e=>(B(O.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ui(gt.AudioIn).catch(e=>{const n=oe(si(e),e);return B(O.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return ui(gt.AudioOut).catch(e=>(k.error("getAudioOutDevices",e),B(O.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return rs(e,n,i)}getDeviceResolutions(e){return F(this,void 0,void 0,function*(){try{return yield(n=>F(void 0,void 0,void 0,function*(){const i=[],s=yield os({video:{deviceId:{exact:n}}}),r=s.getVideoTracks()[0];for(let o=0;o<ju.length;o++){const[a,l]=ju[o];(yield r.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return di(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return F(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Zi(e,["micId","micLabel"]);return o0(s),this._audioConstraints=yield((r,o,a,l)=>F(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(r||o)){const u=yield rs(r,o,a).catch(d=>null);u&&(l.deviceId={exact:u})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?Dy:Py}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ns(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ns(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new e0({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new t0({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const r=yield this.execute(s),{unauthorized:o=[],subscribed:a=[]}=hr(r);return o.length&&o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return F(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new n0({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:r=[],notSubscribed:o=[]}=hr(s);return r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(k.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,k.debug(`Network connectivity lost for session ${this.sessionid}`);const e=oe(my);B(O.Error,{error:e,sessionId:this.sessionid},this.uuid)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return Jt.setStateTelnyx(e)}}class eh{constructor(e,n){this.code=n,this.message=e}}class y0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new Yy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ku(2,6)}handleMessage(e){var n,i,s,r,o,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:f,method:m,params:v={},voice_sdk_id:y}=e,w=v==null?void 0:v.callID,_=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,x=d.calls[w],I=(n=x==null?void 0:x.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(v==null?void 0:v.reattached_sessions)&&v.reattached_sessions.length===0&&Object.keys(d.calls).length>0){const C=xt(Ay);B(O.Warning,{warning:C,sessionId:d.sessionid},d.uuid)}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const A=C=>{var p,g,h,b,E,P;const L={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:m===te.Attach,mediaSettings:v.mediaSettings,debug:(p=d.options.debug)!==null&&p!==void 0&&p,debugOutput:(g=d.options.debugOutput)!==null&&g!==void 0?g:"socket",trickleIce:(h=d.options.trickleIce)!==null&&h!==void 0&&h,prefetchIceCandidates:(b=d.options.prefetchIceCandidates)===null||b===void 0||b,forceRelayCandidate:(E=d.options.forceRelayCandidate)!==null&&E!==void 0&&E,keepConnectionAliveOnSocketClose:(P=d.options.keepConnectionAliveOnSocketClose)!==null&&P!==void 0&&P};w&&(L.id=w),v.telnyx_call_control_id&&(L.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(L.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(L.telnyxLegId=v.telnyx_leg_id),v.client_state&&(L.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(L.customHeaders=v.dialogParams.custom_headers),C&&(L.recoveredCallId=C),performance.mark("new-call-start");const N=new Jt(d,L);return N.nodeId=this.nodeId,N},M=new Du(y),S=new Mu(y);switch(m){case te.Answer:case te.Display:case te.Candidate:case te.Ringing:case te.Bye:case te.Media:if(!w||!x)return void k.error(`Received ${m} for non existing call:`,v);x.handleMessage(e),this._ack(f,m);break;case te.Ping:this.session.setPingReceived(),this.session.execute(S);break;case te.Punt:d.options.keepConnectionAliveOnSocketClose&&I?(k.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(f,m)):(k.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case te.Invite:{const g=A();g.direction=pt.Inbound,g.playRingtone(),g.setState(z.Ringing),this._ack(f,m);break}case te.Attach:{if(!x)return A().answer(),void this._ack(f,m);const g=x.id;k.info(`[${new Date().toISOString()}][${w}] closing existing call on ATTACH.`),x.hangup({isRecovering:!0},!1),k.info(`[${new Date().toISOString()}][${w}] Attach: Creating new call for recovery (recoveredCallId: ${g})`),A(g).answer(),this._ack(f,m);break}case te.Event:case"webrtc.event":if(!_)return void k.error("Verto received an unknown event:",v);const C=d.relayProtocol,p=_.split(".")[0];d._existsSubscription(C,_)?B(C,v,_):_===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(C,p)?B(C,v,p):d.calls.hasOwnProperty(_)?d.calls[_].handleMessage(e):B(O.Notification,v,d.uuid);break;case te.Info:v.type=et.generic,B(O.Notification,v,d.uuid);break;case te.ClientReady:this.session.execute(M);break;default:{const g=or(e);if(g){switch(g){case Ue.REGISTER:case Ue.REGED:if(d.connection.previousGatewayState!==Ue.REGED&&d.connection.previousGatewayState!==Ue.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const h=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;h&&(d.callReportId=h,k.debug("Captured call_report_id from REGED:",h));const b=(o=(r=e==null?void 0:e.result)===null||r===void 0?void 0:r.params)===null||o===void 0?void 0:o.dc;b&&(d.dc=b);const E=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;E&&(d.region=E),k.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=et.vertoClientReady,B(O.Ready,v,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const h=new eh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),b=oe(fu,h);B(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(M)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:if(d.connection.previousGatewayState!==Ue.FAILED&&d.connection.previousGatewayState!==Ue.FAIL_WAIT){const h=oe(fy,new Error(`Gateway state: ${g}`));if(B(O.Error,{error:h,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const b=new eh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),E=oe(hy,b);B(O.Error,{error:E,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const b=oe(45003,new Error("Connection Retry Failed"));B(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(k.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(b=>{var E;return((E=b.peer)===null||E===void 0?void 0:E.instance)&&!b.signalingStateClosed}))return k.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();k.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:k.warn("GatewayState message unknown method:",e)}break}k.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(r=>i.includes(r[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return F(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:r,laName:o,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:o}}})},v={nodeId:this.nodeId,channels:[r],handler:({data:w})=>{const _=f||this._retrieveCallId(w,r);if(_&&n.calls.hasOwnProperty(_)){const T=n.calls[_];T._addChannel(r),T.extension=o,T.handleConferenceUpdate(w,e).then(x=>{x==="INVALID_PACKET"&&m()})}}},y=yield n.vertoSubscribe(v).catch(w=>{k.error("liveArray subscription error:",w);const _=oe(cy,w);B(O.Error,{error:_,sessionId:n.sessionid},n.uuid)});ur(y,r)&&m();break}case"conference-liveArray-part":{let m=null;if(r&&n._existsSubscription(i,r)){const{callId:y=null}=n.subscriptions[i][r];if(m=n.calls[y]||null,y!==null){const w={type:et.conferenceUpdate,action:ze.Leave,conferenceName:o,participantId:Number(u),role:d};B(O.Notification,w,y,!1)||B(O.Notification,w,n.uuid),m===null&&Mt(O.Notification,null,y)}}const v=[r,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:y=[]})=>{m&&(m.channels=m.channels.filter(w=>!y.includes(w)))}).catch(y=>{k.error("liveArray unsubscribe error:",y)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Yu(this.session,e);break;case"logo-info":{const n={type:et.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};B(O.Notification,n,this.session.uuid);break}}}}class b0 extends _0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>F(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new y0(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(k.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return is(this.options)||oi(this.options)}newCall(e){if(!this.validateCallOptions(e))throw oe(ay,void 0,"Error: destinationNumber is required");const n=new Jt(this,e);return performance.mark("new-call-start"),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!oi(this.options)||!!e.destinationNumber}_onSocketOpen(){return F(this,void 0,void 0,function*(){return is(this.options)?this.handleLoginOnSocketOpen():oi(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class w0 extends b0{constructor(e){super(e),k.info(`SDK version: ${Nu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return a0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Se.not_supported},{browserName:"Firefox",supported:Se.not_supported},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",features:["audio"],supported:Se.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",features:["audio"],supported:Se.partial}]}]}}function th(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var nh={exports:{}},ih;function S0(){return ih||(ih=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var m=new s(u,d||l,f),v=n?n+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],m]:l._events[v].push(m):(l._events[v]=m,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,m=new Array(f);d<f;d++)m[d]=u[d].fn;return m},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,f,m){var v=n?n+l:l;if(!this._events[v])return!1;var y=this._events[v],w=arguments.length,_,T;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),w){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,u),!0;case 4:return y.fn.call(y.context,c,u,d),!0;case 5:return y.fn.call(y.context,c,u,d,f),!0;case 6:return y.fn.call(y.context,c,u,d,f,m),!0}for(T=1,_=new Array(w-1);T<w;T++)_[T-1]=arguments[T];y.fn.apply(y.context,_)}else{var x=y.length,I;for(T=0;T<x;T++)switch(y[T].once&&this.removeListener(l,y[T].fn,void 0,!0),w){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,c);break;case 3:y[T].fn.call(y[T].context,c,u);break;case 4:y[T].fn.call(y[T].context,c,u,d);break;default:if(!_)for(I=1,_=new Array(w-1);I<w;I++)_[I-1]=arguments[I];y[T].fn.apply(y[T].context,_)}}return!0},a.prototype.on=function(l,c,u){return r(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return r(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return o(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!d||m.once)&&(!u||m.context===u)&&o(this,f);else{for(var v=0,y=[],w=m.length;v<w;v++)(m[v].fn!==c||d&&!m[v].once||u&&m[v].context!==u)&&y.push(m[v]);y.length?this._events[f]=y.length===1?y[0]:y:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(nh)),nh.exports}var C0=S0();const pr=th(C0),cs=new pr;var gr={exports:{}},T0=gr.exports,sh;function k0(){return sh||(sh=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(T0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(y,w){var _=y[w];if(typeof _.bind=="function")return _.bind(y);try{return Function.prototype.bind.call(_,y)}catch{return function(){return Function.prototype.apply.apply(_,[y,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(y){return y==="debug"&&(y="log"),typeof console===n?!1:y==="trace"&&i?l:console[y]!==void 0?a(console,y):console.log!==void 0?a(console,"log"):e}function u(){for(var y=this.getLevel(),w=0;w<s.length;w++){var _=s[w];this[_]=w<y?e:this.methodFactory(_,y,this.name)}if(this.log=this.debug,typeof console===n&&y<this.levels.SILENT)return"No console available for logging"}function d(y){return function(){typeof console!==n&&(u.call(this),this[y].apply(this,arguments))}}function f(y,w,_){return c(y)||d.apply(this,arguments)}function m(y,w){var _=this,T,x,I,A="loglevel";typeof y=="string"?A+=":"+y:typeof y=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),P=b.indexOf(E+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+E.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&_.levels[b.toUpperCase()]!==void 0&&(b=_.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=_.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=y,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=w||f,_.getLevel=function(){return I??x??T},_.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(_)},_.setDefaultLevel=function(h){x=p(h),S()||_.setLevel(h,!1)},_.resetLevel=function(){I=null,C(),u.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(o!==_&&(T=p(o.getLevel())),u.call(_),o===_)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var g=S();g!=null&&(I=p(g)),u.call(_)}o=new m,o.getLogger=function(y){if(typeof y!="symbol"&&typeof y!="string"||y==="")throw new TypeError("You must supply a name when creating a logger.");var w=r[y];return w||(w=r[y]=new m(y,o.methodFactory)),w};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(gr)),gr.exports}var x0=k0();const E0=th(x0),I0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Me=E0.getLogger("telnyx-ai-agent"),A0=Me.methodFactory;Me.methodFactory=(t,e,n)=>{const i=A0(t,e,n);return function(...s){i(I0(),"-",...s)}},Me.setLevel("info");function R0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const L0=10,P0=500,D0=100,oh=20;class M0{constructor(e){X(this,"remoteIntervalId",null);X(this,"localIntervalId",null);X(this,"remoteStream",null);X(this,"localStream",null);X(this,"remoteAudioContext",null);X(this,"remoteSource",null);X(this,"remoteAnalyser",null);X(this,"localAudioContext",null);X(this,"localSource",null);X(this,"localAnalyser",null);X(this,"thinkingStartTime",null);X(this,"lastState",null);X(this,"userIsSpeaking",!1);X(this,"lastUserAudioTime",null);X(this,"userSpeechStartTime",null);X(this,"userSilenceStartTime",null);X(this,"isFirstAgentSpeech",!0);X(this,"monitorStartTime",null);X(this,"volumeThreshold");X(this,"silenceDurationMs");X(this,"minSpeechDurationMs");X(this,"maxLatencyMs");X(this,"updateAgentState",R0(e=>{Me.debug("AudioStreamMonitor updateAgentState",e),Me.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,cs.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??L0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??P0,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??D0,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Me.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Me.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Me.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var r;Me.debug("AudioContext resumed, state:",(r=this.remoteAudioContext)==null?void 0:r.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const r=n.reduce((l,c)=>l+c,0)/n.length,o=r>=this.volumeThreshold;if(Math.random()<.01&&Me.debug("Remote audio volume:",r,"threshold:",this.volumeThreshold,"above:",o),o)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=o};this.remoteIntervalId=window.setInterval(s,oh)}startLocalMonitor(){if(!this.localStream){Me.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Me.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Me.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((r,o)=>r+o,0)/e.length;if(Math.random()<.02&&Me.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const r=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:r})}};this.localIntervalId=window.setInterval(n,oh)}destroy(){this.stopAudioStreamMonitor()}}function N0(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function O0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function F0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function V0(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function B0(t){return O0(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function U0(t){if(!F0(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class j0 extends pr{constructor(n){super();X(this,"telnyxRTC");X(this,"transcript",[]);X(this,"onSocketMessage",n=>{if(N0(n))switch(n.params.type){case"response.text.delta":{const i=B0(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),cs.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(V0(n)){const i=n.params.item_id,s=this.transcript.findIndex(r=>r.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=U0(n);if(i){const s=this.transcript.findIndex(r=>r.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(O.SocketMessage,this.onSocketMessage)}}class $0 extends pr{constructor(n){super();X(this,"telnyxRTC");X(this,"transcription");X(this,"agentId");X(this,"versionId");X(this,"conversationId");X(this,"debug");X(this,"audioStreamMonitor");X(this,"activeCall");X(this,"chatMode");X(this,"dc",null);X(this,"region",null);X(this,"callReportId",null);X(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const n={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",n)});X(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});X(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});X(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});X(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Me.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new w0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region,skipLastVoiceSdkId:n.skipLastVoiceSdkId??!0}),this.telnyxRTC.on(O.Ready,this.onClientReady),this.telnyxRTC.on(O.Error,this.onClientOrSocketError),this.telnyxRTC.on(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(O.Notification,this.onNotification),this.transcription=new j0(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),cs.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new M0(n.vad)}async connect(){return this.telnyxRTC.connect()}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(O.Ready,this.onClientReady),this.telnyxRTC.off(O.Error,this.onClientOrSocketError),this.telnyxRTC.off(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(O.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),cs.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Me.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){Me.error("Client is not initialized.");return}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:r,...o}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...o,audio:this.chatMode?!1:r??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var rh={exports:{}},fi={},ah;function H0(){if(ah)return fi;ah=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,r){var o=null;if(r!==void 0&&(o=""+r),s.key!==void 0&&(o=""+s.key),"key"in s){r={};for(var a in s)a!=="key"&&(r[a]=s[a])}else r=s;return s=r.ref,{$$typeof:t,type:i,key:o,ref:s!==void 0?s:null,props:r}}return fi.Fragment=e,fi.jsx=n,fi.jsxs=n,fi}var lh;function G0(){return lh||(lh=1,rh.exports=H0()),rh.exports}G0(),bt(void 0),bt(null);const W0=(t,e,n,i,s,r,o,a,l,c)=>new $0({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:r,conversationId:o,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),ds=10,ch=5e3,z0=[46001,46003],q0=["login incorrect","authentication required","authentication failed"];function K0(t){var i;const e=t.code;if(e&&z0.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return q0.some(s=>n.includes(s))}const X0=(t,e,n,i,s,r,o,a,l,c)=>{const u=c??!0,[d,f]=Ee(null),[m,v]=Ee(!1),[y,w]=Ee(null),[_,T]=Ee(!1),x=de(0),I=de(null),A=de(null),M=de(!1),S=We(()=>{I.current&&(clearTimeout(I.current),I.current=null)},[]),C=We(g=>{if(S(),x.current>=ds){he.error(`Max login retry attempts (${ds}) exceeded`),T(!1);return}x.current+=1,he.info(`Scheduling login retry attempt ${x.current}/${ds} in ${ch}ms due to: ${g}`),T(!0),I.current=window.setTimeout(()=>{I.current=null,A.current&&(he.info(`Executing reconnect attempt ${x.current} (disconnect + connect)`),A.current.disconnect(),A.current.connect())},ch)},[S]),p=We(()=>{S(),x.current=0,T(!1),w(null)},[S]);return Ae(()=>{if(!t)return;const g=W0(t,e,n,i,s,r,o,a,l,u);A.current=g;const h=()=>{he.info("Agent connected successfully"),M.current=!0,v(!0),p()},b=()=>{he.info("Agent disconnected"),M.current=!1,v(!1)},E=P=>{if(he.error("AI Agent error:",P),K0(P)){if(M.current){he.debug("Ignoring retryable error — already connected");return}x.current<ds?(w(null),C(P.message)):(w(P),T(!1))}else w(P),T(!1)};return g.on("agent.connected",h),g.on("agent.disconnected",b),g.on("agent.error",E),g.connect(),f(g),()=>{S(),g.off("agent.connected",h),g.off("agent.disconnected",b),g.off("agent.error",E),g.disconnect(),M.current=!1,A.current=null}},[t,e,n,i,s,r,o,a,l,c,u,S,p,C]),{client:d,isConnected:m,error:y,isReconnecting:_}},Y0="telnyx-ai-agent",Nt={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"};function dh(){const t=document.querySelector(Y0);return t instanceof HTMLElement?t:null}function Ot(t,e,n){const i=n||dh();if(!i){he.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),he.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const J0=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:r}=e,o=de(null),a=Ei(qd);Ae(()=>{o.current=dh()},[]),Ae(()=>{if(!t)return;const l=o.current,c=()=>{n();const A=t.telnyxRTC,M={dc:(A==null?void 0:A.dc)??null,region:(A==null?void 0:A.region)??null,callReportId:(A==null?void 0:A.callReportId)??null};a(M),Ot(Nt.AGENT_CONNECTED,M,l)},u=()=>{a(null),Ot(Nt.AGENT_DISCONNECTED,void 0,l)},d=I=>{s(I);const A={message:I.message,name:I.name};Ot(Nt.AGENT_ERROR,A,l)},f=I=>{var A;i(I),Ot(Nt.CONVERSATION_UPDATE,{type:I.type,callState:(A=I.call)==null?void 0:A.state},l)},m=I=>{Ot(Nt.TRANSCRIPT_ITEM,I,l)},v=I=>{Ot(Nt.CONVERSATION_AGENT_STATE,I,l)},y=I=>{Ot(Nt.AGENT_AUDIO_MUTE,{muted:I},l)},_=t.telnyxRTC,T=I=>{r(I)},x=I=>{const A=I,M={code:A==null?void 0:A.code,reason:A==null?void 0:A.reason,wasClean:A==null?void 0:A.wasClean,timestamp:new Date().toISOString()};he.info("[socket.close]",M),Ot(Nt.SOCKET_CLOSE,M,l)};return _&&typeof _=="object"&&(_.on(O.SocketMessage,T),_.on(O.SocketClose,x)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",y),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",y),_&&typeof _=="object"&&(_.off(O.SocketMessage,T),_.off(O.SocketClose,x))}},[t,n,i,s,r,a])},Z0=2e3;async function Q0(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function uh(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const eb=(t,e)=>{const[n,i]=Ee([]),[,s]=Xo(),r=de(e);Ae(()=>{r.current=e},[e]);const o=de(void 0),a=de(void 0);return Ae(()=>{if(!t)return;const c=f=>{i(m=>{const v=m[m.length-1];if(f.role==="assistant"&&v&&uh(v.id)===uh(f.id)&&v.role==="assistant"){const y=r.current.showUserPerceivedLatency&&o.current!==void 0&&v.userPerceivedLatencyMs===void 0,w=r.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,_={...v,content:v.content+f.content,timestamp:f.timestamp,...y&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return y&&(o.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),_]}if(f.role==="assistant"){s(_=>_==="thinking"||_==="processing_image"?"speaking":_);const y=r.current.showUserPerceivedLatency&&o.current!==void 0,w=r.current.showGreetingLatency&&a.current!==void 0;if(y||w){const _={...f,...y&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return o.current=void 0,a.current=void 0,[...m,_]}o.current=void 0,a.current=void 0}if(f.role==="user"){const y=m.findIndex(_=>_.id===f.id);if(y!==-1){const _=[...m];return _[y]={...m[y],content:f.content,timestamp:f.timestamp,attachments:f.attachments},_}if(v&&v.role==="user"&&f.timestamp.getTime()-v.timestamp.getTime()<Z0){const T={...v,id:f.id,content:v.content+" "+f.content,timestamp:f.timestamp,attachments:[...v.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),T]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},u=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:v,thinkingStartedAt:y})=>{(m!==void 0||v!==void 0)&&he.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${v} thinkingStartedAt=${y}`),f==="speaking"?(s("speaking"),m!==void 0&&(o.current=m),v!==void 0&&(a.current=v)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=f=>{var v;const m=(v=f.call)==null?void 0:v.state;(m==="destroy"||m==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const f of u)try{const m=await Q0(f);d.push(m)}catch(m){throw he.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,d)}}},tb=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const r=Xt(),[o,a]=Ee(i?"expanded":r.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=eb(e,n),d=de(!1);switch(Ae(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(m=>{m.enabled=!1,he.info(`[ChatMode] Disabled remote audio track: ${m.label}`)}))}},[i,t]),o){case"collapsed":return R(tu,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return R(Y_,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return R(tu,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},mr=()=>R(vn.div,{layoutId:ei,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:R("div",{className:"rounded-full animate-spin",children:R(b_,{})})}),nb=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(mr,{});case"done":case"purged":case"destroy":return null;case"active":return R(tb,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return R(mr,{})}},ib=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function hh(){const t=Xt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R(ib,{className:"w-8 h-8 mr-2"})}const sb=({client:t,callProps:e,chatMode:n})=>{const i=Xt(),s=de(!1),r=We(()=>{if(!t){he.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return Ae(()=>{n&&t&&!s.current&&(s.current=!0,he.info("[ChatMode] Auto-starting conversation"),r())},[n,t,r]),n?R(vn.div,{layoutId:ei,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:[R(hh,{}),"Connecting..."]}):R(vn.button,{layoutId:ei,onClick:r,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[R(hh,{}),i.start_call_text]})},ob='@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)}}@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)}}',rb=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),ab={duration:.1,ease:"circOut"},lb=({children:t,position:e="fixed"})=>{const n=Xt(),s=(e??n.position??"fixed")==="fixed"?R(rb,{children:t}):t;return R("div",{className:Ct(n.theme==="dark"&&"dark"),children:R(ug,{transition:ab,children:[R("style",{children:ob}),s]})})},cb=t=>R(vn.div,{layoutId:ei,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:[R(__,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(E_,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&R("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:[R(k_,{className:"w-4 h-4"}),"Retry"]})]});function xn(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function db({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":r,"call-custom-headers":o,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:m,"skip-last-voice-sdk-id":v,environment:y,position:w="fixed","version-id":_}){const T=xn(e),x=xn(n),I=xn(f),A=v===void 0?!0:xn(v),M=Xe(()=>{if(l)try{return JSON.parse(l)}catch(re){he.error("Invalid JSON for vad attribute:",l,re);return}},[l]),S=Xe(()=>({showUserPerceivedLatency:xn(c),showGreetingLatency:xn(u)}),[c,u]),{client:C,error:p,isReconnecting:g}=X0(t,y,_,T,x,M,d,I,m,A),[h,b]=Ee(null),[E,P]=Ee(!1),[L,N]=Ee(!1),[D,U]=Ee(!1),[Y,j]=Ee(!1),ae=Ei(Qd),ee=Wv(),$={};if(i&&($.destinationNumber=i),s&&($.callerNumber=s),r&&($.callerName=r),o)try{$.customHeaders=JSON.parse(o)}catch(re){he.error("Invalid JSON for call-custom-headers attribute:",o,re)}if(a)try{$.audio=JSON.parse(a);const re=$.audio;if(typeof re=="object"){const ie=navigator.mediaDevices.getSupportedConstraints();Object.keys(re).forEach(Ie=>{ie[Ie]||he.warn(`Audio constraint not supported by browser: ${Ie}`)})}}catch(re){he.error("Invalid JSON for call-audio attribute:",a,re)}const ue=We(()=>{P(!1)},[]),K=We(re=>{var ie;if(((ie=re.call)==null?void 0:ie.state)==="destroy")return ae(!1),j(!0),b(null);b(re)},[ae]),Z=We(()=>{P(!1),g||N(!0)},[g]),Q=We(()=>{he.info("User triggered retry"),N(!1),P(!0),C&&C.connect()},[C]),ne=We(re=>{if(Gv(re)){const ie=re.params.widget_settings;ie&&Object.keys(ie).length>0&&(ee(ie),U(!0))}},[ee]);return J0(C,{onReady:ue,onConversationUpdate:K,onError:Z,onConfigMessage:ne}),R(lb,{position:w,children:t?L||p?R(cb,{agentId:t,onRetry:Q}):E||g?R(mr,{message:g?"Retrying...":void 0}):h!=null&&h.call?R(nb,{call:h.call,client:C,latencySettings:S,chatMode:I,debug:T}):D?R(sb,{client:C,callProps:$,chatMode:I&&!Y}):null:R("div",{children:"Please provide an assistant ID."})})}Ah(db,"telnyx-ai-agent",$v,{shadow:!0})})();
119
+ `)}))}),k.info(i)}),2e3)}}class _0 extends li{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return V(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return V(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return V(this,void 0,void 0,function*(){try{const i=yield os({audio:e,video:n});return di(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){k.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),k.info("Start hangup for ",i),yield i.hangup({},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){k.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const n in this.calls){const i=this.calls[n];i.setState(q.Purge),i.hangup({},!1)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Au(O.SpeedTest,o=>{const{upDur:a,downDur:l}=o,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const r=".".repeat(1024);for(let o=0;o<s;o++)this.executeRaw(`#SPB ${r}`);this.executeRaw("#SPE")})}getDevices(){return ui().catch(e=>{const n=oe(si(e),e);return U(O.MediaError,n,this.uuid),[]})}getVideoDevices(){return ui(gt.Video).catch(e=>(U(O.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ui(gt.AudioIn).catch(e=>{const n=oe(si(e),e);return U(O.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return ui(gt.AudioOut).catch(e=>(k.error("getAudioOutDevices",e),U(O.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return rs(e,n,i)}getDeviceResolutions(e){return V(this,void 0,void 0,function*(){try{return yield(n=>V(void 0,void 0,void 0,function*(){const i=[],s=yield os({video:{deviceId:{exact:n}}}),r=s.getVideoTracks()[0];for(let o=0;o<ju.length;o++){const[a,l]=ju[o];(yield r.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return di(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return V(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Zi(e,["micId","micLabel"]);return r0(s),this._audioConstraints=yield((r,o,a,l)=>V(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(r||o)){const u=yield rs(r,o,a).catch(d=>null);u&&(l.deviceId={exact:u})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?M_:D_}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=ns(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=ns(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:n="",data:i}){if(!n)throw new Error(`Invalid channel for broadcast: ${n}`);const s=new t0({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(r=>r)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return V(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new n0({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const r=yield this.execute(s),{unauthorized:o=[],subscribed:a=[]}=hr(r);return o.length&&o.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),r})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return V(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new i0({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:r=[],notSubscribed:o=[]}=hr(s);return r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(k.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,k.debug(`Network connectivity lost for session ${this.sessionid}`);const e=oe(v_);U(O.Error,{error:e,sessionId:this.sessionid},this.uuid)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return Jt.setStateTelnyx(e)}}class eh{constructor(e,n){this.code=n,this.message=e}}class b0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new J_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ku(2,6)}handleMessage(e){var n,i,s,r,o,a,l,c,u;const{session:d}=this;d.setPingReceived();const{id:f,method:m,params:v={},voice_sdk_id:_}=e,w=v==null?void 0:v.callID,y=v==null?void 0:v.eventChannel,T=v==null?void 0:v.eventType,x=d.calls[w],I=(n=x==null?void 0:x.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(v==null?void 0:v.reattached_sessions)&&v.reattached_sessions.length===0&&Object.keys(d.calls).length>0){const C=xt(R_);U(O.Warning,{warning:C,sessionId:d.sessionid},d.uuid)}if(T==="channelPvtData")return this._handlePvtEvent(v.pvtData);const A=C=>{var p,g,h,b,E,P;const L={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:m===te.Attach,mediaSettings:v.mediaSettings,debug:(p=d.options.debug)!==null&&p!==void 0&&p,debugOutput:(g=d.options.debugOutput)!==null&&g!==void 0?g:"socket",trickleIce:(h=d.options.trickleIce)!==null&&h!==void 0&&h,prefetchIceCandidates:(b=d.options.prefetchIceCandidates)===null||b===void 0||b,forceRelayCandidate:(E=d.options.forceRelayCandidate)!==null&&E!==void 0&&E,keepConnectionAliveOnSocketClose:(P=d.options.keepConnectionAliveOnSocketClose)!==null&&P!==void 0&&P};w&&(L.id=w),v.telnyx_call_control_id&&(L.telnyxCallControlId=v.telnyx_call_control_id),v.telnyx_session_id&&(L.telnyxSessionId=v.telnyx_session_id),v.telnyx_leg_id&&(L.telnyxLegId=v.telnyx_leg_id),v.client_state&&(L.clientState=v.client_state),v.dialogParams&&v.dialogParams.custom_headers&&v.dialogParams.custom_headers.length&&(L.customHeaders=v.dialogParams.custom_headers),C&&(L.recoveredCallId=C),performance.mark("new-call-start");const N=new Jt(d,L);return N.nodeId=this.nodeId,N},M=new Du(_),S=new Mu(_);switch(m){case te.Answer:case te.Display:case te.Candidate:case te.Ringing:case te.Bye:case te.Media:if(!w||!x)return void k.error(`Received ${m} for non existing call:`,v);x.handleMessage(e),this._ack(f,m);break;case te.Ping:this.session.setPingReceived(),this.session.execute(S);break;case te.Punt:d.options.keepConnectionAliveOnSocketClose&&I?(k.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(f,m)):(k.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case te.Invite:{const g=A();g.direction=pt.Inbound,g.playRingtone(),g.setState(q.Ringing),this._ack(f,m);break}case te.Attach:{if(!x)return A().answer(),void this._ack(f,m);const g=x.id;k.info(`[${new Date().toISOString()}][${w}] closing existing call on ATTACH.`),x.hangup({isRecovering:!0},!1),k.info(`[${new Date().toISOString()}][${w}] Attach: Creating new call for recovery (recoveredCallId: ${g})`),A(g).answer(),this._ack(f,m);break}case te.Event:case"webrtc.event":if(!y)return void k.error("Verto received an unknown event:",v);const C=d.relayProtocol,p=y.split(".")[0];d._existsSubscription(C,y)?U(C,v,y):y===d.sessionid?this._handleSessionEvent(v.eventData):d._existsSubscription(C,p)?U(C,v,p):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(O.Notification,v,d.uuid);break;case te.Info:v.type=et.generic,U(O.Notification,v,d.uuid);break;case te.ClientReady:this.session.execute(M);break;default:{const g=or(e);if(g){switch(g){case Ue.REGISTER:case Ue.REGED:if(d.connection.previousGatewayState!==Ue.REGED&&d.connection.previousGatewayState!==Ue.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const h=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;h&&(d.callReportId=h,k.debug("Captured call_report_id from REGED:",h));const b=(o=(r=e==null?void 0:e.result)===null||r===void 0?void 0:r.params)===null||o===void 0?void 0:o.dc;b&&(d.dc=b);const E=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;E&&(d.region=E),k.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=et.vertoClientReady,U(O.Ready,v,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const h=new eh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),b=oe(fu,h);U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(M)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:if(d.connection.previousGatewayState!==Ue.FAILED&&d.connection.previousGatewayState!==Ue.FAIL_WAIT){const h=oe(p_,new Error(`Gateway state: ${g}`));if(U(O.Error,{error:h,sessionId:d.sessionid},d.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const b=new eh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),E=oe(f_,b);U(O.Error,{error:E,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const b=oe(45003,new Error("Connection Retry Failed"));U(O.Error,{error:b,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(k.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(b=>{var E;return((E=b.peer)===null||E===void 0?void 0:E.instance)&&!b.signalingStateClosed}))return k.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();k.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:k.warn("GatewayState message unknown method:",e)}break}k.debug("Verto message unknown method:",e);break}}}_retrieveCallId(e,n){const i=Object.keys(this.session.calls);if(e.action!=="bootObj")return i.find(s=>this.session.calls[s].channels.includes(n));{const s=e.data.find(r=>i.includes(r[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return V(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:r,laName:o,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:r,data:{liveArray:{command:"bootstrap",context:r,name:o}}})},v={nodeId:this.nodeId,channels:[r],handler:({data:w})=>{const y=f||this._retrieveCallId(w,r);if(y&&n.calls.hasOwnProperty(y)){const T=n.calls[y];T._addChannel(r),T.extension=o,T.handleConferenceUpdate(w,e).then(x=>{x==="INVALID_PACKET"&&m()})}}},_=yield n.vertoSubscribe(v).catch(w=>{k.error("liveArray subscription error:",w);const y=oe(d_,w);U(O.Error,{error:y,sessionId:n.sessionid},n.uuid)});ur(_,r)&&m();break}case"conference-liveArray-part":{let m=null;if(r&&n._existsSubscription(i,r)){const{callId:_=null}=n.subscriptions[i][r];if(m=n.calls[_]||null,_!==null){const w={type:et.conferenceUpdate,action:ze.Leave,conferenceName:o,participantId:Number(u),role:d};U(O.Notification,w,_,!1)||U(O.Notification,w,n.uuid),m===null&&Ot(O.Notification,null,_)}}const v=[r,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:v}).then(({unsubscribedChannels:_=[]})=>{m&&(m.channels=m.channels.filter(w=>!_.includes(w)))}).catch(_=>{k.error("liveArray unsubscribe error:",_)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Yu(this.session,e);break;case"logo-info":{const n={type:et.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};U(O.Notification,n,this.session.uuid);break}}}}class w0 extends _0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new b0(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(k.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return is(this.options)||oi(this.options)}newCall(e){if(!this.validateCallOptions(e))throw oe(l_,void 0,"Error: destinationNumber is required");const n=new Jt(this,e);return performance.mark("new-call-start"),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!oi(this.options)||!!e.destinationNumber}_onSocketOpen(){return V(this,void 0,void 0,function*(){return is(this.options)?this.handleLoginOnSocketOpen():oi(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class S0 extends w0{constructor(e){super(e),k.info(`SDK version: ${Nu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return l0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Se.not_supported},{browserName:"Firefox",supported:Se.not_supported},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",supported:Se.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",features:["video","audio"],supported:Se.full},{browserName:"Edge",features:["audio"],supported:Se.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Se.full},{browserName:"Firefox",features:["audio"],supported:Se.partial},{browserName:"Safari",supported:Se.not_supported},{browserName:"Edge",features:["audio"],supported:Se.partial}]}]}}function th(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var nh={exports:{}},ih;function C0(){return ih||(ih=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function r(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var m=new s(u,d||l,f),v=n?n+c:c;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],m]:l._events[v].push(m):(l._events[v]=m,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,m=new Array(f);d<f;d++)m[d]=u[d].fn;return m},a.prototype.listenerCount=function(l){var c=n?n+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,f,m){var v=n?n+l:l;if(!this._events[v])return!1;var _=this._events[v],w=arguments.length,y,T;if(_.fn){switch(_.once&&this.removeListener(l,_.fn,void 0,!0),w){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,f),!0;case 6:return _.fn.call(_.context,c,u,d,f,m),!0}for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];_.fn.apply(_.context,y)}else{var x=_.length,I;for(T=0;T<x;T++)switch(_[T].once&&this.removeListener(l,_[T].fn,void 0,!0),w){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(!y)for(I=1,y=new Array(w-1);I<w;I++)y[I-1]=arguments[I];_[T].fn.apply(_[T].context,y)}}return!0},a.prototype.on=function(l,c,u){return r(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return r(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return o(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!d||m.once)&&(!u||m.context===u)&&o(this,f);else{for(var v=0,_=[],w=m.length;v<w;v++)(m[v].fn!==c||d&&!m[v].once||u&&m[v].context!==u)&&_.push(m[v]);_.length?this._events[f]=_.length===1?_[0]:_:o(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(nh)),nh.exports}var T0=C0();const pr=th(T0),cs=new pr;var gr={exports:{}},k0=gr.exports,sh;function x0(){return sh||(sh=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(k0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},o=null;function a(_,w){var y=_[w];if(typeof y.bind=="function")return y.bind(_);try{return Function.prototype.bind.call(y,_)}catch{return function(){return Function.prototype.apply.apply(y,[_,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===n?!1:_==="trace"&&i?l:console[_]!==void 0?a(console,_):console.log!==void 0?a(console,"log"):e}function u(){for(var _=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<_?e:this.methodFactory(y,_,this.name)}if(this.log=this.debug,typeof console===n&&_<this.levels.SILENT)return"No console available for logging"}function d(_){return function(){typeof console!==n&&(u.call(this),this[_].apply(this,arguments))}}function f(_,w,y){return c(_)||d.apply(this,arguments)}function m(_,w){var y=this,T,x,I,A="loglevel";typeof _=="string"?A+=":"+_:typeof _=="symbol"&&(A=void 0);function M(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!A)){try{window.localStorage[A]=b;return}catch{}try{window.document.cookie=encodeURIComponent(A)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!A)){try{h=window.localStorage[A]}catch{}if(typeof h===n)try{var b=window.document.cookie,E=encodeURIComponent(A),P=b.indexOf(E+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+E.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function C(){if(!(typeof window===n||!A)){try{window.localStorage.removeItem(A)}catch{}try{window.document.cookie=encodeURIComponent(A)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=_,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return I??x??T},y.setLevel=function(h,b){return I=p(h),b!==!1&&M(I),u.call(y)},y.setDefaultLevel=function(h){x=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){I=null,C(),u.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(o!==y&&(T=p(o.getLevel())),u.call(y),o===y)for(var h in r)r[h].rebuild()},T=p(o?o.getLevel():"WARN");var g=S();g!=null&&(I=p(g)),u.call(y)}o=new m,o.getLogger=function(_){if(typeof _!="symbol"&&typeof _!="string"||_==="")throw new TypeError("You must supply a name when creating a logger.");var w=r[_];return w||(w=r[_]=new m(_,o.methodFactory)),w};var v=typeof window!==n?window.log:void 0;return o.noConflict=function(){return typeof window!==n&&window.log===o&&(window.log=v),o},o.getLoggers=function(){return r},o.default=o,o})}(gr)),gr.exports}var E0=x0();const I0=th(E0),A0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Me=I0.getLogger("telnyx-ai-agent"),R0=Me.methodFactory;Me.methodFactory=(t,e,n)=>{const i=R0(t,e,n);return function(...s){i(A0(),"-",...s)}},Me.setLevel("info");function L0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const P0=10,D0=500,M0=100,oh=20;class N0{constructor(e){Y(this,"remoteIntervalId",null);Y(this,"localIntervalId",null);Y(this,"remoteStream",null);Y(this,"localStream",null);Y(this,"remoteAudioContext",null);Y(this,"remoteSource",null);Y(this,"remoteAnalyser",null);Y(this,"localAudioContext",null);Y(this,"localSource",null);Y(this,"localAnalyser",null);Y(this,"thinkingStartTime",null);Y(this,"lastState",null);Y(this,"userIsSpeaking",!1);Y(this,"lastUserAudioTime",null);Y(this,"userSpeechStartTime",null);Y(this,"userSilenceStartTime",null);Y(this,"isFirstAgentSpeech",!0);Y(this,"monitorStartTime",null);Y(this,"volumeThreshold");Y(this,"silenceDurationMs");Y(this,"minSpeechDurationMs");Y(this,"maxLatencyMs");Y(this,"updateAgentState",L0(e=>{Me.debug("AudioStreamMonitor updateAgentState",e),Me.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,cs.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??P0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??D0,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??M0,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Me.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Me.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Me.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var r;Me.debug("AudioContext resumed, state:",(r=this.remoteAudioContext)==null?void 0:r.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const r=n.reduce((l,c)=>l+c,0)/n.length,o=r>=this.volumeThreshold;if(Math.random()<.01&&Me.debug("Remote audio volume:",r,"threshold:",this.volumeThreshold,"above:",o),o)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=o};this.remoteIntervalId=window.setInterval(s,oh)}startLocalMonitor(){if(!this.localStream){Me.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Me.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Me.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((r,o)=>r+o,0)/e.length;if(Math.random()<.02&&Me.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const r=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:r})}};this.localIntervalId=window.setInterval(n,oh)}destroy(){this.stopAudioStreamMonitor()}}function O0(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function F0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function V0(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function B0(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function U0(t){return F0(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function j0(t){if(!V0(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class $0 extends pr{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcript",[]);Y(this,"onSocketMessage",n=>{if(O0(n))switch(n.params.type){case"response.text.delta":{const i=U0(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),cs.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(B0(n)){const i=n.params.item_id,s=this.transcript.findIndex(r=>r.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=j0(n);if(i){const s=this.transcript.findIndex(r=>r.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(O.SocketMessage,this.onSocketMessage)}}class H0 extends pr{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcription");Y(this,"agentId");Y(this,"versionId");Y(this,"conversationId");Y(this,"debug");Y(this,"audioStreamMonitor");Y(this,"activeCall");Y(this,"chatMode");Y(this,"dc",null);Y(this,"region",null);Y(this,"callReportId",null);Y(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const n={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",n)});Y(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});Y(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Y(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Y(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Me.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new S0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region,skipLastVoiceSdkId:n.skipLastVoiceSdkId??!0}),this.telnyxRTC.on(O.Ready,this.onClientReady),this.telnyxRTC.on(O.Error,this.onClientOrSocketError),this.telnyxRTC.on(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(O.Notification,this.onNotification),this.transcription=new $0(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),cs.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new N0(n.vad)}async connect(){return this.telnyxRTC.connect()}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(O.Ready,this.onClientReady),this.telnyxRTC.off(O.Error,this.onClientOrSocketError),this.telnyxRTC.off(O.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(O.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),cs.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Me.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){Me.error("Client is not initialized.");return}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:r,...o}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...o,audio:this.chatMode?!1:r??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var rh={exports:{}},fi={},ah;function G0(){if(ah)return fi;ah=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,r){var o=null;if(r!==void 0&&(o=""+r),s.key!==void 0&&(o=""+s.key),"key"in s){r={};for(var a in s)a!=="key"&&(r[a]=s[a])}else r=s;return s=r.ref,{$$typeof:t,type:i,key:o,ref:s!==void 0?s:null,props:r}}return fi.Fragment=e,fi.jsx=n,fi.jsxs=n,fi}var lh;function W0(){return lh||(lh=1,rh.exports=G0()),rh.exports}W0(),bt(void 0),bt(null);const z0=(t,e,n,i,s,r,o,a,l,c)=>new H0({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:r,conversationId:o,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),ds=10,ch=5e3,q0=[46001,46003],K0=["login incorrect","authentication required","authentication failed"];function dh(t){var i;const e=t.code;if(e&&q0.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return K0.some(s=>n.includes(s))}const X0=(t,e,n,i,s,r,o,a,l,c)=>{const u=c??!0,[d,f]=Ee(null),[m,v]=Ee(!1),[_,w]=Ee(null),[y,T]=Ee(!1),x=de(0),I=de(null),A=de(null),M=de(!1),S=de(!1),C=We(()=>{I.current&&(clearTimeout(I.current),I.current=null)},[]),p=We(h=>{if(C(),x.current>=ds){ae.error(`Max login retry attempts (${ds}) exceeded`),T(!1);return}x.current+=1,ae.info(`Scheduling login retry attempt ${x.current}/${ds} in ${ch}ms due to: ${h}`),T(!0),I.current=window.setTimeout(()=>{var b;if(I.current=null,M.current||S.current){ae.info("Skipping login retry because login already succeeded before retry timeout fired"),T(!1);return}if(A.current){ae.info(`Executing reconnect attempt ${x.current} (socket disconnect)`);const E=A.current.telnyxRTC;(b=E==null?void 0:E.socketDisconnect)==null||b.call(E)}},ch)},[C]),g=We(()=>{C(),x.current=0,S.current=!0,T(!1),w(null)},[C]);return Ae(()=>{if(!t)return;const h=z0(t,e,n,i,s,r,o,a,l,u);A.current=h,S.current=!1;const b=()=>{ae.info("Agent connected successfully"),M.current=!0,v(!0),g()},E=()=>{ae.info("Agent disconnected"),M.current=!1,S.current=!1,v(!1)},P=F=>{if(ae.error("AI Agent error:",F),dh(F)){if(M.current||S.current){ae.debug("Ignoring retryable error — login already succeeded");return}x.current<ds?(w(null),p(F.message)):(w(F),T(!1))}else w(F),T(!1)},L=h.telnyxRTC??null,N=F=>{var j;const z=F;((j=z==null?void 0:z.result)==null?void 0:j.message)==="logged in"&&(ae.info("Login succeeded; clearing pending login retry flow"),g())},D=()=>{S.current=!1};return h.on("agent.connected",b),h.on("agent.disconnected",E),h.on("agent.error",P),L&&typeof L=="object"&&(L.on(O.SocketMessage,N),L.on(O.SocketClose,D)),h.connect(),f(h),()=>{C(),h.off("agent.connected",b),h.off("agent.disconnected",E),h.off("agent.error",P),L&&typeof L=="object"&&(L.off(O.SocketMessage,N),L.off(O.SocketClose,D)),h.disconnect(),M.current=!1,A.current=null}},[t,e,n,i,s,r,o,a,l,c,u,C,g,p]),{client:d,isConnected:m,error:_,isReconnecting:y}},Y0="telnyx-ai-agent",Et={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"};function uh(){const t=document.querySelector(Y0);return t instanceof HTMLElement?t:null}function It(t,e,n){const i=n||uh();if(!i){ae.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ae.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const J0=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:r}=e,o=de(null),a=Ei(qd);Ae(()=>{o.current=uh()},[]),Ae(()=>{if(!t)return;const l=o.current,c=()=>{n();const A=t.telnyxRTC,M={dc:(A==null?void 0:A.dc)??null,region:(A==null?void 0:A.region)??null,callReportId:(A==null?void 0:A.callReportId)??null};a(M),It(Et.AGENT_CONNECTED,M,l)},u=()=>{a(null),It(Et.AGENT_DISCONNECTED,void 0,l)},d=I=>{const A={message:I.message,name:I.name};if(dh(I)){ae.debug("Ignoring retryable agent.error in widget event layer"),It(Et.AGENT_ERROR,A,l);return}s(I),It(Et.AGENT_ERROR,A,l)},f=I=>{var A;i(I),It(Et.CONVERSATION_UPDATE,{type:I.type,callState:(A=I.call)==null?void 0:A.state},l)},m=I=>{It(Et.TRANSCRIPT_ITEM,I,l)},v=I=>{It(Et.CONVERSATION_AGENT_STATE,I,l)},_=I=>{It(Et.AGENT_AUDIO_MUTE,{muted:I},l)},y=t.telnyxRTC,T=I=>{r(I)},x=I=>{const A=I,M={code:A==null?void 0:A.code,reason:A==null?void 0:A.reason,wasClean:A==null?void 0:A.wasClean,timestamp:new Date().toISOString()};ae.info("[socket.close]",M),It(Et.SOCKET_CLOSE,M,l)};return y&&typeof y=="object"&&(y.on(O.SocketMessage,T),y.on(O.SocketClose,x)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",_),y&&typeof y=="object"&&(y.off(O.SocketMessage,T),y.off(O.SocketClose,x))}},[t,n,i,s,r,a])},Z0=2e3;async function Q0(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function hh(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const eb=(t,e)=>{const[n,i]=Ee([]),[,s]=Xo(),r=de(e);Ae(()=>{r.current=e},[e]);const o=de(void 0),a=de(void 0);return Ae(()=>{if(!t)return;const c=f=>{i(m=>{const v=m[m.length-1];if(f.role==="assistant"&&v&&hh(v.id)===hh(f.id)&&v.role==="assistant"){const _=r.current.showUserPerceivedLatency&&o.current!==void 0&&v.userPerceivedLatencyMs===void 0,w=r.current.showGreetingLatency&&a.current!==void 0&&v.greetingLatencyMs===void 0,y={...v,content:v.content+f.content,timestamp:f.timestamp,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return _&&(o.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const _=r.current.showUserPerceivedLatency&&o.current!==void 0,w=r.current.showGreetingLatency&&a.current!==void 0;if(_||w){const y={...f,..._&&{userPerceivedLatencyMs:o.current},...w&&{greetingLatencyMs:a.current}};return o.current=void 0,a.current=void 0,[...m,y]}o.current=void 0,a.current=void 0}if(f.role==="user"){const _=m.findIndex(y=>y.id===f.id);if(_!==-1){const y=[...m];return y[_]={...m[_],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(v&&v.role==="user"&&f.timestamp.getTime()-v.timestamp.getTime()<Z0){const T={...v,id:f.id,content:v.content+" "+f.content,timestamp:f.timestamp,attachments:[...v.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),T]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},u=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:v,thinkingStartedAt:_})=>{(m!==void 0||v!==void 0)&&ae.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${v} thinkingStartedAt=${_}`),f==="speaking"?(s("speaking"),m!==void 0&&(o.current=m),v!==void 0&&(a.current=v)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=f=>{var v;const m=(v=f.call)==null?void 0:v.state;(m==="destroy"||m==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:n,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const f of u)try{const m=await Q0(f);d.push(m)}catch(m){throw ae.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,d)}}},tb=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const r=Xt(),[o,a]=Ee(i?"expanded":r.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=eb(e,n),d=de(!1);switch(Ae(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(m=>{m.enabled=!1,ae.info(`[ChatMode] Disabled remote audio track: ${m.label}`)}))}},[i,t]),o){case"collapsed":return R(tu,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return R(Jy,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return R(tu,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},mr=()=>R(vn.div,{layoutId:ei,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:R("div",{className:"rounded-full animate-spin",children:R(wy,{})})}),nb=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(mr,{});case"done":case"purged":case"destroy":return null;case"active":return R(tb,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return R(mr,{})}},ib=({className:t})=>R("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:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("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"}),R("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"}),R("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"}),R("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"}),R("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"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function fh(){const t=Xt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R(ib,{className:"w-8 h-8 mr-2"})}const sb=({client:t,callProps:e,chatMode:n})=>{const i=Xt(),s=de(!1),r=We(()=>{if(!t){ae.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return Ae(()=>{n&&t&&!s.current&&(s.current=!0,ae.info("[ChatMode] Auto-starting conversation"),r())},[n,t,r]),n?R(vn.div,{layoutId:ei,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:[R(fh,{}),"Connecting..."]}):R(vn.button,{layoutId:ei,onClick:r,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[R(fh,{}),i.start_call_text]})},ob='@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)}}@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)}}',rb=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),ab={duration:.1,ease:"circOut"},lb=({children:t,position:e="fixed"})=>{const n=Xt(),s=(e??n.position??"fixed")==="fixed"?R(rb,{children:t}):t;return R("div",{className:Ct(n.theme==="dark"&&"dark"),children:R(hg,{transition:ab,children:[R("style",{children:ob}),s]})})},cb=t=>R(vn.div,{layoutId:ei,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:[R(_y,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("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"," ",R(Iy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&R("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:[R(xy,{className:"w-4 h-4"}),"Retry"]})]});function xn(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function db({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":r,"call-custom-headers":o,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:m,"skip-last-voice-sdk-id":v,environment:_,position:w="fixed","version-id":y}){const T=xn(e),x=xn(n),I=xn(f),A=v===void 0?!0:xn(v),M=Xe(()=>{if(l)try{return JSON.parse(l)}catch(re){ae.error("Invalid JSON for vad attribute:",l,re);return}},[l]),S=Xe(()=>({showUserPerceivedLatency:xn(c),showGreetingLatency:xn(u)}),[c,u]),{client:C,error:p,isReconnecting:g}=X0(t,_,y,T,x,M,d,I,m,A),[h,b]=Ee(null),[E,P]=Ee(!1),[L,N]=Ee(!1),[D,F]=Ee(!1),[z,j]=Ee(!1),le=Ei(Qd),ee=zv(),$={};if(i&&($.destinationNumber=i),s&&($.callerNumber=s),r&&($.callerName=r),o)try{$.customHeaders=JSON.parse(o)}catch(re){ae.error("Invalid JSON for call-custom-headers attribute:",o,re)}if(a)try{$.audio=JSON.parse(a);const re=$.audio;if(typeof re=="object"){const ie=navigator.mediaDevices.getSupportedConstraints();Object.keys(re).forEach(Ie=>{ie[Ie]||ae.warn(`Audio constraint not supported by browser: ${Ie}`)})}}catch(re){ae.error("Invalid JSON for call-audio attribute:",a,re)}const he=We(()=>{P(!1)},[]),X=We(re=>{var ie;if(((ie=re.call)==null?void 0:ie.state)==="destroy")return le(!1),j(!0),b(null);b(re)},[le]),Z=We(()=>{P(!1),g||N(!0)},[g]),Q=We(()=>{ae.info("User triggered retry"),N(!1),P(!0),C&&C.connect()},[C]),ne=We(re=>{if(Wv(re)){const ie=re.params.widget_settings;ie&&Object.keys(ie).length>0&&(ee(ie),F(!0))}},[ee]);return J0(C,{onReady:he,onConversationUpdate:X,onError:Z,onConfigMessage:ne}),R(lb,{position:w,children:t?L||p?R(cb,{agentId:t,onRetry:Q}):E||g?R(mr,{message:g?"Retrying...":void 0}):h!=null&&h.call?R(nb,{call:h.call,client:C,latencySettings:S,chatMode:I,debug:T}):D?R(sb,{client:C,callProps:$,chatMode:I&&!z}):null:R("div",{children:"Please provide an assistant ID."})})}Rh(db,"telnyx-ai-agent",Hv,{shadow:!0})})();