@telnyx/ai-agent-widget 0.33.5 → 0.33.7

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 +32 -31
  2. package/package.json +6 -3
@@ -1,119 +1,120 @@
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(`
1
+ var Bb=Object.defineProperty;var jb=(st,q,Ht)=>q in st?Bb(st,q,{enumerable:!0,configurable:!0,writable:!0,value:Ht}):st[q]=Ht;var W=(st,q,Ht)=>jb(st,typeof q!="symbol"?q+"":q,Ht);(function(){"use strict";var st,q,Ht,Gt,Nr,Fr,Vr,Ur,Cs,Ts,ks,Br,Mn={},jr=[],Oh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,On=Array.isArray;function dt(t,e){for(var n in e)t[n]=e[n];return t}function Es(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Xe(t,e,n){var i,s,o,r={};for(o in e)o=="key"?i=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?st.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Nn(t,r,i,s,null)}function Nn(t,e,n,i,s){var o={type:t,props:e,key:n,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Ht,__i:-1,__u:0};return s==null&&q.vnode!=null&&q.vnode(o),o}function ut(t){return t.children}function ot(t,e){this.props=t,this.context=e}function ln(t,e){if(e==null)return t.__?ln(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"?ln(t):null}function $r(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 $r(t)}}function Is(t){(!t.__d&&(t.__d=!0)&&Gt.push(t)&&!Si.__r++||Nr!=q.debounceRendering)&&((Nr=q.debounceRendering)||Fr)(Si)}function Si(){for(var t,e,n,i,s,o,r,a=1;Gt.length;)Gt.length>a&&Gt.sort(Vr),t=Gt.shift(),a=Gt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=dt({},i)).__v=i.__v+1,q.vnode&&q.vnode(n),xs(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??ln(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,zr(o,n,r),n.__e!=s&&$r(n)));Si.__r=0}function Hr(t,e,n,i,s,o,r,a,l,c,u){var d,f,g,y,v,b,_=i&&i.__k||jr,T=e.length;for(l=Nh(n,e,_,l,T),d=0;d<T;d++)(g=n.__k[d])!=null&&(f=g.__i==-1?Mn:_[g.__i]||Mn,g.__i=d,b=xs(t,g,f,s,o,r,a,l,c,u),y=g.__e,g.ref&&f.ref!=g.ref&&(f.ref&&Rs(f.ref,null,g),u.push(g.ref,g.__c||y,g)),v==null&&y!=null&&(v=y),4&g.__u||f.__k===g.__k?l=Gr(g,l,t):typeof g.type=="function"&&b!==void 0?l=b:y&&(l=y.nextSibling),g.__u&=-7);return n.__e=v,l}function Nh(t,e,n,i,s){var o,r,a,l,c,u=n.length,d=u,f=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+f,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Nn(null,r,null,null,null):On(r)?Nn(ut,{children:r},null,null,null):r.constructor==null&&r.__b>0?Nn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=Fh(r,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 r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=ln(a)),Xr(a,a));return i}function Gr(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=Gr(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=ln(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ht(t,e){return e=e||[],t==null||typeof t=="boolean"||(On(t)?t.some(function(n){ht(n,e)}):e.push(t)),e}function Fh(t,e,n,i){var s,o,r=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function Wr(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Oh.test(e)?n:n+"px"}function Ci(t,e,n,i,s){var o,r;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof i=="string"&&(t.style.cssText=i=""),i)for(e in i)n&&e in n||Wr(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||Wr(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Ur,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=n,n?i?n.u=i.u:(n.u=Cs,t.addEventListener(e,o?ks:Ts,o)):t.removeEventListener(e,o?ks:Ts,o);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function qr(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=Cs++;else if(e.t<n.u)return;return n(q.event?q.event(e):e)}}}function xs(t,e,n,i,s,o,r,a,l,c){var u,d,f,g,y,v,b,_,T,E,x,I,O,C,k,p,m,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(u=q.__b)&&u(e);e:if(typeof h=="function")try{if(_=e.props,T="prototype"in h&&h.prototype.render,E=(u=h.contextType)&&i[u.__c],x=u?E?E.props.value:u.__:i,n.__c?b=(d=e.__c=n.__c).__=d.__E:(T?e.__c=d=new h(_,x):(e.__c=d=new ot(_,x),d.constructor=h,d.render=Uh),E&&E.sub(d),d.props=_,d.state||(d.state={}),d.context=x,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=dt({},d.__s)),dt(d.__s,h.getDerivedStateFromProps(_,d.__s))),g=d.props,y=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&&_!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(_,x),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(_,d.__s,x)===!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(w){w&&(w.__=e)}),I=0;I<d._sb.length;I++)d.__h.push(d._sb[I]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(_,d.__s,x),T&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,v)})}if(d.context=x,d.props=_,d.__P=t,d.__e=!1,O=q.__r,C=0,T){for(d.state=d.__s,d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[]}else do d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++C<25);d.state=d.__s,d.getChildContext!=null&&(i=dt(dt({},i),d.getChildContext())),T&&!f&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(g,y)),p=u,u!=null&&u.type===ut&&u.key==null&&(p=Kr(u.props.children)),a=Hr(t,On(p)?p:[p],e,n,i,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(w){if(e.__v=null,l||o!=null)if(w.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(m=o.length;m--;)Es(o[m]);else e.__e=n.__e,e.__k=n.__k;q.__e(w,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Vh(n.__e,e,n,i,s,o,r,l,c);return(u=q.diffed)&&u(e),128&e.__u?void 0:a}function zr(t,e,n){for(var i=0;i<n.length;i++)Rs(n[i],n[++i],n[++i]);q.__c&&q.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){q.__e(o,s.__v)}})}function Kr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:On(t)?t.map(Kr):dt({},t)}function Vh(t,e,n,i,s,o,r,a,l){var c,u,d,f,g,y,v,b=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"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!T&&(T?g.localName==T:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(T==null)return document.createTextNode(_);t=document.createElementNS(s,T,_.is&&_),a&&(q.__m&&q.__m(e,o),a=!1),o=null}if(T==null)b===_||a&&t.data==_||(t.data=_);else{if(o=o&&st.call(t.childNodes),b=n.props||Mn,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(g=t.attributes[c]).name]=g.value;for(c in b)if(g=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in _)){if(c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _)continue;Ci(t,c,null,g,s)}}for(c in _)g=_[c],c=="children"?f=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?y=g:c=="checked"?v=g:a&&typeof g!="function"||b[c]===g||Ci(t,c,g,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Hr(e.type=="template"?t.content:t,On(f)?f:[f],e,n,i,T=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&ln(n,0),a,l),o!=null)for(c=o.length;c--;)Es(o[c]);a||(c="value",T=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[c]||T=="progress"&&!y||T=="option"&&y!=b[c])&&Ci(t,c,y,b[c],s),c="checked",v!=null&&v!=t[c]&&Ci(t,c,v,b[c],s))}return t}function Rs(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){q.__e(s,n)}}function Xr(t,e,n){var i,s;if(q.unmount&&q.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Rs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){q.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Xr(i[s],e,n||typeof t.type!="function");n||Es(t.__e),t.__c=t.__=t.__e=void 0}function Uh(t,e,n){return this.constructor(t,n)}function Ti(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),q.__&&q.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],xs(e,t=(!i&&n||e).__k=Xe(ut,null,[t]),s||Mn,Mn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?st.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),zr(o,t,r)}function Yr(t,e){Ti(t,e,Yr)}function As(t,e,n){var i,s,o,r,a=dt({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?i=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?st.call(arguments,2):n),Nn(t.type,a,i||t.key,s||t.ref,null)}function Ct(t){function e(n){var i,s;return this.getChildContext||(i=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){i=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&i.forEach(function(r){r.__e=!0,Is(r)})},this.sub=function(o){i.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){i&&i.delete(o),r&&r.call(o)}}),n.children}return e.__c="__cC"+Br++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}st=jr.slice,q={__e:function(t,e,n,i){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,i||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Ht=0,ot.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=dt({},this.state),typeof t=="function"&&(t=t(dt({},n),this.props)),t&&dt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Is(this))},ot.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Is(this))},ot.prototype.render=ut,Gt=[],Fr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Vr=function(t,e){return t.__v.__b-e.__v.__b},Si.__r=0,Ur=/(PointerCapture)$|Capture$/i,Cs=0,Ts=qr(!1),ks=qr(!0),Br=0;var Bh=0;function A(t,e,n,i,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Bh,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return q.vnode&&q.vnode(c),c}function Ls(){return(Ls=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 jh=["context","children"];function $h(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(t,jh);return As(e,n)}function Hh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Xe($h,Ls({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Jr(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Xe(Zr,{name:u},c):s[r]=c}var d=i?Xe(Zr,null,s):s;return Xe(i||n.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Yr:Ti)(this._vdom,this._root)}function Jr(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Gh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Jr(t)]=n,this._vdom=As(this._vdom,i),Ti(this._vdom,this._root)}}function Wh(){Ti(this._vdom=null,this._root)}function Zr(t,e){var n=this;return Xe("slot",Ls({},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 qh(t,e,n,i){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=i&&i.shadow?o.attachShadow({mode:i.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=Hh,s.prototype.attributeChangedCallback=Gh,s.prototype.disconnectedCallback=Wh,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=n,n.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var Pt,me,Ds,Qr,Fn=0,ea=[],we=q,ta=we.__b,na=we.__r,ia=we.diffed,sa=we.__c,oa=we.unmount,ra=we.__;function cn(t,e){we.__h&&we.__h(me,t,Fn||e),Fn=0;var n=me.__H||(me.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function xe(t){return Fn=1,aa(da,t)}function aa(t,e,n){var i=cn(Pt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):da(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=me,!me.__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!o||o.call(this,a,l,c);var d=i.__c.props!==a;return u.forEach(function(f){if(f.__N){var g=f.__[0];f.__=f.__N,f.__N=void 0,g!==f.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};me.__f=!0;var o=me.shouldComponentUpdate,r=me.componentWillUpdate;me.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},me.shouldComponentUpdate=s}return i.__N||i.__}function Re(t,e){var n=cn(Pt++,3);!we.__s&&Os(n.__H,e)&&(n.__=t,n.u=e,me.__H.__h.push(n))}function la(t,e){var n=cn(Pt++,4);!we.__s&&Os(n.__H,e)&&(n.__=t,n.u=e,me.__h.push(n))}function he(t){return Fn=5,Ye(function(){return{current:t}},[])}function Ye(t,e){var n=cn(Pt++,7);return Os(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function He(t,e){return Fn=8,Ye(function(){return t},e)}function Ae(t){var e=me.context[t.__c],n=cn(Pt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(me)),e.props.value):t.__}function zh(t,e){we.useDebugValue&&we.useDebugValue(e?e(t):t)}function Ps(){var t=cn(Pt++,11);if(!t.__){for(var e=me.__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 Kh(){for(var t;t=ea.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ki),t.__H.__h.forEach(Ms),t.__H.__h=[]}catch(e){t.__H.__h=[],we.__e(e,t.__v)}}we.__b=function(t){me=null,ta&&ta(t)},we.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ra&&ra(t,e)},we.__r=function(t){na&&na(t),Pt=0;var e=(me=t.__c).__H;e&&(Ds===me?(e.__h=[],me.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ki),e.__h.forEach(Ms),e.__h=[],Pt=0)),Ds=me},we.diffed=function(t){ia&&ia(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ea.push(e)!==1&&Qr===we.requestAnimationFrame||((Qr=we.requestAnimationFrame)||Xh)(Kh)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ds=me=null},we.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ki),n.__h=n.__h.filter(function(i){return!i.__||Ms(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],we.__e(i,n.__v)}}),sa&&sa(t,e)},we.unmount=function(t){oa&&oa(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{ki(i)}catch(s){e=s}}),n.__H=void 0,e&&we.__e(e,n.__v))};var ca=typeof requestAnimationFrame=="function";function Xh(t){var e,n=function(){clearTimeout(i),ca&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);ca&&(e=requestAnimationFrame(n))}function ki(t){var e=me,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),me=e}function Ms(t){var e=me;t.__c=t.__(),me=e}function Os(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function da(t,e){return typeof e=="function"?e(t):e}const Vn={},ua=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ha=t=>"init"in t,Ns=t=>!!t.write,fa=t=>"v"in t||"e"in t,Ei=t=>{if("e"in t)throw t.e;if((Vn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Ii=new WeakMap,pa=t=>{var e;return xi(t)&&!!((e=Ii.get(t))!=null&&e[0])},Yh=t=>{const e=Ii.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},ga=(t,e)=>{let n=Ii.get(t);if(!n){n=[!0,new Set],Ii.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},xi=t=>typeof(t==null?void 0:t.then)=="function",ma=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},Fs=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(xi(e))for(const r of i.d.keys())ma(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,xi(o)&&Yh(o))},va=(t,e,n)=>{var i;const s=new Set;for(const o of((i=n.get(t))==null?void 0:i.t)||[])n.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},Jh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},Vs=()=>{const t={},e=new WeakMap,n=i=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(i)),(o=e.get(i))==null||o.forEach(r=>r())};return n.add=(i,s)=>{const o=i||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},n},Zh=t=>(t.c||(t.c=Vs()),t.m||(t.m=Vs()),t.u||(t.u=Vs()),t.f||(t.f=Jh()),t),Qh=Symbol(),_a=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...g)=>f.read(...g),l=(f,...g)=>f.write(...g),c=(f,g)=>{var y;return(y=f.unstable_onInit)==null?void 0:y.call(f,g)},u=(f,g)=>{var y;return(y=f.onMount)==null?void 0:y.call(f,g)},...d)=>{const f=d[0]||(C=>{if((Vn?"production":void 0)!=="production"&&!C)throw new Error("Atom is undefined or null");let k=t.get(C);return k||(k={d:new Map,p:new Set,n:0},t.set(C,k),c==null||c(C,O)),k}),g=d[1]||(()=>{const C=[],k=p=>{try{p()}catch(m){C.push(m)}};do{r.f&&k(r.f);const p=new Set,m=p.add.bind(p);i.forEach(h=>{var w;return(w=e.get(h))==null?void 0:w.l.forEach(m)}),i.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),p.forEach(k),i.size&&y()}while(i.size||o.size||s.size);if(C.length)throw new AggregateError(C)}),y=d[2]||(()=>{const C=[],k=new WeakSet,p=new WeakSet,m=Array.from(i);for(;m.length;){const h=m[m.length-1],w=f(h);if(p.has(h)){m.pop();continue}if(k.has(h)){if(n.get(h)===w.n)C.push([h,w]);else if((Vn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),m.pop();continue}k.add(h);for(const R of va(h,w,e))k.has(R)||m.push(R)}for(let h=C.length-1;h>=0;--h){const[w,R]=C[h];let L=!1;for(const D of R.d.keys())if(D!==w&&i.has(D)){L=!0;break}L&&(v(w),T(w)),n.delete(w)}}),v=d[3]||(C=>{var k;const p=f(C);if(fa(p)&&(e.has(C)&&n.get(C)!==p.n||Array.from(p.d).every(([P,F])=>v(P).n===F)))return p;p.d.clear();let m=!0;const h=()=>{e.has(C)&&(T(C),y(),g())},w=P=>{var F;if(ua(C,P)){const j=f(P);if(!fa(j))if(ha(P))Fs(P,P.init,f);else throw new Error("no atom init");return Ei(j)}const z=v(P);try{return Ei(z)}finally{p.d.set(P,z.n),pa(p.v)&&ma(C,p.v,z),(F=e.get(P))==null||F.t.add(C),m||h()}};let R,L;const D={get signal(){return R||(R=new AbortController),R.signal},get setSelf(){return(Vn?"production":void 0)!=="production"&&!Ns(C)&&console.warn("setSelf function cannot be used with read-only atom"),!L&&Ns(C)&&(L=(...P)=>{if((Vn?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return _(C,...P)}finally{y(),g()}}),L}},N=p.n;try{const P=a(C,w,D);return Fs(C,P,f),xi(P)&&(ga(P,()=>R==null?void 0:R.abort()),P.then(h,h)),p}catch(P){return delete p.v,p.e=P,++p.n,p}finally{m=!1,N!==p.n&&n.get(C)===N&&(n.set(C,p.n),i.add(C),(k=r.c)==null||k.call(r,C))}}),b=d[4]||(C=>{const k=[C];for(;k.length;){const p=k.pop(),m=f(p);for(const h of va(p,m,e)){const w=f(h);n.set(h,w.n),k.push(h)}}}),_=d[5]||((C,...k)=>{let p=!0;const m=w=>Ei(v(w)),h=(w,...R)=>{var L;const D=f(w);try{if(ua(C,w)){if(!ha(w))throw new Error("atom not writable");const N=D.n,P=R[0];Fs(w,P,f),T(w),N!==D.n&&(i.add(w),(L=r.c)==null||L.call(r,w),b(w));return}else return _(w,...R)}finally{p||(y(),g())}};try{return l(C,m,h,...k)}finally{p=!1}}),T=d[6]||(C=>{var k;const p=f(C),m=e.get(C);if(m&&!pa(p.v)){for(const[h,w]of p.d)if(!m.d.has(h)){const R=f(h);E(h).t.add(C),m.d.add(h),w!==R.n&&(i.add(h),(k=r.c)==null||k.call(r,h),b(h))}for(const h of m.d||[])if(!p.d.has(h)){m.d.delete(h);const w=x(h);w==null||w.t.delete(C)}}}),E=d[7]||(C=>{var k;const p=f(C);let m=e.get(C);if(!m){v(C);for(const h of p.d.keys())E(h).t.add(C);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(C,m),(k=r.m)==null||k.call(r,C),Ns(C)){const h=()=>{let w=!0;const R=(...L)=>{try{return _(C,...L)}finally{w||(y(),g())}};try{const L=u(C,R);L&&(m.u=()=>{w=!0;try{L()}finally{w=!1}})}finally{w=!1}};s.add(h)}}return m}),x=d[8]||(C=>{var k;const p=f(C);let m=e.get(C);if(m&&!m.l.size&&!Array.from(m.t).some(h=>{var w;return(w=e.get(h))==null?void 0:w.d.has(C)})){m.u&&o.add(m.u),m=void 0,e.delete(C),(k=r.u)==null||k.call(r,C);for(const h of p.d.keys()){const w=x(h);w==null||w.t.delete(C)}return}return m}),I=[t,e,n,i,s,o,r,a,l,c,u,f,g,y,v,b,_,T,E,x],O={get:C=>Ei(v(C)),set:(C,...k)=>{try{return _(C,...k)}finally{y(),g()}},sub:(C,k)=>{const m=E(C).l;return m.add(k),g(),()=>{m.delete(k),x(C),g()}}};return Object.defineProperty(O,Qh,{value:I}),O},ef=Zh,ya=ga,Us={};let tf=0;function Ri(t,e){const n=`atom${++tf}`,i={toString(){return(Us?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=nf,i.write=sf),i}function nf(t){return t(this)}function sf(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const of=()=>{let t=0;const e=ef({}),n=new WeakMap,i=new WeakMap,s=_a(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,f]of a)"init"in d&&u(d,f)}finally{--t}}};s.set(l)}})};function rf(){return(Us?"production":void 0)!=="production"?of():_a()}let Un;function af(){return Un||(Un=rf(),(Us?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Un),globalThis.__JOTAI_DEFAULT_STORE__!==Un&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Un}function ba(t,e){for(var n in e)t[n]=e[n];return t}function wa(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 Sa=la;function Ca(t,e){this.props=t,this.context=e}(Ca.prototype=new ot).isPureReactComponent=!0,Ca.prototype.shouldComponentUpdate=function(t,e){return wa(this.props,t)||wa(this.state,e)};var Ta=q.__b;q.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ta&&Ta(t)};var lf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function cf(t){function e(n){var i=ba({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=lf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var ka=function(t,e){return t==null?null:ht(ht(t).map(e))},df={map:ka,forEach:ka,count:function(t){return t?ht(t).length:0},only:function(t){var e=ht(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ht},uf=q.__e;q.__e=function(t,e,n,i){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),s.__c(t,e)}uf(t,e,n,i)};var Ea=q.unmount;function Ia(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=ba({},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 Ia(i,e,n)})),t}function xa(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return xa(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 Bs(){this.__u=0,this.o=null,this.__b=null}function Ra(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Ai(){this.i=null,this.l=null}q.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Ea&&Ea(t)},(Bs.prototype=new ot).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=Ra(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=xa(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},Bs.prototype.componentWillUnmount=function(){this.o=[]},Bs.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]=Ia(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&Xe(ut,null,t.fallback);return s&&(s.__u&=-33),[Xe(ut,null,e.__a?null:t.children),s]};var Aa=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]}};(Ai.prototype=new ot).__a=function(t){var e=this,n=Ra(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),Aa(e,t,i)):s()};n?n(o):o()}},Ai.prototype.render=function(t){this.i=null,this.l=new Map;var e=ht(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},Ai.prototype.componentDidUpdate=Ai.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Aa(t,n,e)})};var La=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,hf=/^(?: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]/,ff=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,pf=/[A-Z0-9]/g,gf=typeof document<"u",mf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};ot.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(ot.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Da=q.event;function vf(){}function _f(){return this.cancelBubble}function yf(){return this.defaultPrevented}q.event=function(t){return Da&&(t=Da(t)),t.persist=vf,t.isPropagationStopped=_f,t.isDefaultPrevented=yf,t.nativeEvent=t};var bf={enumerable:!1,configurable:!0,get:function(){return this.class}},Pa=q.vnode;q.vnode=function(t){typeof t.type=="string"&&function(e){var n=e.props,i=e.type,s={},o=i.indexOf("-")===-1;for(var r in n){var a=n[r];if(!(r==="value"&&"defaultValue"in n&&a==null||gf&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||mf(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":ff.test(r)&&(r=l):l=r="oninput":o&&hf.test(r)?r=r.replace(pf,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ht(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ht(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",bf)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=La,Pa&&Pa(t)};var Ma=q.__r;q.__r=function(t){Ma&&Ma(t),t.__c};var Oa=q.diffed;q.diffed=function(t){Oa&&Oa(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 Na(t){return!!t&&t.$$typeof===La}function wf(t){return Na(t)?As.apply(null,arguments):t}var Fa={};const Sf={},Cf=Ct(void 0);function Va(t){return Ae(Cf)||af()}const js=t=>typeof(t==null?void 0:t.then)=="function",$s=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Tf=Fa.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:($s(t),t)}),Hs=new WeakMap,Ua=(t,e)=>{let n=Hs.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=c=>u=>{o===c&&i(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();js(c)?(Hs.set(c,n),o=c,c.then(r(c),a(c)),ya(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),ya(t,l)}),Hs.set(t,n)),n};function Gs(t,e){const{delay:n,unstable_promiseStatus:i=!Fa.use}={},s=Va(),[[o,r,a],l]=aa(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),Re(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);js(d)&&$s(Ua(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),u},[s,t,n,i]),zh(c),js(c)){const u=Ua(c,()=>s.get(t));return i&&$s(u),Tf(u)}return c}function Li(t,e){const n=Va();return He((...s)=>{if((Sf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function Ba(t,e){return[Gs(t),Li(t)]}const Ws=Ct({});function Di(t){const e=he(null);return e.current===null&&(e.current=t()),e.current}const qs=typeof window<"u",ja=qs?la:Re,Pi=Ct(null);function zs(t,e){t.indexOf(e)===-1&&t.push(e)}function Ks(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const Tt=(t,e,n)=>n>e?e:n<t?t:n;let Xs=()=>{};const kt={},$a=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Ha(t){return typeof t=="object"&&t!==null}const Ga=t=>/^0[^.\s]+$/u.test(t);function Ys(t){let e;return()=>(e===void 0&&(e=t()),e)}const Je=t=>t,kf=(t,e)=>n=>e(t(n)),Bn=(...t)=>t.reduce(kf),jn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Js{constructor(){this.subscriptions=[]}add(e){return zs(this.subscriptions,e),()=>Ks(this.subscriptions,e)}notify(e,n,i){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,n,i);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,n,i)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const ft=t=>t*1e3,pt=t=>t/1e3;function Wa(t,e){return e?t*(1e3/e):0}const qa=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Ef=1e-7,If=12;function xf(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=qa(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>Ef&&++a<If);return r}function $n(t,e,n,i){if(t===e&&n===i)return Je;const s=o=>xf(o,0,1,t,n);return o=>o===0||o===1?o:qa(s(o),e,i)}const za=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Ka=t=>e=>1-t(1-e),Xa=$n(.33,1.53,.69,.99),Zs=Ka(Xa),Ya=za(Zs),Ja=t=>(t*=2)<1?.5*Zs(t):.5*(2-Math.pow(2,-10*(t-1))),Qs=t=>1-Math.sin(Math.acos(t)),Za=Ka(Qs),Qa=za(Qs),Rf=$n(.42,0,1,1),Af=$n(0,0,.58,1),el=$n(.42,0,.58,1),Lf=t=>Array.isArray(t)&&typeof t[0]!="number",tl=t=>Array.isArray(t)&&typeof t[0]=="number",Df={linear:Je,easeIn:Rf,easeInOut:el,easeOut:Af,circIn:Qs,circInOut:Qa,circOut:Za,backIn:Zs,backInOut:Ya,backOut:Xa,anticipate:Ja},Pf=t=>typeof t=="string",nl=t=>{if(tl(t)){Xs(t.length===4);const[e,n,i,s]=t;return $n(e,n,i,s)}else if(Pf(t))return Df[t];return t},Mi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],il={value:null};function Mf(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,f=!1,g=!1)=>{const v=g&&s?n:i;return f&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{i.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&il.value&&il.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Of=40;function sl(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=Mi.reduce((E,x)=>(E[x]=Mf(o,e?x:void 0),E),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:f,render:g,postRender:y}=r,v=()=>{const E=kt.useManualTiming?s.timestamp:performance.now();n=!1,kt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(E-s.timestamp,Of),1)),s.timestamp=E,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),f.process(s),g.process(s),y.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},b=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:Mi.reduce((E,x)=>{const I=r[x];return E[x]=(O,C=!1,k=!1)=>(n||b(),I.schedule(O,C,k)),E},{}),cancel:E=>{for(let x=0;x<Mi.length;x++)r[Mi[x]].cancel(E)},state:s,steps:r}}const{schedule:ye,cancel:Mt,state:Pe,steps:eo}=sl(typeof requestAnimationFrame<"u"?requestAnimationFrame:Je,!0);let Oi;function Nf(){Oi=void 0}const Ge={now:()=>(Oi===void 0&&Ge.set(Pe.isProcessing||kt.useManualTiming?Pe.timestamp:performance.now()),Oi),set:t=>{Oi=t,queueMicrotask(Nf)}},ol=t=>e=>typeof e=="string"&&e.startsWith(t),to=ol("--"),Ff=ol("var(--"),no=t=>Ff(t)?Vf.test(t.split("/*")[0].trim()):!1,Vf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,dn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Hn={...dn,transform:t=>Tt(0,1,t)},Ni={...dn,default:1},Gn=t=>Math.round(t*1e5)/1e5,io=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Uf(t){return t==null}const Bf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,so=(t,e)=>n=>!!(typeof n=="string"&&Bf.test(n)&&n.startsWith(t)||e&&!Uf(n)&&Object.prototype.hasOwnProperty.call(n,e)),rl=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(io);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},jf=t=>Tt(0,255,t),oo={...dn,transform:t=>Math.round(jf(t))},Wt={test:so("rgb","red"),parse:rl("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+oo.transform(t)+", "+oo.transform(e)+", "+oo.transform(n)+", "+Gn(Hn.transform(i))+")"};function $f(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 ro={test:so("#"),parse:$f,transform:Wt.transform},Wn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Ot=Wn("deg"),gt=Wn("%"),K=Wn("px"),Hf=Wn("vh"),Gf=Wn("vw"),al={...gt,parse:t=>gt.parse(t)/100,transform:t=>gt.transform(t*100)},un={test:so("hsl","hue"),parse:rl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+gt.transform(Gn(e))+", "+gt.transform(Gn(n))+", "+Gn(Hn.transform(i))+")"},Ee={test:t=>Wt.test(t)||ro.test(t)||un.test(t),parse:t=>Wt.test(t)?Wt.parse(t):un.test(t)?un.parse(t):ro.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Wt.transform(t):un.transform(t),getAnimatableNone:t=>{const e=Ee.parse(t);return e.alpha=0,Ee.transform(e)}},Wf=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function qf(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(io))==null?void 0:e.length)||0)+(((n=t.match(Wf))==null?void 0:n.length)||0)>0}const ll="number",cl="color",zf="var",Kf="var(",dl="${}",Xf=/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 qn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Xf,l=>(Ee.test(l)?(i.color.push(o),s.push(cl),n.push(Ee.parse(l))):l.startsWith(Kf)?(i.var.push(o),s.push(zf),n.push(l)):(i.number.push(o),s.push(ll),n.push(parseFloat(l))),++o,dl)).split(dl);return{values:n,split:a,indexes:i,types:s}}function ul(t){return qn(t).values}function hl(t){const{split:e,types:n}=qn(t),i=e.length;return s=>{let o="";for(let r=0;r<i;r++)if(o+=e[r],s[r]!==void 0){const a=n[r];a===ll?o+=Gn(s[r]):a===cl?o+=Ee.transform(s[r]):o+=s[r]}return o}}const Yf=t=>typeof t=="number"?0:Ee.test(t)?Ee.getAnimatableNone(t):t;function Jf(t){const e=ul(t);return hl(t)(e.map(Yf))}const Nt={test:qf,parse:ul,createTransformer:hl,getAnimatableNone:Jf};function ao(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 Zf({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=ao(l,a,t+1/3),o=ao(l,a,t),r=ao(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function Fi(t,e){return n=>n>0?e:t}const Se=(t,e,n)=>t+(e-t)*n,lo=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Qf=[ro,Wt,un],ep=t=>Qf.find(e=>e.test(t));function fl(t){const e=ep(t);if(!e)return!1;let n=e.parse(t);return e===un&&(n=Zf(n)),n}const pl=(t,e)=>{const n=fl(t),i=fl(e);if(!n||!i)return Fi(t,e);const s={...n};return o=>(s.red=lo(n.red,i.red,o),s.green=lo(n.green,i.green,o),s.blue=lo(n.blue,i.blue,o),s.alpha=Se(n.alpha,i.alpha,o),Wt.transform(s))},co=new Set(["none","hidden"]);function tp(t,e){return co.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function np(t,e){return n=>Se(t,e,n)}function uo(t){return typeof t=="number"?np:typeof t=="string"?no(t)?Fi:Ee.test(t)?pl:op:Array.isArray(t)?gl:typeof t=="object"?Ee.test(t)?pl:ip:Fi}function gl(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>uo(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function ip(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=uo(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function sp(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][i[o]],a=t.values[r]??0;n[s]=a,i[o]++}return n}const op=(t,e)=>{const n=Nt.createTransformer(e),i=qn(t),s=qn(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?co.has(t)&&!s.values.length||co.has(e)&&!i.values.length?tp(t,e):Bn(gl(sp(i,s),s.values),n):Fi(t,e)};function ml(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?Se(t,e,n):uo(t)(t,e)}const rp=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ye.update(e,n),stop:()=>Mt(e),now:()=>Pe.isProcessing?Pe.timestamp:Ge.now()}},vl=(t,e,n=10)=>{let i="";const s=Math.max(Math.round(e/n),2);for(let o=0;o<s;o++)i+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${i.substring(0,i.length-2)})`},Vi=2e4;function ho(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Vi;)e+=n,i=t.next(e);return e>=Vi?1/0:e}function ap(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(ho(i),Vi);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:pt(s)}}const lp=5;function _l(t,e,n){const i=Math.max(e-lp,0);return Wa(n-t(i),e-i)}const Ce={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},fo=.001;function cp({duration:t=Ce.duration,bounce:e=Ce.bounce,velocity:n=Ce.velocity,mass:i=Ce.mass}){let s,o,r=1-e;r=Tt(Ce.minDamping,Ce.maxDamping,r),t=Tt(Ce.minDuration,Ce.maxDuration,pt(t)),r<1?(s=c=>{const u=c*r,d=u*t,f=u-n,g=po(c,r),y=Math.exp(-d);return fo-f/g*y},o=c=>{const d=c*r*t,f=d*n+n,g=Math.pow(r,2)*Math.pow(c,2)*t,y=Math.exp(-d),v=po(Math.pow(c,2),r);return(-s(c)+fo>0?-1:1)*((f-g)*y)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-n)*t+1;return-fo+u*d},o=c=>{const u=Math.exp(-c*t),d=(n-c)*(t*t);return u*d});const a=5/t,l=up(s,o,a);if(t=ft(t),isNaN(l))return{stiffness:Ce.stiffness,damping:Ce.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const dp=12;function up(t,e,n){let i=n;for(let s=1;s<dp;s++)i=i-t(i)/e(i);return i}function po(t,e){return t*Math.sqrt(1-e*e)}const hp=["duration","bounce"],fp=["stiffness","damping","mass"];function yl(t,e){return e.some(n=>t[n]!==void 0)}function pp(t){let e={velocity:Ce.velocity,stiffness:Ce.stiffness,damping:Ce.damping,mass:Ce.mass,isResolvedFromDuration:!1,...t};if(!yl(t,fp)&&yl(t,hp))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*Tt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ce.mass,stiffness:s,damping:o}}else{const n=cp(t);e={...e,...n,mass:Ce.mass},e.isResolvedFromDuration=!0}return e}function Ui(t=Ce.visualDuration,e=Ce.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:f,isResolvedFromDuration:g}=pp({...n,velocity:-pt(n.velocity||0)}),y=f||0,v=c/(2*Math.sqrt(l*u)),b=r-o,_=pt(Math.sqrt(l/u)),T=Math.abs(b)<5;i||(i=T?Ce.restSpeed.granular:Ce.restSpeed.default),s||(s=T?Ce.restDelta.granular:Ce.restDelta.default);let E;if(v<1){const I=po(_,v);E=O=>{const C=Math.exp(-v*_*O);return r-C*((y+v*_*b)/I*Math.sin(I*O)+b*Math.cos(I*O))}}else if(v===1)E=I=>r-Math.exp(-_*I)*(b+(y+_*b)*I);else{const I=_*Math.sqrt(v*v-1);E=O=>{const C=Math.exp(-v*_*O),k=Math.min(I*O,300);return r-C*((y+v*_*b)*Math.sinh(k)+I*b*Math.cosh(k))/I}}const x={calculatedDuration:g&&d||null,next:I=>{const O=E(I);if(g)a.done=I>=d;else{let C=I===0?y:0;v<1&&(C=I===0?ft(y):_l(E,I,O));const k=Math.abs(C)<=i,p=Math.abs(r-O)<=s;a.done=k&&p}return a.value=a.done?r:O,a},toString:()=>{const I=Math.min(ho(x),Vi),O=vl(C=>x.next(I*C).value,I,30);return I+"ms "+O},toTransition:()=>{}};return x}Ui.applyToOptions=t=>{const e=ap(t,100,Ui);return t.ease=e.ease,t.duration=ft(e.duration),t.type="keyframes",t};function go({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],f={done:!1,value:d},g=k=>a!==void 0&&k<a||l!==void 0&&k>l,y=k=>a===void 0?l:l===void 0||Math.abs(a-k)<Math.abs(l-k)?a:l;let v=n*e;const b=d+v,_=r===void 0?b:r(b);_!==b&&(v=_-d);const T=k=>-v*Math.exp(-k/i),E=k=>_+T(k),x=k=>{const p=T(k),m=E(k);f.done=Math.abs(p)<=c,f.value=f.done?_:m};let I,O;const C=k=>{g(f.value)&&(I=k,O=Ui({keyframes:[f.value,y(f.value)],velocity:_l(E,k,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return C(0),{calculatedDuration:null,next:k=>{let p=!1;return!O&&I===void 0&&(p=!0,x(k),C(k)),I!==void 0&&k>=I?O.next(k-I):(!p&&x(k),f)}}}function gp(t,e,n){const i=[],s=n||kt.mix||ml,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||Je:e;a=Bn(l,a)}i.push(a)}return i}function mp(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Xs(o===e.length),o===1)return()=>e[0];if(o===2&&e[0]===e[1])return()=>e[1];const r=t[0]===t[1];t[0]>t[o-1]&&(t=[...t].reverse(),e=[...e].reverse());const a=gp(e,i,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const f=jn(t[d],t[d+1],u);return a[d](f)};return n?u=>c(Tt(t[0],t[o-1],u)):c}function vp(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=jn(0,e,i);t.push(Se(n,1,s))}}function _p(t){const e=[0];return vp(e,t.length-1),e}function yp(t,e){return t.map(n=>n*e)}function bp(t,e){return t.map(()=>e||el).splice(0,t.length-1)}function zn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Lf(i)?i.map(nl):nl(i),o={done:!1,value:e[0]},r=yp(n&&n.length===e.length?n:_p(e),t),a=mp(r,e,{ease:Array.isArray(s)?s:bp(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const wp=t=>t!==null;function mo(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(wp),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Sp={decay:go,inertia:go,tween:zn,keyframes:zn,spring:Ui};function bl(t){typeof t.type=="string"&&(t.type=Sp[t.type])}class vo{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 Cp=t=>t/100;class _o extends vo{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!==Ge.now()&&this.tick(Ge.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;bl(e);const{type:n=zn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||zn;l!==zn&&typeof a[0]!="number"&&(this.mixKeyframes=Bn(Cp,ml(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=ho(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:f,repeatDelay:g,type:y,onUpdate:v,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const _=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 E=this.currentTime,x=i;if(d){const k=Math.min(this.currentTime,s)/a;let p=Math.floor(k),m=k%1;!m&&k>=1&&(m=1),m===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(f==="reverse"?(m=1-m,g&&(m-=g/a)):f==="mirror"&&(x=r)),E=Tt(0,1,m)*a}const I=T?{done:!1,value:u[0]}:x.next(E);o&&(I.value=o(I.value));let{done:O}=I;!T&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const C=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return C&&y!==go&&(I.value=mo(u,this.options,b,this.speed)),v&&v(I.value),C&&this.finish(),I}then(e,n){return this.finished.then(e,n)}get duration(){return pt(this.calculatedDuration)}get time(){return pt(this.currentTime)}set time(e){var n;e=ft(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(Ge.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=pt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=rp,startTime:n}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const i=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=i):this.holdTime!==null?this.startTime=i-this.holdTime:this.startTime||(this.startTime=n??i),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ge.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 Tp(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const qt=t=>t*180/Math.PI,yo=t=>{const e=qt(Math.atan2(t[1],t[0]));return bo(e)},kp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:yo,rotateZ:yo,skewX:t=>qt(Math.atan(t[1])),skewY:t=>qt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},bo=t=>(t=t%360,t<0&&(t+=360),t),wl=yo,Sl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Cl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Ep={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Sl,scaleY:Cl,scale:t=>(Sl(t)+Cl(t))/2,rotateX:t=>bo(qt(Math.atan2(t[6],t[5]))),rotateY:t=>bo(qt(Math.atan2(-t[2],t[0]))),rotateZ:wl,rotate:wl,skewX:t=>qt(Math.atan(t[4])),skewY:t=>qt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function wo(t){return t.includes("scale")?1:0}function So(t,e){if(!t||t==="none")return wo(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=Ep,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=kp,s=a}if(!s)return wo(e);const o=i[e],r=s[1].split(",").map(xp);return typeof o=="function"?o(r):r[o]}const Ip=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return So(n,e)};function xp(t){return parseFloat(t.trim())}const hn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],fn=new Set(hn),Tl=t=>t===dn||t===K,Rp=new Set(["x","y","z"]),Ap=hn.filter(t=>!Rp.has(t));function Lp(t){const e=[];return Ap.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const zt={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})=>So(e,"x"),y:(t,{transform:e})=>So(e,"y")};zt.translateX=zt.x,zt.translateY=zt.y;const Kt=new Set;let Co=!1,To=!1,ko=!1;function kl(){if(To){const t=Array.from(Kt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Lp(i);s.length&&(n.set(i,s),i.render())}),t.forEach(i=>i.measureInitialState()),e.forEach(i=>{i.render();const s=n.get(i);s&&s.forEach(([o,r])=>{var a;(a=i.getValue(o))==null||a.set(r)})}),t.forEach(i=>i.measureEndState()),t.forEach(i=>{i.suspendedScrollY!==void 0&&window.scrollTo(0,i.suspendedScrollY)})}To=!1,Co=!1,Kt.forEach(t=>t.complete(ko)),Kt.clear()}function El(){Kt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(To=!0)})}function Dp(){ko=!0,El(),kl(),ko=!1}class Eo{constructor(e,n,i,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=n,this.name=i,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Kt.add(this),Co||(Co=!0,ye.read(El),ye.resolveKeyframes(kl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:n,element:i,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(i&&n){const a=i.readValue(n,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Tp(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Kt.delete(this)}cancel(){this.state==="scheduled"&&(Kt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Pp=t=>t.startsWith("--");function Mp(t,e,n){Pp(e)?t.style.setProperty(e,n):t.style[e]=n}const Op=Ys(()=>window.ScrollTimeline!==void 0),Np={};function Fp(t,e){const n=Ys(t);return()=>Np[e]??n()}const Il=Fp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Kn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,xl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Kn([0,.65,.55,1]),circOut:Kn([.55,0,1,.45]),backIn:Kn([.31,.01,.66,-.59]),backOut:Kn([.33,1.53,.69,.99])};function Rl(t,e){if(t)return typeof t=="function"?Il()?vl(t,e):"ease-out":tl(t)?Kn(t):Array.isArray(t)?t.map(n=>Rl(n,e)||xl.easeOut):xl[t]}function Vp(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:n};l&&(u.offset=l);const d=Rl(a,s);Array.isArray(d)&&(u.easing=d);const f={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(u,f)}function Al(t){return typeof t=="function"&&"applyToOptions"in t}function Up({type:t,...e}){return Al(t)&&Il()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Bp extends vo{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Xs(typeof e.type!="string");const c=Up(e);this.animation=Vp(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=mo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Mp(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 pt(Number(e))}get time(){return pt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=ft(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&&Op()?(this.animation.timeline=e,Je):n(this)}}const Ll={anticipate:Ja,backInOut:Ya,circInOut:Qa};function jp(t){return t in Ll}function $p(t){typeof t.ease=="string"&&jp(t.ease)&&(t.ease=Ll[t.ease])}const Dl=10;class Hp extends Bp{constructor(e){$p(e),bl(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:n,onUpdate:i,onComplete:s,element:o,...r}=this.options;if(!n)return;if(e!==void 0){n.set(e);return}const a=new _o({...r,autoplay:!1}),l=ft(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-Dl).value,a.sample(l).value,Dl),a.stop()}}const Pl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Nt.test(t)||t==="0")&&!t.startsWith("url("));function Gp(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 Wp(t,e,n,i){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=Pl(s,e),a=Pl(o,e);return!r||!a?!1:Gp(t)||(n==="spring"||Al(n))&&i}function Io(t){return Ha(t)&&"offsetHeight"in t}const qp=new Set(["opacity","clipPath","filter","transform"]),zp=Ys(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Kp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!Io((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return zp()&&n&&qp.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const Xp=40;class Yp extends vo{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var y;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=Ge.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Eo;this.keyframeResolver=new g(a,(v,b,_)=>this.onKeyframesResolved(v,b,f,!_),l,c,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=i;this.resolvedAt=Ge.now(),Wp(e,o,r,a)||((kt.instantAnimations||!l)&&(u==null||u(mo(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>Xp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!c&&Kp(f)?new Hp({...f,element:f.motionValue.owner.current}):new _o(f);g.finished.then(()=>this.notifyFinished()).catch(Je),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Dp()),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 Jp=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Zp(t){const e=Jp.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function Ml(t,e,n=1){const[i,s]=Zp(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return $a(r)?parseFloat(r):r}return no(s)?Ml(s,e,n+1):s}function xo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Ol=new Set(["width","height","top","left","right","bottom",...hn]),Qp={test:t=>t==="auto",parse:t=>t},Nl=t=>e=>e.test(t),Fl=[dn,K,gt,Ot,Gf,Hf,Qp],Vl=t=>Fl.find(Nl(t));function eg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ga(t):!0}const tg=new Set(["brightness","contrast","saturate","opacity"]);function ng(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(io)||[];if(!i)return t;const s=n.replace(i,"");let o=tg.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const ig=/\b([a-z-]*)\(.*?\)/gu,Ro={...Nt,getAnimatableNone:t=>{const e=t.match(ig);return e?e.map(ng).join(" "):t}},Ul={...dn,transform:Math.round},Ao={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Ot,rotateX:Ot,rotateY:Ot,rotateZ:Ot,scale:Ni,scaleX:Ni,scaleY:Ni,scaleZ:Ni,skew:Ot,skewX:Ot,skewY:Ot,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:Hn,originX:al,originY:al,originZ:K},zIndex:Ul,fillOpacity:Hn,strokeOpacity:Hn,numOctaves:Ul},sg={...Ao,color:Ee,backgroundColor:Ee,outlineColor:Ee,fill:Ee,stroke:Ee,borderColor:Ee,borderTopColor:Ee,borderRightColor:Ee,borderBottomColor:Ee,borderLeftColor:Ee,filter:Ro,WebkitFilter:Ro},Bl=t=>sg[t];function jl(t,e){let n=Bl(t);return n!==Ro&&(n=Nt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const og=new Set(["auto","none","0"]);function rg(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!og.has(o)&&qn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=jl(n,s)}class ag extends Eo{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),no(c))){const u=Ml(c,n.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ol.has(i)||e.length!==2)return;const[s,o]=e,r=Vl(s),a=Vl(o);if(r!==a)if(Tl(r)&&Tl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else zt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||eg(e[s]))&&i.push(s);i.length&&rg(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=zt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),n[0]=this.measuredOrigin;const s=n[n.length-1];s!==void 0&&e.getValue(i,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:n,unresolvedKeyframes:i}=this;if(!e||!e.current)return;const s=e.getValue(n);s&&s.jump(this.measuredOrigin,!1);const o=i.length-1,r=i[o];i[o]=zt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function lg(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 $l=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Hl=30,cg=t=>!isNaN(parseFloat(t));class dg{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Ge.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Ge.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=cg(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 Js);const i=this.events[e].add(n);return e==="change"?()=>{i(),ye.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=Ge.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Hl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Hl);return Wa(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 pn(t,e){return new dg(t,e)}const{schedule:Lo}=sl(queueMicrotask,!1),rt={x:!1,y:!1};function Gl(){return rt.x||rt.y}function ug(t){return t==="x"||t==="y"?rt[t]?null:(rt[t]=!0,()=>{rt[t]=!1}):rt.x||rt.y?null:(rt.x=rt.y=!0,()=>{rt.x=rt.y=!1})}function Wl(t,e){const n=lg(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function ql(t){return!(t.pointerType==="touch"||Gl())}function hg(t,e,n={}){const[i,s,o]=Wl(t,n),r=a=>{if(!ql(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{ql(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const zl=(t,e)=>e?t===e?!0:zl(t,e.parentElement):!1,Do=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,fg=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function pg(t){return fg.has(t.tagName)||t.tabIndex!==-1}const Bi=new WeakSet;function Kl(t){return e=>{e.key==="Enter"&&t(e)}}function Po(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const gg=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Kl(()=>{if(Bi.has(n))return;Po(n,"down");const s=Kl(()=>{Po(n,"up")}),o=()=>Po(n,"cancel");n.addEventListener("keyup",s,e),n.addEventListener("blur",o,e)});n.addEventListener("keydown",i,e),n.addEventListener("blur",()=>n.removeEventListener("keydown",i),e)};function Xl(t){return Do(t)&&!Gl()}function mg(t,e,n={}){const[i,s,o]=Wl(t,n),r=a=>{const l=a.currentTarget;if(!Xl(a))return;Bi.add(l);const c=e(l,a),u=(g,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",f),Bi.has(l)&&Bi.delete(l),Xl(g)&&typeof c=="function"&&c(g,{success:y})},d=g=>{u(g,l===window||l===document||n.useGlobalTarget||zl(l,g.target))},f=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Io(a)&&(a.addEventListener("focus",c=>gg(c,s)),!pg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Yl(t){return Ha(t)&&"ownerSVGElement"in t}function vg(t){return Yl(t)&&t.tagName==="svg"}const Ne=t=>!!(t&&t.getVelocity),_g=[...Fl,Ee,Nt],yg=t=>_g.find(Nl(t)),Xn=Ct({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class bg extends ot{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=Io(i)&&i.offsetWidth||0,o=this.props.sizeRef.current;o.height=n.offsetHeight||0,o.width=n.offsetWidth||0,o.top=n.offsetTop,o.left=n.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function wg({children:t,isPresent:e,anchorX:n,root:i}){const s=Ps(),o=he(null),r=he({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Ae(Xn);return Sa(()=>{const{width:l,height:c,top:u,left:d,right:f}=r.current;if(e||!o.current||!l||!c)return;const g=n==="left"?`left: ${d}`:`right: ${f}`;o.current.dataset.motionPopId=s;const y=document.createElement("style");a&&(y.nonce=a);const v=i??document.head;return v.appendChild(y),y.sheet&&y.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
5
5
  height: ${c}px !important;
6
- ${m}px !important;
6
+ ${g}px !important;
7
7
  top: ${u}px !important;
8
8
  }
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})};/**!
9
+ `),()=>{v.removeChild(y),v.contains(y)&&v.removeChild(y)}},[e]),A(bg,{isPresent:e,childRef:o,sizeRef:r,children:wf(t,{ref:o})})}const Sg=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Di(Cg),u=Ps();let d=!0,f=Ye(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:g=>{c.set(g,!0);for(const y of c.values())if(!y)return;i&&i()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[n,c,i]);return o&&d&&(f={...f}),Ye(()=>{c.forEach((g,y)=>c.set(y,!1))},[n]),Re(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=A(wg,{isPresent:n,anchorX:a,root:l,children:t})),A(Pi.Provider,{value:f,children:t})};function Cg(){return new Map}function Jl(t=!0){const e=Ae(Pi);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=Ps();Re(()=>{if(t)return s(o)},[t]);const r=He(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const ji=t=>t.key||"";function Zl(t){const e=[];return df.forEach(t,n=>{Na(n)&&e.push(n)}),e}const Tg=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=Jl(r),d=Ye(()=>Zl(t),[t]),f=r&&!c?[]:d.map(ji),g=he(!0),y=he(d),v=Di(()=>new Map),[b,_]=xe(d),[T,E]=xe(d);ja(()=>{g.current=!1,y.current=d;for(let O=0;O<T.length;O++){const C=ji(T[O]);f.includes(C)?v.delete(C):v.get(C)!==!0&&v.set(C,!1)}},[T,f.length,f.join("-")]);const x=[];if(d!==b){let O=[...d];for(let C=0;C<T.length;C++){const k=T[C],p=ji(k);f.includes(p)||(O.splice(C,0,k),x.push(k))}return o==="wait"&&x.length&&(O=x),E(Zl(O)),_(d),null}const{forceRender:I}=Ae(Ws);return A(ut,{children:T.map(O=>{const C=ji(O),k=r&&!c?!1:d===T||f.includes(C),p=()=>{if(v.has(C))v.set(C,!0);else return;let m=!0;v.forEach(h=>{h||(m=!1)}),m&&(I==null||I(),E(y.current),r&&(u==null||u()),i&&i())};return A(Sg,{isPresent:k,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:k?void 0:p,anchorX:a,children:O},C)})})},Ql=Ct({strict:!1}),ec={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"]},gn={};for(const t in ec)gn[t]={isEnabled:e=>ec[t].some(n=>!!e[n])};function kg(t){for(const e in t)gn[e]={...gn[e],...t[e]}}const Eg=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 $i(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Eg.has(t)}let tc=t=>!$i(t);function nc(t){typeof t=="function"&&(tc=e=>e.startsWith("on")?!$i(e):t(e))}try{nc(require("@emotion/is-prop-valid").default)}catch{}function Ig(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(tc(s)||n===!0&&$i(s)||!e&&!$i(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function xg({children:t,isValidProp:e,...n}){e&&nc(e),n={...Ae(Xn),...n},n.isStatic=Di(()=>n.isStatic);const i=Ye(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return A(Xn.Provider,{value:i,children:t})}function Rg(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 Hi=Ct({});function Gi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Yn(t){return typeof t=="string"||Array.isArray(t)}const Mo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Oo=["initial",...Mo];function Wi(t){return Gi(t.animate)||Oo.some(e=>Yn(t[e]))}function ic(t){return!!(Wi(t)||t.variants)}function Ag(t,e){if(Wi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Yn(n)?n:void 0,animate:Yn(i)?i:void 0}}return t.inherit!==!1?e:{}}function Lg(t){const{initial:e,animate:n}=Ag(t,Ae(Hi));return Ye(()=>({initial:e,animate:n}),[sc(e),sc(n)])}function sc(t){return Array.isArray(t)?t.join(" "):t}const Dg=Symbol.for("motionComponentSymbol");function mn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Pg(t,e,n){return He(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):mn(n)&&(n.current=i))},[e])}const No=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),oc="data-"+No("framerAppearId"),rc=Ct({});function Mg(t,e,n,i,s){var v,b;const{visualElement:o}=Ae(Hi),r=Ae(Ql),a=Ae(Pi),l=Ae(Xn).reducedMotion,c=he(null);i=i||r.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Ae(rc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Og(c.current,n,s,d);const f=he(!1);Sa(()=>{u&&f.current&&u.update(n,a)});const g=n[oc],y=he(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,g)));return ja(()=>{u&&(f.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Lo.render(u.render),y.current&&u.animationState&&u.animationState.animateChanges())}),Re(()=>{u&&(!y.current&&u.animationState&&u.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{var _;(_=window.MotionHandoffMarkAsComplete)==null||_.call(window,g)}),y.current=!1))}),u}function Og(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:ac(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&mn(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:l,layoutRoot:c})}function ac(t){if(t)return t.options.allowProjection!==!1?t.projection:ac(t.parent)}function Ng({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&kg(t);function o(a,l){let c;const u={...Ae(Xn),...a,layoutId:Fg(a)},{isStatic:d}=u,f=Lg(a),g=i(a,d);if(!d&&qs){Vg();const y=Ug(u);c=y.MeasureLayout,f.visualElement=Mg(s,g,u,e,y.ProjectionNode)}return A(Hi.Provider,{value:f,children:[c&&f.visualElement?A(c,{visualElement:f.visualElement,...u}):null,n(s,a,Pg(g,f.visualElement,l),g,d,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=cf(o);return r[Dg]=s,r}function Fg({layoutId:t}){const e=Ae(Ws).id;return e&&t!==void 0?e+"-"+t:t}function Vg(t,e){Ae(Ql).strict}function Ug(t){const{drag:e,layout:n}=gn;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 Jn={};function Bg(t){for(const e in t)Jn[e]=t[e],to(e)&&(Jn[e].isCSSVariable=!0)}function lc(t,{layout:e,layoutId:n}){return fn.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Jn[t]||t==="opacity")}const jg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},$g=hn.length;function Hg(t,e,n){let i="",s=!0;for(let o=0;o<$g;o++){const r=hn[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=$l(a,Ao[r]);if(!l){s=!1;const u=jg[r]||r;i+=`${u}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function Fo(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(fn.has(l)){r=!0;continue}else if(to(l)){s[l]=c;continue}else{const u=$l(c,Ao[l]);l.startsWith("origin")?(a=!0,o[l]=u):i[l]=u}}if(e.transform||(r||n?i.transform=Hg(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;i.transformOrigin=`${l} ${c} ${u}`}}const Vo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function cc(t,e,n){for(const i in e)!Ne(e[i])&&!lc(i,n)&&(t[i]=e[i])}function Gg({transformTemplate:t},e){return Ye(()=>{const n=Vo();return Fo(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Wg(t,e){const n=t.style||{},i={};return cc(i,n,t),Object.assign(i,Gg(t,e)),i}function qg(t,e){const n={},i=Wg(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 zg={offset:"stroke-dashoffset",array:"stroke-dasharray"},Kg={offset:"strokeDashoffset",array:"strokeDasharray"};function Xg(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?zg:Kg;t[o.offset]=K.transform(-i);const r=K.transform(e),a=K.transform(n);t[o.array]=`${r} ${a}`}function dc(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(Fo(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&&Xg(d,s,o,r,!1)}const uc=()=>({...Vo(),attrs:{}}),hc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Yg(t,e,n,i){const s=Ye(()=>{const o=uc();return dc(o,e,hc(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};cc(o,t.style,t),s.style={...o,...s.style}}return s}const Jg=["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 Uo(t){return typeof t!="string"||t.includes("-")?!1:!!(Jg.indexOf(t)>-1||/[A-Z]/u.test(t))}function Zg(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(Uo(n)?Yg:qg)(i,o,r,n),c=Ig(i,typeof n=="string",t),u=n!==ut?{...c,...l,ref:s}:{},{children:d}=i,f=Ye(()=>Ne(d)?d.get():d,[d]);return Xe(n,{...u,children:f})}}function fc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Bo(t,e,n,i){if(typeof e=="function"){const[s,o]=fc(i);e=e(n!==void 0?n:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=fc(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function qi(t){return Ne(t)?t.get():t}function Qg({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:em(n,i,s,t),renderState:e()}}const pc=t=>(e,n)=>{const i=Ae(Hi),s=Ae(Pi),o=()=>Qg(t,e,i,s);return n?o():Di(o)};function em(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=qi(o[f]);let{initial:r,animate:a}=t;const l=Wi(t),c=ic(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=n?n.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!Gi(d)){const f=Array.isArray(d)?d:[d];for(let g=0;g<f.length;g++){const y=Bo(t,f[g]);if(y){const{transitionEnd:v,transition:b,..._}=y;for(const T in _){let E=_[T];if(Array.isArray(E)){const x=u?E.length-1:0;E=E[x]}E!==null&&(s[T]=E)}for(const T in v)s[T]=v[T]}}}return s}function jo(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Ne(i[r])||e.style&&Ne(e.style[r])||lc(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const tm={useVisualState:pc({scrapeMotionValuesFromProps:jo,createRenderState:Vo})};function gc(t,e,n){const i=jo(t,e,n);for(const s in t)if(Ne(t[s])||Ne(e[s])){const o=hn.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const nm={useVisualState:pc({scrapeMotionValuesFromProps:gc,createRenderState:uc})};function im(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Uo(i)?nm:tm,preloadedFeatures:t,useRender:Zg(s),createVisualElement:e,Component:i};return Ng(r)}}function Zn(t,e,n){const i=t.getProps();return Bo(i,e,n!==void 0?n:i.custom,t)}const $o=t=>Array.isArray(t);function sm(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,pn(n))}function om(t){return $o(t)?t[t.length-1]||0:t}function rm(t,e){const n=Zn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=om(o[r]);sm(t,r,a)}}function am(t){return!!(Ne(t)&&t.add)}function Ho(t,e){const n=t.getValue("willChange");if(am(n))return n.add(e);if(!n&&kt.WillChange){const i=new kt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function mc(t){return t.props[oc]}const lm=t=>t!==null;function cm(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(lm),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const dm={type:"spring",stiffness:500,damping:25,restSpeed:10},um=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),hm={type:"keyframes",duration:.8},fm={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},pm=(t,{keyframes:e})=>e.length>2?hm:fn.has(t)?t.startsWith("scale")?um(e[1]):dm:fm;function gm({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Go=(t,e,n,i={},s,o)=>r=>{const a=xo(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-ft(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:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};gm(a)||Object.assign(u,pm(t,u)),u.duration&&(u.duration=ft(u.duration)),u.repeatDelay&&(u.repeatDelay=ft(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)),(kt.instantAnimations||kt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const f=cm(u.keyframes,a);if(f!==void 0){ye.update(()=>{u.onUpdate(f),u.onComplete()});return}}return a.isSync?new _o(u):new Yp(u)};function mm({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function vc(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),f=a[u];if(f===void 0||c&&mm(c,u))continue;const g={delay:n,...xo(o||{},u)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(f)&&f===y&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const _=mc(t);if(_){const T=window.MotionHandoffAnimation(_,u,ye);T!==null&&(g.startTime=T,v=!0)}}Ho(t,u),d.start(Go(u,d,f,t.shouldReduceMotion&&Ol.has(u)?{type:!1}:g,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{ye.update(()=>{r&&rm(t,r)})}),l}function Wo(t,e,n={}){var l;const i=Zn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(vc(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:f}=s;return vm(t,e,c,u,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(n.delay)])}function vm(t,e,n=0,i=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof i=="function",d=u?f=>i(f,l):o===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(_m).forEach((f,g)=>{f.notify("AnimationStart",e),a.push(Wo(f,e,{...r,delay:n+(u?0:i)+d(g)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function _m(t,e){return t.sortNodePosition(e)}function ym(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>Wo(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=Wo(t,e,n);else{const s=typeof e=="function"?Zn(t,e,n.custom):e;i=Promise.all(vc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function _c(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 bm=Oo.length;function yc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?yc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<bm;n++){const i=Oo[n],s=t.props[i];(Yn(s)||s===!1)&&(e[i]=s)}return e}const wm=[...Mo].reverse(),Sm=Mo.length;function Cm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>ym(t,n,i)))}function Tm(t){let e=Cm(t),n=bc(),i=!0;const s=l=>(c,u)=>{var f;const d=Zn(t,u,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(d){const{transition:g,transitionEnd:y,...v}=d;c={...c,...v,...y}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=yc(t.parent)||{},d=[],f=new Set;let g={},y=1/0;for(let b=0;b<Sm;b++){const _=wm[b],T=n[_],E=c[_]!==void 0?c[_]:u[_],x=Yn(E),I=_===l?T.isActive:null;I===!1&&(y=b);let O=E===u[_]&&E!==c[_]&&x;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),T.protectedKeys={...g},!T.isActive&&I===null||!E&&!T.prevProp||Gi(E)||typeof E=="boolean")continue;const C=km(T.prevProp,E);let k=C||_===l&&T.isActive&&!O&&x||b>y&&x,p=!1;const m=Array.isArray(E)?E:[E];let h=m.reduce(s(_),{});I===!1&&(h={});const{prevResolvedValues:w={}}=T,R={...w,...h},L=P=>{k=!0,f.has(P)&&(p=!0,f.delete(P)),T.needsAnimating[P]=!0;const F=t.getValue(P);F&&(F.liveStyle=!1)};for(const P in R){const F=h[P],z=w[P];if(g.hasOwnProperty(P))continue;let j=!1;$o(F)&&$o(z)?j=!_c(F,z):j=F!==z,j?F!=null?L(P):f.add(P):F!==void 0&&f.has(P)?L(P):T.protectedKeys[P]=!0}T.prevProp=E,T.prevResolvedValues=h,T.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(k=!1),k&&(!(O&&C)||p)&&d.push(...m.map(P=>({animation:P,options:{type:_}})))}if(f.size){const b={};if(typeof c.initial!="boolean"){const _=Zn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);_&&_.transition&&(b.transition=_.transition)}f.forEach(_=>{const T=t.getBaseTarget(_),E=t.getValue(_);E&&(E.liveStyle=!0),b[_]=T??null}),d.push({animation:b})}let v=!!d.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),i=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(n[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(l,c)}),n[l].isActive=c;const u=r(l);for(const f in n)n[f].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=bc(),i=!0}}}function km(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!_c(e,t):!1}function Xt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function bc(){return{animate:Xt(!0),whileInView:Xt(),whileHover:Xt(),whileTap:Xt(),whileDrag:Xt(),whileFocus:Xt(),exit:Xt()}}class Ft{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Em extends Ft{constructor(e){super(e),e.animationState||(e.animationState=Tm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Gi(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 Im=0;class xm extends Ft{constructor(){super(...arguments),this.id=Im++}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 Rm={animation:{Feature:Em},exit:{Feature:xm}};function Qn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function ei(t){return{point:{x:t.pageX,y:t.pageY}}}const Am=t=>e=>Do(e)&&t(e,ei(e));function ti(t,e,n,i){return Qn(t,e,Am(n),i)}function wc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Lm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Dm(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 Sc=1e-4,Pm=1-Sc,Mm=1+Sc,Cc=.01,Om=0-Cc,Nm=0+Cc;function Be(t){return t.max-t.min}function Fm(t,e,n){return Math.abs(t-e)<=n}function Tc(t,e,n,i=.5){t.origin=i,t.originPoint=Se(e.min,e.max,t.origin),t.scale=Be(n)/Be(e),t.translate=Se(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Pm&&t.scale<=Mm||isNaN(t.scale))&&(t.scale=1),(t.translate>=Om&&t.translate<=Nm||isNaN(t.translate))&&(t.translate=0)}function ni(t,e,n,i){Tc(t.x,e.x,n.x,i?i.originX:void 0),Tc(t.y,e.y,n.y,i?i.originY:void 0)}function kc(t,e,n){t.min=n.min+e.min,t.max=t.min+Be(e)}function Vm(t,e,n){kc(t.x,e.x,n.x),kc(t.y,e.y,n.y)}function Ec(t,e,n){t.min=e.min-n.min,t.max=t.min+Be(e)}function ii(t,e,n){Ec(t.x,e.x,n.x),Ec(t.y,e.y,n.y)}const Ic=()=>({translate:0,scale:1,origin:0,originPoint:0}),vn=()=>({x:Ic(),y:Ic()}),xc=()=>({min:0,max:0}),ke=()=>({x:xc(),y:xc()});function Ze(t){return[t("x"),t("y")]}function qo(t){return t===void 0||t===1}function zo({scale:t,scaleX:e,scaleY:n}){return!qo(t)||!qo(e)||!qo(n)}function Yt(t){return zo(t)||Rc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Rc(t){return Ac(t.x)||Ac(t.y)}function Ac(t){return t&&t!=="0%"}function zi(t,e,n){const i=t-n,s=e*i;return n+s}function Lc(t,e,n,i,s){return s!==void 0&&(t=zi(t,s,i)),zi(t,n,i)+e}function Ko(t,e=0,n=1,i,s){t.min=Lc(t.min,e,n,i,s),t.max=Lc(t.max,e,n,i,s)}function Dc(t,{x:e,y:n}){Ko(t.x,e.translate,e.scale,e.originPoint),Ko(t.y,n.translate,n.scale,n.originPoint)}const Pc=.999999999999,Mc=1.0000000000001;function Um(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&yn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Dc(t,r)),i&&Yt(o.latestValues)&&yn(t,o.latestValues))}e.x<Mc&&e.x>Pc&&(e.x=1),e.y<Mc&&e.y>Pc&&(e.y=1)}function _n(t,e){t.min=t.min+e,t.max=t.max+e}function Oc(t,e,n,i,s=.5){const o=Se(t.min,t.max,s);Ko(t,e,n,o,i)}function yn(t,e){Oc(t.x,e.x,e.scaleX,e.scale,e.originX),Oc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Nc(t,e){return wc(Dm(t.getBoundingClientRect(),e))}function Bm(t,e,n){const i=Nc(t,n),{scroll:s}=e;return s&&(_n(i.x,s.offset.x),_n(i.y,s.offset.y)),i}const Fc=({current:t})=>t?t.ownerDocument.defaultView:null,Vc=(t,e)=>Math.abs(t-e);function jm(t,e){const n=Vc(t.x,e.x),i=Vc(t.y,e.y);return Math.sqrt(n**2+i**2)}class Uc{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=Yo(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=jm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:v}=f,{timestamp:b}=Pe;this.history.push({...v,timestamp:b});const{onStart:_,onMove:T}=this.handlers;g||(_&&_(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),T&&T(this.lastMoveEvent,f)},this.handlePointerMove=(f,g)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Xo(g,this.transformPagePoint),ye.update(this.updatePoint,!0)},this.handlePointerUp=(f,g)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=Yo(f.type==="pointercancel"?this.lastMoveEventInfo:Xo(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(f,_),v&&v(f,_)},!Do(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=ei(e),l=Xo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,Yo(l,this.history)),this.removeListeners=Bn(ti(this.contextWindow,"pointermove",this.handlePointerMove),ti(this.contextWindow,"pointerup",this.handlePointerUp),ti(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Mt(this.updatePoint)}}function Xo(t,e){return e?{point:e(t.point)}:t}function Bc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Yo({point:t},e){return{point:t,delta:Bc(t,jc(e)),offset:Bc(t,$m(e)),velocity:Hm(e,.1)}}function $m(t){return t[0]}function jc(t){return t[t.length-1]}function Hm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=jc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>ft(e)));)n--;if(!i)return{x:0,y:0};const o=pt(s.timestamp-i.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-i.x)/o,y:(s.y-i.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function Gm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?Se(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?Se(n,t,i.max):Math.min(t,n)),t}function $c(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 Wm(t,{top:e,left:n,bottom:i,right:s}){return{x:$c(t.x,n,s),y:$c(t.y,e,i)}}function Hc(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 qm(t,e){return{x:Hc(t.x,e.x),y:Hc(t.y,e.y)}}function zm(t,e){let n=.5;const i=Be(t),s=Be(e);return s>i?n=jn(e.min,e.max-i,t.min):i>s&&(n=jn(t.min,t.max-s,e.min)),Tt(0,1,n)}function Km(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 Jo=.35;function Xm(t=Jo){return t===!1?t=0:t===!0&&(t=Jo),{x:Gc(t,"left","right"),y:Gc(t,"top","bottom")}}function Gc(t,e,n){return{min:Wc(t,e),max:Wc(t,n)}}function Wc(t,e){return typeof t=="number"?t:t[e]||0}const Ym=new WeakMap;class Jm{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ke(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:n=!1,distanceThreshold:i}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(ei(d).point)},r=(d,f)=>{const{drag:g,dragPropagation:y,onDragStart:v}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=ug(g),!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),Ze(_=>{let T=this.getAxisMotionValue(_).get()||0;if(gt.test(T)){const{projection:E}=this.visualElement;if(E&&E.layout){const x=E.layout.layoutBox[_];x&&(T=Be(x)*(parseFloat(T)/100))}}this.originPoint[_]=T}),v&&ye.postRender(()=>v(d,f)),Ho(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:v,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:_}=f;if(y&&this.currentDirection===null){this.currentDirection=Zm(_),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,_),this.updateAxis("y",f.point,_),this.visualElement.render(),b&&b(d,f)},l=(d,f)=>{this.latestPointerEvent=d,this.latestPanInfo=f,this.stop(d,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ze(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 Uc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:Fc(this.visualElement)})}stop(e,n){const i=e||this.latestPointerEvent,s=n||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!i)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&ye.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||!Ki(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Gm(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:n}=this.getProps(),i=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;e&&mn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Wm(i.layoutBox,e):this.constraints=!1,this.elastic=Xm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Km(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!mn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Bm(i,s.root,this.visualElement.getTransformPagePoint());let r=qm(s.layout.layoutBox,o);if(n){const a=n(Lm(r));this.hasMutatedConstraints=!!a,a&&(r=wc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ze(u=>{if(!Ki(u,n,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const f=s?200:1e6,g=s?40:1e7,y={type:"inertia",velocity:i?e[u]:0,bounceStiffness:f,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,y)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Ho(this.visualElement,e),i.start(Go(e,i,0,n,this.visualElement,!1))}stopAnimation(){Ze(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Ze(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){Ze(n=>{const{drag:i}=this.getProps();if(!Ki(n,i,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(n);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[n];o.set(e[n]-Se(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!mn(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Ze(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=zm({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Ze(r=>{if(!Ki(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Se(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;Ym.set(this.visualElement,this);const e=this.visualElement.current,n=ti(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();mn(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ye.read(i);const r=Qn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ze(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),n(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:i=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Jo,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Ki(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Zm(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class Qm extends Ft{constructor(e){super(e),this.removeGroupControls=Je,this.removeListeners=Je,this.controls=new Jm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Je}unmount(){this.removeGroupControls(),this.removeListeners()}}const qc=t=>(e,n)=>{t&&ye.postRender(()=>t(e,n))};class ev extends Ft{constructor(){super(...arguments),this.removePointerDownListener=Je}onPointerDown(e){this.session=new Uc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Fc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:qc(e),onStart:qc(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&ye.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=ti(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 Xi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function zc(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const si={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const n=zc(t,e.target.x),i=zc(t,e.target.y);return`${n}% ${i}%`}},tv={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=Nt.parse(t);if(s.length>5)return i;const o=Nt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=Se(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Kc=!1;class nv extends ot{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Bg(iv),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Kc&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Xi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Kc=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||ye.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Lo.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 Xc(t){const[e,n]=Jl(),i=Ae(Ws);return A(nv,{...t,layoutGroup:i,switchLayoutGroup:Ae(rc),isPresent:e,safeToRemove:n})}const iv={borderRadius:{...si,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:si,borderTopRightRadius:si,borderBottomLeftRadius:si,borderBottomRightRadius:si,boxShadow:tv};function sv(t,e,n){const i=Ne(t)?t:pn(t);return i.start(Go("",i,e,n)),i.animation}const ov=(t,e)=>t.depth-e.depth;class rv{constructor(){this.children=[],this.isDirty=!1}add(e){zs(this.children,e),this.isDirty=!0}remove(e){Ks(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(ov),this.isDirty=!1,this.children.forEach(e)}}function av(t,e){const n=Ge.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Mt(i),t(o-e))};return ye.setup(i,!0),()=>Mt(i)}const Yc=["TopLeft","TopRight","BottomLeft","BottomRight"],lv=Yc.length,Jc=t=>typeof t=="string"?parseFloat(t):t,Zc=t=>typeof t=="number"||K.test(t);function cv(t,e,n,i,s,o){s?(t.opacity=Se(0,n.opacity??1,dv(i)),t.opacityExit=Se(e.opacity??1,0,uv(i))):o&&(t.opacity=Se(e.opacity??1,n.opacity??1,i));for(let r=0;r<lv;r++){const a=`border${Yc[r]}Radius`;let l=Qc(e,a),c=Qc(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Zc(l)===Zc(c)?(t[a]=Math.max(Se(Jc(l),Jc(c),i),0),(gt.test(c)||gt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=Se(e.rotate||0,n.rotate||0,i))}function Qc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const dv=ed(0,.5,Za),uv=ed(.5,.95,Je);function ed(t,e,n){return i=>i<t?0:i>e?1:n(jn(t,e,i))}function td(t,e){t.min=e.min,t.max=e.max}function Qe(t,e){td(t.x,e.x),td(t.y,e.y)}function nd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function id(t,e,n,i,s){return t-=e,t=zi(t,1/n,i),s!==void 0&&(t=zi(t,1/s,i)),t}function hv(t,e=0,n=1,i=.5,s,o=t,r=t){if(gt.test(e)&&(e=parseFloat(e),e=Se(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Se(o.min,o.max,i);t===o&&(a-=e),t.min=id(t.min,e,n,a,s),t.max=id(t.max,e,n,a,s)}function sd(t,e,[n,i,s],o,r){hv(t,e[n],e[i],e[s],e.scale,o,r)}const fv=["x","scaleX","originX"],pv=["y","scaleY","originY"];function od(t,e,n,i){sd(t.x,e,fv,n?n.x:void 0,i?i.x:void 0),sd(t.y,e,pv,n?n.y:void 0,i?i.y:void 0)}function rd(t){return t.translate===0&&t.scale===1}function ad(t){return rd(t.x)&&rd(t.y)}function ld(t,e){return t.min===e.min&&t.max===e.max}function gv(t,e){return ld(t.x,e.x)&&ld(t.y,e.y)}function cd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function dd(t,e){return cd(t.x,e.x)&&cd(t.y,e.y)}function ud(t){return Be(t.x)/Be(t.y)}function hd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class mv{constructor(){this.members=[]}add(e){zs(this.members,e),e.scheduleRender()}remove(e){if(Ks(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(e){const n=this.members.findIndex(s=>e===s);if(n===0)return!1;let i;for(let s=n;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){i=o;break}}return i?(this.promote(i),!0):!1}promote(e,n){const i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,n&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:n,resumingFrom:i}=e;n.onExitComplete&&n.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function vv(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:f,skewX:g,skewY:y}=n;c&&(i=`perspective(${c}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),f&&(i+=`rotateY(${f}deg) `),g&&(i+=`skewX(${g}deg) `),y&&(i+=`skewY(${y}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 Zo=["","X","Y","Z"],_v=1e3;let yv=0;function Qo(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function fd(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=mc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ye,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&fd(i)}function pd({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=yv++,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(Sv),this.nodes.forEach(Ev),this.nodes.forEach(Iv),this.nodes.forEach(Cv)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new rv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Js),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=Yl(r)&&!vg(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const f=()=>this.root.updateBlockedByResize=!1;ye.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=av(f,250),Xi.hasAnimatedSinceResize&&(Xi.hasAnimatedSinceResize=!1,this.nodes.forEach(vd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:f,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||c.getDefaultTransition()||Dv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),_=!this.targetLayout||!dd(this.targetLayout,g),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 E={...xo(y,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(E.delay=0,E.type=!1),this.startAnimation(E),this.setAnimationOrigin(u,T)}else d||vd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Mt(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(xv),this.animationId++)}getTransformTemplate(){const{visualElement:r}=this.options;return r&&r.getProps().transformTemplate}willUpdate(r=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&fd(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(gd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(md);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(kv),this.nodes.forEach(bv),this.nodes.forEach(wv)):this.nodes.forEach(md),this.clearAllSnapshots();const a=Ge.now();Pe.delta=Tt(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,eo.update.process(Pe),eo.preRender.process(Pe),eo.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Lo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Tv),this.sharedNodes.forEach(Rv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ye.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ye.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Be(this.snapshot.measuredBox.x)&&!Be(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ke(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!ad(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Yt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),Pv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Mv))){const{scroll:u}=this.root;u&&(_n(a.x,u.offset.x),_n(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(Qe(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:f}=u;u!==this.root&&d&&f.layoutScroll&&(d.wasRoot&&Qe(a,r),_n(a.x,d.offset.x),_n(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();Qe(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&yn(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Yt(u.latestValues)&&yn(l,u.latestValues)}return Yt(this.latestValues)&&yn(l,this.latestValues),l}removeTransform(r){const a=ke();Qe(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Yt(c.latestValues))continue;zo(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();Qe(u,d),od(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Yt(this.latestValues)&&od(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Pe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var 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(!(r||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 g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ii(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),Qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Vm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Qe(this.target,this.layout.layoutBox),Dc(this.target,this.targetDelta)):Qe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),ii(this.relativeTargetOrigin,this.target,g.target),Qe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||zo(this.parent.latestValues)||Rc(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 y;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(y=this.parent)!=null&&y.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;Qe(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,f=this.treeScale.y;Um(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=ke());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(nd(this.prevProjectionDelta.x,this.projectionDelta.x),nd(this.prevProjectionDelta.y,this.projectionDelta.y)),ni(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==f||!hd(this.projectionDelta.x,this.prevProjectionDelta.x)||!hd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=vn(),this.projectionDelta=vn(),this.projectionDeltaWithTransform=vn()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=vn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=ke(),g=l?l.source:void 0,y=this.layout?this.layout.source:void 0,v=g!==y,b=this.getStack(),_=!b||b.members.length<=1,T=!!(v&&!_&&this.options.crossfade===!0&&!this.path.some(Lv));this.animationProgress=0;let E;this.mixTargetDelta=x=>{const I=x/1e3;_d(d.x,r.x,I),_d(d.y,r.y,I),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ii(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Av(this.relativeTarget,this.relativeTargetOrigin,f,I),E&&gv(this.relativeTarget,E)&&(this.isProjectionDirty=!1),E||(E=ke()),Qe(E,this.relativeTarget)),v&&(this.animationValues=u,cv(u,c,this.latestValues,I,T,_)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=I},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Mt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ye.update(()=>{Xi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=pn(0)),this.currentAnimation=sv(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(_v),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&Cd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=Be(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const f=Be(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Qe(a,l),yn(a,u),ni(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new mv),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Qo("z",r,c,this.animationValues);for(let u=0;u<Zo.length;u++)Qo(`rotate${Zo[u]}`,r,c,this.animationValues),Qo(`skew${Zo[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=qi(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=qi(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Yt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=vv(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:f,y:g}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const y in Jn){if(u[y]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:_}=Jn[y],T=d==="none"?u[y]:v(u[y],c);if(b){const E=b.length;for(let x=0;x<E;x++)r[b[x]]=T}else _?this.options.visualElement.renderState.vars[y]=T:r[y]=T}this.options.layoutId&&(r.pointerEvents=c===this?qi(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(r=>{var a;return(a=r.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(gd),this.root.sharedNodes.clear()}}}function bv(t){t.updateLayout()}function wv(t){var n;const e=((n=t.resumeFrom)==null?void 0:n.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:i,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?Ze(d=>{const f=r?e.measuredBox[d]:e.layoutBox[d],g=Be(f);f.min=i[d].min,f.max=f.min+g}):Cd(o,e.layoutBox,i)&&Ze(d=>{const f=r?e.measuredBox[d]:e.layoutBox[d],g=Be(i[d]);f.max=f.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=vn();ni(a,i,e.layoutBox);const l=vn();r?ni(l,t.applyTransform(s,!0),e.measuredBox):ni(l,i,e.layoutBox);const c=!ad(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:f,layout:g}=d;if(f&&g){const y=ke();ii(y,e.layoutBox,f.layoutBox);const v=ke();ii(v,i,g.layoutBox),dd(y,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=y,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 Sv(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 Cv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Tv(t){t.clearSnapshot()}function gd(t){t.clearMeasurements()}function md(t){t.isLayoutDirty=!1}function kv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function vd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Ev(t){t.resolveTargetDelta()}function Iv(t){t.calcProjection()}function xv(t){t.resetSkewAndRotation()}function Rv(t){t.removeLeadSnapshot()}function _d(t,e,n){t.translate=Se(e.translate,0,n),t.scale=Se(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function yd(t,e,n,i){t.min=Se(e.min,n.min,i),t.max=Se(e.max,n.max,i)}function Av(t,e,n,i){yd(t.x,e.x,n.x,i),yd(t.y,e.y,n.y,i)}function Lv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Dv={duration:.45,ease:[.4,0,.1,1]},bd=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),wd=bd("applewebkit/")&&!bd("chrome/")?Math.round:Je;function Sd(t){t.min=wd(t.min),t.max=wd(t.max)}function Pv(t){Sd(t.x),Sd(t.y)}function Cd(t,e,n){return t==="position"||t==="preserve-aspect"&&!Fm(ud(e),ud(n),.2)}function Mv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Ov=pd({attachResizeListener:(t,e)=>Qn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),er={current:void 0},Td=pd({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!er.current){const t=new Ov({});t.mount(window),t.setOptions({layoutScroll:!0}),er.current=t}return er.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Nv={pan:{Feature:ev},drag:{Feature:Qm,ProjectionNode:Td,MeasureLayout:Xc}};function kd(t,e,n){const{props:i}=t;t.animationState&&i.whileHover&&t.animationState.setActive("whileHover",n==="Start");const s="onHover"+n,o=i[s];o&&ye.postRender(()=>o(e,ei(e)))}class Fv extends Ft{mount(){const{current:e}=this.node;e&&(this.unmount=hg(e,(n,i)=>(kd(this.node,i,"Start"),s=>kd(this.node,s,"End"))))}unmount(){}}class Vv extends Ft{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=Bn(Qn(this.node.current,"focus",()=>this.onFocus()),Qn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ed(t,e,n){const{props:i}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&i.whileTap&&t.animationState.setActive("whileTap",n==="Start");const s="onTap"+(n==="End"?"":n),o=i[s];o&&ye.postRender(()=>o(e,ei(e)))}class Uv extends Ft{mount(){const{current:e}=this.node;e&&(this.unmount=mg(e,(n,i)=>(Ed(this.node,i,"Start"),(s,{success:o})=>Ed(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const tr=new WeakMap,nr=new WeakMap,Bv=t=>{const e=tr.get(t.target);e&&e(t)},jv=t=>{t.forEach(Bv)};function $v({root:t,...e}){const n=t||document;nr.has(n)||nr.set(n,{});const i=nr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(jv,{root:t,...e})),i[s]}function Hv(t,e,n){const i=$v(e);return tr.set(t,n),i.observe(t),()=>{tr.delete(t),i.unobserve(t)}}const Gv={some:0,all:1};class Wv extends Ft{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:n,margin:i,amount:s="some",once:o}=e,r={root:n?n.current:void 0,rootMargin:i,threshold:typeof s=="number"?s:Gv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),f=c?u:d;f&&f(l)};return Hv(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:n}=this.node;["amount","margin","root"].some(qv(e,n))&&this.startObserver()}unmount(){}}function qv({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const zv={inView:{Feature:Wv},tap:{Feature:Uv},focus:{Feature:Vv},hover:{Feature:Fv}},Kv={layout:{ProjectionNode:Td,MeasureLayout:Xc}},ir={current:null},Id={current:!1};function Xv(){if(Id.current=!0,!!qs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>ir.current=t.matches;t.addEventListener("change",e),e()}else ir.current=!1}const Yv=new WeakMap;function Jv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Ne(s))t.addValue(i,s);else if(Ne(o))t.addValue(i,pn(s,{owner:t}));else if(o!==s)if(t.hasValue(i)){const r=t.getValue(i);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(i);t.addValue(i,pn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const xd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Zv{scrapeMotionValuesFromProps(e,n,i){return{}}constructor({parent:e,props:n,presenceContext:i,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=Eo,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=Ge.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ye.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Wi(n),this.isVariantNode=ic(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 g=d[f];l[f]!==void 0&&Ne(g)&&g.set(l[f],!1)}}mount(e){this.current=e,Yv.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)),Id.current||Xv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ir.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Mt(this.notifyUpdate),Mt(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=fn.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ye.preRender(this.notifyUpdate),i&&this.projection&&(this.projection.isTransformDirty=!0)}),o=n.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,n)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),n.owner&&n.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in gn){const n=gn[e];if(!n)continue;const{isEnabled:i,Feature:s}=n;if(!this.features[e]&&s&&i(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ke()}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<xd.length;i++){const s=xd[i];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=Jv(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=pn(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"&&($a(i)||Ga(i))?i=parseFloat(i):!yg(i)&&Nt.test(n)&&(i=jl(e,n)),this.setBaseTarget(e,Ne(i)?i.get():i)),Ne(i)?i.get():i}setBaseTarget(e,n){this.baseTarget[e]=n}getBaseTarget(e){var o;const{initial:n}=this.props;let i;if(typeof n=="string"||typeof n=="object"){const r=Bo(this.props,n,(o=this.presenceContext)==null?void 0:o.custom);r&&(i=r[e])}if(n&&i!==void 0)return i;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ne(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 Js),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class Rd extends Zv{constructor(){super(...arguments),this.KeyframeResolver=ag}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;Ne(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Ad(t,{style:e,vars:n},i,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,i);for(r in n)o.setProperty(r,n[r])}function Qv(t){return window.getComputedStyle(t)}class e_ extends Rd{constructor(){super(...arguments),this.type="html",this.renderInstance=Ad}readValueFromInstance(e,n){var i;if(fn.has(n))return(i=this.projection)!=null&&i.isProjecting?wo(n):Ip(e,n);{const s=Qv(e),o=(to(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return Nc(e,n)}build(e,n,i){Fo(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return jo(e,n,i)}}const Ld=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 t_(t,e,n,i){Ad(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(Ld.has(s)?s:No(s),e.attrs[s])}class n_ extends Rd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(fn.has(n)){const i=Bl(n);return i&&i.default||0}return n=Ld.has(n)?n:No(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return gc(e,n,i)}build(e,n,i){dc(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){t_(e,n,i,s)}mount(e){this.isSVGTag=hc(e.tagName),super.mount(e)}}const i_=(t,e)=>Uo(t)?new n_(e):new e_(e,{allowProjection:t!==ut}),s_=im({...Rm,...zv,...Nv,...Kv},i_),bn=Rg(s_),o_=["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"],oi="widget-layout-id";function Dd(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=Dd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function Et(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=Dd(t))&&(i&&(i+=" "),i+=e);return i}const r_=Ri("listening"),sr=()=>Ba(r_);function a_(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 Yi={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},Pd=Ri(Yi),l_=()=>{const t=Li(Pd);return He(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Yi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Yi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Yi.speak_to_interrupt_text),n}),[t])},Jt=()=>Gs(Pd),Md=({size:t="large",className:e})=>{const n=Jt(),[i]=sr();return A("h1",{className:Et({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},Od=({stream:t,chatMode:e})=>{const n=he(null);return Re(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:A("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 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]})]})};/**
16
+ */const c_="4.5.1",or=Math.PI,wn=2*or,rr=or/2,Nd=8.17579892,Fd="dual-combined",Ji="dual-horizontal",It="single",mt="dual-vertical",Vd="bar-index",Ud="bar-level",Zi="gradient",Bd=60,jd="click",d_="fullscreenchange",$d="resize",u_="#111",Hd="",Gd="A",Wd="B",qd="C",zd="D",Kd="468",Qi="sans-serif",h_="#0f0",f_="#7f7f7f22",Sn=10,Xd="create",Yd="fschange",p_="lores",g_=$d,ar="user",m_="#000c",Jd="#fff",v_="#4f4",Zd="#888",__="#555",lr="bark",ri="linear",Cn="log",cr="mel",Qd=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],eu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Qd}],["rainbow",{dir:"h",colorStops:["#817",...Qd,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],ai={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:It,colorMode:Zi,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Cn,gradient:eu[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:Hd,width:void 0},y_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],b_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],w_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],dr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],S_=["ERR_INVALID_MODE","Invalid mode"],C_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],T_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],k_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],E_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],I_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class et extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const tu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),nu=t=>{for(const e in t)return!1;return!0},es=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],x_=(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 R_{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||(nu(n)&&!nu(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 eu)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 et(y_)}}if(!s.createGain)throw new et(b_);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),n.source&&this.connectInput(n.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(g_),this._fsTimeout=0)},Bd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener($d,l,{signal:c}),i.addEventListener(d_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Yd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Bd)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(jd,u))};window.addEventListener(jd,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(Xd)}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=es(e,[It,Ji,mt,Fd]),this._input.disconnect(),this._input.connect(this._chLayout!=It?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=It?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=es(e,[Zi,Vd,Ud])}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=es(e,[Cn,lr,cr,ri]),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||ai.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(ar)}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(p_)}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 et(dr);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 et(dr);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 et(S_,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||ai.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 et(C_);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=-rr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return tu("stereo","channelLayout"),this._chLayout!=It}set stereo(e){tu("stereo","channelLayout"),this.channelLayout=e?mt:It}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=es(e,[Hd,Gd,Wd,qd,zd,Kd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(ar)}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 c_}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new et(T_);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==It&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const o of i.mediaStream.getAudioTracks())o.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==It?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(ai))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 et(k_);if(typeof n!="object")throw new et(E_);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new et(I_);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||u_,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(ar)}setFreqRange(e,n){if(e<1||n<1)throw new et(dr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:f}=this,g=s.width>>1,y=s.height>>1,v=o==mt&&!u,b=o==Ji,_=c%10!=0,T=_&&this._frequencyScale==Cn,E=this._showLeds&&_&&!u,x=this._lumiBars&&_&&!u,I=this._alphaBars&&!x&&c!=Sn,O=this._outlineBars&&_&&!x&&!E,C=this._roundBars&&_&&!x&&!E,k=o!=mt||f>0&&!x,p=s.height-(v&&!E?.5:0)>>v,m=p*(x||u?1:1-f)|0,h=s.width-g*(b||l!=0),w=v?s.height-p*2:0,R=g*(l==-1&&!b&&!u);let L=Math.min(s.width,s.height)*.375*(o==mt?1:this._radius)|0,D=Math.min(g,y);d&&o!=mt&&([L,D]=[D,L]);const N=Y=>e.push({...Y,peak:[0,0],hold:[0],alpha:[0],value:[0]}),P=Y=>{const ee=this._freqToBin(Y,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),pe=Math.log2(Y/te)/Math.log2(ie/te);return[ee,pe]};let F,z,j;if(T){const Y=(ue,be,fe)=>+ue.toPrecision(fe?Math.max(be,1+Math.log10(ue)|0):be),ee=ue=>{const be=[1,1.12,1.25,1.4,1.6,1.8,2,2.24,2.5,2.8,3.15,3.55,4,4.5,5,5.6,6.3,7.1,8,9,10],fe=Math.log10(ue)|0,yt=ue/10**fe;let lt=1;for(;lt<be.length&&yt>be[lt];)lt++;return yt-be[lt-1]<be[lt]-yt&&lt--,(be[lt]*10**(fe+5)|0)/1e5},te=[0,24,12,8,6,4,3,2,1][c],ie=n?10**(3/(te*10)):2**(1/te),pe=ie**.5;let Ue=n?7.94328235/(te%2?1:pe):Nd;do{let ue=Ue;const be=Y(ue/pe,4,!0),fe=Y(ue*pe,4,!0),[yt,lt]=P(be),[_i,bt]=P(fe);n?ue=te<4?ee(ue):Y(ue,ue.toString()[0]<5?3:2):ue=Y(ue,4,!0),ue>=a&&N({posX:0,freq:ue,freqLo:be,freqHi:fe,binLo:yt,binHi:_i,ratioLo:lt,ratioHi:bt}),Ue*=ie}while(Ue<=r);F=h/e.length,e.forEach((ue,be)=>ue.posX=R+be*F);const ne=e[0],ve=e[e.length-1];z=this._freqScaling(ne.freqLo),j=h/(this._freqScaling(ve.freqHi)-z),ne.freqLo<a&&(ne.freqLo=a,[ne.binLo,ne.ratioLo]=P(a)),ve.freqHi>r&&(ve.freqHi=r,[ve.binHi,ve.ratioHi]=P(r))}else if(_){const Y=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case lr:return 1960/(26.81/(te+.53)-1);case cr:return 700*(2**te-1);case ri:return te}};F=h/Y,z=this._freqScaling(a),j=h/(this._freqScaling(r)-z);for(let te=0,ie=0;te<Y;te++,ie+=F){const pe=ee(z+ie/j),Ue=ee(z+(ie+F/2)/j),ne=ee(z+(ie+F)/j),[ve,ue]=P(pe),[be,fe]=P(ne);N({posX:R+ie,freq:Ue,freqLo:pe,freqHi:ne,binLo:ve,binHi:be,ratioLo:ue,ratioHi:fe})}}else{F=1,z=this._freqScaling(a),j=h/(this._freqScaling(r)-z);const Y=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=Y;ie<=ee;ie++){const pe=this._binToFreq(ie),Ue=R+Math.round(j*(this._freqScaling(pe)-z));if(Ue>te)N({posX:Ue,freq:pe,freqLo:pe,freqHi:pe,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Ue;else if(e.length){const ne=e[e.length-1];ne.binHi=ie,ne.freqHi=pe,ne.freq=(ne.freqLo*pe)**.5}}}let de=0,J=0;if(E){const Y=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),ee=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],te=this._ledParams,[ie,pe,Ue]=te||ee[c];let ne,ve=m;if(te){const ue=2*Y;let be;ne=ie+1;do ne--,be=ve/ne/(1+pe),J=be*pe;while((be<ue||J<ue)&&ne>1)}else{const ue=540/pe;J=Math.min(pe*Y,Math.max(2,ve/ue+.1|0))}k&&(ve+=J),te||(ne=Math.min(ie,ve/(J*2)|0)),de=Ue>=1?Ue:F*Ue,this._leds=[ne,de,J,ve/ne-J]}const H=Math.min(F-1,i*(i>0&&i<1?F:1));_&&(F-=Math.max(E?de:0,H)),e.forEach((Y,ee)=>{let te=Y.posX,ie=F;_&&(i==0&&!E?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(E?de:0,H)/2,Y.posX=te),Y.barCenter=te+(F==1?0:ie/2),Y.width=ie});const ae=[];for(const Y of[0,1]){const ee=o==mt?(p+w)*Y:0,te=ee+p,ie=ee+m-(!E||k?0:J);ae.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:y,channelCoords:ae,channelHeight:p,channelGap:w,initialX:R,innerRadius:L,outerRadius:D,scaleMin:z,unitWidth:j},this._flg={isAlpha:I,isBands:_,isLeds:E,isLumi:x,isOctaves:T,isOutline:O,isRound:C,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:f}=this,g=d.canvas,y=f.canvas,v=[],b=this._chLayout==Ji,_=this._chLayout==mt,T=Math.min(r.width,r.height),E=["C",,"D",,"E","F",,"G",,"A",,"B"],x=T/34|0,I=g.height>>1,O=x>>1,C=I*(c?.7:1.5),k=O*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=Cn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ri?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let D=Nd;for(let N=-1;N<11;N++)for(let P=0;P<12;P++){if(D>=this._minFreq&&D<=this._maxFreq){const F=E[P],z=F=="C";(F&&c&&!l&&!b||z)&&v.push(c?[D,F+(z?N:"")]:D)}D*=p}}y.width=y.height=Math.max(T*.15,(i<<1)+_*x);const m=y.width>>1,h=m-x*.7,w=(D,N)=>{const P=wn*(D/r.width),F=P-rr,z=h*Math.cos(F),j=h*Math.sin(F);f.save(),f.translate(m+z,m+j),f.rotate(P),f.fillText(N,0,0),f.restore()};g.width|=0,d.fillStyle=f.strokeStyle=m_,d.fillRect(0,0,g.width,g.height),f.arc(m,m,m-x/2,0,wn),f.lineWidth=x,f.stroke(),d.fillStyle=f.fillStyle=Jd,d.font=`${I}px ${Qi}`,f.font=`${O}px ${Qi}`,d.textAlign=f.textAlign="center";let R=-C/4,L=-k;for(const D of v){const[N,P]=Array.isArray(D)?D:[D,D<1e3?D|0:`${(D/100|0)/10}k`],F=o*(this._freqScaling(N)-s),z=g.height*.75,j=P[0]=="C",de=I*(c&&!l&&!b?j?1.2:.6:3);if(d.fillStyle=f.fillStyle=j&&!l&&!b?v_:Jd,c){const J=a==Cn,H=a==ri;let ae=["C"];if((J||N>2e3||!H&&N>250||(!u||_)&&(!H&&N>125||N>1e3))&&ae.push("G"),(J||N>4e3||!H&&N>500||(!u||_)&&(!H&&N>250||N>2e3))&&ae.push("E"),(H&&N>4e3||(!u||_)&&(J||N>2e3||!H&&N>500))&&ae.push("D","F","A","B"),!ae.includes(P[0]))continue}F>=R+C/2&&F<=e&&(d.fillText(P,b&&l==-1?e-F:n+F,z,de),(b||l&&(F>C||l==1))&&d.fillText(P,b&&l!=1?e+F:(n||r.width)-F,z,de),R=F+Math.min(de,d.measureText(P).width)/2),F>=L+k&&F<e-k&&(w(b&&l==1?e-F:F,P),(b||l&&(F>k||l==1))&&w(b&&l!=-1?e+F:-F,P),L=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:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:f}=this._flg,{analyzerHeight:g,centerX:y,centerY:v,channelCoords:b,channelHeight:_,channelGap:T,initialX:E,innerRadius:x,outerRadius:I}=this._aux,{_bars:O,canvas:C,_canvasGradients:k,_chLayout:p,_colorMode:m,_ctx:h,_energy:w,_fadePeaks:R,fillAlpha:L,_fps:D,_linearAmplitude:N,_lineWidth:P,maxDecibels:F,minDecibels:z,_mirror:j,_mode:de,overlay:J,_radial:H,showBgColor:ae,showPeaks:Y,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,pe=this._scaleR.canvas,Ue=D*this._peakFadeTime/1e3,ne=D**2,ve=this._gravity*1e3,ue=D*this._peakHoldTime/1e3,be=p==Fd,fe=p==Ji,yt=p==mt,lt=p==It,_i=a&&this._trueLeds&&m==Zi,bt=H?C.width:this._aux.analyzerWidth,xr=E+bt,yi=Y&&this._peakLine&&de==Sn,Ut=H?I-x:g,Mb=Ut/this._pixelRatio,[Ob,Wb,bi,Rr]=this._leds||[];w.val>0&&D>0&&(this._spinAngle+=this._spinSpeed*wn/60/D);const Nb=B=>{if(this._reflexRatio>0&&!l&&!H){let le,wt;this.reflexFit||yt?(le=yt&&B==0?_+T:0,wt=_-g):(le=C.height-g*2,wt=g),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,C.height),h.drawImage(C,0,b[B].channelTop,C.width,g,0,le,C.width,wt),h.restore()}},Fb=()=>{this.showScaleX&&(H?(h.save(),h.translate(y,v),this._spinSpeed&&h.rotate(this._spinAngle+rr),h.drawImage(pe,-pe.width>>1,-pe.width>>1),h.restore()):h.drawImage(ie,0,C.height-ie.height))},Vb=B=>{const le=B**2,wt=424.36,Oe=11599.29,bs=25122.25,Bt=544496.41,Dt=148693636,nn=sn=>20*Math.log10(sn);switch(te){case Gd:const sn=Dt*le**2/((le+wt)*Math.sqrt((le+Oe)*(le+Bt))*(le+Dt));return 2+nn(sn);case Wd:const on=Dt*le*B/((le+wt)*Math.sqrt(le+bs)*(le+Dt));return .17+nn(on);case qd:const Dr=Dt*le/((le+wt)*(le+Dt));return .06+nn(Dr);case zd:const ws=((103791848e-2-le)**2+108076816e-2*le)/((9837328-le)**2+11723776*le),Pr=B/68966888496476e-18*Math.sqrt(ws/((le+79919.29)*(le+1345600)));return nn(Pr);case Kd:const Ss=-4737338981378384e-39*B**6+2043828333606125e-30*B**4-1363894795463638e-22*le+1,rn=1306612257412824e-34*B**5-2118150887518656e-26*B**3+.0005559488023498642*B,Ke=.0001246332637532143*B/Math.hypot(Ss,rn);return 18.2+nn(Ke)}return 0},Ar=(B,le,wt)=>{h.beginPath(),h.moveTo(B,le),h.lineTo(B,wt),h.stroke()},Lr=B=>{if(B&&P){const le=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=le}},tn=B=>Math.max(0,(B*Ob|0)*(Rr+bi)-bi),Ub=B=>{w.val=B,w.peak>0&&(w.hold--,w.hold<0&&(w.peak+=w.hold*ve/ne/C.height*this._pixelRatio)),B>=w.peak&&(w.peak=B,w.hold=ue)};J&&h.clearRect(0,0,C.width,C.height);let Ah=0;const Lh=O.length,Dh=lt?1:2;for(let B=0;B<Dh;B++){const{channelTop:le,channelBottom:wt,analyzerBottom:Oe}=b[B],bs=this._gradients[this._selectedGrads[B]],Bt=bs.colorStops,Dt=Bt.length,nn=!ae||a&&!J?"#000":bs.bgColor,sn=yt&&H&&B?-1:1,on=!B&&j==-1||B&&j==1,Dr=!fe||B&&j!=1?0:bt>>(B||!on),ws=fe&&on?-1:1,Pr=()=>{const G=ie.height,X=G>>1,Q=N?100:F,_e=N?0:z,Ie=N?20:5,qe=g/(Q-_e),St=j!=-1&&(!fe||B==0||j==1),jt=j!=1&&(!fe||B!=j);h.save(),h.fillStyle=Zd,h.font=`${X}px ${Qi}`,h.textAlign="right",h.lineWidth=1;for(let $t=Q;$t>_e;$t-=Ie){const Dn=le+(Q-$t)*qe,De=$t%2==0|0;if(De){const $e=Dn+X*(Dn==le?.8:.35);St&&h.fillText($t,G*.85,$e),jt&&h.fillText($t,(fe?bt:C.width)-G*.1,$e),h.strokeStyle=Zd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=__,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(E+G*De*St,~~Dn+.5),h.lineTo(xr-G*De*jt,~~Dn+.5),h.stroke()}h.restore()},Ss=(G,X)=>{const Q=ct[G]+(G<ct.length-1?(ct[G+1]-ct[G])*X:0);return isNaN(Q)?-1/0:Q},rn=(G,X=ws)=>X*wn*((G+Dr)/C.width)+this._spinAngle,Ke=(G,X,Q)=>{const _e=x+X*sn,Ie=rn(G,Q);return[y+_e*Math.cos(Ie),v+_e*Math.sin(Ie)]},Mr=(G,X,Q,_e,Ie)=>{h.beginPath();for(const qe of j&&!fe?[1,-1]:[ws]){const[St,jt]=d?[rn(G,qe),rn(G+Q,qe)]:[];h.moveTo(...Ke(G,X,qe)),h.lineTo(...Ke(G,X+_e,qe)),d?h.arc(y,v,x+(X+_e)*sn,St,jt,qe!=1):h.lineTo(...Ke(G+Q,X+_e,qe)),h.lineTo(...Ke(G+Q,X,qe)),d&&!Ie&&h.arc(y,v,x+X*sn,jt,St,qe==1)}Lr(Ie),h.fill()},Or=(G=0,X=0)=>{let Q;if(m==Zi&&!_i||de==Sn)Q=k[B];else{const _e=m==Vd?X%Dt:Bt.findLastIndex(Ie=>a?tn(G)<=tn(Ie.level):G<=Ie.level);Q=Bt[_e].color}h.fillStyle=h.strokeStyle=Q};if(ee){if(fe&&!H){const G=bt*(B+on),X=on?-1:1;h.setTransform(X,0,0,1,G,0)}if((!J||ae)&&(J&&(h.globalAlpha=this.bgAlpha),h.fillStyle=nn,(B==0||!H&&!be)&&h.fillRect(E,le-T,bt,(J&&this.reflexAlpha==1?g:_)+T),h.globalAlpha=1),this.showScaleY&&!l&&!H&&(B==0||!be)&&Pr(),a?(h.setLineDash([Rr,bi]),h.lineWidth=O[0].width):h.lineWidth=u?Math.min(P,O[0].width/2):P,h.save(),!H){const G=new Path2D;G.rect(0,le,C.width,g),h.clip(G)}}let ct=this._fftData[B];this._analyzer[B].getFloatFrequencyData(ct),te&&(ct=ct.map((G,X)=>G+Vb(this._binToFreq(X)))),h.beginPath();let wi=[];for(let G=0;G<Lh;G++){const X=O[G],{posX:Q,barCenter:_e,width:Ie,freq:qe,binLo:St,binHi:jt,ratioLo:$t,ratioHi:Dn}=X;let De=Math.max(Ss(St,$t),Ss(jt,Dn));for(let ge=St+1;ge<jt;ge++)ct[ge]>De&&(De=ct[ge]);if(De=this._normalizedB(De),X.value[B]=De,Ah+=De,X.peak[B]>0&&X.alpha[B]>0&&(X.hold[B]--,X.hold[B]<0)){if(R&&!yi){const ge=!o||u&&P>0?1:o?X.peak[B]:L;X.alpha[B]=ge*(1+X.hold[B]/Ue)}else X.peak[B]+=X.hold[B]*ve/ne/Mb;X.alpha[B]<=0&&(X.peak[B]=0)}if(De>=X.peak[B]&&(X.peak[B]=De,X.hold[B]=ue,X.alpha[B]=!o||u&&P>0?1:o?De:L),!ee)continue;h.globalAlpha=l||o?De:u?L:1,Or(De,G);const $e=l?Ut:a?tn(De):De*Ut|0;if(de==Sn){const ge=G?0:(this._normalizedB(ct[O[1].binLo])*Ut+$e)/2;if(H){if(G==0&&(fe&&h.moveTo(...Ke(0,0)),h.lineTo(...Ke(0,Q<0?ge:$e))),Q>=0){const it=[Q,$e];h.lineTo(...Ke(...it)),wi.push(it)}}else{if(G==0)if(j==-1&&!fe)h.moveTo(E,Oe-(Q<E?ge:$e));else{const it=St?this._normalizedB(ct[St-1])*Ut:$e;h.moveTo(E-P,Oe-it)}(fe||j!=-1||Q>=E)&&h.lineTo(Q,Oe-$e)}}else if(a){if(ae&&!J&&(B==0||!be)){const ge=h.globalAlpha;h.strokeStyle=f_,h.globalAlpha=1,Ar(_e,le,Oe),h.strokeStyle=h.fillStyle,h.globalAlpha=ge}if(_i){const ge=l?0:Bt.findLastIndex(an=>tn(De)<=tn(an.level));let it=Oe;for(let an=Dt-1;an>=ge;an--){h.strokeStyle=Bt[an].color;let Mh=Oe-(an==ge?$e:tn(Bt[an].level));Ar(_e,it,Mh),it=Mh-bi}}else Ar(_e,Oe,Oe-$e)}else if(Q>=E)if(H)Mr(Q,0,Ie,$e,u);else if(d){const ge=Ie/2,it=Oe+ge;h.beginPath(),h.moveTo(Q,it),h.lineTo(Q,it-$e),h.arc(_e,it-$e,ge,or,wn),h.lineTo(Q+Ie,it),Lr(u),h.fill()}else{const ge=u?h.lineWidth:0;h.beginPath(),h.rect(Q,Oe+ge,Ie,-$e-ge),Lr(u),h.fill()}const Pn=X.peak[B],Ph=X.alpha[B];if(Pn>0&&Ph>0&&Y&&!yi&&!l&&Q>=E&&Q<xr){if(R?h.globalAlpha=Ph:u&&P>0?h.globalAlpha=1:o&&(h.globalAlpha=Pn),(m==Ud||_i)&&Or(Pn),a){const ge=tn(Pn);ge>=bi&&h.fillRect(Q,Oe-ge,Ie,Rr)}else if(!H)h.fillRect(Q,Oe-Pn*Ut,Ie,2);else if(de!=Sn){const ge=Pn*Ut;Mr(Q,ge,Ie,!this._radialInvert||yt||ge+x>=2?-2:2)}}}if(ee){if(h.globalAlpha=1,de==Sn){if(Or(),H&&!fe){if(j){let G;for(;G=wi.pop();)h.lineTo(...Ke(...G,-1))}h.closePath()}if(P>0&&h.stroke(),L>0){if(H){const G=fe?rn(bt>>1):0,X=fe?rn(bt):wn;h.moveTo(...Ke(fe?bt>>1:0,0)),h.arc(y,v,x,G,X,fe?!on:!0)}else h.lineTo(xr,Oe),h.lineTo(E,Oe);h.globalAlpha=L,h.fill(),h.globalAlpha=1}if((yi||H&&Y)&&(wi=[],h.beginPath(),O.forEach((G,X)=>{let Q=G.posX,_e=G.peak[B],Ie=X?"lineTo":"moveTo";if(H&&Q<0){const qe=O[X+1];_e=x_(Q,_e,qe.posX,qe.peak[B],0),Q=0}_e*=Ut,yi?(h[Ie](...H?Ke(Q,_e):[Q,Oe-_e]),H&&j&&!fe&&wi.push([Q,_e])):_e>0&&Mr(Q,_e,1,-2)}),yi)){let G;for(;G=wi.pop();)h.lineTo(...Ke(...G,-1));h.lineWidth=1,h.stroke()}}h.restore(),fe&&!H&&h.setTransform(1,0,0,1,0,0),(!fe&&!be||B)&&Nb(B)}}if(Ub(Ah/(Lh<<Dh-1)),ee&&(j&&!H&&!fe&&(h.setTransform(-1,0,0,1,C.width-E,0),h.drawImage(C,E,0,y,C.height,0,0,y,C.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),Fb()),this.showFPS){const B=ie.height;h.font=`bold ${B}px ${Qi}`,h.fillStyle=h_,h.textAlign="right",h.fillText(Math.round(D),C.width-B,B*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case Cn:return Math.log2(e);case lr:return 26.81*e/(1960+e)-.53;case cr:return Math.log2(1+e/700);case ri:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,f=this._chLayout==mt,g=1-s,y=d?e.height:e.height*(1-s*!f)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],_=b.colorStops,T=b.dir=="h";let E;if(i?E=n.createRadialGradient(r,a,u,r,a,c-(u-c)*f):E=n.createLinearGradient(...T?[l,0,l+o,0]:[0,0,0,y]),_){const x=f&&!this._splitGradient&&(!T||i);for(let I=0;I<1+x;I++){const O=_.length-1;_.forEach((C,k)=>{let p=C.pos;if(x&&(p/=2),f&&!d&&!i&&!T&&(p*=g,!x&&p>.5*g&&(p+=.5*s)),I==1)if(i||d){const m=O-k;C=_[m],p=1-C.pos/2}else k==0&&p>0&&E.addColorStop(.5,C.color),p+=.5;E.addColorStop(p,C.color),f&&k==O&&p<.5&&E.addColorStop(.5,C.color)})}}this._canvasGradients[v]=E}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==n,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Xd&&n.width==u&&n.height==d)&&(n.width=u,n.height=d,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,u,d)),i.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Yd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new et(w_,e);[0,1].includes(n)||(this._selectedGrads[1]=e,n=0),this._selectedGrads[n]=e,this._makeGrad()}_setProps(e,n){const i=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(ai).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...ai,...e});for(const r of Object.keys(e))i.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const A_={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}]}},iu=({stream:t,className:e,onClick:n})=>{var o;const i=he(null),s=Jt();return Re(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new R_(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",A_[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),A("div",{onClick:n,className:Et("w-full",e),ref:i})},su=Ri(null),ou=({className:t,debug:e=!1})=>{const n=Gs(su);return!e||!n||!(n.region||n.dc)?null:A("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[n.region&&A("span",{"data-testid":"connection-info-region",children:["region: ",n.region]}),n.region&&n.dc&&A("span",{children:" · "}),n.dc&&A("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(),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();/**
21
+ */const ru=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),L_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),au=t=>{const e=L_(t);return e.charAt(0).toUpperCase()+e.slice(1)},D_=(...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 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"};/**
26
+ */var P_={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 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)]);/**
31
+ */const M_=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>Xe("svg",{...P_,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Xe(l,c)),...ht(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(yy,{...r,iconNode:e,class:my(`lucide-${Xd(Yd(t))}`,`lucide-${Xd(t)}`,i)},s);return n.displayName=Yd(t),n};/**
36
+ */const je=(t,e)=>{const n=({class:i="",children:s,...o})=>Xe(M_,{...o,iconNode:e,class:D_(`lucide-${ru(au(t))}`,`lucide-${ru(t)}`,i)},s);return n.displayName=au(t),n};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const Jd=Be("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
41
+ */const lu=je("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const _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"}]]);/**
46
+ */const O_=je("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const Zd=Be("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
51
+ */const cu=je("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
52
52
  * @license lucide-preact v0.515.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const 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"}]]);/**
56
+ */const N_=je("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 wy=Be("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const F_=je("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 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"}]]);/**
66
+ */const V_=je("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 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"}]]);/**
71
+ */const U_=je("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 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"}]]);/**
76
+ */const B_=je("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 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"}]]);/**
81
+ */const j_=je("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 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"}]]);/**
86
+ */const $_=je("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 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"}]]);/**
91
+ */const H_=je("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 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"}]]);/**
96
+ */const G_=je("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const Ay=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 W_=je("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 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"}]]);/**
106
+ */const q_=je("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),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
- `,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=>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
- `,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}`]||!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
- ${o.type}
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 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})})();
111
+ */const ur=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),du=Ri(!1),z_=()=>Ba(du),xt=({children:t,className:e,onClick:n,tooltip:i})=>A("button",{title:i,onClick:n,className:Et("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),uu=({call:t,chatMode:e})=>{const[n,i]=z_(),s=()=>{i(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return A("div",{className:"flex items-center justify-center gap-2",children:[!e&&A(xt,{tooltip:n?"Unmute":"Mute",onClick:s,className:Et(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?A(V_,{className:"w-5 h-5 text-black dark:text-white"}):A(U_,{className:"w-5 h-5 text-black dark:text-white"})}),A(xt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:A(j_,{className:"w-4 h-4 text-black dark:text-white"})})]})},hu=({call:t,onExpand:e,chatMode:n,debug:i=!1})=>A(bn.div,{layoutId:oi,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&&A(iu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),A(Od,{stream:t.remoteStream,chatMode:n}),A(Md,{size:"small"}),A(uu,{call:t,chatMode:n}),A(ou,{debug:i})]});function K_(){const[t,e]=xe(!1),n=Jt();if(!n.give_feedback_url&&!n.report_issue_url&&!n.view_history_url)return null;const i=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{i(n.give_feedback_url)},o=()=>{i(n.report_issue_url)},r=()=>{i(n.view_history_url)};return A("div",{children:[A(xt,{tooltip:"More",onClick:()=>e(!t),children:A(cu,{className:"text-black dark:text-white"})}),t&&A("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:[A(xt,{tooltip:"More",onClick:()=>e(!t),children:A(cu,{className:"text-black dark:text-white"})}),A("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&A("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",A(W_,{className:"w-4 h-4"})]}),n.report_issue_url&&A("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",A(q_,{className:"w-4 h-4"})]}),n.view_history_url&&A("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",A(N_,{className:"w-4 h-4"})]})]})]})]})}function X_(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ts={exports:{}},Y_=ts.exports,fu;function J_(){return fu||(fu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(Y_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var _=v[b];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var _=s[b];this[_]=b<v?e:this.methodFactory(_,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==n&&(u.call(this),this[v].apply(this,arguments))}}function f(v,b,_){return c(v)||d.apply(this,arguments)}function g(v,b){var _=this,T,E,x,I="loglevel";typeof v=="string"?I+=":"+v:typeof v=="symbol"&&(I=void 0);function O(h){var w=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!I)){try{window.localStorage[I]=w;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+w+";"}catch{}}}function C(){var h;if(!(typeof window===n||!I)){try{h=window.localStorage[I]}catch{}if(typeof h===n)try{var w=window.document.cookie,R=encodeURIComponent(I),L=w.indexOf(R+"=");L!==-1&&(h=/^([^;]+)/.exec(w.slice(L+R.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var w=h;if(typeof w=="string"&&_.levels[w.toUpperCase()]!==void 0&&(w=_.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=_.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=b||f,_.getLevel=function(){return x??E??T},_.setLevel=function(h,w){return x=p(h),w!==!1&&O(x),u.call(_)},_.setDefaultLevel=function(h){E=p(h),C()||_.setLevel(h,!1)},_.resetLevel=function(){x=null,k(),u.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(r!==_&&(T=p(r.getLevel())),u.call(_),r===_)for(var h in o)o[h].rebuild()},T=p(r?r.getLevel():"WARN");var m=C();m!=null&&(x=p(m)),u.call(_)}r=new g,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var _=o[b];return _||(_=o[b]=new g(b,r.methodFactory)),_};var y=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(ts)),ts.exports}var Z_=J_();const Q_=X_(Z_),ey=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ty="[ai-agent-widget]",ce=Q_.getLogger("telnyx-ai-agent-widget"),ny=ce.methodFactory;ce.methodFactory=(t,e,n)=>{const i=ny(t,e,n);return function(...s){i(ey(),ty,...s)}},ce.setLevel("info");function iy({onCapture:t,onClose:e}){const n=he(null),i=he(null),s=he(null),[o,r]=xe(null),[a,l]=xe(!0);Re(()=>((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){ce.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?r("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const d=n.current,f=i.current,g=f.getContext("2d");if(!g)return;f.width=d.videoWidth,f.height=d.videoHeight,g.drawImage(d,0,0,f.width,f.height);const y=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(y),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return A("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:[A("div",{className:"absolute top-2 right-2 z-10",children:A(xt,{tooltip:"Close",onClick:u,children:A(ur,{className:"text-white w-5 h-5"})})}),A("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&A("div",{className:"absolute text-white text-center",children:A("p",{className:"text-sm",children:"Loading camera..."})}),o&&A("div",{className:"text-white text-center max-w-xs",children:[A("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),A("p",{className:"text-xs",children:o}),A("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&A(ut,{children:[A("video",{ref:n,autoPlay:!0,playsInline:!0,className:Et("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),A("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&A("div",{className:"p-3 flex justify-center",children:A("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:[A(lu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const hr=["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"],sy=["audio","lang","mark","p","s","sub","w"],pu=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function gu(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`</?(?:${n})(?:\\s+[^<>]*)?\\s*/?>`,e)}function mu(t,e){const n=[...t].sort((i,s)=>s.length-i.length).join("|");return new RegExp(`<\\/?(?:${n})(?:\\s+[^<>]*)?$`,e)}const vu=hr.filter(t=>!sy.includes(t)),oy=gu(hr,"gi"),_u=gu(vu,"gi"),ry=mu(hr,"i"),ay=mu(vu,"i"),ly=new RegExp(`${_u.source}|${pu.source}`,"i");function cy(t){const e=ly.test(t),n=e?oy:_u,i=e?ry:ay;return t.replace(n,"").replace(i,"").replace(pu,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function dy({item:t,containerRef:e}){const n=he(null),i=t.role==="assistant"?cy(t.content):t.content;return Re(()=>{var s;n.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),A("li",{className:Et("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[A("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&A("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&A("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),A("div",{className:Et("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&A("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&A("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),i&&A("p",{className:Et("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:i})]})]})}const uy=({transcript:t,call:e})=>{const n=he(null),i=he(null),s=he(null),[o,r]=xe([]),[a,l]=xe(!1),[c,u]=xe([]),[,d]=sr();Re(()=>()=>{o.forEach(C=>URL.revokeObjectURL(C.preview))},[o]),Re(()=>{if(c.length===0)return;const C=t.filter(k=>k.role==="user"&&!k.id.startsWith("optimistic-"));if(C.length>0){const k=C[C.length-1];u(p=>p.filter(m=>m.timestamp>k.timestamp))}},[t,c]);const f=C=>new Promise((k,p)=>{const m=new FileReader;m.onload=()=>k(m.result),m.onerror=p,m.readAsDataURL(C)}),g=async C=>{if(C.type.startsWith("image/"))try{const k=await f(C),p=URL.createObjectURL(C),m={id:Date.now().toString(),file:C,base64:k,preview:p};r(h=>[...h,m])}catch(k){ce.error("Error processing image:",k)}},y=C=>{r(k=>{const p=k.find(m=>m.id===C);return p&&URL.revokeObjectURL(p.preview),k.filter(m=>m.id!==C)})},v=C=>{const k=C.target,p=k.files;p&&p.length>0&&(Array.from(p).forEach(g),k.value="")},b=C=>{var p;const k=(p=C.clipboardData)==null?void 0:p.items;k&&Array.from(k).forEach(m=>{if(m.type.startsWith("image/")){const h=m.getAsFile();h&&g(h)}})},_=()=>{var C;(C=i.current)==null||C.click()},T=()=>{l(!0)},E=C=>{fetch(C).then(k=>k.blob()).then(k=>{const p=new File([k],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(k=>{ce.error("Error processing camera capture:",k)})},x=async()=>{var p;const C=n.current&&n.current.value.trim()!=="",k=o.length>0;if(C||k){const m=((p=n.current)==null?void 0:p.value)||"",h=new Date,w={id:`optimistic-${h.getTime()}`,role:"user",content:m,timestamp:h,attachments:o.map(R=>({type:"image",url:R.base64}))};u(R=>[...R,w]),k&&d("processing_image"),e.sendConversationMessage(m,o.map(R=>R.base64)),n.current&&(n.current.value=""),o.forEach(R=>URL.revokeObjectURL(R.preview)),r([])}},I=C=>{C.key==="Enter"&&(C.preventDefault(),x())},O=[...t,...c];return A("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:[A("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((C,k)=>A(dy,{item:C,containerRef:s},C.id+k))}),o.length>0&&A("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(C=>A("div",{className:"relative",children:[A("img",{src:C.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),A("button",{onClick:()=>y(C.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:A(ur,{className:"w-3 h-3"})})]},C.id))}),A("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:[A("input",{ref:n,type:"text",onKeyDown:I,onPaste:b,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),A("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),A(xt,{tooltip:"Attach image",onClick:_,children:A(B_,{className:"text-[#969696] w-4 h-4"})}),A(xt,{tooltip:"Take photo",onClick:T,children:A(lu,{className:"text-[#969696] w-4 h-4"})}),A(xt,{tooltip:"Send",children:A(H_,{onClick:x,className:"text-[#969696] w-4 h-4"})})]}),a&&A(iy,{onCapture:E,onClose:()=>l(!1)})]})};function hy({onCollapse:t}){return A("div",{className:"flex items-center justify-between w-full",children:[A(K_,{}),A(xt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:A(ur,{className:"text-black dark:text-white"})})]})}const fy=({call:t,onCollapse:e,transcript:n,chatMode:i,debug:s=!1})=>A(Tg,{children:A(bn.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:[A("div",{className:"p-4 text-center",children:[A(hy,{onCollapse:e}),!i&&A(iu,{className:"h-[144px]",stream:t.remoteStream}),A(Md,{size:"large",className:"mb-4"}),A(uu,{call:t,chatMode:i}),A(ou,{className:"mt-2",debug:s})]}),A(Od,{stream:t.remoteStream,chatMode:i}),A(uy,{call:t,transcript:n})]})});function ns(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function U(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(u){o(u)}}function a(c){try{l(i.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof n?u:new n(function(d){d(u)})).then(r,a)}l((i=i.apply(t,[])).next())})}var yu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),py=new Uint8Array(16);function gy(){if(!yu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return yu(py)}for(var bu=[],is=0;is<256;++is)bu[is]=(is+256).toString(16).substr(1);function Tn(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||gy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=bu;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const my={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,UNEXPECTED_ERROR:49001},vy={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,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,ICE_CANDIDATE_PAIR_CHANGED:33008,DUPLICATE_INBOUND_ANSWER:33007,TOKEN_EXPIRING_SOON:34001,SESSION_NOT_REATTACHED:35001,SIGNALING_HEALTH_PROBE_TIMEOUT:36001,SIGNALING_REQUEST_TIMEOUT:36002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004},{SDP_CREATE_OFFER_FAILED:_y,SDP_CREATE_ANSWER_FAILED:yy,SDP_SET_LOCAL_DESCRIPTION_FAILED:by,SDP_SET_REMOTE_DESCRIPTION_FAILED:wu,SDP_SEND_FAILED:Su,MEDIA_MICROPHONE_PERMISSION_DENIED:wy,MEDIA_DEVICE_NOT_FOUND:Sy,MEDIA_GET_USER_MEDIA_FAILED:Cu,HOLD_FAILED:Cy,INVALID_CALL_PARAMETERS:Ty,BYE_SEND_FAILED:ky,SUBSCRIBE_FAILED:Ey,PEER_CLOSED_DURING_INIT:fr,WEBSOCKET_CONNECTION_FAILED:Iy,WEBSOCKET_ERROR:xy,RECONNECTION_EXHAUSTED:Tu,GATEWAY_FAILED:Ry,LOGIN_FAILED:ku,INVALID_CREDENTIALS:Ay,AUTHENTICATION_REQUIRED:Ly,ICE_RESTART_FAILED:Dy,NETWORK_OFFLINE:Py,UNEXPECTED_ERROR:Eu}=my,{HIGH_RTT:My,HIGH_JITTER:Oy,HIGH_PACKET_LOSS:Ny,LOW_MOS:Iu,LOW_LOCAL_AUDIO:ss,LOW_BYTES_RECEIVED:xu,LOW_BYTES_SENT:Ru,ICE_CONNECTIVITY_LOST:Fy,ICE_GATHERING_TIMEOUT:Vy,ICE_GATHERING_EMPTY:Uy,PEER_CONNECTION_FAILED:By,ONLY_HOST_ICE_CANDIDATES:jy,ANSWER_WHILE_PEER_ACTIVE:$y,ICE_CANDIDATE_PAIR_CHANGED:Hy,DUPLICATE_INBOUND_ANSWER:Gy,TOKEN_EXPIRING_SOON:Wy,SESSION_NOT_REATTACHED:qy,SIGNALING_HEALTH_PROBE_TIMEOUT:zy,SIGNALING_REQUEST_TIMEOUT:Ky,SIGNALING_RECOVERY_REQUIRED:Xy,MEDIA_RECOVERY_REQUIRED:Yy}=vy,Jy=/^a=candidate:.+typ (srflx|prflx|relay)/m,Au="wss://rtc.telnyx.com",Lu={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Du={urls:"stun:stun.l.google.com:19302"},Zy=[{urls:"stun:stun.telnyx.com:3478"},Du,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Qy=[{urls:"stun:stundev.telnyx.com:3478"},Du,{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 M;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"})(M||(M={}));const e0={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"]},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"]},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"]}},t0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},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"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36001:{name:"SIGNALING_HEALTH_PROBE_TIMEOUT",message:"Signaling health probe timed out",description:"A signaling liveness probe (Ping) was sent during an active call but no response was received within the timeout window. This indicates the WebSocket may be half-dead — the browser reports it as OPEN but data is not flowing. The SDK will force-close the socket to trigger reconnection.",causes:["Network interface removed mid-call while another interface remains","TCP connection bound to a removed IP/route became half-dead","Firewall or NAT state expired silently","WebSocket proxy or load balancer dropped the connection without a close frame"],solutions:["The SDK will automatically force-close the socket and reconnect","Check for network interface changes during the call","Verify firewall/NAT timeout settings"]},36002:{name:"SIGNALING_REQUEST_TIMEOUT",message:"Signaling request timed out",description:"A signaling-critical JSON-RPC request (e.g. ICE restart Modify) did not receive a response within the timeout window while the socket reports OPEN. This may indicate the WebSocket is half-dead or the server is unresponsive. The SDK will mark signaling as unhealthy and force reconnection.",causes:["Half-dead WebSocket (browser reports OPEN but data does not flow)","Server unresponsive or overloaded","Network path interruption without TCP RST"],solutions:["The SDK will automatically force-close the socket and reconnect","Check server health and response times","Check for network path issues"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. If media was still flowing, the reconnect is delayed briefly to allow the application to notify the user about a short interruption. Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},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 tt(t,e){const n=t0[t];return{code:t,name:n.name,message:n.message,description:n.description,causes:[...n.causes],solutions:[...n.solutions]}}class li 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,li.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 ci(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return wy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Sy}return Cu}function re(t,e,n){const i=e0[t],s=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new li({code:t,name:i.name,description:i.description,message:n||i.message,causes:[...i.causes],solutions:[...i.solutions],originalError:s})}class n0 extends Error{constructor(e,n,i=""){super(`Signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${n}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=n,this.method=i}}class pr extends Error{constructor(e,n,i){super(`Stale request cancelled (id=${e}, gen=${n}, current=${i})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=n,this.currentGeneration=i}}var i0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Pu(t,e){return t(e={exports:{}},e.exports),e.exports}var s0=Pu(function(t){var e,n;e=i0,n=function(){var i=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,_){var T=b[_];if(typeof T.bind=="function")return T.bind(b);try{return Function.prototype.bind.call(T,b)}catch{return function(){return Function.prototype.apply.apply(T,[b,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(b,_){for(var T=0;T<r.length;T++){var E=r[T];this[E]=T<b?i:this.methodFactory(E,b,_)}this.log=this.debug}function u(b,_,T){return function(){typeof console!==s&&(c.call(this,_,T),this[b].apply(this,arguments))}}function d(b,_,T){return function(E){return E==="debug"&&(E="log"),typeof console!==s&&(E==="trace"&&o?l:console[E]!==void 0?a(console,E):console.log!==void 0?a(console,"log"):i)}(b)||u.apply(this,arguments)}function f(b,_,T){var E,x=this;_=_??"WARN";var I="loglevel";function O(){var k;if(typeof window!==s&&I){try{k=window.localStorage[I]}catch{}if(typeof k===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(I)+"=");m!==-1&&(k=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return x.levels[k]===void 0&&(k=void 0),k}}typeof b=="string"?I+=":"+b:typeof b=="symbol"&&(I=void 0),x.name=b,x.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},x.methodFactory=T||d,x.getLevel=function(){return E},x.setLevel=function(k,p){if(typeof k=="string"&&x.levels[k.toUpperCase()]!==void 0&&(k=x.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=x.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(E=k,p!==!1&&function(m){var h=(r[m]||"silent").toUpperCase();if(typeof window!==s&&I){try{return void(window.localStorage[I]=h)}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+h+";"}catch{}}}(k),c.call(x,k,b),typeof console===s&&k<x.levels.SILENT)return"No console available for logging"},x.setDefaultLevel=function(k){_=k,O()||x.setLevel(k,!1)},x.resetLevel=function(){x.setLevel(_,!1),function(){if(typeof window!==s&&I){try{return void window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},x.enableAll=function(k){x.setLevel(x.levels.TRACE,k)},x.disableAll=function(k){x.setLevel(x.levels.SILENT,k)};var C=O();C==null&&(C=_),x.setLevel(C,!1)}var g=new f,y={};g.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var _=y[b];return _||(_=y[b]=new f(b,g.getLevel(),g.methodFactory)),_};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return y},g.default=g,g},t.exports?t.exports=n():e.log=n()});const Mu={debug:0,info:1,warn:2,error:3};class o0{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||Mu[e]<Mu[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 Ou=null;const S=s0.getLogger("telnyx"),os={trace:0,debug:1,info:2,warn:3,error:4};let Nu=os.info;function Fu(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 r0=S.methodFactory;S.methodFactory=(t,e,n)=>{const i=r0(t,e,n);return function(...s){if(os[t]>=Nu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);i(...r)}const o=Ou;if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?Fu(a[0]):{args:a.map(Fu)}),o.addEntry(t,l,c)}}},S.setLevel("debug",!1);const rs=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{S.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Vu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},kn=t=>t instanceof Function||typeof t=="function",di=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,a0=/^(ws|wss):\/\//,Uu=(t,e=null)=>{const{result:n={},error:i}=t;if(i)return{error:i};const{result:s=null}=n;if(s===null)return e!==null&&(n.node_id=e),{result:n};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Uu(a,r):{result:s}},Bu=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),as=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),ui=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,gr=t=>{var e,n,i,s,o,r;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function ju({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?l0(i,t):i,n=s}),resolve:e,reject:n}}const l0=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},mr="telnyx-voice-sdk-id",ls="telnyx-voice-sdk-session-id",cs="telnyx-voice-sdk-session-id-stored-at",c0=9e4;function $u(t=Date.now()){const e=function(){const n=Number(sessionStorage.getItem(cs));return Number.isFinite(n)?n:null}();return e!==null&&t-e<=c0}function hi(){return sessionStorage.getItem(mr)}function Hu(t,e=Date.now()){sessionStorage.setItem(ls,t),sessionStorage.setItem(cs,String(e))}function Gu(){sessionStorage.removeItem(mr),sessionStorage.removeItem(ls),sessionStorage.removeItem(cs)}var Me,at,Z;(function(t){t.Offer="offer",t.Answer="answer"})(Me||(Me={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(at||(at={})),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"}(Z||(Z={}));const nt={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},d0={invalidCredentialsOptions:"InvalidCredentialsOptions"},u0={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 $,vr,ze,vt,Fe,En;(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"})($||($={})),function(t){t.Participant="participant",t.Moderator="moderator"}(vr||(vr={})),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"}(vt||(vt={})),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"}(Fe||(Fe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(En||(En={}));const In="GLOBAL",We={},fi=(t,e)=>`${t}|${e}`,Wu=(t,e=In)=>fi(t,e)in We,Vt=(t,e,n=In)=>{const i=fi(t,n);i in We||(We[i]=[]),We[i].push(e)},qu=(t,e,n=In)=>{const i=function(s){_t(t,i,n),e(s)};return i.prototype.targetRef=e,Vt(t,i,n)},_t=(t,e,n=In)=>{if(!Wu(t,n))return!1;const i=fi(t,n);if(kn(e))for(let s=We[i].length-1;s>=0;s--){const o=We[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&We[i].splice(s,1)}else We[i]=[];return We[i].length===0&&delete We[i],!0},V=(t,e,n=In,i=!0)=>{const s=i&&n!==In;if(!Wu(t,n))return s&&V(t,e),!1;const o=fi(t,n),r=We[o].length;if(!r)return s&&V(t,e),!1;for(let a=r-1;a>=0;a--)We[o][a](e);return s&&V(t,e),!0},_r=t=>{const e=fi(t,"");Object.keys(We).filter(n=>n.indexOf(e)===0).forEach(n=>delete We[n])};let h0=typeof WebSocket<"u"?WebSocket:null;const f0=0,p0=1,g0=2,zu=3;class ds{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Au,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Au),n&&(this._host=(r=>`${a0.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===p0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===f0}get closing(){return!!this._wsClient&&this._wsClient.readyState===g0}get closed(){return!!this._wsClient&&this._wsClient.readyState===zu}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=hi();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"),S.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true");try{const i=this.socketGeneration;this._wsClient=new h0(e.toString()),this.socketGeneration+=1,S.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:i}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(i){S.error("WebSocket connection failed:",i);const s=re(Iy,i);V(M.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,n){var i;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const f=g=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),u)return;const{result:y,error:v}=Uu(g);return v?c(v):l(y)};qu(s.id,f),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),n&&n>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),_t(s.id,f),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return S.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new pr(s.id,o,this.socketGeneration));c(new n0(s.id,n,r))},n),this._pendingRequestTimers.set(s.id,d))});return S.debug(`SEND:
112
+ `,JSON.stringify(s,null,2),`
113
+ `),(i=this._wsClient)===null||i===void 0||i.send(JSON.stringify(s)),a}close(){if(!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;kn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>V(M.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),V(M.SocketClose,n,this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const i=re(xy);return V(M.Error,{error:i,sessionId:this.session.sessionid},this.session.uuid),V(M.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=n=>{var i,s;this.lastInboundAt=Date.now(),V(M.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const o=Vu(n.data);var r;if(typeof o!="string"){if(o.voice_sdk_id&&(this.session.callReportVoiceSdkId=o.voice_sdk_id,r=o.voice_sdk_id,sessionStorage.setItem(mr,r)),this._unsetTimer(o.id),S.debug(`RECV:
114
+ `,JSON.stringify(o,null,2),`
115
+ `),Fe[`${(s=(i=o==null?void 0:o.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!V(o.id,o)){const a=gr(o);V(M.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==zu?(S.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||V(M.SocketClose,{code:Lu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):S.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(S.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(S.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):S.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{_t(e);const n=this._pendingRequestTimers.get(e),i=this._pendingRequestRejecters.get(e);n&&(clearTimeout(n),this._pendingRequestTimers.delete(e),i&&i.reject(new pr(e,i.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),V(M.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else S.warn("Unknown message from socket",e)}}ds.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class pi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Tn()},e)}}const Ku={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ve extends pi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=ns(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in Ku)i&&n.hasOwnProperty(i)&&(n[Ku[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class Xu extends Ve{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class m0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>U(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(gr(n))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const n=new Xu(hi());this.pendingRequestId=n.request.id,this.gatewayStateTask=ju({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Fe.REGISTER,Fe.REGED].includes(i)}),this.session=e,this.gatewayStateTask=ju({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class yr extends Ve{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class xn{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null}static isCriticalMethod(e){return xn.CRITICAL_METHODS.has(e)}start(){this._intervalId||(S.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,S.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight||(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),S.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery))return;const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(S.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason,e.source))}_probeIfNeeded(e){var n;!((n=this._session.connection)===null||n===void 0)&&n.connected&&(this._probeInFlight?S.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(S.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,n,i=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(xn.isCriticalMethod(i)?(S.warn(`Critical signaling request timed out (id=${e}, method=${i}, timeout=${n}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${i}, id=${e}, timeout=${n}ms)`,"request")):S.warn(`Non-critical signaling request timed out (id=${e}, method=${i||"unknown"}, timeout=${n}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,n){S.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${n})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${n})`,`Peer failure detected (${n}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,n){S.warn(`Signaling health: no RTP detected (callId=${e}, direction=${n})`),this._recoverMediaOrSignaling(e,`No RTP ${n} while media should be active`,`No RTP ${n} while signaling is unhealthy`,"no_rtp")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const n=Date.now(),i=n-this._lastInboundAt;if(i<2e4)return;if(!this._probeInFlight)return S.info(`Signaling health: no inbound WS activity for ${Math.round(i/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=n-this._lastProbeSentAt;s>=5e3&&(S.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const n=new yr(hi());(e=this._session.connection)===null||e===void 0||e.send(n).then(()=>this._resolveProbe()).catch(i=>{S.warn("Signaling health: probe Ping failed to send",i)})}_recoverMediaOrSignaling(e,n,i,s){if(!this._session.hasActiveCall())return void S.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(S.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,n,s)):o==="unknown"?(S.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:n,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(S.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(i,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const n=Date.now(),i=this._lastInboundAt||this._session.connection.lastInboundAt||0;return i===0?"unknown":n-i<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,n="probe"){var i;let s;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,s=n==="probe"?zy:n==="request"?Ky:Xy;const o=tt(s);V(M.Warning,{warning:o,reason:e,source:n,sessionId:this._session.sessionid},this._session.uuid),!((i=this._session.connection)===null||i===void 0)&&i.connected&&(S.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect())}_triggerIceRestart(e,n,i){S.info(`Signaling health: triggering ICE restart for call ${e}`);const s=this._session.triggerIceRestart(e);if(!s.started)return S.info(`Signaling health: ICE restart not started for call ${e}: ${s.reason}`),void(s.recoverSignaling&&this._triggerSignalingRecovery(`${n}; ICE restart disabled for reattached call, forcing socket reconnect`,i));const o=tt(Yy);V(M.Warning,{warning:o,reason:n,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}xn.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var Yu="2.27.1",br=Yu;class v0 extends Ve{constructor(e,n,i,s,o={},r){super(),this.method="login";const a={login:e,passwd:n,login_token:i,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:br,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class _0 extends Ve{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class Ju extends Ve{toString(){return Z.Invite}}class Zu extends Ve{toString(){return Z.Answer}}class Qu extends Ve{toString(){return Z.Attach}}class y0 extends Ve{toString(){return Z.Bye}}class b0 extends Ve{toString(){return Z.Candidate}}class w0 extends Ve{toString(){return Z.EndOfCandidates}}class us extends Ve{toString(){return Z.Modify}}class eh extends Ve{toString(){return Z.Info}}class S0 extends Ve{toString(){return Z.Broadcast}}class C0 extends Ve{toString(){return Z.Subscribe}}class T0 extends Ve{toString(){return Z.Unsubscribe}}class k0 extends Ve{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:br,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class Zt{constructor(e){if(this.options=e,this.uuid=Tn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new xn(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",Nu=(i=os[n])!==null&&i!==void 0?i:os.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new ds(this),this.registerAgent=new m0(this)}get __logger(){return S}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return U(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Bu(2,6)}execute(e){var n;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),S.debug("Calling connect from execute since not currently connected."),this.connect()});const i=xn.isCriticalMethod(((n=e.request)===null||n===void 0?void 0:n.method)||"")?ds.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(i!=null?this.connection.send(e,i):this.connection.send(e)).catch(s=>U(this,void 0,void 0,function*(){if(s instanceof pr)throw S.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=re(Ly,s);V(M.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return U(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let n=!1;yield Promise.race([Promise.all(e.map(i=>i.catch(()=>{}))),new Promise(i=>setTimeout(()=>{n=!0,i()},Zt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),n&&S.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return as(this.options)||ui(this.options)}broadcast(e){}disconnect(){return U(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),S.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Vt(e,n,this.uuid),this}off(e,n){return _t(e,n,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(S.debug("No existing connection found, creating a new one."),this.connection=new ds(this)),this._attachListeners(),this._autoReconnect||(this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(S.debug("Initiating connection to the server..."),this.connection.connect()),S.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0}_handleLoginError(e){const n=re(ku,e);V(M.Error,{error:n,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Gu()}_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<=Zt.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-Zt.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{S.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=tt(Wy);V(M.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:n,onError:i}={}){return U(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),as(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(ui(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";S.error(s);const o=re(Ay,void 0,s);return void V(M.Error,{error:o,type:d0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return U(this,void 0,void 0,function*(){let s;const o=!!hi(),r=o&&(this.sessionid&&$u()?this.sessionid:function(l=Date.now()){const c=sessionStorage.getItem(ls);return c?$u(l)?c:(sessionStorage.removeItem(ls),sessionStorage.removeItem(cs),null):null}())||"";s=e==="login"?new v0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,r,this.options.userVariables,o):new k0({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:r,userVariables:this.options.userVariables,reconnection:o});const a=yield this.execute(s).catch(l=>{this._handleLoginError(l),i&&i(l)});a&&(this.sessionid=a.sessid,this.sessionid&&Hu(this.sessionid),this._checkTokenExpiry(),n&&n())})}_onSocketOpen(){return U(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const n=this.calls;n&&Object.values(n).forEach(i=>{if(i!=null&&i.flushIntermediateCallReport)try{i.flushIntermediateCallReport(e)}catch(s){S.error("Failed to flush intermediate call report",{callId:i.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const n=Object.entries(Lu).find(([,i])=>i===e);return n==null?void 0:n[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var n;this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),this.relayProtocol&&_r(this.relayProtocol);for(const i in this.subscriptions)_r(i);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Hu(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const i=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:10;if(this._reconnectAttempts+=1,i>0&&this._reconnectAttempts>i){S.info(`Reconnection exhausted after ${i} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1;const s=re(Tu);return void V(M.Error,{error:s,sessionId:this.sessionid},this.uuid)}S.debug(`Reconnect attempt ${this._reconnectAttempts}${i>0?` of ${i}`:""}`),this._reconnectTimeout=setTimeout(()=>{S.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],_t(e,null,n)):(delete this.subscriptions[e],_r(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},kn(n)&&Vt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(M.SocketOpen,this._onSocketOpen),this.on(M.SocketClose,this.onNetworkClose),this.on(M.SocketError,this.onNetworkClose),this.on(M.SocketMessage,this._onSocketMessage),this.on(M.SocketActivity,this._onSocketActivity)}_detachListeners(){this.off(M.SocketOpen,this._onSocketOpen),this.off(M.SocketClose,this.onNetworkClose),this.off(M.SocketError,this.onNetworkClose),this.off(M.SocketMessage,this._onSocketMessage),this.off(M.SocketActivity,this._onSocketActivity)}_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.stopSignalingHealthMonitor(),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(S.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new yr(hi()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){S.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const n=new Set([$.Early,$.Active,$.Held]);return Object.values(e).some(i=>i&&i._state!=null&&n.has(i._state))}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){var n;const i=this.calls,s=i==null?void 0:i[e];if(!s)return S.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};if(!((n=s.options)===null||n===void 0)&&n.attach||s.recoveredCallId)return S.warn(`Signaling health: ICE restart skipped for call ${e}: call was recovered via attach`),{started:!1,reason:"call recovered via attach",recoverSignaling:!0};const o=s.peer;if(!(o!=null&&o.restartIce))return S.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const r=o.restartIce();return r.started||S.debug(`Signaling health: ICE restart skipped for call ${e}: ${r.reason}`),r}onSignalingRequestTimeout(e,n,i=""){this._signalingHealthMonitor.onRequestTimeout(e,n,i)}reportPeerFailure(e,n){this._signalingHealthMonitor.onPeerFailure(e,n)}reportNoRtp(e,n){this._signalingHealthMonitor.onNoRtp(e,n)}static on(e,n){Vt(e,n)}static off(e){_t(e)}static uuid(){return Tn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Zt.TOKEN_EXPIRY_WARNING_SECONDS=120,Zt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const hs=t=>navigator.mediaDevices.getUserMedia(t),Rn=t=>t&&t instanceof MediaStream,fs=(t,e)=>{const n=di(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},th=(t,e)=>{const n=di(t);if(n){if(e&&n.srcObject!==e)return;n.srcObject=null}},nh=(t,e)=>U(void 0,void 0,void 0,function*(){const n=di(t);if(n===null)return S.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return S.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),E0=t=>{t&&t.readyState==="live"&&t.stop()},gi=t=>{Rn(t)&&t.getTracks().forEach(E0),t=null},ps=t=>U(void 0,void 0,void 0,function*(){S.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield hs(t)}catch(i){if(S.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=ns(r,["deviceId"]);c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=ns(a,["deviceId"]);u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){S.warn("Device not found or not readable, falling back to default device");try{return yield hs(s)}catch(o){throw S.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),mi=(t=null,e=!1)=>U(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===vt.AudioIn||s===vt.AudioOut,video:!s||s===vt.Video}))(t)).catch(s=>(S.error(s),null));if(i){if(gi(i),n=yield navigator.mediaDevices.enumerateDevices(),t&&(n=n.filter(o=>o.kind===t)),e===!0)return n;const s=[];n=n.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return n}),ih=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],gs=(t,e,n)=>U(void 0,void 0,void 0,function*(){const i=yield mi(n,!0);for(let s=0;s<i.length;s++){const{deviceId:o,label:r}=i[s];if(t===o||e===r)return o}return null}),I0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},wr=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=Sr(t);return n.includes(e)||i.includes(e)},Sr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},An=(t,e=null,n=null)=>{if(!Rn(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}})},sh=t=>{An(t,"audio",!0)},Cr=t=>{An(t,"audio",!1)},oh=t=>{An(t,"audio",null)},x0=t=>((e,n=null)=>{if(!Rn(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 R0(){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()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!ps}}catch(t){return t.message}}var Te;function rh(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 ah(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{S.error("playAudio",e),t._playFulfilled=!0}))}function lh(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Te||(Te={}));const ch=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 A0 extends pi{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Tn(),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 oe{constructor(e,n){var i;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new o0(s)}(this.logCollectorOptions),this.logCollector.start(),i=this.logCollector,Ou=i)}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,S.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:oe.INITIAL_COLLECTION_INTERVAL_MS,initialDuration:oe.INITIAL_COLLECTION_DURATION_MS,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this._scheduleNextCollection())}stop(){var e,n;return U(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),S.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,n){var i,s;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const o=this._segmentIndex++,r=this.statsBuffer;this.statsBuffer=[];const a=(s=(i=this.logCollector)===null||i===void 0?void 0:i.drain())!==null&&s!==void 0?s:[],l=new Date;this._lastIntermediateFlushTime=l;const c=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(l.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:l.toISOString()}),stats:r},a.length>0?{logs:a}:{}),{segment:o}),n?{flushReason:n}:{});return S.info("CallReportCollector: Flushed intermediate segment",{segment:o,intervals:r.length,logEntries:a.length,callId:e.callId,flushReason:n}),c}finally{this._flushing=!1}}postReport(e,n,i,s){var o,r;return U(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void S.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void S.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,n,i,s,!0)})}sendPayload(e,n,i,s){return U(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s,!1)})}_sendPayload(e,n,i,s,o=!0){var r,a;return U(this,void 0,void 0,function*(){const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,u=o?"final report":`intermediate segment ${e.segment}`;S.info(`CallReportCollector: Posting ${u}`,{endpoint:c,intervals:e.stats.length,logEntries:(a=(r=e.logs)===null||r===void 0?void 0:r.length)!==null&&a!==void 0?a:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const f=JSON.stringify(e),g=o&&f.length<=oe.KEEPALIVE_BODY_LIMIT_BYTES;let y;for(let v=0;v<=oe.RETRY_DELAYS_MS.length;v++){try{const _=yield fetch(c,Object.assign({method:"POST",headers:d,body:f},g?{keepalive:!0}:{}));if(_.ok)return void S.info(`CallReportCollector: Successfully posted ${u}`,{attempt:v+1,status:_.status});{const T=yield _.text();y=new Error(`Call report POST failed with status ${_.status}`),S.error(`CallReportCollector: Failed to post ${u}`,{attempt:v+1,status:_.status,error:T})}}catch(_){y=_,S.warn(`CallReportCollector: Network error posting ${u}`,{attempt:v+1,error:_})}const b=oe.RETRY_DELAYS_MS[v];if(b===void 0)break;S.info(`CallReportCollector: Retrying ${u} in ${b}ms`,{attempt:v+2}),yield new Promise(_=>setTimeout(_,b))}throw S.error(`CallReportCollector: Exhausted retries posting ${u}`,{error:y}),y instanceof Error?y:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,n,i,s,o,r,a,l,c,u,d,f,g,y,v,b;if(this.statsBuffer.length<2)return!1;const _=this.statsBuffer[this.statsBuffer.length-1],T=this.statsBuffer[this.statsBuffer.length-2],E=(e=_.ice)===null||e===void 0?void 0:e.local;if(!((E==null?void 0:E.networkType)==="vpn"&&(E==null?void 0:E.candidateType)!=="relay"))return!1;const x=((n=_.ice)===null||n===void 0?void 0:n.writable)===!1,I=((i=_.transport)===null||i===void 0?void 0:i.iceState)==="disconnected"||((s=_.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=_.ice)===null||o===void 0?void 0:o.requestsSent,(r=T.ice)===null||r===void 0?void 0:r.requestsSent),C=this._positiveDelta((a=_.ice)===null||a===void 0?void 0:a.responsesReceived,(l=T.ice)===null||l===void 0?void 0:l.responsesReceived),k=O>0&&C===0,p=this._positiveDelta((u=(c=_.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(f=(d=T.audio)===null||d===void 0?void 0:d.outbound)===null||f===void 0?void 0:f.bytesSent),m=this._positiveDelta((y=(g=_.audio)===null||g===void 0?void 0:g.inbound)===null||y===void 0?void 0:y.bytesReceived,(b=(v=T.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return x||I||k||p>0&&m===0}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}_positiveDelta(e,n){return e===void 0||n===void 0?0:Math.max(0,e-n)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor(this.intervalStartTime);this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(e){const n=this._positiveInterval(this.options.interval,5e3);return e.getTime()-this.callStartTime.getTime()<oe.INITIAL_COLLECTION_DURATION_MS?Math.min(oe.INITIAL_COLLECTION_INTERVAL_MS,n):n}_positiveInterval(e,n){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:n}_collectStats(e=!1){return U(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const n=yield this.peerConnection.getStats(),i=new Date;let s,o,r,a,l,c=null,u=null,d=null,f=null;if(n.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(n,c);if(v!==null&&this.intervalAudioLevels.outbound.push(v),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const b=(c.bytesSent||0)-this.previousStats.outboundBytes,_=(c.timestamp||i.getTime())-this.previousStats.timestamp;if(_>0){const T=8*b*1e3/_;this.intervalBitrates.outbound.push(T)}}this.previousStats.outboundBytes=c.bytesSent}if(u){const v=this._getInboundAudioLevel(n,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 b=(u.bytesReceived||0)-this.previousStats.inboundBytes,_=(u.timestamp||i.getTime())-this.previousStats.timestamp;if(_>0){const T=8*b*1e3/_;this.intervalBitrates.inbound.push(T)}}this.previousStats.inboundBytes=u.bytesReceived}d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(s=this._resolveCandidate(n,d.localCandidateId),o=this._resolveCandidate(n,d.remoteCandidateId)),d&&(r=Object.assign(Object.assign({id:d.id,state:d.state,nominated:d.nominated,writable:d.writable,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},s?{local:s}:{}),o?{remote:o}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(S.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:r}),this._emitWarning(Hy)),this.previousCandidatePairSnapshot=r),c&&(a=this._getLocalAudioTrackSnapshot(),l=this._getOutboundAudioSourceStats(n,c)),this._logLocalAudioTrackSnapshot(a,l),this.previousStats.timestamp=i.getTime();const g=i.getTime()-this.intervalStartTime.getTime(),y=this._collectionIntervalFor(this.intervalStartTime);if(e||g>=y){const v=this._createStatsEntry(this.intervalStartTime,i,c,u,d,s,o,f,a,l);this.statsBuffer.push(v),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),S.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(v,u),this._requestIntermediateFlushIfNeeded(i),this.intervalStartTime=i,this._resetIntervalAccumulators()}}catch(n){S.error("CallReportCollector: Error collecting stats",{error:n})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:oe.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var n,i;if(!this.onFlushNeeded||this._flushing||this.statsBuffer.length===0)return;const s=this.statsBuffer.length,o=(i=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&i!==void 0?i:0,r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=oe.STATS_FLUSH_THRESHOLD||o>=oe.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){S.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){S.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,n){var i,s,o,r,a,l,c,u,d,f,g,y,v,b,_;if(!this.onWarning)return;const T=(i=e.connection)===null||i===void 0?void 0:i.roundTripTimeAvg,E=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let x;if(n){const I=(r=n.packetsReceived)!==null&&r!==void 0?r:0,O=(a=n.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const C=I-this._prevPacketsReceived,k=O-this._prevPacketsLost,p=C+k;p>0&&(x=k/p*100)}this._prevPacketsReceived=I,this._prevPacketsLost=O}if(this._trackBreach(My,T!==void 0&&T>oe.THRESHOLD_RTT_MS),this._trackBreach(Oy,E!==void 0&&E>oe.THRESHOLD_JITTER_MS),this._trackBreach(Ny,x!==void 0&&x>oe.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),T!==void 0&&E!==void 0&&x!==void 0){const I=93.2-.11*E-2.5*x-.01*(1e3*T),O=Math.max(1,Math.min(4.5,1+.035*I+I*(I-60)*(100-I)*7e-6));this._trackBreach(Iu,O<oe.THRESHOLD_MOS)}else this._trackBreach(Iu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const I=(f=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||f===void 0?void 0:f.bytesReceived,O=e.audio.inbound.bytesReceived;this._trackBreach(xu,I!==void 0&&O-I==0)}if(((y=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||y===void 0?void 0:y.bytesSent)!==void 0){const I=(_=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||_===void 0?void 0:_.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(Ru,I!==void 0&&O-I==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var n;const i=(n=e.audio)===null||n===void 0?void 0:n.outbound,s=i==null?void 0:i.audioLevelAvg,o=i==null?void 0:i.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=oe.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(ss,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=oe.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(ss)):this._trackBreach(ss,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(ss,!1)}_getStatsIntervalDurationMs(e){const n=new Date(e.intervalStartUtc).getTime(),i=new Date(e.intervalEndUtc).getTime()-n;return Number.isFinite(i)&&i>0?i:this.options.interval}_trackBreach(e,n){var i,s;if(n){if(this._breachCounters[e]=((i=this._breachCounters[e])!==null&&i!==void 0?i:0)+1,this._breachCounters[e]>=oe.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=oe.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var n;try{const i=tt(e);S.warn(`CallReportCollector: warning ${i.code}: ${i.message}`),(n=this.onWarning)===null||n===void 0||n.call(this,i)}catch(i){S.error(`CallReportCollector: Failed to emit warning ${e}`,{error:i})}}_createStatsEntry(e,n,i,s,o,r,a,l,c,u){const d={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(d.audio.outbound=Object.assign(Object.assign({packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{})),s&&(d.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)}),o&&(d.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived},d.ice=Object.assign(Object.assign({id:o.id,state:o.state,nominated:o.nominated,writable:o.writable,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(d.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}:{})),d}_resolveCandidate(e,n){if(!n)return void S.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void S.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0?s.address=i.address:i.ip!==void 0&&(s.address=i.ip),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;S.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundMediaSource(e,n){let i;return n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),i}_getLocalAudioTrackSnapshot(){var e,n;try{const i=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=i==null?void 0:i.track;if(!s)return;const o=(n=s.getSettings)===null||n===void 0?void 0:n.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(i){return void S.debug("CallReportCollector: unable to snapshot local audio track",{error:i})}}_getOutboundAudioSourceStats(e,n){const i=this._getOutboundMediaSource(e,n);if(!i)return;const s=this._withoutUndefined({id:i.id,trackIdentifier:i.trackIdentifier,audioLevel:i.audioLevel,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration,echoReturnLoss:i.echoReturnLoss,echoReturnLossEnhancement:i.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,n){if(!e||Object.keys(e).length===0)return;const i=this._stableStringify(e);i!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=i,S.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:n}))}_withoutUndefined(e){return Object.keys(e).reduce((n,i)=>{const s=e[i];return s!==void 0&&(n[i]=s),n},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(n=>this._sortObjectKeys(n)):e&&typeof e=="object"?Object.keys(e).sort().reduce((n,i)=>(n[i]=this._sortObjectKeys(e[i]),n),{}):e}_getOutboundAudioLevel(e,n){const i=this._getOutboundMediaSource(e,n);if((i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=n,r===void 0||a===void 0)return null;const l=e-r,c=n-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}oe.INITIAL_COLLECTION_INTERVAL_MS=1e3,oe.INITIAL_COLLECTION_DURATION_MS=1e4,oe.STATS_FLUSH_THRESHOLD=300,oe.LOGS_FLUSH_THRESHOLD=800,oe.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,oe.CONSECUTIVE_BREACHES_REQUIRED=3,oe.THRESHOLD_RTT_MS=.4,oe.THRESHOLD_JITTER_MS=30,oe.THRESHOLD_PACKET_LOSS_PCT=1,oe.THRESHOLD_MOS=3.5,oe.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,oe.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,oe.WARNING_THROTTLE_MS=15e3,oe.RETRY_DELAYS_MS=[500,1e3,2e3],oe.KEEPALIVE_BODY_LIMIT_BYTES=61440;var ms,dh=Pu(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,m,h,w){var R,L,D;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((L=p._events)?(L.newListener&&(p.emit("newListener",m,h.listener?h.listener:h),L=p._events),D=L[m]):(L=p._events=new i,p._eventsCount=0),D){if(typeof D=="function"?D=L[m]=w?[h,D]:[D,h]:w?D.unshift(h):D.push(h),!D.warned&&(R=o(p))&&0<R&&D.length>R){D.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=m,N.count=D.length,function(P){typeof console.warn=="function"?console.warn(P):console.log(P)}(N)}}else D=L[m]=h,++p._eventsCount;return p}function a(p,m,h){function w(){p.removeListener(m,w),R||(R=!0,h.apply(p,arguments))}var R=!1;return w.listener=h,w}function l(p){var m=this._events;if(m){var h=m[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,m){for(var h=Array(m);m--;)h[m]=p[m];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 o(this)},s.prototype.emit=function(p){var m,h,w,R,L,D,N,P=p==="error";if(D=this._events)P=P&&D.error==null;else if(!P)return!1;if(N=this.domain,P){if(m=arguments[1],!N){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(h=D[p]))return!1;var z=typeof h=="function";switch(w=arguments.length){case 1:(function(j,de,J){if(de)j.call(J);else for(var H=j.length,ae=c(j,H),Y=0;Y<H;++Y)ae[Y].call(J)})(h,z,this);break;case 2:(function(j,de,J,H){if(de)j.call(J,H);else for(var ae=j.length,Y=c(j,ae),ee=0;ee<ae;++ee)Y[ee].call(J,H)})(h,z,this,arguments[1]);break;case 3:(function(j,de,J,H,ae){if(de)j.call(J,H,ae);else for(var Y=j.length,ee=c(j,Y),te=0;te<Y;++te)ee[te].call(J,H,ae)})(h,z,this,arguments[1],arguments[2]);break;case 4:(function(j,de,J,H,ae,Y){if(de)j.call(J,H,ae,Y);else for(var ee=j.length,te=c(j,ee),ie=0;ie<ee;++ie)te[ie].call(J,H,ae,Y)})(h,z,this,arguments[1],arguments[2],arguments[3]);break;default:for(R=Array(w-1),L=1;L<w;L++)R[L-1]=arguments[L];(function(j,de,J,H){if(de)j.apply(J,H);else for(var ae=j.length,Y=c(j,ae),ee=0;ee<ae;++ee)Y[ee].apply(J,H)})(h,z,this,R)}return!0},s.prototype.addListener=function(p,m){return r(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return r(this,p,m,!0)},s.prototype.once=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,m)),this},s.prototype.prependOnceListener=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,m)),this},s.prototype.removeListener=function(p,m){var h,w,R,L,D;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(w=this._events))return this;if(!(h=w[p]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete w[p],w.removeListener&&this.emit("removeListener",p,h.listener||m));else if(typeof h!="function"){for(R=-1,L=h.length;0<L--;)if(h[L]===m||h[L].listener&&h[L].listener===m){D=h[L].listener,R=L;break}if(0>R)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete w[p]}else(function(N,P){for(var F=P,z=F+1,j=N.length;z<j;F+=1,z+=1)N[F]=N[z];N.pop()})(h,R);w.removeListener&&this.emit("removeListener",p,D||m)}return this},s.prototype.removeAllListeners=function(p){var m,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 w,R=Object.keys(h),L=0;L<R.length;++L)(w=R[L])!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[p])=="function")this.removeListener(p,m);else if(m)do this.removeListener(p,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(p){var m,h,w=this._events;return w?h=(m=w[p])?typeof m=="function"?[m.listener||m]:function(R){for(var L=Array(R.length),D=0;D<L.length;++D)L[D]=R[D].listener||R[D];return L}(m):[]:h=[],h},s.listenerCount=function(p,m){return typeof p.listenerCount=="function"?p.listenerCount(m):l.call(p,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function 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 g=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,y=[],v=0;256>v;++v)y.push((v+256).toString(16).substr(1));function b(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(y[p[m+0]]+y[p[m+1]]+y[p[m+2]]+y[p[m+3]]+"-"+y[p[m+4]]+y[p[m+5]]+"-"+y[p[m+6]]+y[p[m+7]]+"-"+y[p[m+8]]+y[p[m+9]]+"-"+y[p[m+10]]+y[p[m+11]]+y[p[m+12]]+y[p[m+13]]+y[p[m+14]]+y[p[m+15]]).toLowerCase();if(!function(w){return typeof w=="string"&&g.test(w)}(h))throw TypeError("Stringified UUID is invalid");return h}function _(p,m,h){var w=(p=p||{}).random||(p.rng||f)();return w[6]=64|15&w[6],w[8]=128|63&w[8],b(w)}function T(p,m){if(!p||!m)return{};const h={...p};if(h.localCandidateId){const w=m.get(h.localCandidateId);h.local={...w}}if(h.remoteCandidateId){const w=m.get(h.remoteCandidateId);h.remote={...w}}return h}function E(p,m,h){return 8*function(w,R,L){const D=w[L],N=R?R[L]:null;return D===null||N===null?null:(D-N)/(w.timestamp-R.timestamp)*1e3}(p,m,h)}function x(p){if(!p.entries)return p;const m={};return p.forEach(function(h,w){m[w]=h}),m}function I(p,m,h={}){if(!p)return null;let w={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(w.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const R of p.values())switch(R.type){case"outbound-rtp":{const L=R.mediaType||R.kind,D={};let N={};if(!["audio","video"].includes(L))continue;if(R.codecId){const P=p.get(R.codecId);P&&(D.clockRate=P.clockRate,D.mimeType=P.mimeType,D.payloadType=P.payloadType)}N=p.get(R.mediaSourceId)||p.get(R.trackId)||{},w[L].outbound.push({...R,...D,track:{...N}});break}case"inbound-rtp":{let L=R.mediaType||R.kind,D={};const N={};if(!["audio","video"].includes(L))if(R.id.includes("Video"))L="video";else{if(!R.id.includes("Audio"))continue;L="audio"}if(R.codecId){const P=p.get(R.codecId);P&&(N.clockRate=P.clockRate,N.mimeType=P.mimeType,N.payloadType=P.payloadType)}if(!w.connection.id&&R.transportId){const P=p.get(R.transportId);if(P&&P.selectedCandidatePairId){const F=p.get(P.selectedCandidatePairId);w.connection=T(F,p)}}D=p.get(R.mediaSourceId)||p.get(R.trackId)||{},w[L].inbound.push({...R,...N,track:{...D}});break}case"peer-connection":w.connection.dataChannelsClosed=R.dataChannelsClosed,w.connection.dataChannelsOpened=R.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let L=R.mediaType||R.kind;const D={};if(!["audio","video"].includes(L))if(R.id.includes("Video"))L="video";else{if(!R.id.includes("Audio"))continue;L="audio"}if(R.codecId){const N=p.get(R.codecId);N&&(D.clockRate=N.clockRate,D.mimeType=N.mimeType,D.payloadType=N.payloadType)}if(!w.connection.id&&R.transportId){const N=p.get(R.transportId);if(N&&N.selectedCandidatePairId){const P=p.get(N.selectedCandidatePairId);w.connection=T(P,p)}}w.remote[L].inbound.push({...R,...D});break}case"remote-outbound-rtp":{if(!h.remote)break;const L=R.mediaType||R.kind,D={};if(!["audio","video"].includes(L))continue;if(R.codecId){const N=p.get(R.codecId);N&&(D.clockRate=N.clockRate,D.mimeType=N.mimeType,D.payloadType=N.payloadType)}w.remote[L].outbound.push({...R,...D});break}}if(!w.connection.id)for(const R of p.values())R.type==="candidate-pair"&&R.nominated&&R.state==="succeeded"&&(w.connection=T(R,p));return w=function(R,L){return L&&(R.audio.inbound.map(D=>{let N=L.audio.inbound.find(P=>P.id===D.id);D.bitrate=E(D,N,"bytesReceived"),D.packetRate=E(D,N,"packetsReceived")}),R.audio.outbound.map(D=>{let N=L.audio.outbound.find(P=>P.id===D.id);D.bitrate=E(D,N,"bytesSent"),D.packetRate=E(D,N,"packetsSent")}),R.video.inbound.map(D=>{let N=L.video.inbound.find(P=>P.id===D.id);D.bitrate=E(D,N,"bytesReceived"),D.packetRate=E(D,N,"packetsReceived")}),R.video.outbound.map(D=>{let N=L.video.outbound.find(P=>P.id===D.id);D.bitrate=E(D,N,"bytesSent"),D.packetRate=E(D,N,"packetsSent")})),R}(w,m),w}let O,C={},k=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:m})}async addConnection(p){const{pc:m,peerId:h}=p;let{connectionId:w,remote:R}=p;if(R=typeof R=="boolean"?R:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(w&&w in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${w}.`);for(let D in this.peersToMonitor[h]){const N=this.peersToMonitor[h][D];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const L=m.getConfiguration();return L.iceServers&&L.iceServers.forEach(function(D){delete D.credential}),w||(w=_()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:w,data:{options:p,peerConfiguration:L}}),this.monitorPeer({peerId:h,connectionId:w,pc:m,remote:R}),{connectionId:w}}getTimeline(p){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(m=>m.tag===p):this.timeline}get logger(){const p=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(p){let m,{connectionId:h,pc:w}=p;if(!w&&!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 R in this.peersToMonitor)h in this.peersToMonitor[R]&&(w=this.peersToMonitor[R][h].pc,m=R)}else if(w){if(!(w instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let R in this.peersToMonitor)for(let L in this.peersToMonitor[R])this.peersToMonitor[R][L].pc===w&&(h=L,m=R)}if(!w||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,w),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{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 m in this.peersToMonitor[p]){let h=this.peersToMonitor[p][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),k.forEach(p=>{this.removeTrackEventListeners(p)}),k=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(p){let{peerId:m,connectionId:h,pc:w,remote:R}=p;if(!w)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const L={pc:w,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:R}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=L}else this.peersToMonitor[m]={[h]:L};this.addPeerConnectionEventListeners(m,h,w),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let m={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);m[p]=this.peersToMonitor[p]}else m=this.peersToMonitor;let h=[];for(const w in m)for(const R in m[w]){const L=m[w][R],D=L.pc;if(D&&!this.checkIfConnectionIsClosed(w,R,D))try{const N=this.getTimestamp(),P=D.getStats(null);if(P){const F=await P,z=this.getTimestamp(),j=x(F),de={remote:L.options.remote},J=I(F,L.stats.parsed,de),H={event:"stats",tag:"stats",peerId:w,connectionId:R,timeTaken:z-N,data:J};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=j),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(j)),h.push(H),L.stats.parsed=J}else this.logger.error(`PeerConnection from peer ${w} 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 m in this.peersToMonitor[p]){const h=this.peersToMonitor[p][m].pc;this.checkIfConnectionIsClosed(p,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,m,h){const w=this.isConnectionClosed(h);if(w){this.removeConnection({pc:h});let R=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:R,peerId:p,connectionId:m,tag:"connection",data:"closed"})}return w}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(p({stream:m}),m),m=>(p({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const m={...p};for(const w in m){var h=m[w];this.statsToMonitor.includes(h.type)||delete m[w]}return m}get peerConnectionListeners(){return{icecandidate:(p,m,h,w)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",w),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:m,data:w.candidate})},track:(p,m,h,w)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,w);const R=w.track,L=w.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=L),this.addTrackEventListeners(R,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:L?this.getStreamDetails(L):null,track:R?this.getMediaTrackDetails(R):null,title:w.track.kind+":"+w.track.id+" "+w.streams.map(function(D){return"stream:"+D.id})}})},signalingstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(p,m,h,w)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:m,error:{errorCode:w.errorCode}})},connectionstatechange:(p,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:h.connectionState})},negotiationneeded:(p,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:m})},datachannel:(p,m,h,w)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,w),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:m,data:w.channel})}}}addPeerConnectionEventListeners(p,m,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${m}.`),C[m]={},Object.keys(this.peerConnectionListeners).forEach(w=>{C[m][w]=this.peerConnectionListeners[w].bind(this,p,m,h),h.addEventListener(w,C[m][w],!1)})}parseGetUserMedia(p){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(m.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),k.push(h)})),this.emitEvent(m)}catch{}}parseStream(p){const m={audio:[],video:[]};return p.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(p,m){C[p.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(w=>{C[p.id][w]=h[w].bind(this),p.addEventListener(w,C[p.id][w])}),C[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let w=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(w)}},1e3)}removeTrackEventListeners(p){if(p.id in C){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{p.removeEventListener(h,C[p.id][h])}),clearInterval(C[p.id].readyState),delete C[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const m={...p,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,m){p in C&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,C[p][h],!1)}),delete C[p]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(w){return w},function(w){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,w.name),Promise.reject(w)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(ms=dh)&&ms.__esModule&&Object.prototype.hasOwnProperty.call(ms,"default")&&ms.default;var L0=dh.WebRTCStats;function D0(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=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}),r=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-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function P0(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 M0 extends pi{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class O0 extends pi{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class N0 extends pi{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function F0(t,e){const n=Tn();let i=!1;const s=new L0({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>U(this,void 0,void 0,function*(){r.event==="stats"&&V(M.StatsFrame,function({data:a}){var l,c,u,d,f,g,y,v;const{audio:b,remote:_}=a,{audio:T}=_,E=(c=(l=T.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,x=(d=(u=T.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,I=(g=(f=b.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&g!==void 0?g:-1,O=(v=(y=b.inbound[0])===null||y===void 0?void 0:y.packetsLost)!==null&&v!==void 0?v:-1,C=D0({jitter:1e3*E,rtt:1e3*x,packetsLost:O,packetsReceived:I});return{jitter:E,rtt:x,mos:C,quality:P0(C),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:T.inbound[0],remoteOutboundAudio:T.outbound[0]}}(r),t.uuid),yield t.execute(new N0(n,r))});return{get isRunning(){return i},start:(r,a,l)=>U(this,void 0,void 0,function*(){if(i)S.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new M0(n,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0}catch(c){S.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>U(this,void 0,void 0,function*(){const a=s.getTimeline();V(M.StatsReport,a,t.uuid),r==="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 O0(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const uh=(t,e)=>{const{contentType:n,canvasType:i,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&i!=="mcu-personal-canvas"&&delete o.memberID;const a={type:nt.conferenceUpdate,call:t.calls[s],canvasInfo:V0(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:ze.LayerInfo},a);V(M.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ze.LayoutInfo},a);V(M.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 Vu(e)},hh=["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"],U0={"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 se(t,e){return`telnyx:call:${t}:${e}`}function fh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Tr(t){for(const e of hh)try{performance.clearMarks(se(t,e))}catch{S.warn("Clearing performance marks is failed")}}class Qt{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>U(this,void 0,void 0,function*(){var r,a;const{connectionState:l}=this.instance;if(S.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return U(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const g=f[0].sender,y=g==null?void 0:g.transport;y&&(d.dtlsState=y.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(y=>{y.type==="candidate-pair"&&y.state==="succeeded"&&(d.candidatePairState=y.state,g.forEach(v=>{v.type==="local-candidate"&&v.id===y.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===y.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),y.type==="transport"&&(d.dtlsCipher=y.dtlsCipher,d.srtpCipher=y.srtpCipher,d.tlsVersion=y.tlsVersion,y.dtlsState&&(d.dtlsState=y.dtlsState))})}catch(g){S.error("Error gathering connection state details:",g)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=tt(Fy);V(M.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=tt(By);V(M.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(se(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(se(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(se(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;const l=this.instance.iceConnectionState;S.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(se(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;S.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},S.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=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(S.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(S.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},Qt.ICE_RESTART_TIMEOUT_MS),S.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(S.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(S.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Me.Offer}get isAnswer(){return this.type===Me.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(se(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return U(this,void 0,void 0,function*(){performance.mark(se(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){this.instance?(S.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{S.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),S.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):S.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(S.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":V(M.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(S.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){S.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?S.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()&&!this.isIceRestarting?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(se(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;this.options.remoteStream=n,s===!1&&fs(i,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(se(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",n=this.isOffer?"outbound":"inbound",i=function(s,o,r){const a=fh(se(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of hh){if(d==="new-call-start")continue;const f=fh(se(s,d));f!==void 0&&l.push({label:U0[d]||d,fromStart:f-a})}l.sort((d,f)=>d.fromStart-f.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,n);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void S.info(`${l} No timing data collected`);const c=Math.max(...a.map(y=>y.label.length),4)+2,u=(y,v)=>{for(;y.length<v;)y+=" ";return y},d=(y,v)=>{for(;y.length<v;)y=" "+y;return y},f=u("Step",c)+d("Delta",14)+d("From Start",14);let g="";for(let y=0;y<f.length;y++)g+="-";S.info(`${l} Call establishment timing breakdown:`),S.info(`${l} ${f}`),S.info(`${l} ${g}`),S.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const y of a){const v=y.delta.toFixed(2)+"ms",b=y.fromStart.toFixed(2)+"ms";S.info(`${l} ${u(y.label,c)}${d(v,14)}${d(b,14)}`)}S.info(`${l} ${g}`)})(i),Tr(this.options.id)}createPeerConnection(){return U(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Me.Offer}),performance.mark(se(this.options.id,"set-remote-description")),!this.instance))throw re(fr);const n=!!this.options.receiveOnlyAudio&&!this.options.audio;let i=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>U(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),V(M.Error,{error:re(ci(s),s),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>U(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),i=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return i=s,null})),!this.instance)throw re(fr);if(!this.options.localStream&&!n)throw re(i?ci(i):Cu,i??void 0);performance.mark(se(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Rn(this.options.localStream)&&(S.info("Muting local audio tracks on start"),Cr(this.options.localStream)),performance.mark(se(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=tt(Uy);V(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=tt(Vy);V(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},Qt.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return U(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw re(fr);this.isDebugEnabled&&(this.statsReporter=F0(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(Rn(i)){const o=i.getAudioTracks();let r=[...o];if(S.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{S.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],S.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{S.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=ch(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&fs(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});S.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=ch(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),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);S.info("Add transceiver",e,n)}}_createOffer(){return U(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,S.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(se(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(se(this.options.id,"set-local-description")),performance.mark(se(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){S.error("Peer _createOffer error:",e);const n=re(_y,e);V(M.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setRemoteDescription(e){return U(this,void 0,void 0,function*(){S.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(n){S.error("Peer _setRemoteDescription error:",n);const i=re(wu,n);throw V(M.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_createAnswer(){return U(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return S.debug("Skipping negotiation, state:",this.instance.signalingState),S.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:Me.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(se(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(se(this.options.id,"set-local-description")),performance.mark(se(this.options.id,"ice-gathering-started")),e}catch(e){S.error("Peer _createAnswer error:",e);const n=re(yy,e);V(M.Error,{error:n,sessionId:this._session.sessionid},this.options.id)}}})}_setLocalDescription(e){return U(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(n){S.error("Peer _setLocalDescription error:",n);const i=re(by,n);throw V(M.Error,{error:i,sessionId:this._session.sessionid},this.options.id),n}})}_sdpReady(){kn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(Rn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,U(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield gs(s,a,vt.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield gs(r,l,vt.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return ps(e)})}_isOffer(){return this.type===Me.Offer}_isAnswer(){return this.type===Me.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 S.info("RTC config",s),s}restartStatsReporter(){return U(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?S.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(S.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):S.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return U(this,void 0,void 0,function*(){Tr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}Qt.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,Qt.ICE_RESTART_TIMEOUT_MS=15e3;const vs=br;class ph{constructor(e,n){this.session=e,this._callReportCollector=null,this.id="",this.recoveredCallId="",this.state=$[$.New],this.prevState="",this.channels=[],this.role=vr.Participant,this.extension=null,this._state=$.New,this._prevState=$.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=b=>{const _=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return _&&b>=0&&(this._lastSerno=b),_},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(_=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const E in T.constraints)if(T.constraints.hasOwnProperty(E)&&T.constraints[E]!==_[E])return}T.callback(_)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:f,video:g},ringtoneFile:y,ringbackFile:v}=e;this.options=Object.assign({},u0,{audio:f,video:g,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:i,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:y,ringbackFile:v,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._init(),this.options&&(this._ringtone=rh(this.options.ringtoneFile,"_ringtone"),this._ringback=rh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
+ `).map(n=>n.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return!x0(this.options.localStream)}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(n=>n.enabled===!0&&n.muted!==!0&&n.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,n;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(n=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&n!==void 0&&n}invite(){return U(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=at.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(se(this.id,"new-peer")),this.peer=new Qt(Me.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){S.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const n=e instanceof li?e:re(Eu,e instanceof Error?e:void 0);return V(M.Error,{error:n,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var n,i,s,o,r;return U(this,void 0,void 0,function*(){if(this._creatingPeer||!((n=this.peer)===null||n===void 0)&&n.instance&&this.peer.instance.signalingState!=="closed"){const a=tt($y);return V(M.Warning,{warning:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void S.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(o=(s=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||s===void 0?void 0:s.signalingState)!==null&&o!==void 0?o:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(se(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=at.Inbound,((r=e==null?void 0:e.customHeaders)===null||r===void 0?void 0:r.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(se(this.id,"new-peer")),this.peer=new Qt(Me.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(a){S.error("Peer init failed, aborting call",a),this._creatingPeer=!1;const l=a instanceof li?a:re(Eu,a instanceof Error?a:void 0);return V(M.Error,{error:l,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){ah(this._ringtone)}stopRingtone(){lh(this._ringtone)}playRingback(){ah(this._ringback)}stopRingback(){lh(this._ringback)}hangup(e,n){var i,s,o,r,a,l;return U(this,void 0,void 0,function*(){const c=e||{},u=n!==!1,d=this.state,f=this.prevState,g=this._captureHangupCallerStack(),y=c.initiator||"app:call.hangup",v=this._state<$.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],S.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:f,cause:this.cause,causeCode:this.causeCode,initiator:y,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:g}),c.isRecovering)return this._isRecovering=!0,this.setState($.Recovering),void this._finalize();if(this.setState($.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new y0({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(b)}catch(_){S.error("telnyx_rtc.bye failed!",_);const T=re(ky,_);V(M.Error,{error:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}S.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState($.Destroy)})}hold(){const e=new us({sessid:this.session.sessionid,action:En.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new us({sessid:this.session.sessionid,action:En.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new us({sessid:this.session.sessionid,action:En.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const n=new eh({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 eh({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Cr(this.options.localStream)}unmuteAudio(){sh(this.options.localStream)}toggleAudioMute(){oh(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){var i;return U(this,void 0,void 0,function*(){const{instance:s}=this.peer,o=s.getSenders().find(({track:{kind:r}})=>r==="audio");if(o){let r;try{r=yield hs({audio:{deviceId:{exact:e}}})}catch(c){const u=re(ci(c),c);return void V(M.MediaError,u,((i=this.options)===null||i===void 0?void 0:i.id)||this.id)}const a=r.getAudioTracks()[0];a.enabled=!n,o.replaceTrack(a),this.options.micId=e;const{localStream:l}=this.options;l.getAudioTracks().forEach(c=>c.stop()),l.getVideoTracks().forEach(c=>r.addTrack(c)),this.options.localStream=r}})}muteVideo(){var e;e=this.options.localStream,An(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,An(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,An(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="video");if(i){const s=yield hs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;fs(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){Cr(this.options.remoteStream)}undeaf(){sh(this.options.remoteStream)}toggleDeaf(){oh(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void S.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 S.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===n);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),S.info("Parameters: ",r),S.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{S.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>S.error(a))}else S.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[$.Hangup,$.Destroy,$.Purge].includes(this._state)}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n,i;switch(this._prevState=this._state,this._state=e,this.state=$[this._state].toLowerCase(),this.prevState=$[this._prevState].toLowerCase(),S.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:nt.callUpdate,call:this}),e){case $.Purge:S.info(`[${this.id}] Entering Purge state.`);break;case $.Active:performance.mark(se(this.id,"call-active")),(n=this.peer)===null||n===void 0||n.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,S.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:s,speakerId:o}=this.options;s&&o&&nh(s,o)},0),this._callReportCollector&&!((i=this.peer)===null||i===void 0)&&i.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case $.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case Z.Answer:if(performance.mark(se(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=$.Active)return;this._state>=$.Early&&this.setState($.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case Z.Media:if(performance.mark(se(this.id,"telnyx-rtc-media")),this._state>=$.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case Z.Display:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===at.Inbound?at.Outbound:at.Inbound,c={type:nt[n],call:this,displayName:o,displayNumber:r,displayDirection:l};V(M.Notification,c,this.id)||V(M.Notification,c,this.session.uuid);break}case Z.Candidate:this._addIceCandidate(i);break;case Z.Info:case Z.Event:{const o=Object.assign(Object.assign({},i),{type:nt.generic,call:this});V(M.Notification,o,this.id)||V(M.Notification,o,this.session.uuid);break}case Z.Ringing:performance.mark(se(this.id,"ringing")),this.playRingback(),i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id);break;case Z.Bye:const s=i.client_state||i.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},i),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,n){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return S.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role: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 g=[];for(const y in s)g.push(Object.assign({callId:s[y][0],index:Number(y)},rs(s[y][1])));this._dispatchConferenceUpdate({action:ze.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ze.Add,callId:o,index:r},rs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ze.Modify,callId:o,index:r},rs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ze.Delete,callId:o,index:r},rs(s)));break;case"clear":this._dispatchConferenceUpdate({action:ze.Clear});break;default:this._dispatchConferenceUpdate({action:i,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const n=this.session.relayProtocol;this.session._existsSubscription(n,e)&&(this.session.subscriptions[n][e]=Object.assign(Object.assign({},this.session.subscriptions[n][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ze.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{S.error("ConfChat subscription error:",s)});wr(i,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,uh(this.session,o)):S.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{S.error("ConfInfo subscription error:",s)});wr(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($.Active):this.setState($.Held),!0}_handleChangeHoldStateError(e){S.error(`Failed to ${e.action} on call ${this.id}`);const n=re(Cy,e);return V(M.Error,{error:n,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e){const n=new us({sessid:this.session.sessionid,action:En.UpdateMedia,callID:this.options.id,sdp:e,dialogParams:this.options});S.info("ICE restart: sending Modify with new offer SDP"),this._execute(n).then(i=>U(this,void 0,void 0,function*(){var s;i!=null&&i.sdp?(S.info("ICE restart Modify response received"),(s=this.peer)===null||s===void 0||s.finishIceRestart(),yield this._onRemoteSdp(i.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(i=>{this._onIceRestartFailed("ICE restart Modify failed",i)})}_onIceRestartFailed(e,n){var i;S.error(e,n),(i=this.peer)===null||i===void 0||i.finishIceRestart();const s=re(Dy,n);V(M.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onRemoteSdp(e){return U(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Me.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{performance.mark(se(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState($.Early),this.gotAnswer&&this.setState($.Active)}).catch(i=>U(this,void 0,void 0,function*(){S.error("Call setRemoteDescription Error: ",i);const s=re(wu,i);V(M.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){S.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){kn(this.peer.onSdpReadyTwice)?V(M.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.peer.iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var n,i,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void S.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return S.info(`No candidate - retry
117
+ `),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),!Jy.test(o)){const c=tt(jy);S.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),V(M.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(se(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${vs}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Me.Offer:this.setState($.Requesting),a=new Ju(l);break;case Me.Answer:this._isRecovering||this.setState($.Answering),a=this.options.attach===!0?new Qu(l):new Zu(l);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(se(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void S.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Me.Offer?this.setState($.Trying):this.setState($.Active)}).catch(c=>U(this,void 0,void 0,function*(){S.error(`${this.id} - Sending ${r} error:`,c);const u=re(Su,c);V(M.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){S.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var n;if(!e)return S.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:i,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:i,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${vs}`};if(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)this._sendIceRestartModify(i);else{switch(s){case Me.Offer:this.setState($.Requesting),o=new Ju(r);break;case Me.Answer:this._isRecovering||this.setState($.Answering),o=this.options.attach===!0?new Qu(r):new Zu(r);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(se(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void S.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Me.Offer?this.setState($.Trying):this.setState($.Active)}).catch(a=>U(this,void 0,void 0,function*(){S.error(`${this.id} - Sending ${s} error:`,a);const l=re(Su,a);V(M.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){S.error("Error during hangup after SDP send failure:",c)}}))}}_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?(S.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?(S.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 b0({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 S.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(()=>{S.debug("Successfully added ICE candidate:",e)}).catch(i=>{S.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new w0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var n;if(this._firstCandidateSent||(performance.mark(se(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const i=(n=e.candidate.match(/typ (\w+)/))===null||n===void 0?void 0:n[1];i&&i!=="host"&&(performance.mark(se(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(n=>{this._addIceCandidateToPeer(n)})}_registerPeerEvents(e){e.onicecandidate=n=>{var i,s;if(this.options.trickleIce&&!(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting))this._onTrickleIce(n);else{if(!((s=this.peer)===null||s===void 0)&&s.iceDone)return;this._onIce(n)}},e.onicegatheringstatechange=n=>{S.debug("ICE gathering state changed:",e.iceGatheringState,n),e.iceGatheringState==="complete"&&(S.debug("Finished gathering candidates"),performance.mark(se(this.id,"ice-gathering-completed")))},e.onicecandidateerror=n=>{var i;if(S.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&fs(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:nt.userMediaError,error:s,call:this,errorName:n,errorMessage:i}),S.error(`Media error (${n}): ${i}`,e),V(M.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:nt.peerConnectionFailureError,error:e.error}),S.error("Peer connection failure error"),e.warning&&V(M.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:nt.signalingStateClosed},e)),S.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:nt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(V(M.Notification,e,this.id,!1)||V(M.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){if(this.options.attach||this._isRecovering)return!0;for(const e of this._getSessionInboundAnswerCalls()){if(e.id===this.id||!e._isBlockingInboundAnswer())continue;const n=tt(Gy);return V(M.Warning,{warning:n,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),S.warn(`[${this.id}] answer() ignored: inbound call ${e.id} is already answering or active`),!1}return!0}_getSessionInboundAnswerCalls(){return Object.values(this.session.calls).filter(e=>!!e).filter(e=>!e.options.attach&&!e._isRecovering&&e.direction===at.Inbound)}_isBlockingInboundAnswer(){var e;if([$.Hangup,$.Destroy,$.Purge].includes(this._state))return!1;const n=[$.Answering,$.Early,$.Active,$.Held].includes(this._state);return!(!this._creatingPeer&&!n)&&(!(!this._creatingPeer||!((e=this.peer)===null||e===void 0)&&e.instance)||this._hasUsablePeerConnection())}_hasUsablePeerConnection(){var e;const n=(e=this.peer)===null||e===void 0?void 0:e.instance;return!!n&&n.signalingState!=="closed"&&n.connectionState!=="closed"&&n.iceConnectionState!=="closed"}_init(){var e,n,i;const{id:s,userVariables:o,remoteCallerNumber:r,onNotification:a,recoveredCallId:l}=this.options;var c;this.options.id=s?s.toString():Tn(),this.id=this.options.id,l&&(this.recoveredCallId=l,this._isRecovering=!0),o&&(c=o,Object.keys(c).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Vt(M.MediaError,this._onMediaError,this.id),Vt(M.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Vt(M.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),kn(a)&&Vt(M.Notification,a.bind(this),this.id);const u=this.session.options.enableCallReports!==!1,d=this.session.options.callReportInterval||5e3,f=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,g=this.session.options.debugLogLevel||"debug",y=this.session.options.debugLogMaxEntries||1e3;u&&(this._callReportCollector=new oe({enabled:!0,interval:d,intermediateReportInterval:f},{enabled:!0,level:g,maxEntries:y}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=v=>{var b,_,T,E;V(M.Warning,{warning:v,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),v.code===xu?(_=(b=this.session).reportNoRtp)===null||_===void 0||_.call(b,this.id,"inbound"):v.code===Ru&&this._hasActiveUnmutedLocalAudioTrack()&&((E=(T=this.session).reportNoRtp)===null||E===void 0||E.call(T,this.id,"outbound"))}),this._isRecovering?this.setState($.Recovering):this.setState($.New),S.info(`New Call — region: ${(n=this.session.region)!==null&&n!==void 0?n:"unknown"}, dc: ${(i=this.session.dc)!==null&&i!==void 0?i:"unknown"}`,this.options)}_finalize(){var e;this._stopStats(),Tr(this.id),S.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i,remoteElement:s,localElement:o}=this.options;gi(n),gi(i),th(s,n),th(o,i),_t(M.MediaError,null,this.id),_t(M.PeerConnectionFailureError,null,this.id),_t(M.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const r=this._postCallReport().catch(a=>{S.error("Unexpected error in _postCallReport",{error:a})});this.session.trackCallReportUpload(r)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var n;if(!this._callReportCollector)return;const i=this.session.callReportId;if(!i)return void S.debug("Cannot flush intermediate report: call_report_id not available");const s=(n=this.session.connection)===null||n===void 0?void 0:n.host;if(!s)return void S.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===at.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:vs},r=this._callReportCollector.flush(o,e);if(!r)return;S.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=this._callReportCollector.sendPayload(r,i,s,a).catch(c=>{S.error("Failed to post intermediate call report segment",{error:c})});this.session.trackCallReportUpload(l)}_postCallReport(){var e,n;return U(this,void 0,void 0,function*(){if(!this._callReportCollector)return void S.warn("Call report collector not initialized");yield this._callReportCollector.stop();const i=this.session.callReportId;if(!i)return S.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===at.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:vs},o=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!o)return void S.error("Cannot post call report: connection host not available");const r=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(s,i,o,r)}catch(a){throw S.error("Failed to post call report",{error:a}),a}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),S.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),S.debug("Stats stopped")}}ph.setStateTelnyx=t=>{if(t){switch(t._state){case $.Recovering:t.state="recovering";break;case $.Requesting:case $.Trying:case $.Early:t.state="connecting";break;case $.Active:t.state="active";break;case $.Held:t.state="held";break;case $.Hangup:case $.Destroy:t.state="done";break;case $.Answering:t.state="ringing";break;case $.New:t.state="new"}return t}};class en extends ph{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new A0(e,n))}hangup(e={},n=!0){const i=Object.create(null,{hangup:{get:()=>super.hangup}});return U(this,void 0,void 0,function*(){this.screenShare instanceof en&&(yield this.screenShare.hangup(e,n)),yield i.hangup.call(this,e,n)})}startScreenShare(e){return U(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>U(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new en(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return U(this,void 0,void 0,function*(){this.screenShare instanceof en&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&nh(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>U(this,void 0,void 0,function*(){const n=yield this.peer.instance.getStats(null);let i="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];n.forEach(r=>{s.includes(r.type)||(i+=`
118
+ ${r.type}
119
+ `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
120
+ `)}))}),S.info(i)}),2e3)}}class B0 extends Zt{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 U(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return U(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return U(this,void 0,void 0,function*(){try{const i=yield ps({audio:e,video:n});return gi(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){S.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($.Purge),S.info("Start hangup for ",i),yield i.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){S.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($.Purge),i.hangup({initiator:"sdk:server-disconnect"},!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(qu(M.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return mi().catch(e=>{const n=re(ci(e),e);return V(M.MediaError,n,this.uuid),[]})}getVideoDevices(){return mi(vt.Video).catch(e=>(V(M.MediaError,e,this.uuid),[]))}getAudioInDevices(){return mi(vt.AudioIn).catch(e=>{const n=re(ci(e),e);return V(M.MediaError,n,this.uuid),[]})}getAudioOutDevices(){return mi(vt.AudioOut).catch(e=>(S.error("getAudioOutDevices",e),V(M.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return gs(e,n,i)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(n=>U(void 0,void 0,void 0,function*(){const i=[],s=yield ps({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<ih.length;r++){const[a,l]=ih[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return gi(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=ns(e,["micId","micLabel"]);return I0(s),this._audioConstraints=yield((o,r,a,l)=>U(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield gs(o,r,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?Qy:Zy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=di(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=di(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 S0({sessid:this.sessionid,eventChannel:n,data:i});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:n=[],handler:i}){return U(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new C0({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Sr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return U(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new T0({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Sr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(S.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,S.debug(`Network connectivity lost for session ${this.sessionid}`);const e=re(Py);V(M.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 en.setStateTelnyx(e)}}class gh{constructor(e,n){this.code=n,this.message=e}}class j0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,n){const i=new _0(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Bu(2,6)}handleMessage(e){var n,i,s,o,r,a,l,c,u,d,f;const{session:g}=this;g.setPingReceived();const{id:y,method:v,params:b={},voice_sdk_id:_}=e,T=b==null?void 0:b.callID,E=b==null?void 0:b.eventChannel,x=b==null?void 0:b.eventType,I=g.calls[T],O=(n=I==null?void 0:I.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(Array.isArray(b==null?void 0:b.reattached_sessions)&&b.reattached_sessions.length===0&&Object.keys(g.calls).length>0){const m=tt(qy);V(M.Warning,{warning:m,sessionId:g.sessionid},g.uuid)}if(x==="channelPvtData")return this._handlePvtEvent(b.pvtData);const C=(m,h)=>{var w,R,L,D,N;const P={audio:!0,video:g.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Z.Attach,mediaSettings:b.mediaSettings,debug:(w=g.options.debug)!==null&&w!==void 0&&w,debugOutput:(R=g.options.debugOutput)!==null&&R!==void 0?R:"socket",trickleIce:(L=g.options.trickleIce)!==null&&L!==void 0&&L,prefetchIceCandidates:(D=g.options.prefetchIceCandidates)===null||D===void 0||D,forceRelayCandidate:h||g.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(N=g.options.keepConnectionAliveOnSocketClose)!==null&&N!==void 0&&N};T&&(P.id=T),b.telnyx_call_control_id&&(P.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(P.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(P.telnyxLegId=b.telnyx_leg_id),b.client_state&&(P.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(P.customHeaders=b.dialogParams.custom_headers),m&&(P.recoveredCallId=m),performance.mark(se(P.id,"new-call-start"));const F=new en(g,P);return F.nodeId=this.nodeId,F},k=new Xu(_),p=new yr(_);switch(v){case Z.Answer:case Z.Display:case Z.Candidate:case Z.Ringing:case Z.Bye:case Z.Media:if(!T||!I)return void S.error(`Received ${v} for non existing call:`,b);I.handleMessage(e),this._ack(y,v);break;case Z.Ping:this.session.setPingReceived(),this.session.execute(p);break;case Z.Punt:g.options.keepConnectionAliveOnSocketClose&&O?(S.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),g.socketDisconnect(),this._ack(y,v)):(S.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),g.serverDisconnect());break;case Z.Invite:{const w=C();w.direction=at.Inbound,w.playRingtone(),w.setState($.Ringing),this._ack(y,v);break}case Z.Attach:{if(!I)return C().answer(),void this._ack(y,v);const w=I.id,R=(s=(i=I.shouldForceRelayCandidateForRecovery)===null||i===void 0?void 0:i.call(I))!==null&&s!==void 0&&s;R&&S.warn(`[${new Date().toISOString()}][${T}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),S.info(`[${new Date().toISOString()}][${T}] closing existing call on ATTACH.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1),S.info(`[${new Date().toISOString()}][${T}] Attach: Creating new call for recovery (recoveredCallId: ${w})`),C(w,R).answer(),this._ack(y,v);break}case Z.Event:case"webrtc.event":if(!E)return void S.error("Verto received an unknown event:",b);const m=g.relayProtocol,h=E.split(".")[0];g._existsSubscription(m,E)?V(m,b,E):E===g.sessionid?this._handleSessionEvent(b.eventData):g._existsSubscription(m,h)?V(m,b,h):g.calls.hasOwnProperty(E)?g.calls[E].handleMessage(e):V(M.Notification,b,g.uuid);break;case Z.Info:b.type=nt.generic,V(M.Notification,b,g.uuid);break;case Z.ClientReady:this.session.execute(k);break;default:{const w=gr(e);if(w){switch(w){case Fe.REGISTER:case Fe.REGED:if(g.connection.previousGatewayState!==Fe.REGED&&g.connection.previousGatewayState!==Fe.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,w===Fe.REGED&&this.session.resetReconnectAttempts();const R=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.call_report_id;R&&(g.callReportId=R,S.debug("Captured call_report_id from REGED:",R));const L=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;L&&(g.dc=L);const D=(u=(c=e==null?void 0:e.result)===null||c===void 0?void 0:c.params)===null||u===void 0?void 0:u.region;D&&(g.region=D),S.info(`Connected to Telnyx — region: ${(d=g.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(f=g.dc)!==null&&f!==void 0?f:"unknown"}`),b.type=nt.vertoClientReady,V(M.Ready,b,g.uuid)}break;case Fe.UNREGED:case Fe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const R=new gh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),L=re(ku,R);V(M.Error,{error:L,sessionId:g.sessionid},g.uuid);break}setTimeout(()=>{this.session.execute(k)},this.reconnectDelay());break;case Fe.FAILED:case Fe.FAIL_WAIT:if(g.connection.previousGatewayState!==Fe.FAILED&&g.connection.previousGatewayState!==Fe.FAIL_WAIT){const R=re(Ry,new Error(`Gateway state: ${w}`));if(V(M.Error,{error:R,sessionId:g.sessionid},g.uuid),!this.session.hasAutoReconnect()){this.retriedConnect=0;const L=new gh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),D=re(Tu,L);V(M.Error,{error:D,sessionId:g.sessionid},g.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const L=re(45003,new Error("Connection Retry Failed"));V(M.Error,{error:L,sessionId:g.sessionid},g.uuid);break}setTimeout(()=>{if(S.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(g.calls).some(L=>{var D;return((D=L.peer)===null||D===void 0?void 0:D.instance)&&!L.signalingStateClosed}))return S.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();S.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:S.warn("GatewayState message unknown method:",e)}break}S.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(o=>i.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:f}=e;switch(s){case"conference-liveArray-join":{const g=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},y={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const _=f||this._retrieveCallId(b,o);if(_&&n.calls.hasOwnProperty(_)){const T=n.calls[_];T._addChannel(o),T.extension=r,T.handleConferenceUpdate(b,e).then(E=>{E==="INVALID_PACKET"&&g()})}}},v=yield n.vertoSubscribe(y).catch(b=>{S.error("liveArray subscription error:",b);const _=re(Ey,b);V(M.Error,{error:_,sessionId:n.sessionid},n.uuid)});wr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(g=n.calls[v]||null,v!==null){const b={type:nt.conferenceUpdate,action:ze.Leave,conferenceName:r,participantId:Number(u),role:d};V(M.Notification,b,v,!1)||V(M.Notification,b,n.uuid),g===null&&_t(M.Notification,null,v)}}const y=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(b=>!v.includes(b)))}).catch(v=>{S.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":uh(this.session,e);break;case"logo-info":{const n={type:nt.conferenceUpdate,action:ze.LogoInfo,logo:e.logoURL};V(M.Notification,n,this.session.uuid);break}}}}class $0 extends B0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new j0(this),e.hangupOnBeforeUnload!==!1&&window.addEventListener("beforeunload",n=>{Gu(),this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(S.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({initiator:"sdk:beforeunload"},!0))})})}validateOptions(){return as(this.options)||ui(this.options)}newCall(e){if(!this.validateCallOptions(e))throw re(Ty,void 0,"Error: destinationNumber is required");const n=new en(this,e);return performance.mark(se(n.id,"new-call-start")),n.invite(),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!ui(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return U(this,void 0,void 0,function*(){return yield e._onSocketOpen.call(this),as(this.options)?this.handleLoginOnSocketOpen():ui(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class H0 extends $0{constructor(e){super(e),S.info(`SDK version: ${Yu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return R0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Te.not_supported},{browserName:"Firefox",supported:Te.not_supported},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",features:["audio"],supported:Te.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",features:["audio"],supported:Te.partial}]}]}}function mh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var vh={exports:{}},_h;function G0(){return _h||(_h=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,f){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,f),y=n?n+c:c;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],g]:l._events[y].push(g):(l._events[y]=g,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(n?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},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,g){var y=n?n+l:l;if(!this._events[y])return!1;var v=this._events[y],b=arguments.length,_,T;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,f),!0;case 6:return v.fn.call(v.context,c,u,d,f,g),!0}for(T=1,_=new Array(b-1);T<b;T++)_[T-1]=arguments[T];v.fn.apply(v.context,_)}else{var E=v.length,x;for(T=0;T<E;T++)switch(v[T].once&&this.removeListener(l,v[T].fn,void 0,!0),b){case 1:v[T].fn.call(v[T].context);break;case 2:v[T].fn.call(v[T].context,c);break;case 3:v[T].fn.call(v[T].context,c,u);break;case 4:v[T].fn.call(v[T].context,c,u,d);break;default:if(!_)for(x=1,_=new Array(b-1);x<b;x++)_[x-1]=arguments[x];v[T].fn.apply(v[T].context,_)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var g=this._events[f];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&r(this,f);else{for(var y=0,v=[],b=g.length;y<b;y++)(g[y].fn!==c||d&&!g[y].once||u&&g[y].context!==u)&&v.push(g[y]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(vh)),vh.exports}var W0=G0();const kr=mh(W0),_s=new kr;var Er={exports:{}},q0=Er.exports,yh;function z0(){return yh||(yh=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(q0,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var _=v[b];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var _=s[b];this[_]=b<v?e:this.methodFactory(_,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==n&&(u.call(this),this[v].apply(this,arguments))}}function f(v,b,_){return c(v)||d.apply(this,arguments)}function g(v,b){var _=this,T,E,x,I="loglevel";typeof v=="string"?I+=":"+v:typeof v=="symbol"&&(I=void 0);function O(h){var w=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!I)){try{window.localStorage[I]=w;return}catch{}try{window.document.cookie=encodeURIComponent(I)+"="+w+";"}catch{}}}function C(){var h;if(!(typeof window===n||!I)){try{h=window.localStorage[I]}catch{}if(typeof h===n)try{var w=window.document.cookie,R=encodeURIComponent(I),L=w.indexOf(R+"=");L!==-1&&(h=/^([^;]+)/.exec(w.slice(L+R.length+1))[1])}catch{}return _.levels[h]===void 0&&(h=void 0),h}}function k(){if(!(typeof window===n||!I)){try{window.localStorage.removeItem(I)}catch{}try{window.document.cookie=encodeURIComponent(I)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var w=h;if(typeof w=="string"&&_.levels[w.toUpperCase()]!==void 0&&(w=_.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=_.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+h)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=b||f,_.getLevel=function(){return x??E??T},_.setLevel=function(h,w){return x=p(h),w!==!1&&O(x),u.call(_)},_.setDefaultLevel=function(h){E=p(h),C()||_.setLevel(h,!1)},_.resetLevel=function(){x=null,k(),u.call(_)},_.enableAll=function(h){_.setLevel(_.levels.TRACE,h)},_.disableAll=function(h){_.setLevel(_.levels.SILENT,h)},_.rebuild=function(){if(r!==_&&(T=p(r.getLevel())),u.call(_),r===_)for(var h in o)o[h].rebuild()},T=p(r?r.getLevel():"WARN");var m=C();m!=null&&(x=p(m)),u.call(_)}r=new g,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new g(v,r.methodFactory)),b};var y=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(Er)),Er.exports}var K0=z0();const X0=mh(K0),Y0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Le=X0.getLogger("telnyx-ai-agent"),J0=Le.methodFactory;Le.methodFactory=(t,e,n)=>{const i=J0(t,e,n);return function(...s){i(Y0(),"-",...s)}},Le.setLevel("info");function Z0(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const Q0=10,eb=500,tb=100,bh=20;class nb{constructor(e){W(this,"remoteIntervalId",null);W(this,"localIntervalId",null);W(this,"remoteStream",null);W(this,"localStream",null);W(this,"remoteAudioContext",null);W(this,"remoteSource",null);W(this,"remoteAnalyser",null);W(this,"localAudioContext",null);W(this,"localSource",null);W(this,"localAnalyser",null);W(this,"thinkingStartTime",null);W(this,"lastState",null);W(this,"userIsSpeaking",!1);W(this,"lastUserAudioTime",null);W(this,"userSpeechStartTime",null);W(this,"userSilenceStartTime",null);W(this,"isFirstAgentSpeech",!0);W(this,"monitorStartTime",null);W(this,"volumeThreshold");W(this,"silenceDurationMs");W(this,"minSpeechDurationMs");W(this,"maxLatencyMs");W(this,"updateAgentState",Z0(e=>{Le.debug("AudioStreamMonitor updateAgentState",e),Le.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,_s.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Q0,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??eb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??tb,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){Le.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Le.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Le.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Le.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Le.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)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=r};this.remoteIntervalId=window.setInterval(s,bh)}startLocalMonitor(){if(!this.localStream){Le.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Le.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Le.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Le.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,bh)}destroy(){this.stopAudioStreamMonitor()}}function ib(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function sb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function ob(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function rb(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 ab(t){return sb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function lb(t){if(!ob(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 cb extends kr{constructor(n){super();W(this,"telnyxRTC");W(this,"transcript",[]);W(this,"onSocketMessage",n=>{if(ib(n))switch(n.params.type){case"response.text.delta":{const i=ab(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),_s.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(rb(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=lb(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage)}}const Rt=t=>typeof t=="object"&&t!==null,wh=t=>{const e=Rt(t)&&Rt(t.result)?t.result:t;if(!(!Rt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},db=t=>Rt(t)&&Rt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),ub=(t,e)=>{if(!e||!Rt(t)||!Rt(t.request))return;const{request:n}=t;if(n.method!=="login"&&n.method!=="anonymous_login"||!Rt(n.params))return;const i=n.params;Rt(i["User-Agent"])&&(i["User-Agent"].widgetVersion=e),n.method==="anonymous_login"&&(i.widget_version=e)};class hb extends kr{constructor(n){super();W(this,"telnyxRTC");W(this,"transcription");W(this,"removeLoginSuccessHook",null);W(this,"authenticated",!1);W(this,"authenticating",!1);W(this,"agentId");W(this,"versionId");W(this,"widgetVersion");W(this,"conversationId");W(this,"debug");W(this,"audioStreamMonitor");W(this,"activeCall");W(this,"chatMode");W(this,"dc",null);W(this,"region",null);W(this,"callReportId",null);W(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)});W(this,"onClientOrSocketError",n=>{this.emit("agent.error",n.error)});W(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1});W(this,"onSocketMessage",n=>{const i=wh(n);i!==void 0&&this.emitLoginSuccess({sessionId:i})});W(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()))});W(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});W(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.widgetVersion=n.widgetVersion,this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Le.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}),n.widgetVersion&&(i.widget_version=n.widgetVersion),this.telnyxRTC=new H0({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region,skipLastVoiceSdkId:n.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(M.Ready,this.onClientReady),this.telnyxRTC.on(M.Error,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketClose,this.onSocketClose),this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(M.Notification,this.onNotification),this.transcription=new cb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),_s.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new nb(n.vad)}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var n;this.audioStreamMonitor.destroy(),(n=this.removeLoginSuccessHook)==null||n.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(M.Ready,this.onClientReady),this.telnyxRTC.off(M.Error,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketClose,this.onSocketClose),this.telnyxRTC.off(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(M.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),_s.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Le.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw Le.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw Le.warn(d.message),this.emit("agent.error",d),d}const i=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}installLoginSuccessHook(){const n=this.telnyxRTC,i=n.execute,s=n.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=g=>{c===g&&(this.authenticating=!1)},d=function(g){const y=db(g),v=c;return y&&ub(g,a),i.call(this,g).then(b=>{const _=y?wh(b):void 0;return l&&_!==void 0&&(u(v),r({sessionId:_})),b})},f=function(g){const y=++c;if(l){const v={sessionId:n.sessionid||null};o(v)}return s.call(this,g).finally(()=>{l&&n.login===f&&u(y)})};return n.execute=d,n.login=f,()=>{l=!1,n.execute===d&&(n.execute=i),n.login===f&&(n.login=s)}}emitLoginStarted(n){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",n)}emitLoginSuccess(n){const i=this.telnyxRTC,s=i.sessionid||null;n.sessionId&&(i.sessionid=n.sessionId);const o=n.sessionId||i.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}var Sh={exports:{}},vi={},Ch;function fb(){if(Ch)return vi;Ch=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return vi.Fragment=e,vi.jsx=n,vi.jsxs=n,vi}var Th;function pb(){return Th||(Th=1,Sh.exports=fb()),Sh.exports}pb(),Ct(void 0),Ct(null);const gb=(t,e,n,i,s,o,r,a,l,c)=>new hb({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),ys=10,kh=5e3,mb=[46001,46003],vb=["login incorrect","authentication required","authentication failed"];function Eh(t){var i;const e=t.code;if(e&&mb.includes(e))return!0;const n=((i=t.message)==null?void 0:i.toLowerCase())||"";return vb.some(s=>n.includes(s))}const _b=(t,e,n,i,s,o,r,a,l,c)=>{const u=c??!0,[d,f]=xe(null),[g,y]=xe(!1),[v,b]=xe(null),[_,T]=xe(!1),E=he(0),x=he(null),I=he(null),O=he(!1),C=he(!1),k=he(0),p=he(0),m=He(()=>{x.current&&(clearTimeout(x.current),x.current=null)},[]),h=He(()=>{m(),E.current=0,C.current=!0,T(!1),b(null)},[m]),w=He(()=>{m(),T(!1)},[m]),R=He(L=>{if(m(),E.current>=ys){ce.error(`Max login retry attempts (${ys}) exceeded`),T(!1);return}E.current+=1;const D=k.current,N=p.current;ce.info(`Scheduling login retry attempt ${E.current}/${ys} in ${kh}ms due to: ${L}`),T(!0),x.current=window.setTimeout(()=>{var z;x.current=null;const P=I.current,F=P==null?void 0:P.telnyxRTC;if(k.current!==D||p.current!==N||P!=null&&P.isAuthenticating){ce.info("Skipping login retry because a newer socket/login is already in progress"),w();return}if(O.current||C.current||P!=null&&P.isAuthenticated){ce.info("Skipping login retry because login already succeeded before retry timeout fired"),h();return}I.current&&(ce.info(`Executing reconnect attempt ${E.current} (socket disconnect)`),(z=F==null?void 0:F.socketDisconnect)==null||z.call(F))},kh)},[m,w,h]);return Re(()=>{if(!t)return;const L=gb(t,e,n,i,s,o,r,a,l,u);O.current=!1,C.current=!1,y(!1),b(null),T(!1),I.current=L;const D=()=>{ce.info("Agent connected successfully"),O.current=!0,y(!0),h()},N=()=>{ce.info("Agent disconnected"),O.current=!1,C.current=!1,y(!1)},P=H=>{if(ce.error("AI Agent error:",H),Eh(H)){if(O.current||C.current){ce.debug("Ignoring retryable error — login already succeeded");return}E.current<ys?(b(null),R(H.message)):(b(H),T(!1))}else b(H),T(!1)},F=L.telnyxRTC??null,z=()=>{p.current+=1,C.current=!1},j=()=>{ce.info("Login succeeded; clearing pending login retry flow"),h()},de=()=>{k.current+=1,C.current=!1},J=()=>{C.current=!1};return L.on("agent.connected",D),L.on("agent.disconnected",N),L.on("agent.error",P),L.on("agent.login.started",z),L.on("agent.login.success",j),F&&typeof F=="object"&&(F.on(M.SocketOpen,de),F.on(M.SocketClose,J)),L.connect(),f(L),()=>{m(),L.off("agent.connected",D),L.off("agent.disconnected",N),L.off("agent.error",P),L.off("agent.login.started",z),L.off("agent.login.success",j),F&&typeof F=="object"&&(F.off(M.SocketOpen,de),F.off(M.SocketClose,J)),L.disconnect(),O.current=!1,I.current=null}},[t,e,n,i,s,o,r,a,l,c,u,m,h,R]),{client:d,isConnected:g,error:v,isReconnecting:_}},yb="telnyx-ai-agent",At={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 Ih(){const t=document.querySelector(yb);return t instanceof HTMLElement?t:null}function Lt(t,e,n){const i=n||Ih();if(!i){ce.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),ce.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const bb=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=he(null),a=Li(su);Re(()=>{r.current=Ih()},[]),Re(()=>{if(!t)return;const l=r.current,c=()=>{n();const I=t.telnyxRTC,O={dc:(I==null?void 0:I.dc)??null,region:(I==null?void 0:I.region)??null,callReportId:(I==null?void 0:I.callReportId)??null};a(O),Lt(At.AGENT_CONNECTED,O,l)},u=()=>{a(null),Lt(At.AGENT_DISCONNECTED,void 0,l)},d=x=>{const I={message:x.message,name:x.name};if(Eh(x)){ce.debug("Ignoring retryable agent.error in widget event layer"),Lt(At.AGENT_ERROR,I,l);return}s(x),Lt(At.AGENT_ERROR,I,l)},f=x=>{var I;i(x),Lt(At.CONVERSATION_UPDATE,{type:x.type,callState:(I=x.call)==null?void 0:I.state},l)},g=x=>{Lt(At.TRANSCRIPT_ITEM,x,l)},y=x=>{Lt(At.CONVERSATION_AGENT_STATE,x,l)},v=x=>{Lt(At.AGENT_AUDIO_MUTE,{muted:x},l)},_=t.telnyxRTC,T=x=>{o(x)},E=x=>{const I=x,O={code:I==null?void 0:I.code,reason:I==null?void 0:I.reason,wasClean:I==null?void 0:I.wasClean,timestamp:new Date().toISOString()};ce.info("[socket.close]",O),Lt(At.SOCKET_CLOSE,O,l)};return _&&typeof _=="object"&&(_.on(M.SocketMessage,T),_.on(M.SocketClose,E)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",f),t.on("transcript.item",g),t.on("conversation.agent.state",y),t.on("agent.audio.mute",v),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",f),t.off("transcript.item",g),t.off("conversation.agent.state",y),t.off("agent.audio.mute",v),_&&typeof _=="object"&&(_.off(M.SocketMessage,T),_.off(M.SocketClose,E))}},[t,n,i,s,o,a])},wb=2e3;async function Sb(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function xh(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 Cb=(t,e)=>{const[n,i]=xe([]),[,s]=sr(),o=he(e);Re(()=>{o.current=e},[e]);const r=he(void 0),a=he(void 0);return Re(()=>{if(!t)return;const c=f=>{i(g=>{const y=g[g.length-1];if(f.role==="assistant"&&y&&xh(y.id)===xh(f.id)&&y.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&y.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&y.greetingLatencyMs===void 0,_={...y,content:y.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...g.slice(0,-1),_]}if(f.role==="assistant"){s(_=>_==="thinking"||_==="processing_image"?"speaking":_);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const _={...f,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,_]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=g.findIndex(_=>_.id===f.id);if(v!==-1){const _=[...g];return _[v]={...g[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},_}if(y&&y.role==="user"&&f.timestamp.getTime()-y.timestamp.getTime()<wb){const T={...y,id:f.id,content:y.content+" "+f.content,timestamp:f.timestamp,attachments:[...y.attachments||[],...f.attachments||[]]};return[...g.slice(0,-1),T]}const b=f.attachments&&f.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,f]})},u=({state:f,userPerceivedLatencyMs:g,greetingLatencyMs:y,thinkingStartedAt:v})=>{(g!==void 0||y!==void 0)&&ce.info(`[AgentState] state=${f} userPerceivedLatencyMs=${g} greetingLatencyMs=${y} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),y!==void 0&&(a.current=y)):f==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=f=>{var y;const g=(y=f.call)==null?void 0:y.state;(g==="destroy"||g==="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 g=await Sb(f);d.push(g)}catch(g){throw ce.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},Tb=({call:t,client:e,latencySettings:n,chatMode:i,debug:s=!1})=>{const o=Jt(),[r,a]=xe(i?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=Cb(e,n),d=he(!1);switch(Re(()=>{if(i&&t&&!d.current){const f="remoteStream"in t?t.remoteStream:null;f&&(d.current=!0,f.getAudioTracks().forEach(g=>{g.enabled=!1,ce.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[i,t]),r){case"collapsed":return A(hu,{onExpand:l,call:t,client:e,chatMode:i,debug:s});case"expanded":return A(fy,{transcript:u,onCollapse:c,call:t,chatMode:i,debug:s});default:return A(hu,{onExpand:l,call:t,client:e,chatMode:i,debug:s})}},Ir=()=>A(bn.div,{layoutId:oi,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:A("div",{className:"rounded-full animate-spin",children:A(F_,{})})}),kb=({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 A(Ir,{});case"done":case"purged":case"destroy":return null;case"active":return A(Tb,{client:e,call:t,latencySettings:n,chatMode:i,debug:s});default:return A(Ir,{})}},Eb=({className:t})=>A("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:[A("g",{clipPath:"url(#:R5lfm:)",children:[A("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),A("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),A("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),A("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),A("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),A("defs",{children:A("clipPath",{id:":R5lfm:",children:A("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Rh(){const t=Jt();return t.logo_icon_url?A("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:A("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):A(Eb,{className:"w-8 h-8 mr-2"})}const Ib=({client:t,callProps:e,chatMode:n,isReady:i})=>{const s=Jt(),o=he(!1),r=He(async()=>{if(!t){ce.error("Client is not initialized.");return}if(!i){ce.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){ce.error("Failed to start AI Agent conversation:",a)}},[t,e,i]);return Re(()=>{n&&t&&i&&!o.current&&(o.current=!0,ce.info("[ChatMode] Auto-starting conversation"),r())},[n,t,i,r]),n?A(bn.div,{layoutId:oi,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:[A(Rh,{}),"Connecting..."]}):A(bn.button,{layoutId:oi,onClick:r,disabled:!i,"aria-busy":!i,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[A(Rh,{}),s.start_call_text]})},xb='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',Rb=({children:t})=>A("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:A("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),Ab={duration:.1,ease:"circOut"},Lb=({children:t,position:e="fixed"})=>{const n=Jt(),s=(e??n.position??"fixed")==="fixed"?A(Rb,{children:t}):t;return A("div",{className:Et(n.theme==="dark"&&"dark"),children:A(xg,{transition:Ab,children:[A("style",{children:xb}),s]})})},Db=t=>A(bn.div,{layoutId:oi,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[A(O_,{className:"w-8 h-8 text-red-400"}),A("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),A("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[A("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),A("li",{children:["Make sure that the"," ",A("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${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"," ",A(G_,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&A("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:[A($_,{className:"w-4 h-4"}),"Retry"]})]});function Ln(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Pb({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":f,region:g,"skip-last-voice-sdk-id":y,environment:v,position:b="fixed","version-id":_}){const T=Ln(e),E=Ln(n),x=Ln(f),I=y===void 0?!0:Ln(y),O=Ye(()=>{if(l)try{return JSON.parse(l)}catch(ne){ce.error("Invalid JSON for vad attribute:",l,ne);return}},[l]),C=Ye(()=>({showUserPerceivedLatency:Ln(c),showGreetingLatency:Ln(u)}),[c,u]),{client:k,error:p,isConnected:m,isReconnecting:h}=_b(t,v,_,T,E,O,d,x,g,I),[w,R]=xe(null),[L,D]=xe(!1),[N,P]=xe(!1),[F,z]=xe(!1),[j,de]=xe(!1),J=Li(du),H=l_(),ae={};if(i&&(ae.destinationNumber=i),s&&(ae.callerNumber=s),o&&(ae.callerName=o),r)try{ae.customHeaders=JSON.parse(r)}catch(ne){ce.error("Invalid JSON for call-custom-headers attribute:",r,ne)}if(a)try{ae.audio=JSON.parse(a);const ne=ae.audio;if(typeof ne=="object"){const ve=navigator.mediaDevices.getSupportedConstraints();Object.keys(ne).forEach(ue=>{ve[ue]||ce.warn(`Audio constraint not supported by browser: ${ue}`)})}}catch(ne){ce.error("Invalid JSON for call-audio attribute:",a,ne)}const Y=He(()=>{D(!1)},[]),ee=He(ne=>{var ve;if(((ve=ne.call)==null?void 0:ve.state)==="destroy")return J(!1),de(!0),R(null);R(ne)},[J]),te=He(()=>{D(!1),h||P(!0)},[h]),ie=He(()=>{ce.info("User triggered retry"),P(!1),D(!0),k&&k.connect()},[k]),pe=He(ne=>{if(a_(ne)){const ve=ne.params.widget_settings;ve&&Object.keys(ve).length>0&&(H(ve),z(!0))}},[H]);return bb(k,{onReady:Y,onConversationUpdate:ee,onError:te,onConfigMessage:pe}),A(Lb,{position:b,children:t?N||p?A(Db,{agentId:t,onRetry:ie}):L||h?A(Ir,{message:h?"Retrying...":void 0}):w!=null&&w.call?A(kb,{call:w.call,client:k,latencySettings:C,chatMode:x,debug:T}):F?A(Ib,{client:k,callProps:ae,chatMode:x&&!j,isReady:m&&!!k}):null:A("div",{children:"Please provide an assistant ID."})})}qh(Pb,"telnyx-ai-agent",o_,{shadow:!0})})();