@telnyx/ai-agent-widget 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(){"use strict";var gn,K,eo,It,to,no,io,so,zi,Wi,qi,ro,vn={},oo=[],bu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_n=Array.isArray;function tt(t,e){for(var n in e)t[n]=e[n];return t}function Ki(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function He(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?gn.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 yn(t,r,i,s,null)}function yn(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??++eo,__i:-1,__u:0};return s==null&&K.vnode!=null&&K.vnode(o),o}function Xe(t){return t.children}function Ye(t,e){this.props=t,this.context=e}function Kt(t,e){if(e==null)return t.__?Kt(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"?Kt(t):null}function ao(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 ao(t)}}function Xi(t){(!t.__d&&(t.__d=!0)&&It.push(t)&&!ti.__r++||to!=K.debounceRendering)&&((to=K.debounceRendering)||no)(ti)}function ti(){for(var t,e,n,i,s,o,r,a=1;It.length;)It.length>a&&It.sort(io),t=It.shift(),a=It.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=tt({},i)).__v=i.__v+1,K.vnode&&K.vnode(n),Yi(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??Kt(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,fo(o,n,r),n.__e!=s&&ao(n)));ti.__r=0}function co(t,e,n,i,s,o,r,a,c,l,u){var d,m,g,y,k,x,b=i&&i.__k||oo,S=e.length;for(c=wu(n,e,b,c,S),d=0;d<S;d++)(g=n.__k[d])!=null&&(m=g.__i==-1?vn:b[g.__i]||vn,g.__i=d,x=Yi(t,g,m,s,o,r,a,c,l,u),y=g.__e,g.ref&&m.ref!=g.ref&&(m.ref&&Zi(m.ref,null,g),u.push(g.ref,g.__c||y,g)),k==null&&y!=null&&(k=y),4&g.__u||m.__k===g.__k?c=lo(g,c,t):typeof g.type=="function"&&x!==void 0?c=x:y&&(c=y.nextSibling),g.__u&=-7);return n.__e=k,c}function wu(t,e,n,i,s){var o,r,a,c,l,u=n.length,d=u,m=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(c=o+m,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?yn(null,r,null,null,null):_n(r)?yn(Xe,{children:r},null,null,null):r.constructor==null&&r.__b>0?yn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(l=r.__i=xu(r,n,c,d))!=-1&&(d--,(a=n[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(s>u?m--:s<u&&m++),typeof r.type!="function"&&(r.__u|=4)):l!=c&&(l==c-1?m--:l==c+1?m++:(l>c?m--:m++,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=Kt(a)),mo(a,a));return i}function lo(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=lo(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=Kt(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function nt(t,e){return e=e||[],t==null||typeof t=="boolean"||(_n(t)?t.some(function(n){nt(n,e)}):e.push(t)),e}function xu(t,e,n,i){var s,o,r=t.key,a=t.type,c=e[n];if(c===null&&t.key==null||c&&r==c.key&&a==c.type&&(2&c.__u)==0)return n;if(i>(c!=null&&(2&c.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((c=e[s])&&(2&c.__u)==0&&r==c.key&&a==c.type)return s;s--}if(o<e.length){if((c=e[o])&&(2&c.__u)==0&&r==c.key&&a==c.type)return o;o++}}return-1}function uo(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||bu.test(e)?n:n+"px"}function ni(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||uo(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||uo(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(so,"$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=zi,t.addEventListener(e,o?qi:Wi,o)):t.removeEventListener(e,o?qi:Wi,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 ho(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=zi++;else if(e.t<n.u)return;return n(K.event?K.event(e):e)}}}function Yi(t,e,n,i,s,o,r,a,c,l){var u,d,m,g,y,k,x,b,S,C,A,M,O,_,w,f,p,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),o=[a=e.__e=n.__e]),(u=K.__b)&&u(e);e:if(typeof h=="function")try{if(b=e.props,S="prototype"in h&&h.prototype.render,C=(u=h.contextType)&&i[u.__c],A=u?C?C.props.value:u.__:i,n.__c?x=(d=e.__c=n.__c).__=d.__E:(S?e.__c=d=new h(b,A):(e.__c=d=new Ye(b,A),d.constructor=h,d.render=ku),C&&C.sub(d),d.props=b,d.state||(d.state={}),d.context=A,d.__n=i,m=d.__d=!0,d.__h=[],d._sb=[]),S&&d.__s==null&&(d.__s=d.state),S&&h.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=tt({},d.__s)),tt(d.__s,h.getDerivedStateFromProps(b,d.__s))),g=d.props,y=d.state,d.__v=e,m)S&&h.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),S&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(S&&h.getDerivedStateFromProps==null&&b!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,A)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(v){v&&(v.__=e)}),M=0;M<d._sb.length;M++)d.__h.push(d._sb[M]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,A),S&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,k)})}if(d.context=A,d.props=b,d.__P=t,d.__e=!1,O=K.__r,_=0,S){for(d.state=d.__s,d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),w=0;w<d._sb.length;w++)d.__h.push(d._sb[w]);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&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=tt(tt({},i),d.getChildContext())),S&&!m&&d.getSnapshotBeforeUpdate!=null&&(k=d.getSnapshotBeforeUpdate(g,y)),f=u,u!=null&&u.type===Xe&&u.key==null&&(f=po(u.props.children)),a=co(t,_n(f)?f:[f],e,n,i,s,o,r,a,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),x&&(d.__E=d.__=null)}catch(v){if(e.__v=null,c||o!=null)if(v.then){for(e.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(p=o.length;p--;)Ki(o[p]);else e.__e=n.__e,e.__k=n.__k;K.__e(v,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Su(n.__e,e,n,i,s,o,r,c,l);return(u=K.diffed)&&u(e),128&e.__u?void 0:a}function fo(t,e,n){for(var i=0;i<n.length;i++)Zi(n[i],n[++i],n[++i]);K.__c&&K.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){K.__e(o,s.__v)}})}function po(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:_n(t)?t.map(po):tt({},t)}function Su(t,e,n,i,s,o,r,a,c){var l,u,d,m,g,y,k,x=n.props,b=e.props,S=e.type;if(S=="svg"?s="http://www.w3.org/2000/svg":S=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((g=o[l])&&"setAttribute"in g==!!S&&(S?g.localName==S:g.nodeType==3)){t=g,o[l]=null;break}}if(t==null){if(S==null)return document.createTextNode(b);t=document.createElementNS(s,S,b.is&&b),a&&(K.__m&&K.__m(e,o),a=!1),o=null}if(S==null)x===b||a&&t.data==b||(t.data=b);else{if(o=o&&gn.call(t.childNodes),x=n.props||vn,!a&&o!=null)for(x={},l=0;l<t.attributes.length;l++)x[(g=t.attributes[l]).name]=g.value;for(l in x)if(g=x[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=g;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ni(t,l,null,g,s)}}for(l in b)g=b[l],l=="children"?m=g:l=="dangerouslySetInnerHTML"?u=g:l=="value"?y=g:l=="checked"?k=g:a&&typeof g!="function"||x[l]===g||ni(t,l,g,x[l],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),co(e.type=="template"?t.content:t,_n(m)?m:[m],e,n,i,S=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&Kt(n,0),a,c),o!=null)for(l=o.length;l--;)Ki(o[l]);a||(l="value",S=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[l]||S=="progress"&&!y||S=="option"&&y!=x[l])&&ni(t,l,y,x[l],s),l="checked",k!=null&&k!=t[l]&&ni(t,l,k,x[l],s))}return t}function Zi(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){K.__e(s,n)}}function mo(t,e,n){var i,s;if(K.unmount&&K.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Zi(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){K.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&mo(i[s],e,n||typeof t.type!="function");n||Ki(t.__e),t.__c=t.__=t.__e=void 0}function ku(t,e,n){return this.constructor(t,n)}function ii(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),K.__&&K.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],Yi(e,t=(!i&&n||e).__k=He(Xe,null,[t]),s||vn,vn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?gn.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),fo(o,t,r)}function go(t,e){ii(t,e,go)}function Ji(t,e,n){var i,s,o,r,a=tt({},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?gn.call(arguments,2):n),yn(t.type,a,i||t.key,s||t.ref,null)}function Pt(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,Xi(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"+ro++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}gn=oo.slice,K={__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}},eo=0,Ye.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=tt({},this.state),typeof t=="function"&&(t=t(tt({},n),this.props)),t&&tt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Xi(this))},Ye.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Xi(this))},Ye.prototype.render=Xe,It=[],no=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,io=function(t,e){return t.__v.__b-e.__v.__b},ti.__r=0,so=/(PointerCapture)$|Capture$/i,zi=0,Wi=ho(!1),qi=ho(!0),ro=0;var Cu=0;function E(t,e,n,i,s,o){e||(e={});var r,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?r=e[a]:c[a]=e[a];var l={type:t,props:c,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Cu,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)c[a]===void 0&&(c[a]=r[a]);return K.vnode&&K.vnode(l),l}function Qi(){return(Qi=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 Tu=["context","children"];function Eu(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},c=Object.keys(i);for(r=0;r<c.length;r++)s.indexOf(o=c[r])>=0||(a[o]=i[o]);return a}(t,Tu);return Ji(e,n)}function Au(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=He(Eu,Qi({},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,c=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[vo(a[r].name)]=a[r].value);for(r=c.length;r--;){var l=e(c[r],null),u=c[r].slot;u?o[u]=He(_o,{name:u},l):s[r]=l}var d=i?He(_o,null,s):s;return He(i||n.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?go:ii)(this._vdom,this._root)}function vo(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Iu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[vo(t)]=n,this._vdom=Ji(this._vdom,i),ii(this._vdom,this._root)}}function Pu(){ii(this._vdom=null,this._root)}function _o(t,e){var n=this;return He("slot",Qi({},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 Ru(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=Au,s.prototype.attributeChangedCallback=Iu,s.prototype.disconnectedCallback=Pu,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 yt,ae,es,yo,bn=0,bo=[],pe=K,wo=pe.__b,xo=pe.__r,So=pe.diffed,ko=pe.__c,Co=pe.unmount,To=pe.__;function Xt(t,e){pe.__h&&pe.__h(ae,t,bn||e),bn=0;var n=ae.__H||(ae.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Re(t){return bn=1,Eo(Io,t)}function Eo(t,e,n){var i=Xt(yt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Io(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,a);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=ae,!ae.__f)){var s=function(a,c,l){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(m){return!!m.__c});if(u.every(function(m){return!m.__N}))return!o||o.call(this,a,c,l);var d=i.__c.props!==a;return u.forEach(function(m){if(m.__N){var g=m.__[0];m.__=m.__N,m.__N=void 0,g!==m.__[0]&&(d=!0)}}),o&&o.call(this,a,c,l)||d};ae.__f=!0;var o=ae.shouldComponentUpdate,r=ae.componentWillUpdate;ae.componentWillUpdate=function(a,c,l){if(this.__e){var u=o;o=void 0,s(a,c,l),o=u}r&&r.call(this,a,c,l)},ae.shouldComponentUpdate=s}return i.__N||i.__}function Ne(t,e){var n=Xt(yt++,3);!pe.__s&&ss(n.__H,e)&&(n.__=t,n.u=e,ae.__H.__h.push(n))}function ts(t,e){var n=Xt(yt++,4);!pe.__s&&ss(n.__H,e)&&(n.__=t,n.u=e,ae.__h.push(n))}function ke(t){return bn=5,it(function(){return{current:t}},[])}function it(t,e){var n=Xt(yt++,7);return ss(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function si(t,e){return bn=8,it(function(){return t},e)}function we(t){var e=ae.context[t.__c],n=Xt(yt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ae)),e.props.value):t.__}function Mu(t,e){pe.useDebugValue&&pe.useDebugValue(e?e(t):t)}function ns(){var t=Xt(yt++,11);if(!t.__){for(var e=ae.__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 Lu(){for(var t;t=bo.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ri),t.__H.__h.forEach(is),t.__H.__h=[]}catch(e){t.__H.__h=[],pe.__e(e,t.__v)}}pe.__b=function(t){ae=null,wo&&wo(t)},pe.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),To&&To(t,e)},pe.__r=function(t){xo&&xo(t),yt=0;var e=(ae=t.__c).__H;e&&(es===ae?(e.__h=[],ae.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ri),e.__h.forEach(is),e.__h=[],yt=0)),es=ae},pe.diffed=function(t){So&&So(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(bo.push(e)!==1&&yo===pe.requestAnimationFrame||((yo=pe.requestAnimationFrame)||Du)(Lu)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),es=ae=null},pe.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ri),n.__h=n.__h.filter(function(i){return!i.__||is(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],pe.__e(i,n.__v)}}),ko&&ko(t,e)},pe.unmount=function(t){Co&&Co(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{ri(i)}catch(s){e=s}}),n.__H=void 0,e&&pe.__e(e,n.__v))};var Ao=typeof requestAnimationFrame=="function";function Du(t){var e,n=function(){clearTimeout(i),Ao&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ao&&(e=requestAnimationFrame(n))}function ri(t){var e=ae,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ae=e}function is(t){var e=ae;t.__c=t.__(),ae=e}function ss(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Io(t,e){return typeof e=="function"?e(t):e}const wn={},Po=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ro=t=>"init"in t,rs=t=>!!t.write,Mo=t=>"v"in t||"e"in t,oi=t=>{if("e"in t)throw t.e;if((wn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},ai=new WeakMap,Lo=t=>{var e;return ci(t)&&!!((e=ai.get(t))!=null&&e[0])},Ou=t=>{const e=ai.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Do=(t,e)=>{let n=ai.get(t);if(!n){n=[!0,new Set],ai.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},ci=t=>typeof(t==null?void 0:t.then)=="function",Oo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},os=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(ci(e))for(const r of i.d.keys())Oo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,ci(o)&&Ou(o))},No=(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},Nu=()=>{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,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},Vu=t=>(t.c||(t.c=as()),t.m||(t.m=as()),t.u||(t.u=as()),t.f||(t.f=Nu()),t),Fu=Symbol(),Vo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(m,...g)=>m.read(...g),c=(m,...g)=>m.write(...g),l=(m,g)=>{var y;return(y=m.unstable_onInit)==null?void 0:y.call(m,g)},u=(m,g)=>{var y;return(y=m.onMount)==null?void 0:y.call(m,g)},...d)=>{const m=d[0]||(_=>{if((wn?"production":void 0)!=="production"&&!_)throw new Error("Atom is undefined or null");let w=t.get(_);return w||(w={d:new Map,p:new Set,n:0},t.set(_,w),l==null||l(_,O)),w}),g=d[1]||(()=>{const _=[],w=f=>{try{f()}catch(p){_.push(p)}};do{r.f&&w(r.f);const f=new Set,p=f.add.bind(f);i.forEach(h=>{var v;return(v=e.get(h))==null?void 0:v.l.forEach(p)}),i.clear(),o.forEach(p),o.clear(),s.forEach(p),s.clear(),f.forEach(w),i.size&&y()}while(i.size||o.size||s.size);if(_.length)throw new AggregateError(_)}),y=d[2]||(()=>{const _=[],w=new WeakSet,f=new WeakSet,p=Array.from(i);for(;p.length;){const h=p[p.length-1],v=m(h);if(f.has(h)){p.pop();continue}if(w.has(h)){if(n.get(h)===v.n)_.push([h,v]);else if((wn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");f.add(h),p.pop();continue}w.add(h);for(const T of No(h,v,e))w.has(T)||p.push(T)}for(let h=_.length-1;h>=0;--h){const[v,T]=_[h];let P=!1;for(const I of T.d.keys())if(I!==v&&i.has(I)){P=!0;break}P&&(k(v),S(v)),n.delete(v)}}),k=d[3]||(_=>{var w;const f=m(_);if(Mo(f)&&(e.has(_)&&n.get(_)!==f.n||Array.from(f.d).every(([R,V])=>k(R).n===V)))return f;f.d.clear();let p=!0;const h=()=>{e.has(_)&&(S(_),y(),g())},v=R=>{var V;if(Po(_,R)){const B=m(R);if(!Mo(B))if(Ro(R))os(R,R.init,m);else throw new Error("no atom init");return oi(B)}const X=k(R);try{return oi(X)}finally{f.d.set(R,X.n),Lo(f.v)&&Oo(_,f.v,X),(V=e.get(R))==null||V.t.add(_),p||h()}};let T,P;const I={get signal(){return T||(T=new AbortController),T.signal},get setSelf(){return(wn?"production":void 0)!=="production"&&!rs(_)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&rs(_)&&(P=(...R)=>{if((wn?"production":void 0)!=="production"&&p&&console.warn("setSelf function cannot be called in sync"),!p)try{return b(_,...R)}finally{y(),g()}}),P}},L=f.n;try{const R=a(_,v,I);return os(_,R,m),ci(R)&&(Do(R,()=>T==null?void 0:T.abort()),R.then(h,h)),f}catch(R){return delete f.v,f.e=R,++f.n,f}finally{p=!1,L!==f.n&&n.get(_)===L&&(n.set(_,f.n),i.add(_),(w=r.c)==null||w.call(r,_))}}),x=d[4]||(_=>{const w=[_];for(;w.length;){const f=w.pop(),p=m(f);for(const h of No(f,p,e)){const v=m(h);n.set(h,v.n),w.push(h)}}}),b=d[5]||((_,...w)=>{let f=!0;const p=v=>oi(k(v)),h=(v,...T)=>{var P;const I=m(v);try{if(Po(_,v)){if(!Ro(v))throw new Error("atom not writable");const L=I.n,R=T[0];os(v,R,m),S(v),L!==I.n&&(i.add(v),(P=r.c)==null||P.call(r,v),x(v));return}else return b(v,...T)}finally{f||(y(),g())}};try{return c(_,p,h,...w)}finally{f=!1}}),S=d[6]||(_=>{var w;const f=m(_),p=e.get(_);if(p&&!Lo(f.v)){for(const[h,v]of f.d)if(!p.d.has(h)){const T=m(h);C(h).t.add(_),p.d.add(h),v!==T.n&&(i.add(h),(w=r.c)==null||w.call(r,h),x(h))}for(const h of p.d||[])if(!f.d.has(h)){p.d.delete(h);const v=A(h);v==null||v.t.delete(_)}}}),C=d[7]||(_=>{var w;const f=m(_);let p=e.get(_);if(!p){k(_);for(const h of f.d.keys())C(h).t.add(_);if(p={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(_,p),(w=r.m)==null||w.call(r,_),rs(_)){const h=()=>{let v=!0;const T=(...P)=>{try{return b(_,...P)}finally{v||(y(),g())}};try{const P=u(_,T);P&&(p.u=()=>{v=!0;try{P()}finally{v=!1}})}finally{v=!1}};s.add(h)}}return p}),A=d[8]||(_=>{var w;const f=m(_);let p=e.get(_);if(p&&!p.l.size&&!Array.from(p.t).some(h=>{var v;return(v=e.get(h))==null?void 0:v.d.has(_)})){p.u&&o.add(p.u),p=void 0,e.delete(_),(w=r.u)==null||w.call(r,_);for(const h of f.d.keys()){const v=A(h);v==null||v.t.delete(_)}return}return p}),M=[t,e,n,i,s,o,r,a,c,l,u,m,g,y,k,x,b,S,C,A],O={get:_=>oi(k(_)),set:(_,...w)=>{try{return b(_,...w)}finally{y(),g()}},sub:(_,w)=>{const p=C(_).l;return p.add(w),g(),()=>{p.delete(w),A(_),g()}}};return Object.defineProperty(O,Fu,{value:M}),O},Bu=Vu,Fo=Do,cs={};let ju=0;function ls(t,e){const n=`atom${++ju}`,i={toString(){return(cs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=$u,i.write=Uu),i}function $u(t){return t(this)}function Uu(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const Hu=()=>{let t=0;const e=Bu({}),n=new WeakMap,i=new WeakMap,s=Vo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,c,l,...u)=>t?l(a,...u):a.write(c,l,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const c=n.get(a);c.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const c=n.get(a);delete c.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 c={read:()=>null,write:(l,u)=>{++t;try{for(const[d,m]of a)"init"in d&&u(d,m)}finally{--t}}};s.set(c)}})};function Gu(){return(cs?"production":void 0)!=="production"?Hu():Vo()}let xn;function zu(){return xn||(xn=Gu(),(cs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=xn),globalThis.__JOTAI_DEFAULT_STORE__!==xn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),xn}function Bo(t,e){for(var n in e)t[n]=e[n];return t}function jo(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 $o=ts;function Uo(t,e){this.props=t,this.context=e}(Uo.prototype=new Ye).isPureReactComponent=!0,Uo.prototype.shouldComponentUpdate=function(t,e){return jo(this.props,t)||jo(this.state,e)};var Ho=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ho&&Ho(t)};var Wu=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function qu(t){function e(n){var i=Bo({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Wu,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Go=function(t,e){return t==null?null:nt(nt(t).map(e))},Ku={map:Go,forEach:Go,count:function(t){return t?nt(t).length:0},only:function(t){var e=nt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:nt},Xu=K.__e;K.__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)}Xu(t,e,n,i)};var zo=K.unmount;function Wo(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=Bo({},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 Wo(i,e,n)})),t}function qo(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return qo(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 ds(){this.__u=0,this.o=null,this.__b=null}function Ko(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function li(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),zo&&zo(t)},(ds.prototype=new Ye).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=Ko(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 c=i.state.__a;i.__v.__k[0]=qo(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},ds.prototype.componentWillUnmount=function(){this.o=[]},ds.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]=Wo(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&He(Xe,null,t.fallback);return s&&(s.__u&=-33),[He(Xe,null,e.__a?null:t.children),s]};var Xo=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]}};(li.prototype=new Ye).__a=function(t){var e=this,n=Ko(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),Xo(e,t,i)):s()};n?n(o):o()}},li.prototype.render=function(t){this.i=null,this.l=new Map;var e=nt(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},li.prototype.componentDidUpdate=li.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Xo(t,n,e)})};var Yo=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Yu=/^(?: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]/,Zu=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ju=/[A-Z0-9]/g,Qu=typeof document<"u",eh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};Ye.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(Ye.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Zo=K.event;function th(){}function nh(){return this.cancelBubble}function ih(){return this.defaultPrevented}K.event=function(t){return Zo&&(t=Zo(t)),t.persist=th,t.isPropagationStopped=nh,t.isDefaultPrevented=ih,t.nativeEvent=t};var sh={enumerable:!1,configurable:!0,get:function(){return this.class}},Jo=K.vnode;K.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||Qu&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var c=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?r="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||eh(n.type)?c==="onfocus"?r="onfocusin":c==="onblur"?r="onfocusout":Zu.test(r)&&(r=c):c=r="oninput":o&&Yu.test(r)?r=r.replace(Ju,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&s[r=c]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=nt(n.children).forEach(function(l){l.props.selected=s.value.indexOf(l.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=nt(n.children).forEach(function(l){l.props.selected=s.multiple?s.defaultValue.indexOf(l.props.value)!=-1:s.defaultValue==l.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",sh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=Yo,Jo&&Jo(t)};var Qo=K.__r;K.__r=function(t){Qo&&Qo(t),t.__c};var ea=K.diffed;K.diffed=function(t){ea&&ea(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 ta(t){return!!t&&t.$$typeof===Yo}function rh(t){return ta(t)?Ji.apply(null,arguments):t}var na={};const oh={},ah=Pt(void 0);function ia(t){return we(ah)||zu()}const us=t=>typeof(t==null?void 0:t.then)=="function",hs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},ch=na.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(hs(t),t)}),fs=new WeakMap,sa=(t,e)=>{let n=fs.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=l=>u=>{o===l&&i(u)},a=l=>u=>{o===l&&s(u)},c=()=>{try{const l=e();us(l)?(fs.set(l,n),o=l,l.then(r(l),a(l)),Fo(l,c)):i(l)}catch(l){s(l)}};t.then(r(t),a(t)),Fo(t,c)}),fs.set(t,n)),n};function ra(t,e){const{delay:n,unstable_promiseStatus:i=!na.use}={},s=ia(),[[o,r,a],c]=Eo(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 l=o;if((r!==s||a!==t)&&(c(),l=s.get(t)),Ne(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);us(d)&&hs(sa(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(c,n);return}c()});return c(),u},[s,t,n,i]),Mu(l),us(l)){const u=sa(l,()=>s.get(t));return i&&hs(u),ch(u)}return l}function ps(t,e){const n=ia();return si((...s)=>{if((oh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function oa(t,e){return[ra(t),ps(t)]}const ms=Pt({});function di(t){const e=ke(null);return e.current===null&&(e.current=t()),e.current}const gs=typeof window<"u",aa=gs?ts:Ne,ui=Pt(null);function vs(t,e){t.indexOf(e)===-1&&t.push(e)}function _s(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const ht=(t,e,n)=>n>e?e:n<t?t:n;let ys=()=>{};const ft={},ca=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function la(t){return typeof t=="object"&&t!==null}const da=t=>/^0[^.\s]+$/u.test(t);function bs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ge=t=>t,lh=(t,e)=>n=>e(t(n)),Sn=(...t)=>t.reduce(lh),kn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class ws{constructor(){this.subscriptions=[]}add(e){return vs(this.subscriptions,e),()=>_s(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 st=t=>t*1e3,rt=t=>t/1e3;function ua(t,e){return e?t*(1e3/e):0}const ha=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,dh=1e-7,uh=12;function hh(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=ha(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>dh&&++a<uh);return r}function Cn(t,e,n,i){if(t===e&&n===i)return Ge;const s=o=>hh(o,0,1,t,n);return o=>o===0||o===1?o:ha(s(o),e,i)}const fa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,pa=t=>e=>1-t(1-e),ma=Cn(.33,1.53,.69,.99),xs=pa(ma),ga=fa(xs),va=t=>(t*=2)<1?.5*xs(t):.5*(2-Math.pow(2,-10*(t-1))),Ss=t=>1-Math.sin(Math.acos(t)),_a=pa(Ss),ya=fa(Ss),fh=Cn(.42,0,1,1),ph=Cn(0,0,.58,1),ba=Cn(.42,0,.58,1),mh=t=>Array.isArray(t)&&typeof t[0]!="number",wa=t=>Array.isArray(t)&&typeof t[0]=="number",gh={linear:Ge,easeIn:fh,easeInOut:ba,easeOut:ph,circIn:Ss,circInOut:ya,circOut:_a,backIn:xs,backInOut:ga,backOut:ma,anticipate:va},vh=t=>typeof t=="string",xa=t=>{if(wa(t)){ys(t.length===4);const[e,n,i,s]=t;return Cn(e,n,i,s)}else if(vh(t))return gh[t];return t},hi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Sa={value:null};function _h(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},c=0;function l(d){r.has(d)&&(u.schedule(d),t()),c++,d(a)}const u={schedule:(d,m=!1,g=!1)=>{const k=g&&s?n:i;return m&&r.add(d),k.has(d)||k.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(l),e&&Sa.value&&Sa.value.frameloop[e].push(c),c=0,n.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const yh=40;function ka(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=hi.reduce((C,A)=>(C[A]=_h(o,e?A:void 0),C),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:m,render:g,postRender:y}=r,k=()=>{const C=ft.useManualTiming?s.timestamp:performance.now();n=!1,ft.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(C-s.timestamp,yh),1)),s.timestamp=C,s.isProcessing=!0,a.process(s),c.process(s),l.process(s),u.process(s),d.process(s),m.process(s),g.process(s),y.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(k))},x=()=>{n=!0,i=!0,s.isProcessing||t(k)};return{schedule:hi.reduce((C,A)=>{const M=r[A];return C[A]=(O,_=!1,w=!1)=>(n||x(),M.schedule(O,_,w)),C},{}),cancel:C=>{for(let A=0;A<hi.length;A++)r[hi[A]].cancel(C)},state:s,steps:r}}const{schedule:de,cancel:bt,state:Ce,steps:ks}=ka(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ge,!0);let fi;function bh(){fi=void 0}const Ve={now:()=>(fi===void 0&&Ve.set(Ce.isProcessing||ft.useManualTiming?Ce.timestamp:performance.now()),fi),set:t=>{fi=t,queueMicrotask(bh)}},Ca=t=>e=>typeof e=="string"&&e.startsWith(t),Cs=Ca("--"),wh=Ca("var(--"),Ts=t=>wh(t)?xh.test(t.split("/*")[0].trim()):!1,xh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Yt={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Tn={...Yt,transform:t=>ht(0,1,t)},pi={...Yt,default:1},En=t=>Math.round(t*1e5)/1e5,Es=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Sh(t){return t==null}const kh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,As=(t,e)=>n=>!!(typeof n=="string"&&kh.test(n)&&n.startsWith(t)||e&&!Sh(n)&&Object.prototype.hasOwnProperty.call(n,e)),Ta=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Es);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Ch=t=>ht(0,255,t),Is={...Yt,transform:t=>Math.round(Ch(t))},Rt={test:As("rgb","red"),parse:Ta("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Is.transform(t)+", "+Is.transform(e)+", "+Is.transform(n)+", "+En(Tn.transform(i))+")"};function Th(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 Ps={test:As("#"),parse:Th,transform:Rt.transform},An=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),wt=An("deg"),ot=An("%"),H=An("px"),Eh=An("vh"),Ah=An("vw"),Ea={...ot,parse:t=>ot.parse(t)/100,transform:t=>ot.transform(t*100)},Zt={test:As("hsl","hue"),parse:Ta("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ot.transform(En(e))+", "+ot.transform(En(n))+", "+En(Tn.transform(i))+")"},ye={test:t=>Rt.test(t)||Ps.test(t)||Zt.test(t),parse:t=>Rt.test(t)?Rt.parse(t):Zt.test(t)?Zt.parse(t):Ps.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Rt.transform(t):Zt.transform(t),getAnimatableNone:t=>{const e=ye.parse(t);return e.alpha=0,ye.transform(e)}},Ih=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Ph(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Es))==null?void 0:e.length)||0)+(((n=t.match(Ih))==null?void 0:n.length)||0)>0}const Aa="number",Ia="color",Rh="var",Mh="var(",Pa="${}",Lh=/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 In(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Lh,c=>(ye.test(c)?(i.color.push(o),s.push(Ia),n.push(ye.parse(c))):c.startsWith(Mh)?(i.var.push(o),s.push(Rh),n.push(c)):(i.number.push(o),s.push(Aa),n.push(parseFloat(c))),++o,Pa)).split(Pa);return{values:n,split:a,indexes:i,types:s}}function Ra(t){return In(t).values}function Ma(t){const{split:e,types:n}=In(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===Aa?o+=En(s[r]):a===Ia?o+=ye.transform(s[r]):o+=s[r]}return o}}const Dh=t=>typeof t=="number"?0:ye.test(t)?ye.getAnimatableNone(t):t;function Oh(t){const e=Ra(t);return Ma(t)(e.map(Dh))}const xt={test:Ph,parse:Ra,createTransformer:Ma,getAnimatableNone:Oh};function Rs(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 Nh({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,c=2*n-a;s=Rs(c,a,t+1/3),o=Rs(c,a,t),r=Rs(c,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function mi(t,e){return n=>n>0?e:t}const me=(t,e,n)=>t+(e-t)*n,Ms=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Vh=[Ps,Rt,Zt],Fh=t=>Vh.find(e=>e.test(t));function La(t){const e=Fh(t);if(!e)return!1;let n=e.parse(t);return e===Zt&&(n=Nh(n)),n}const Da=(t,e)=>{const n=La(t),i=La(e);if(!n||!i)return mi(t,e);const s={...n};return o=>(s.red=Ms(n.red,i.red,o),s.green=Ms(n.green,i.green,o),s.blue=Ms(n.blue,i.blue,o),s.alpha=me(n.alpha,i.alpha,o),Rt.transform(s))},Ls=new Set(["none","hidden"]);function Bh(t,e){return Ls.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function jh(t,e){return n=>me(t,e,n)}function Ds(t){return typeof t=="number"?jh:typeof t=="string"?Ts(t)?mi:ye.test(t)?Da:Hh:Array.isArray(t)?Oa:typeof t=="object"?ye.test(t)?Da:$h:mi}function Oa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ds(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function $h(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Ds(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function Uh(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 Hh=(t,e)=>{const n=xt.createTransformer(e),i=In(t),s=In(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?Ls.has(t)&&!s.values.length||Ls.has(e)&&!i.values.length?Bh(t,e):Sn(Oa(Uh(i,s),s.values),n):mi(t,e)};function Na(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?me(t,e,n):Ds(t)(t,e)}const Gh=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>de.update(e,n),stop:()=>bt(e),now:()=>Ce.isProcessing?Ce.timestamp:Ve.now()}},Va=(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)})`},gi=2e4;function Os(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<gi;)e+=n,i=t.next(e);return e>=gi?1/0:e}function zh(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Os(i),gi);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:rt(s)}}const Wh=5;function Fa(t,e,n){const i=Math.max(e-Wh,0);return ua(n-t(i),e-i)}const ge={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},Ns=.001;function qh({duration:t=ge.duration,bounce:e=ge.bounce,velocity:n=ge.velocity,mass:i=ge.mass}){let s,o,r=1-e;r=ht(ge.minDamping,ge.maxDamping,r),t=ht(ge.minDuration,ge.maxDuration,rt(t)),r<1?(s=l=>{const u=l*r,d=u*t,m=u-n,g=Vs(l,r),y=Math.exp(-d);return Ns-m/g*y},o=l=>{const d=l*r*t,m=d*n+n,g=Math.pow(r,2)*Math.pow(l,2)*t,y=Math.exp(-d),k=Vs(Math.pow(l,2),r);return(-s(l)+Ns>0?-1:1)*((m-g)*y)/k}):(s=l=>{const u=Math.exp(-l*t),d=(l-n)*t+1;return-Ns+u*d},o=l=>{const u=Math.exp(-l*t),d=(n-l)*(t*t);return u*d});const a=5/t,c=Xh(s,o,a);if(t=st(t),isNaN(c))return{stiffness:ge.stiffness,damping:ge.damping,duration:t};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:r*2*Math.sqrt(i*l),duration:t}}}const Kh=12;function Xh(t,e,n){let i=n;for(let s=1;s<Kh;s++)i=i-t(i)/e(i);return i}function Vs(t,e){return t*Math.sqrt(1-e*e)}const Yh=["duration","bounce"],Zh=["stiffness","damping","mass"];function Ba(t,e){return e.some(n=>t[n]!==void 0)}function Jh(t){let e={velocity:ge.velocity,stiffness:ge.stiffness,damping:ge.damping,mass:ge.mass,isResolvedFromDuration:!1,...t};if(!Ba(t,Zh)&&Ba(t,Yh))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*ht(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ge.mass,stiffness:s,damping:o}}else{const n=qh(t);e={...e,...n,mass:ge.mass},e.isResolvedFromDuration=!0}return e}function vi(t=ge.visualDuration,e=ge.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:c,damping:l,mass:u,duration:d,velocity:m,isResolvedFromDuration:g}=Jh({...n,velocity:-rt(n.velocity||0)}),y=m||0,k=l/(2*Math.sqrt(c*u)),x=r-o,b=rt(Math.sqrt(c/u)),S=Math.abs(x)<5;i||(i=S?ge.restSpeed.granular:ge.restSpeed.default),s||(s=S?ge.restDelta.granular:ge.restDelta.default);let C;if(k<1){const M=Vs(b,k);C=O=>{const _=Math.exp(-k*b*O);return r-_*((y+k*b*x)/M*Math.sin(M*O)+x*Math.cos(M*O))}}else if(k===1)C=M=>r-Math.exp(-b*M)*(x+(y+b*x)*M);else{const M=b*Math.sqrt(k*k-1);C=O=>{const _=Math.exp(-k*b*O),w=Math.min(M*O,300);return r-_*((y+k*b*x)*Math.sinh(w)+M*x*Math.cosh(w))/M}}const A={calculatedDuration:g&&d||null,next:M=>{const O=C(M);if(g)a.done=M>=d;else{let _=M===0?y:0;k<1&&(_=M===0?st(y):Fa(C,M,O));const w=Math.abs(_)<=i,f=Math.abs(r-O)<=s;a.done=w&&f}return a.value=a.done?r:O,a},toString:()=>{const M=Math.min(Os(A),gi),O=Va(_=>A.next(M*_).value,M,30);return M+"ms "+O},toTransition:()=>{}};return A}vi.applyToOptions=t=>{const e=zh(t,100,vi);return t.ease=e.ease,t.duration=st(e.duration),t.type="keyframes",t};function Fs({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:c,restDelta:l=.5,restSpeed:u}){const d=t[0],m={done:!1,value:d},g=w=>a!==void 0&&w<a||c!==void 0&&w>c,y=w=>a===void 0?c:c===void 0||Math.abs(a-w)<Math.abs(c-w)?a:c;let k=n*e;const x=d+k,b=r===void 0?x:r(x);b!==x&&(k=b-d);const S=w=>-k*Math.exp(-w/i),C=w=>b+S(w),A=w=>{const f=S(w),p=C(w);m.done=Math.abs(f)<=l,m.value=m.done?b:p};let M,O;const _=w=>{g(m.value)&&(M=w,O=vi({keyframes:[m.value,y(m.value)],velocity:Fa(C,w,m.value),damping:s,stiffness:o,restDelta:l,restSpeed:u}))};return _(0),{calculatedDuration:null,next:w=>{let f=!1;return!O&&M===void 0&&(f=!0,A(w),_(w)),M!==void 0&&w>=M?O.next(w-M):(!f&&A(w),m)}}}function Qh(t,e,n){const i=[],s=n||ft.mix||Na,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const c=Array.isArray(e)?e[r]||Ge:e;a=Sn(c,a)}i.push(a)}return i}function ef(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(ys(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=Qh(e,i,s),c=a.length,l=u=>{if(r&&u<t[0])return e[0];let d=0;if(c>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const m=kn(t[d],t[d+1],u);return a[d](m)};return n?u=>l(ht(t[0],t[o-1],u)):l}function tf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=kn(0,e,i);t.push(me(n,1,s))}}function nf(t){const e=[0];return tf(e,t.length-1),e}function sf(t,e){return t.map(n=>n*e)}function rf(t,e){return t.map(()=>e||ba).splice(0,t.length-1)}function Pn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=mh(i)?i.map(xa):xa(i),o={done:!1,value:e[0]},r=sf(n&&n.length===e.length?n:nf(e),t),a=ef(r,e,{ease:Array.isArray(s)?s:rf(e,s)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const of=t=>t!==null;function Bs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(of),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const af={decay:Fs,inertia:Fs,tween:Pn,keyframes:Pn,spring:vi};function ja(t){typeof t.type=="string"&&(t.type=af[t.type])}class js{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 cf=t=>t/100;class $s extends js{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!==Ve.now()&&this.tick(Ve.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;ja(e);const{type:n=Pn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const c=n||Pn;c!==Pn&&typeof a[0]!="number"&&(this.mixKeyframes=Sn(cf,Na(a[0],a[1])),a=[0,100]);const l=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-r})),l.calculatedDuration===null&&(l.calculatedDuration=Os(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=l}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:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:m,repeatDelay:g,type:y,onUpdate:k,finalKeyframe:x}=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 b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),S=this.playbackSpeed>=0?b<0:b>s;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let C=this.currentTime,A=i;if(d){const w=Math.min(this.currentTime,s)/a;let f=Math.floor(w),p=w%1;!p&&w>=1&&(p=1),p===1&&f--,f=Math.min(f,d+1),!!(f%2)&&(m==="reverse"?(p=1-p,g&&(p-=g/a)):m==="mirror"&&(A=r)),C=ht(0,1,p)*a}const M=S?{done:!1,value:u[0]}:A.next(C);o&&(M.value=o(M.value));let{done:O}=M;!S&&c!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return _&&y!==Fs&&(M.value=Bs(u,this.options,x,this.speed)),k&&k(M.value),_&&this.finish(),M}then(e,n){return this.finished.then(e,n)}get duration(){return rt(this.calculatedDuration)}get time(){return rt(this.currentTime)}set time(e){var n;e=st(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(Ve.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=rt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Gh,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(Ve.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 lf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Mt=t=>t*180/Math.PI,Us=t=>{const e=Mt(Math.atan2(t[1],t[0]));return Hs(e)},df={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Us,rotateZ:Us,skewX:t=>Mt(Math.atan(t[1])),skewY:t=>Mt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Hs=t=>(t=t%360,t<0&&(t+=360),t),$a=Us,Ua=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ha=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),uf={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ua,scaleY:Ha,scale:t=>(Ua(t)+Ha(t))/2,rotateX:t=>Hs(Mt(Math.atan2(t[6],t[5]))),rotateY:t=>Hs(Mt(Math.atan2(-t[2],t[0]))),rotateZ:$a,rotate:$a,skewX:t=>Mt(Math.atan(t[4])),skewY:t=>Mt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Gs(t){return t.includes("scale")?1:0}function zs(t,e){if(!t||t==="none")return Gs(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=uf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=df,s=a}if(!s)return Gs(e);const o=i[e],r=s[1].split(",").map(ff);return typeof o=="function"?o(r):r[o]}const hf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return zs(n,e)};function ff(t){return parseFloat(t.trim())}const Jt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Qt=new Set(Jt),Ga=t=>t===Yt||t===H,pf=new Set(["x","y","z"]),mf=Jt.filter(t=>!pf.has(t));function gf(t){const e=[];return mf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Lt={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})=>zs(e,"x"),y:(t,{transform:e})=>zs(e,"y")};Lt.translateX=Lt.x,Lt.translateY=Lt.y;const Dt=new Set;let Ws=!1,qs=!1,Ks=!1;function za(){if(qs){const t=Array.from(Dt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=gf(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)})}qs=!1,Ws=!1,Dt.forEach(t=>t.complete(Ks)),Dt.clear()}function Wa(){Dt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(qs=!0)})}function vf(){Ks=!0,Wa(),za(),Ks=!1}class Xs{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?(Dt.add(this),Ws||(Ws=!0,de.read(Wa),de.resolveKeyframes(za))):(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])}lf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Dt.delete(this)}cancel(){this.state==="scheduled"&&(Dt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const _f=t=>t.startsWith("--");function yf(t,e,n){_f(e)?t.style.setProperty(e,n):t.style[e]=n}const bf=bs(()=>window.ScrollTimeline!==void 0),wf={};function xf(t,e){const n=bs(t);return()=>wf[e]??n()}const qa=xf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Rn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Ka={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Rn([0,.65,.55,1]),circOut:Rn([.55,0,1,.45]),backIn:Rn([.31,.01,.66,-.59]),backOut:Rn([.33,1.53,.69,.99])};function Xa(t,e){if(t)return typeof t=="function"?qa()?Va(t,e):"ease-out":wa(t)?Rn(t):Array.isArray(t)?t.map(n=>Xa(n,e)||Ka.easeOut):Ka[t]}function Sf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:c}={},l=void 0){const u={[e]:n};c&&(u.offset=c);const d=Xa(a,s);Array.isArray(d)&&(u.easing=d);const m={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return l&&(m.pseudoElement=l),t.animate(u,m)}function Ya(t){return typeof t=="function"&&"applyToOptions"in t}function kf({type:t,...e}){return Ya(t)&&qa()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Cf extends js{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:c}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,ys(typeof e.type!="string");const l=kf(e);this.animation=Sf(n,i,s,l,o),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Bs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):yf(n,i,u),this.animation.cancel()}c==null||c(),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 rt(Number(e))}get time(){return rt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=st(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&&bf()?(this.animation.timeline=e,Ge):n(this)}}const Za={anticipate:va,backInOut:ga,circInOut:ya};function Tf(t){return t in Za}function Ef(t){typeof t.ease=="string"&&Tf(t.ease)&&(t.ease=Za[t.ease])}const Ja=10;class Af extends Cf{constructor(e){Ef(e),ja(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 $s({...r,autoplay:!1}),c=st(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Ja).value,a.sample(c).value,Ja),a.stop()}}const Qa=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(xt.test(t)||t==="0")&&!t.startsWith("url("));function If(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 Pf(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=Qa(s,e),a=Qa(o,e);return!r||!a?!1:If(t)||(n==="spring"||Ya(n))&&i}function Ys(t){return la(t)&&"offsetHeight"in t}const Rf=new Set(["opacity","clipPath","filter","transform"]),Mf=bs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Lf(t){var l;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!Ys((l=e==null?void 0:e.owner)==null?void 0:l.current))return!1;const{onUpdate:a,transformTemplate:c}=e.owner.getProps();return Mf()&&n&&Rf.has(n)&&(n!=="transform"||!c)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const Df=40;class Of extends js{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:c,motionValue:l,element:u,...d}){var y;super(),this.stop=()=>{var k,x;this._animation&&(this._animation.stop(),(k=this.stopTimeline)==null||k.call(this)),(x=this.keyframeResolver)==null||x.cancel()},this.createdAt=Ve.now();const m={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:c,motionValue:l,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Xs;this.keyframeResolver=new g(a,(k,x,b)=>this.onKeyframesResolved(k,x,m,!b),c,l,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=Ve.now(),Pf(e,o,r,a)||((ft.instantAnimations||!c)&&(u==null||u(Bs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const m={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Df?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!l&&Lf(m)?new Af({...m,element:m.motionValue.owner.current}):new $s(m);g.finished.then(()=>this.notifyFinished()).catch(Ge),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(),vf()),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 Nf=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vf(t){const e=Nf.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function ec(t,e,n=1){const[i,s]=Vf(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return ca(r)?parseFloat(r):r}return Ts(s)?ec(s,e,n+1):s}function Zs(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const tc=new Set(["width","height","top","left","right","bottom",...Jt]),Ff={test:t=>t==="auto",parse:t=>t},nc=t=>e=>e.test(t),ic=[Yt,H,ot,wt,Ah,Eh,Ff],sc=t=>ic.find(nc(t));function Bf(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||da(t):!0}const jf=new Set(["brightness","contrast","saturate","opacity"]);function $f(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Es)||[];if(!i)return t;const s=n.replace(i,"");let o=jf.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const Uf=/\b([a-z-]*)\(.*?\)/gu,Js={...xt,getAnimatableNone:t=>{const e=t.match(Uf);return e?e.map($f).join(" "):t}},rc={...Yt,transform:Math.round},Qs={borderWidth:H,borderTopWidth:H,borderRightWidth:H,borderBottomWidth:H,borderLeftWidth:H,borderRadius:H,radius:H,borderTopLeftRadius:H,borderTopRightRadius:H,borderBottomRightRadius:H,borderBottomLeftRadius:H,width:H,maxWidth:H,height:H,maxHeight:H,top:H,right:H,bottom:H,left:H,padding:H,paddingTop:H,paddingRight:H,paddingBottom:H,paddingLeft:H,margin:H,marginTop:H,marginRight:H,marginBottom:H,marginLeft:H,backgroundPositionX:H,backgroundPositionY:H,...{rotate:wt,rotateX:wt,rotateY:wt,rotateZ:wt,scale:pi,scaleX:pi,scaleY:pi,scaleZ:pi,skew:wt,skewX:wt,skewY:wt,distance:H,translateX:H,translateY:H,translateZ:H,x:H,y:H,z:H,perspective:H,transformPerspective:H,opacity:Tn,originX:Ea,originY:Ea,originZ:H},zIndex:rc,fillOpacity:Tn,strokeOpacity:Tn,numOctaves:rc},Hf={...Qs,color:ye,backgroundColor:ye,outlineColor:ye,fill:ye,stroke:ye,borderColor:ye,borderTopColor:ye,borderRightColor:ye,borderBottomColor:ye,borderLeftColor:ye,filter:Js,WebkitFilter:Js},oc=t=>Hf[t];function ac(t,e){let n=oc(t);return n!==Js&&(n=xt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Gf=new Set(["auto","none","0"]);function zf(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!Gf.has(o)&&In(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=ac(n,s)}class Wf extends Xs{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 c=0;c<e.length;c++){let l=e[c];if(typeof l=="string"&&(l=l.trim(),Ts(l))){const u=ec(l,n.current);u!==void 0&&(e[c]=u),c===e.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!tc.has(i)||e.length!==2)return;const[s,o]=e,r=sc(s),a=sc(o);if(r!==a)if(Ga(r)&&Ga(a))for(let c=0;c<e.length;c++){const l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}else Lt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Bf(e[s]))&&i.push(s);i.length&&zf(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=Lt[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]=Lt[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(([c,l])=>{e.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function qf(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 cc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,lc=30,Kf=t=>!isNaN(parseFloat(t));class Xf{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Ve.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 c of this.dependents)c.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=Ve.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Kf(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 ws);const i=this.events[e].add(n);return e==="change"?()=>{i(),de.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=Ve.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>lc)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,lc);return ua(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 en(t,e){return new Xf(t,e)}const{schedule:er}=ka(queueMicrotask,!1),Ze={x:!1,y:!1};function dc(){return Ze.x||Ze.y}function Yf(t){return t==="x"||t==="y"?Ze[t]?null:(Ze[t]=!0,()=>{Ze[t]=!1}):Ze.x||Ze.y?null:(Ze.x=Ze.y=!0,()=>{Ze.x=Ze.y=!1})}function uc(t,e){const n=qf(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function hc(t){return!(t.pointerType==="touch"||dc())}function Zf(t,e,n={}){const[i,s,o]=uc(t,n),r=a=>{if(!hc(a))return;const{target:c}=a,l=e(c,a);if(typeof l!="function"||!c)return;const u=d=>{hc(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const fc=(t,e)=>e?t===e?!0:fc(t,e.parentElement):!1,tr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Jf=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Qf(t){return Jf.has(t.tagName)||t.tabIndex!==-1}const _i=new WeakSet;function pc(t){return e=>{e.key==="Enter"&&t(e)}}function nr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const ep=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=pc(()=>{if(_i.has(n))return;nr(n,"down");const s=pc(()=>{nr(n,"up")}),o=()=>nr(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 mc(t){return tr(t)&&!dc()}function tp(t,e,n={}){const[i,s,o]=uc(t,n),r=a=>{const c=a.currentTarget;if(!mc(a))return;_i.add(c);const l=e(c,a),u=(g,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",m),_i.has(c)&&_i.delete(c),mc(g)&&typeof l=="function"&&l(g,{success:y})},d=g=>{u(g,c===window||c===document||n.useGlobalTarget||fc(c,g.target))},m=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",m,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Ys(a)&&(a.addEventListener("focus",l=>ep(l,s)),!Qf(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function gc(t){return la(t)&&"ownerSVGElement"in t}function np(t){return gc(t)&&t.tagName==="svg"}const Ae=t=>!!(t&&t.getVelocity),ip=[...ic,ye,xt],sp=t=>ip.find(nc(t)),Mn=Pt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class rp extends Ye{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=Ys(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 op({children:t,isPresent:e,anchorX:n,root:i}){const s=ns(),o=ke(null),r=ke({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=we(Mn);return $o(()=>{const{width:c,height:l,top:u,left:d,right:m}=r.current;if(e||!o.current||!c||!l)return;const g=n==="left"?`left: ${d}`:`right: ${m}`;o.current.dataset.motionPopId=s;const y=document.createElement("style");a&&(y.nonce=a);const k=i??document.head;return k.appendChild(y),y.sheet&&y.sheet.insertRule(`
1
+ (function(){"use strict";var gn,K,eo,It,to,no,io,so,zi,Wi,qi,ro,vn={},oo=[],bu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_n=Array.isArray;function tt(t,e){for(var n in e)t[n]=e[n];return t}function Ki(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function He(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?gn.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 yn(t,r,i,s,null)}function yn(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??++eo,__i:-1,__u:0};return s==null&&K.vnode!=null&&K.vnode(o),o}function Xe(t){return t.children}function Ye(t,e){this.props=t,this.context=e}function Kt(t,e){if(e==null)return t.__?Kt(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"?Kt(t):null}function ao(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 ao(t)}}function Xi(t){(!t.__d&&(t.__d=!0)&&It.push(t)&&!ti.__r++||to!=K.debounceRendering)&&((to=K.debounceRendering)||no)(ti)}function ti(){for(var t,e,n,i,s,o,r,a=1;It.length;)It.length>a&&It.sort(io),t=It.shift(),a=It.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=tt({},i)).__v=i.__v+1,K.vnode&&K.vnode(n),Yi(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??Kt(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,fo(o,n,r),n.__e!=s&&ao(n)));ti.__r=0}function co(t,e,n,i,s,o,r,a,c,l,u){var d,p,g,y,k,x,b=i&&i.__k||oo,S=e.length;for(c=wu(n,e,b,c,S),d=0;d<S;d++)(g=n.__k[d])!=null&&(p=g.__i==-1?vn:b[g.__i]||vn,g.__i=d,x=Yi(t,g,p,s,o,r,a,c,l,u),y=g.__e,g.ref&&p.ref!=g.ref&&(p.ref&&Zi(p.ref,null,g),u.push(g.ref,g.__c||y,g)),k==null&&y!=null&&(k=y),4&g.__u||p.__k===g.__k?c=lo(g,c,t):typeof g.type=="function"&&x!==void 0?c=x:y&&(c=y.nextSibling),g.__u&=-7);return n.__e=k,c}function wu(t,e,n,i,s){var o,r,a,c,l,u=n.length,d=u,p=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(c=o+p,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?yn(null,r,null,null,null):_n(r)?yn(Xe,{children:r},null,null,null):r.constructor==null&&r.__b>0?yn(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(l=r.__i=xu(r,n,c,d))!=-1&&(d--,(a=n[l])&&(a.__u|=2)),a==null||a.__v==null?(l==-1&&(s>u?p--:s<u&&p++),typeof r.type!="function"&&(r.__u|=4)):l!=c&&(l==c-1?p--:l==c+1?p++:(l>c?p--:p++,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=Kt(a)),mo(a,a));return i}function lo(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=lo(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=Kt(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function nt(t,e){return e=e||[],t==null||typeof t=="boolean"||(_n(t)?t.some(function(n){nt(n,e)}):e.push(t)),e}function xu(t,e,n,i){var s,o,r=t.key,a=t.type,c=e[n];if(c===null&&t.key==null||c&&r==c.key&&a==c.type&&(2&c.__u)==0)return n;if(i>(c!=null&&(2&c.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((c=e[s])&&(2&c.__u)==0&&r==c.key&&a==c.type)return s;s--}if(o<e.length){if((c=e[o])&&(2&c.__u)==0&&r==c.key&&a==c.type)return o;o++}}return-1}function uo(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||bu.test(e)?n:n+"px"}function ni(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||uo(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||uo(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(so,"$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=zi,t.addEventListener(e,o?qi:Wi,o)):t.removeEventListener(e,o?qi:Wi,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 ho(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=zi++;else if(e.t<n.u)return;return n(K.event?K.event(e):e)}}}function Yi(t,e,n,i,s,o,r,a,c,l){var u,d,p,g,y,k,x,b,S,C,I,M,O,_,w,f,m,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(c=!!(32&n.__u),o=[a=e.__e=n.__e]),(u=K.__b)&&u(e);e:if(typeof h=="function")try{if(b=e.props,S="prototype"in h&&h.prototype.render,C=(u=h.contextType)&&i[u.__c],I=u?C?C.props.value:u.__:i,n.__c?x=(d=e.__c=n.__c).__=d.__E:(S?e.__c=d=new h(b,I):(e.__c=d=new Ye(b,I),d.constructor=h,d.render=ku),C&&C.sub(d),d.props=b,d.state||(d.state={}),d.context=I,d.__n=i,p=d.__d=!0,d.__h=[],d._sb=[]),S&&d.__s==null&&(d.__s=d.state),S&&h.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=tt({},d.__s)),tt(d.__s,h.getDerivedStateFromProps(b,d.__s))),g=d.props,y=d.state,d.__v=e,p)S&&h.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),S&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(S&&h.getDerivedStateFromProps==null&&b!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(b,I),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(b,d.__s,I)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(d.props=b,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(v){v&&(v.__=e)}),M=0;M<d._sb.length;M++)d.__h.push(d._sb[M]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(b,d.__s,I),S&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,k)})}if(d.context=I,d.props=b,d.__P=t,d.__e=!1,O=K.__r,_=0,S){for(d.state=d.__s,d.__d=!1,O&&O(e),u=d.render(d.props,d.state,d.context),w=0;w<d._sb.length;w++)d.__h.push(d._sb[w]);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&&++_<25);d.state=d.__s,d.getChildContext!=null&&(i=tt(tt({},i),d.getChildContext())),S&&!p&&d.getSnapshotBeforeUpdate!=null&&(k=d.getSnapshotBeforeUpdate(g,y)),f=u,u!=null&&u.type===Xe&&u.key==null&&(f=po(u.props.children)),a=co(t,_n(f)?f:[f],e,n,i,s,o,r,a,c,l),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),x&&(d.__E=d.__=null)}catch(v){if(e.__v=null,c||o!=null)if(v.then){for(e.__u|=c?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--;)Ki(o[m]);else e.__e=n.__e,e.__k=n.__k;K.__e(v,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Su(n.__e,e,n,i,s,o,r,c,l);return(u=K.diffed)&&u(e),128&e.__u?void 0:a}function fo(t,e,n){for(var i=0;i<n.length;i++)Zi(n[i],n[++i],n[++i]);K.__c&&K.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){K.__e(o,s.__v)}})}function po(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:_n(t)?t.map(po):tt({},t)}function Su(t,e,n,i,s,o,r,a,c){var l,u,d,p,g,y,k,x=n.props,b=e.props,S=e.type;if(S=="svg"?s="http://www.w3.org/2000/svg":S=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(l=0;l<o.length;l++)if((g=o[l])&&"setAttribute"in g==!!S&&(S?g.localName==S:g.nodeType==3)){t=g,o[l]=null;break}}if(t==null){if(S==null)return document.createTextNode(b);t=document.createElementNS(s,S,b.is&&b),a&&(K.__m&&K.__m(e,o),a=!1),o=null}if(S==null)x===b||a&&t.data==b||(t.data=b);else{if(o=o&&gn.call(t.childNodes),x=n.props||vn,!a&&o!=null)for(x={},l=0;l<t.attributes.length;l++)x[(g=t.attributes[l]).name]=g.value;for(l in x)if(g=x[l],l!="children"){if(l=="dangerouslySetInnerHTML")d=g;else if(!(l in b)){if(l=="value"&&"defaultValue"in b||l=="checked"&&"defaultChecked"in b)continue;ni(t,l,null,g,s)}}for(l in b)g=b[l],l=="children"?p=g:l=="dangerouslySetInnerHTML"?u=g:l=="value"?y=g:l=="checked"?k=g:a&&typeof g!="function"||x[l]===g||ni(t,l,g,x[l],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),co(e.type=="template"?t.content:t,_n(p)?p:[p],e,n,i,S=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&Kt(n,0),a,c),o!=null)for(l=o.length;l--;)Ki(o[l]);a||(l="value",S=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[l]||S=="progress"&&!y||S=="option"&&y!=x[l])&&ni(t,l,y,x[l],s),l="checked",k!=null&&k!=t[l]&&ni(t,l,k,x[l],s))}return t}function Zi(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){K.__e(s,n)}}function mo(t,e,n){var i,s;if(K.unmount&&K.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||Zi(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){K.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&mo(i[s],e,n||typeof t.type!="function");n||Ki(t.__e),t.__c=t.__=t.__e=void 0}function ku(t,e,n){return this.constructor(t,n)}function ii(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),K.__&&K.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],Yi(e,t=(!i&&n||e).__k=He(Xe,null,[t]),s||vn,vn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?gn.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),fo(o,t,r)}function go(t,e){ii(t,e,go)}function Ji(t,e,n){var i,s,o,r,a=tt({},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?gn.call(arguments,2):n),yn(t.type,a,i||t.key,s||t.ref,null)}function Pt(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,Xi(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"+ro++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}gn=oo.slice,K={__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}},eo=0,Ye.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=tt({},this.state),typeof t=="function"&&(t=t(tt({},n),this.props)),t&&tt(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Xi(this))},Ye.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Xi(this))},Ye.prototype.render=Xe,It=[],no=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,io=function(t,e){return t.__v.__b-e.__v.__b},ti.__r=0,so=/(PointerCapture)$|Capture$/i,zi=0,Wi=ho(!1),qi=ho(!0),ro=0;var Cu=0;function E(t,e,n,i,s,o){e||(e={});var r,a,c=e;if("ref"in c)for(a in c={},e)a=="ref"?r=e[a]:c[a]=e[a];var l={type:t,props:c,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Cu,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)c[a]===void 0&&(c[a]=r[a]);return K.vnode&&K.vnode(l),l}function Qi(){return(Qi=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 Tu=["context","children"];function Eu(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},c=Object.keys(i);for(r=0;r<c.length;r++)s.indexOf(o=c[r])>=0||(a[o]=i[o]);return a}(t,Tu);return Ji(e,n)}function Au(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=He(Eu,Qi({},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,c=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[vo(a[r].name)]=a[r].value);for(r=c.length;r--;){var l=e(c[r],null),u=c[r].slot;u?o[u]=He(_o,{name:u},l):s[r]=l}var d=i?He(_o,null,s):s;return He(i||n.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?go:ii)(this._vdom,this._root)}function vo(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function Iu(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[vo(t)]=n,this._vdom=Ji(this._vdom,i),ii(this._vdom,this._root)}}function Pu(){ii(this._vdom=null,this._root)}function _o(t,e){var n=this;return He("slot",Qi({},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 Ru(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=Au,s.prototype.attributeChangedCallback=Iu,s.prototype.disconnectedCallback=Pu,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 yt,ae,es,yo,bn=0,bo=[],pe=K,wo=pe.__b,xo=pe.__r,So=pe.diffed,ko=pe.__c,Co=pe.unmount,To=pe.__;function Xt(t,e){pe.__h&&pe.__h(ae,t,bn||e),bn=0;var n=ae.__H||(ae.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Re(t){return bn=1,Eo(Io,t)}function Eo(t,e,n){var i=Xt(yt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Io(void 0,e),function(a){var c=i.__N?i.__N[0]:i.__[0],l=i.t(c,a);c!==l&&(i.__N=[l,i.__[1]],i.__c.setState({}))}],i.__c=ae,!ae.__f)){var s=function(a,c,l){if(!i.__c.__H)return!0;var u=i.__c.__H.__.filter(function(p){return!!p.__c});if(u.every(function(p){return!p.__N}))return!o||o.call(this,a,c,l);var d=i.__c.props!==a;return u.forEach(function(p){if(p.__N){var g=p.__[0];p.__=p.__N,p.__N=void 0,g!==p.__[0]&&(d=!0)}}),o&&o.call(this,a,c,l)||d};ae.__f=!0;var o=ae.shouldComponentUpdate,r=ae.componentWillUpdate;ae.componentWillUpdate=function(a,c,l){if(this.__e){var u=o;o=void 0,s(a,c,l),o=u}r&&r.call(this,a,c,l)},ae.shouldComponentUpdate=s}return i.__N||i.__}function Ne(t,e){var n=Xt(yt++,3);!pe.__s&&ss(n.__H,e)&&(n.__=t,n.u=e,ae.__H.__h.push(n))}function ts(t,e){var n=Xt(yt++,4);!pe.__s&&ss(n.__H,e)&&(n.__=t,n.u=e,ae.__h.push(n))}function ke(t){return bn=5,it(function(){return{current:t}},[])}function it(t,e){var n=Xt(yt++,7);return ss(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function si(t,e){return bn=8,it(function(){return t},e)}function we(t){var e=ae.context[t.__c],n=Xt(yt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ae)),e.props.value):t.__}function Mu(t,e){pe.useDebugValue&&pe.useDebugValue(e?e(t):t)}function ns(){var t=Xt(yt++,11);if(!t.__){for(var e=ae.__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 Lu(){for(var t;t=bo.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ri),t.__H.__h.forEach(is),t.__H.__h=[]}catch(e){t.__H.__h=[],pe.__e(e,t.__v)}}pe.__b=function(t){ae=null,wo&&wo(t)},pe.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),To&&To(t,e)},pe.__r=function(t){xo&&xo(t),yt=0;var e=(ae=t.__c).__H;e&&(es===ae?(e.__h=[],ae.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ri),e.__h.forEach(is),e.__h=[],yt=0)),es=ae},pe.diffed=function(t){So&&So(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(bo.push(e)!==1&&yo===pe.requestAnimationFrame||((yo=pe.requestAnimationFrame)||Du)(Lu)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),es=ae=null},pe.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ri),n.__h=n.__h.filter(function(i){return!i.__||is(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],pe.__e(i,n.__v)}}),ko&&ko(t,e)},pe.unmount=function(t){Co&&Co(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{ri(i)}catch(s){e=s}}),n.__H=void 0,e&&pe.__e(e,n.__v))};var Ao=typeof requestAnimationFrame=="function";function Du(t){var e,n=function(){clearTimeout(i),Ao&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ao&&(e=requestAnimationFrame(n))}function ri(t){var e=ae,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ae=e}function is(t){var e=ae;t.__c=t.__(),ae=e}function ss(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Io(t,e){return typeof e=="function"?e(t):e}const wn={},Po=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ro=t=>"init"in t,rs=t=>!!t.write,Mo=t=>"v"in t||"e"in t,oi=t=>{if("e"in t)throw t.e;if((wn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},ai=new WeakMap,Lo=t=>{var e;return ci(t)&&!!((e=ai.get(t))!=null&&e[0])},Ou=t=>{const e=ai.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Do=(t,e)=>{let n=ai.get(t);if(!n){n=[!0,new Set],ai.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},ci=t=>typeof(t==null?void 0:t.then)=="function",Oo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},os=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(ci(e))for(const r of i.d.keys())Oo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,ci(o)&&Ou(o))},No=(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},Nu=()=>{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,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},Vu=t=>(t.c||(t.c=as()),t.m||(t.m=as()),t.u||(t.u=as()),t.f||(t.f=Nu()),t),Fu=Symbol(),Vo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(p,...g)=>p.read(...g),c=(p,...g)=>p.write(...g),l=(p,g)=>{var y;return(y=p.unstable_onInit)==null?void 0:y.call(p,g)},u=(p,g)=>{var y;return(y=p.onMount)==null?void 0:y.call(p,g)},...d)=>{const p=d[0]||(_=>{if((wn?"production":void 0)!=="production"&&!_)throw new Error("Atom is undefined or null");let w=t.get(_);return w||(w={d:new Map,p:new Set,n:0},t.set(_,w),l==null||l(_,O)),w}),g=d[1]||(()=>{const _=[],w=f=>{try{f()}catch(m){_.push(m)}};do{r.f&&w(r.f);const f=new Set,m=f.add.bind(f);i.forEach(h=>{var v;return(v=e.get(h))==null?void 0:v.l.forEach(m)}),i.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),f.forEach(w),i.size&&y()}while(i.size||o.size||s.size);if(_.length)throw new AggregateError(_)}),y=d[2]||(()=>{const _=[],w=new WeakSet,f=new WeakSet,m=Array.from(i);for(;m.length;){const h=m[m.length-1],v=p(h);if(f.has(h)){m.pop();continue}if(w.has(h)){if(n.get(h)===v.n)_.push([h,v]);else if((wn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");f.add(h),m.pop();continue}w.add(h);for(const T of No(h,v,e))w.has(T)||m.push(T)}for(let h=_.length-1;h>=0;--h){const[v,T]=_[h];let P=!1;for(const A of T.d.keys())if(A!==v&&i.has(A)){P=!0;break}P&&(k(v),S(v)),n.delete(v)}}),k=d[3]||(_=>{var w;const f=p(_);if(Mo(f)&&(e.has(_)&&n.get(_)!==f.n||Array.from(f.d).every(([R,V])=>k(R).n===V)))return f;f.d.clear();let m=!0;const h=()=>{e.has(_)&&(S(_),y(),g())},v=R=>{var V;if(Po(_,R)){const B=p(R);if(!Mo(B))if(Ro(R))os(R,R.init,p);else throw new Error("no atom init");return oi(B)}const X=k(R);try{return oi(X)}finally{f.d.set(R,X.n),Lo(f.v)&&Oo(_,f.v,X),(V=e.get(R))==null||V.t.add(_),m||h()}};let T,P;const A={get signal(){return T||(T=new AbortController),T.signal},get setSelf(){return(wn?"production":void 0)!=="production"&&!rs(_)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&rs(_)&&(P=(...R)=>{if((wn?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return b(_,...R)}finally{y(),g()}}),P}},L=f.n;try{const R=a(_,v,A);return os(_,R,p),ci(R)&&(Do(R,()=>T==null?void 0:T.abort()),R.then(h,h)),f}catch(R){return delete f.v,f.e=R,++f.n,f}finally{m=!1,L!==f.n&&n.get(_)===L&&(n.set(_,f.n),i.add(_),(w=r.c)==null||w.call(r,_))}}),x=d[4]||(_=>{const w=[_];for(;w.length;){const f=w.pop(),m=p(f);for(const h of No(f,m,e)){const v=p(h);n.set(h,v.n),w.push(h)}}}),b=d[5]||((_,...w)=>{let f=!0;const m=v=>oi(k(v)),h=(v,...T)=>{var P;const A=p(v);try{if(Po(_,v)){if(!Ro(v))throw new Error("atom not writable");const L=A.n,R=T[0];os(v,R,p),S(v),L!==A.n&&(i.add(v),(P=r.c)==null||P.call(r,v),x(v));return}else return b(v,...T)}finally{f||(y(),g())}};try{return c(_,m,h,...w)}finally{f=!1}}),S=d[6]||(_=>{var w;const f=p(_),m=e.get(_);if(m&&!Lo(f.v)){for(const[h,v]of f.d)if(!m.d.has(h)){const T=p(h);C(h).t.add(_),m.d.add(h),v!==T.n&&(i.add(h),(w=r.c)==null||w.call(r,h),x(h))}for(const h of m.d||[])if(!f.d.has(h)){m.d.delete(h);const v=I(h);v==null||v.t.delete(_)}}}),C=d[7]||(_=>{var w;const f=p(_);let m=e.get(_);if(!m){k(_);for(const h of f.d.keys())C(h).t.add(_);if(m={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(_,m),(w=r.m)==null||w.call(r,_),rs(_)){const h=()=>{let v=!0;const T=(...P)=>{try{return b(_,...P)}finally{v||(y(),g())}};try{const P=u(_,T);P&&(m.u=()=>{v=!0;try{P()}finally{v=!1}})}finally{v=!1}};s.add(h)}}return m}),I=d[8]||(_=>{var w;const f=p(_);let m=e.get(_);if(m&&!m.l.size&&!Array.from(m.t).some(h=>{var v;return(v=e.get(h))==null?void 0:v.d.has(_)})){m.u&&o.add(m.u),m=void 0,e.delete(_),(w=r.u)==null||w.call(r,_);for(const h of f.d.keys()){const v=I(h);v==null||v.t.delete(_)}return}return m}),M=[t,e,n,i,s,o,r,a,c,l,u,p,g,y,k,x,b,S,C,I],O={get:_=>oi(k(_)),set:(_,...w)=>{try{return b(_,...w)}finally{y(),g()}},sub:(_,w)=>{const m=C(_).l;return m.add(w),g(),()=>{m.delete(w),I(_),g()}}};return Object.defineProperty(O,Fu,{value:M}),O},Bu=Vu,Fo=Do,cs={};let ju=0;function ls(t,e){const n=`atom${++ju}`,i={toString(){return(cs?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=$u,i.write=Uu),i}function $u(t){return t(this)}function Uu(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const Hu=()=>{let t=0;const e=Bu({}),n=new WeakMap,i=new WeakMap,s=Vo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,c,l,...u)=>t?l(a,...u):a.write(c,l,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const c=n.get(a);c.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const c=n.get(a);delete c.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 c={read:()=>null,write:(l,u)=>{++t;try{for(const[d,p]of a)"init"in d&&u(d,p)}finally{--t}}};s.set(c)}})};function Gu(){return(cs?"production":void 0)!=="production"?Hu():Vo()}let xn;function zu(){return xn||(xn=Gu(),(cs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=xn),globalThis.__JOTAI_DEFAULT_STORE__!==xn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),xn}function Bo(t,e){for(var n in e)t[n]=e[n];return t}function jo(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 $o=ts;function Uo(t,e){this.props=t,this.context=e}(Uo.prototype=new Ye).isPureReactComponent=!0,Uo.prototype.shouldComponentUpdate=function(t,e){return jo(this.props,t)||jo(this.state,e)};var Ho=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ho&&Ho(t)};var Wu=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function qu(t){function e(n){var i=Bo({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Wu,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Go=function(t,e){return t==null?null:nt(nt(t).map(e))},Ku={map:Go,forEach:Go,count:function(t){return t?nt(t).length:0},only:function(t){var e=nt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:nt},Xu=K.__e;K.__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)}Xu(t,e,n,i)};var zo=K.unmount;function Wo(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=Bo({},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 Wo(i,e,n)})),t}function qo(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return qo(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 ds(){this.__u=0,this.o=null,this.__b=null}function Ko(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function li(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),zo&&zo(t)},(ds.prototype=new Ye).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=Ko(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 c=i.state.__a;i.__v.__k[0]=qo(c,c.__c.__P,c.__c.__O)}var l;for(i.setState({__a:i.__b=null});l=i.o.pop();)l.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},ds.prototype.componentWillUnmount=function(){this.o=[]},ds.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]=Wo(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&He(Xe,null,t.fallback);return s&&(s.__u&=-33),[He(Xe,null,e.__a?null:t.children),s]};var Xo=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]}};(li.prototype=new Ye).__a=function(t){var e=this,n=Ko(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),Xo(e,t,i)):s()};n?n(o):o()}},li.prototype.render=function(t){this.i=null,this.l=new Map;var e=nt(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},li.prototype.componentDidUpdate=li.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){Xo(t,n,e)})};var Yo=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Yu=/^(?: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]/,Zu=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ju=/[A-Z0-9]/g,Qu=typeof document<"u",eh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};Ye.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(Ye.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Zo=K.event;function th(){}function nh(){return this.cancelBubble}function ih(){return this.defaultPrevented}K.event=function(t){return Zo&&(t=Zo(t)),t.persist=th,t.isPropagationStopped=nh,t.isDefaultPrevented=ih,t.nativeEvent=t};var sh={enumerable:!1,configurable:!0,get:function(){return this.class}},Jo=K.vnode;K.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||Qu&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var c=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?r="ondblclick":c!=="onchange"||i!=="input"&&i!=="textarea"||eh(n.type)?c==="onfocus"?r="onfocusin":c==="onblur"?r="onfocusout":Zu.test(r)&&(r=c):c=r="oninput":o&&Yu.test(r)?r=r.replace(Ju,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&s[r=c]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=nt(n.children).forEach(function(l){l.props.selected=s.value.indexOf(l.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=nt(n.children).forEach(function(l){l.props.selected=s.multiple?s.defaultValue.indexOf(l.props.value)!=-1:s.defaultValue==l.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",sh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=Yo,Jo&&Jo(t)};var Qo=K.__r;K.__r=function(t){Qo&&Qo(t),t.__c};var ea=K.diffed;K.diffed=function(t){ea&&ea(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 ta(t){return!!t&&t.$$typeof===Yo}function rh(t){return ta(t)?Ji.apply(null,arguments):t}var na={};const oh={},ah=Pt(void 0);function ia(t){return we(ah)||zu()}const us=t=>typeof(t==null?void 0:t.then)=="function",hs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},ch=na.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(hs(t),t)}),fs=new WeakMap,sa=(t,e)=>{let n=fs.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=l=>u=>{o===l&&i(u)},a=l=>u=>{o===l&&s(u)},c=()=>{try{const l=e();us(l)?(fs.set(l,n),o=l,l.then(r(l),a(l)),Fo(l,c)):i(l)}catch(l){s(l)}};t.then(r(t),a(t)),Fo(t,c)}),fs.set(t,n)),n};function ra(t,e){const{delay:n,unstable_promiseStatus:i=!na.use}={},s=ia(),[[o,r,a],c]=Eo(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 l=o;if((r!==s||a!==t)&&(c(),l=s.get(t)),Ne(()=>{const u=s.sub(t,()=>{if(i)try{const d=s.get(t);us(d)&&hs(sa(d,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(c,n);return}c()});return c(),u},[s,t,n,i]),Mu(l),us(l)){const u=sa(l,()=>s.get(t));return i&&hs(u),ch(u)}return l}function ps(t,e){const n=ia();return si((...s)=>{if((oh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function oa(t,e){return[ra(t),ps(t)]}const ms=Pt({});function di(t){const e=ke(null);return e.current===null&&(e.current=t()),e.current}const gs=typeof window<"u",aa=gs?ts:Ne,ui=Pt(null);function vs(t,e){t.indexOf(e)===-1&&t.push(e)}function _s(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const ht=(t,e,n)=>n>e?e:n<t?t:n;let ys=()=>{};const ft={},ca=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function la(t){return typeof t=="object"&&t!==null}const da=t=>/^0[^.\s]+$/u.test(t);function bs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ge=t=>t,lh=(t,e)=>n=>e(t(n)),Sn=(...t)=>t.reduce(lh),kn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class ws{constructor(){this.subscriptions=[]}add(e){return vs(this.subscriptions,e),()=>_s(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 st=t=>t*1e3,rt=t=>t/1e3;function ua(t,e){return e?t*(1e3/e):0}const ha=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,dh=1e-7,uh=12;function hh(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=ha(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>dh&&++a<uh);return r}function Cn(t,e,n,i){if(t===e&&n===i)return Ge;const s=o=>hh(o,0,1,t,n);return o=>o===0||o===1?o:ha(s(o),e,i)}const fa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,pa=t=>e=>1-t(1-e),ma=Cn(.33,1.53,.69,.99),xs=pa(ma),ga=fa(xs),va=t=>(t*=2)<1?.5*xs(t):.5*(2-Math.pow(2,-10*(t-1))),Ss=t=>1-Math.sin(Math.acos(t)),_a=pa(Ss),ya=fa(Ss),fh=Cn(.42,0,1,1),ph=Cn(0,0,.58,1),ba=Cn(.42,0,.58,1),mh=t=>Array.isArray(t)&&typeof t[0]!="number",wa=t=>Array.isArray(t)&&typeof t[0]=="number",gh={linear:Ge,easeIn:fh,easeInOut:ba,easeOut:ph,circIn:Ss,circInOut:ya,circOut:_a,backIn:xs,backInOut:ga,backOut:ma,anticipate:va},vh=t=>typeof t=="string",xa=t=>{if(wa(t)){ys(t.length===4);const[e,n,i,s]=t;return Cn(e,n,i,s)}else if(vh(t))return gh[t];return t},hi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Sa={value:null};function _h(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},c=0;function l(d){r.has(d)&&(u.schedule(d),t()),c++,d(a)}const u={schedule:(d,p=!1,g=!1)=>{const k=g&&s?n:i;return p&&r.add(d),k.has(d)||k.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(l),e&&Sa.value&&Sa.value.frameloop[e].push(c),c=0,n.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const yh=40;function ka(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=hi.reduce((C,I)=>(C[I]=_h(o,e?I:void 0),C),{}),{setup:a,read:c,resolveKeyframes:l,preUpdate:u,update:d,preRender:p,render:g,postRender:y}=r,k=()=>{const C=ft.useManualTiming?s.timestamp:performance.now();n=!1,ft.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(C-s.timestamp,yh),1)),s.timestamp=C,s.isProcessing=!0,a.process(s),c.process(s),l.process(s),u.process(s),d.process(s),p.process(s),g.process(s),y.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(k))},x=()=>{n=!0,i=!0,s.isProcessing||t(k)};return{schedule:hi.reduce((C,I)=>{const M=r[I];return C[I]=(O,_=!1,w=!1)=>(n||x(),M.schedule(O,_,w)),C},{}),cancel:C=>{for(let I=0;I<hi.length;I++)r[hi[I]].cancel(C)},state:s,steps:r}}const{schedule:de,cancel:bt,state:Ce,steps:ks}=ka(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ge,!0);let fi;function bh(){fi=void 0}const Ve={now:()=>(fi===void 0&&Ve.set(Ce.isProcessing||ft.useManualTiming?Ce.timestamp:performance.now()),fi),set:t=>{fi=t,queueMicrotask(bh)}},Ca=t=>e=>typeof e=="string"&&e.startsWith(t),Cs=Ca("--"),wh=Ca("var(--"),Ts=t=>wh(t)?xh.test(t.split("/*")[0].trim()):!1,xh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Yt={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Tn={...Yt,transform:t=>ht(0,1,t)},pi={...Yt,default:1},En=t=>Math.round(t*1e5)/1e5,Es=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Sh(t){return t==null}const kh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,As=(t,e)=>n=>!!(typeof n=="string"&&kh.test(n)&&n.startsWith(t)||e&&!Sh(n)&&Object.prototype.hasOwnProperty.call(n,e)),Ta=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Es);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Ch=t=>ht(0,255,t),Is={...Yt,transform:t=>Math.round(Ch(t))},Rt={test:As("rgb","red"),parse:Ta("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Is.transform(t)+", "+Is.transform(e)+", "+Is.transform(n)+", "+En(Tn.transform(i))+")"};function Th(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 Ps={test:As("#"),parse:Th,transform:Rt.transform},An=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),wt=An("deg"),ot=An("%"),H=An("px"),Eh=An("vh"),Ah=An("vw"),Ea={...ot,parse:t=>ot.parse(t)/100,transform:t=>ot.transform(t*100)},Zt={test:As("hsl","hue"),parse:Ta("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ot.transform(En(e))+", "+ot.transform(En(n))+", "+En(Tn.transform(i))+")"},ye={test:t=>Rt.test(t)||Ps.test(t)||Zt.test(t),parse:t=>Rt.test(t)?Rt.parse(t):Zt.test(t)?Zt.parse(t):Ps.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Rt.transform(t):Zt.transform(t),getAnimatableNone:t=>{const e=ye.parse(t);return e.alpha=0,ye.transform(e)}},Ih=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Ph(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Es))==null?void 0:e.length)||0)+(((n=t.match(Ih))==null?void 0:n.length)||0)>0}const Aa="number",Ia="color",Rh="var",Mh="var(",Pa="${}",Lh=/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 In(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(Lh,c=>(ye.test(c)?(i.color.push(o),s.push(Ia),n.push(ye.parse(c))):c.startsWith(Mh)?(i.var.push(o),s.push(Rh),n.push(c)):(i.number.push(o),s.push(Aa),n.push(parseFloat(c))),++o,Pa)).split(Pa);return{values:n,split:a,indexes:i,types:s}}function Ra(t){return In(t).values}function Ma(t){const{split:e,types:n}=In(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===Aa?o+=En(s[r]):a===Ia?o+=ye.transform(s[r]):o+=s[r]}return o}}const Dh=t=>typeof t=="number"?0:ye.test(t)?ye.getAnimatableNone(t):t;function Oh(t){const e=Ra(t);return Ma(t)(e.map(Dh))}const xt={test:Ph,parse:Ra,createTransformer:Ma,getAnimatableNone:Oh};function Rs(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 Nh({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,c=2*n-a;s=Rs(c,a,t+1/3),o=Rs(c,a,t),r=Rs(c,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function mi(t,e){return n=>n>0?e:t}const me=(t,e,n)=>t+(e-t)*n,Ms=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},Vh=[Ps,Rt,Zt],Fh=t=>Vh.find(e=>e.test(t));function La(t){const e=Fh(t);if(!e)return!1;let n=e.parse(t);return e===Zt&&(n=Nh(n)),n}const Da=(t,e)=>{const n=La(t),i=La(e);if(!n||!i)return mi(t,e);const s={...n};return o=>(s.red=Ms(n.red,i.red,o),s.green=Ms(n.green,i.green,o),s.blue=Ms(n.blue,i.blue,o),s.alpha=me(n.alpha,i.alpha,o),Rt.transform(s))},Ls=new Set(["none","hidden"]);function Bh(t,e){return Ls.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function jh(t,e){return n=>me(t,e,n)}function Ds(t){return typeof t=="number"?jh:typeof t=="string"?Ts(t)?mi:ye.test(t)?Da:Hh:Array.isArray(t)?Oa:typeof t=="object"?ye.test(t)?Da:$h:mi}function Oa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ds(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function $h(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Ds(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function Uh(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 Hh=(t,e)=>{const n=xt.createTransformer(e),i=In(t),s=In(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?Ls.has(t)&&!s.values.length||Ls.has(e)&&!i.values.length?Bh(t,e):Sn(Oa(Uh(i,s),s.values),n):mi(t,e)};function Na(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?me(t,e,n):Ds(t)(t,e)}const Gh=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>de.update(e,n),stop:()=>bt(e),now:()=>Ce.isProcessing?Ce.timestamp:Ve.now()}},Va=(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)})`},gi=2e4;function Os(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<gi;)e+=n,i=t.next(e);return e>=gi?1/0:e}function zh(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Os(i),gi);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:rt(s)}}const Wh=5;function Fa(t,e,n){const i=Math.max(e-Wh,0);return ua(n-t(i),e-i)}const ge={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},Ns=.001;function qh({duration:t=ge.duration,bounce:e=ge.bounce,velocity:n=ge.velocity,mass:i=ge.mass}){let s,o,r=1-e;r=ht(ge.minDamping,ge.maxDamping,r),t=ht(ge.minDuration,ge.maxDuration,rt(t)),r<1?(s=l=>{const u=l*r,d=u*t,p=u-n,g=Vs(l,r),y=Math.exp(-d);return Ns-p/g*y},o=l=>{const d=l*r*t,p=d*n+n,g=Math.pow(r,2)*Math.pow(l,2)*t,y=Math.exp(-d),k=Vs(Math.pow(l,2),r);return(-s(l)+Ns>0?-1:1)*((p-g)*y)/k}):(s=l=>{const u=Math.exp(-l*t),d=(l-n)*t+1;return-Ns+u*d},o=l=>{const u=Math.exp(-l*t),d=(n-l)*(t*t);return u*d});const a=5/t,c=Xh(s,o,a);if(t=st(t),isNaN(c))return{stiffness:ge.stiffness,damping:ge.damping,duration:t};{const l=Math.pow(c,2)*i;return{stiffness:l,damping:r*2*Math.sqrt(i*l),duration:t}}}const Kh=12;function Xh(t,e,n){let i=n;for(let s=1;s<Kh;s++)i=i-t(i)/e(i);return i}function Vs(t,e){return t*Math.sqrt(1-e*e)}const Yh=["duration","bounce"],Zh=["stiffness","damping","mass"];function Ba(t,e){return e.some(n=>t[n]!==void 0)}function Jh(t){let e={velocity:ge.velocity,stiffness:ge.stiffness,damping:ge.damping,mass:ge.mass,isResolvedFromDuration:!1,...t};if(!Ba(t,Zh)&&Ba(t,Yh))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*ht(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ge.mass,stiffness:s,damping:o}}else{const n=qh(t);e={...e,...n,mass:ge.mass},e.isResolvedFromDuration=!0}return e}function vi(t=ge.visualDuration,e=ge.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:c,damping:l,mass:u,duration:d,velocity:p,isResolvedFromDuration:g}=Jh({...n,velocity:-rt(n.velocity||0)}),y=p||0,k=l/(2*Math.sqrt(c*u)),x=r-o,b=rt(Math.sqrt(c/u)),S=Math.abs(x)<5;i||(i=S?ge.restSpeed.granular:ge.restSpeed.default),s||(s=S?ge.restDelta.granular:ge.restDelta.default);let C;if(k<1){const M=Vs(b,k);C=O=>{const _=Math.exp(-k*b*O);return r-_*((y+k*b*x)/M*Math.sin(M*O)+x*Math.cos(M*O))}}else if(k===1)C=M=>r-Math.exp(-b*M)*(x+(y+b*x)*M);else{const M=b*Math.sqrt(k*k-1);C=O=>{const _=Math.exp(-k*b*O),w=Math.min(M*O,300);return r-_*((y+k*b*x)*Math.sinh(w)+M*x*Math.cosh(w))/M}}const I={calculatedDuration:g&&d||null,next:M=>{const O=C(M);if(g)a.done=M>=d;else{let _=M===0?y:0;k<1&&(_=M===0?st(y):Fa(C,M,O));const w=Math.abs(_)<=i,f=Math.abs(r-O)<=s;a.done=w&&f}return a.value=a.done?r:O,a},toString:()=>{const M=Math.min(Os(I),gi),O=Va(_=>I.next(M*_).value,M,30);return M+"ms "+O},toTransition:()=>{}};return I}vi.applyToOptions=t=>{const e=zh(t,100,vi);return t.ease=e.ease,t.duration=st(e.duration),t.type="keyframes",t};function Fs({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:c,restDelta:l=.5,restSpeed:u}){const d=t[0],p={done:!1,value:d},g=w=>a!==void 0&&w<a||c!==void 0&&w>c,y=w=>a===void 0?c:c===void 0||Math.abs(a-w)<Math.abs(c-w)?a:c;let k=n*e;const x=d+k,b=r===void 0?x:r(x);b!==x&&(k=b-d);const S=w=>-k*Math.exp(-w/i),C=w=>b+S(w),I=w=>{const f=S(w),m=C(w);p.done=Math.abs(f)<=l,p.value=p.done?b:m};let M,O;const _=w=>{g(p.value)&&(M=w,O=vi({keyframes:[p.value,y(p.value)],velocity:Fa(C,w,p.value),damping:s,stiffness:o,restDelta:l,restSpeed:u}))};return _(0),{calculatedDuration:null,next:w=>{let f=!1;return!O&&M===void 0&&(f=!0,I(w),_(w)),M!==void 0&&w>=M?O.next(w-M):(!f&&I(w),p)}}}function Qh(t,e,n){const i=[],s=n||ft.mix||Na,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const c=Array.isArray(e)?e[r]||Ge:e;a=Sn(c,a)}i.push(a)}return i}function ef(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(ys(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=Qh(e,i,s),c=a.length,l=u=>{if(r&&u<t[0])return e[0];let d=0;if(c>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const p=kn(t[d],t[d+1],u);return a[d](p)};return n?u=>l(ht(t[0],t[o-1],u)):l}function tf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=kn(0,e,i);t.push(me(n,1,s))}}function nf(t){const e=[0];return tf(e,t.length-1),e}function sf(t,e){return t.map(n=>n*e)}function rf(t,e){return t.map(()=>e||ba).splice(0,t.length-1)}function Pn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=mh(i)?i.map(xa):xa(i),o={done:!1,value:e[0]},r=sf(n&&n.length===e.length?n:nf(e),t),a=ef(r,e,{ease:Array.isArray(s)?s:rf(e,s)});return{calculatedDuration:t,next:c=>(o.value=a(c),o.done=c>=t,o)}}const of=t=>t!==null;function Bs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(of),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const af={decay:Fs,inertia:Fs,tween:Pn,keyframes:Pn,spring:vi};function ja(t){typeof t.type=="string"&&(t.type=af[t.type])}class js{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 cf=t=>t/100;class $s extends js{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!==Ve.now()&&this.tick(Ve.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;ja(e);const{type:n=Pn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const c=n||Pn;c!==Pn&&typeof a[0]!="number"&&(this.mixKeyframes=Sn(cf,Na(a[0],a[1])),a=[0,100]);const l=c({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=c({...e,keyframes:[...a].reverse(),velocity:-r})),l.calculatedDuration===null&&(l.calculatedDuration=Os(l));const{calculatedDuration:u}=l;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=l}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:c}=this;if(this.startTime===null)return i.next(0);const{delay:l=0,keyframes:u,repeat:d,repeatType:p,repeatDelay:g,type:y,onUpdate:k,finalKeyframe:x}=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 b=this.currentTime-l*(this.playbackSpeed>=0?1:-1),S=this.playbackSpeed>=0?b<0:b>s;this.currentTime=Math.max(b,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let C=this.currentTime,I=i;if(d){const w=Math.min(this.currentTime,s)/a;let f=Math.floor(w),m=w%1;!m&&w>=1&&(m=1),m===1&&f--,f=Math.min(f,d+1),!!(f%2)&&(p==="reverse"?(m=1-m,g&&(m-=g/a)):p==="mirror"&&(I=r)),C=ht(0,1,m)*a}const M=S?{done:!1,value:u[0]}:I.next(C);o&&(M.value=o(M.value));let{done:O}=M;!S&&c!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const _=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return _&&y!==Fs&&(M.value=Bs(u,this.options,x,this.speed)),k&&k(M.value),_&&this.finish(),M}then(e,n){return this.finished.then(e,n)}get duration(){return rt(this.calculatedDuration)}get time(){return rt(this.currentTime)}set time(e){var n;e=st(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(Ve.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=rt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Gh,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(Ve.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 lf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Mt=t=>t*180/Math.PI,Us=t=>{const e=Mt(Math.atan2(t[1],t[0]));return Hs(e)},df={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Us,rotateZ:Us,skewX:t=>Mt(Math.atan(t[1])),skewY:t=>Mt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Hs=t=>(t=t%360,t<0&&(t+=360),t),$a=Us,Ua=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ha=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),uf={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ua,scaleY:Ha,scale:t=>(Ua(t)+Ha(t))/2,rotateX:t=>Hs(Mt(Math.atan2(t[6],t[5]))),rotateY:t=>Hs(Mt(Math.atan2(-t[2],t[0]))),rotateZ:$a,rotate:$a,skewX:t=>Mt(Math.atan(t[4])),skewY:t=>Mt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Gs(t){return t.includes("scale")?1:0}function zs(t,e){if(!t||t==="none")return Gs(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=uf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=df,s=a}if(!s)return Gs(e);const o=i[e],r=s[1].split(",").map(ff);return typeof o=="function"?o(r):r[o]}const hf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return zs(n,e)};function ff(t){return parseFloat(t.trim())}const Jt=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Qt=new Set(Jt),Ga=t=>t===Yt||t===H,pf=new Set(["x","y","z"]),mf=Jt.filter(t=>!pf.has(t));function gf(t){const e=[];return mf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Lt={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})=>zs(e,"x"),y:(t,{transform:e})=>zs(e,"y")};Lt.translateX=Lt.x,Lt.translateY=Lt.y;const Dt=new Set;let Ws=!1,qs=!1,Ks=!1;function za(){if(qs){const t=Array.from(Dt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=gf(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)})}qs=!1,Ws=!1,Dt.forEach(t=>t.complete(Ks)),Dt.clear()}function Wa(){Dt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(qs=!0)})}function vf(){Ks=!0,Wa(),za(),Ks=!1}class Xs{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?(Dt.add(this),Ws||(Ws=!0,de.read(Wa),de.resolveKeyframes(za))):(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])}lf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Dt.delete(this)}cancel(){this.state==="scheduled"&&(Dt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const _f=t=>t.startsWith("--");function yf(t,e,n){_f(e)?t.style.setProperty(e,n):t.style[e]=n}const bf=bs(()=>window.ScrollTimeline!==void 0),wf={};function xf(t,e){const n=bs(t);return()=>wf[e]??n()}const qa=xf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Rn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,Ka={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Rn([0,.65,.55,1]),circOut:Rn([.55,0,1,.45]),backIn:Rn([.31,.01,.66,-.59]),backOut:Rn([.33,1.53,.69,.99])};function Xa(t,e){if(t)return typeof t=="function"?qa()?Va(t,e):"ease-out":wa(t)?Rn(t):Array.isArray(t)?t.map(n=>Xa(n,e)||Ka.easeOut):Ka[t]}function Sf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:c}={},l=void 0){const u={[e]:n};c&&(u.offset=c);const d=Xa(a,s);Array.isArray(d)&&(u.easing=d);const p={delay:i,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return l&&(p.pseudoElement=l),t.animate(u,p)}function Ya(t){return typeof t=="function"&&"applyToOptions"in t}function kf({type:t,...e}){return Ya(t)&&qa()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Cf extends js{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:c}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,ys(typeof e.type!="string");const l=kf(e);this.animation=Sf(n,i,s,l,o),l.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Bs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):yf(n,i,u),this.animation.cancel()}c==null||c(),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 rt(Number(e))}get time(){return rt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=st(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&&bf()?(this.animation.timeline=e,Ge):n(this)}}const Za={anticipate:va,backInOut:ga,circInOut:ya};function Tf(t){return t in Za}function Ef(t){typeof t.ease=="string"&&Tf(t.ease)&&(t.ease=Za[t.ease])}const Ja=10;class Af extends Cf{constructor(e){Ef(e),ja(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 $s({...r,autoplay:!1}),c=st(this.finishedTime??this.time);n.setWithVelocity(a.sample(c-Ja).value,a.sample(c).value,Ja),a.stop()}}const Qa=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(xt.test(t)||t==="0")&&!t.startsWith("url("));function If(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 Pf(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=Qa(s,e),a=Qa(o,e);return!r||!a?!1:If(t)||(n==="spring"||Ya(n))&&i}function Ys(t){return la(t)&&"offsetHeight"in t}const Rf=new Set(["opacity","clipPath","filter","transform"]),Mf=bs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Lf(t){var l;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!Ys((l=e==null?void 0:e.owner)==null?void 0:l.current))return!1;const{onUpdate:a,transformTemplate:c}=e.owner.getProps();return Mf()&&n&&Rf.has(n)&&(n!=="transform"||!c)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const Df=40;class Of extends js{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:c,motionValue:l,element:u,...d}){var y;super(),this.stop=()=>{var k,x;this._animation&&(this._animation.stop(),(k=this.stopTimeline)==null||k.call(this)),(x=this.keyframeResolver)==null||x.cancel()},this.createdAt=Ve.now();const p={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:c,motionValue:l,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Xs;this.keyframeResolver=new g(a,(k,x,b)=>this.onKeyframesResolved(k,x,p,!b),c,l,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:c,isHandoff:l,onUpdate:u}=i;this.resolvedAt=Ve.now(),Pf(e,o,r,a)||((ft.instantAnimations||!c)&&(u==null||u(Bs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const p={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>Df?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},g=!l&&Lf(p)?new Af({...p,element:p.motionValue.owner.current}):new $s(p);g.finished.then(()=>this.notifyFinished()).catch(Ge),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(),vf()),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 Nf=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Vf(t){const e=Nf.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function ec(t,e,n=1){const[i,s]=Vf(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return ca(r)?parseFloat(r):r}return Ts(s)?ec(s,e,n+1):s}function Zs(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const tc=new Set(["width","height","top","left","right","bottom",...Jt]),Ff={test:t=>t==="auto",parse:t=>t},nc=t=>e=>e.test(t),ic=[Yt,H,ot,wt,Ah,Eh,Ff],sc=t=>ic.find(nc(t));function Bf(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||da(t):!0}const jf=new Set(["brightness","contrast","saturate","opacity"]);function $f(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Es)||[];if(!i)return t;const s=n.replace(i,"");let o=jf.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const Uf=/\b([a-z-]*)\(.*?\)/gu,Js={...xt,getAnimatableNone:t=>{const e=t.match(Uf);return e?e.map($f).join(" "):t}},rc={...Yt,transform:Math.round},Qs={borderWidth:H,borderTopWidth:H,borderRightWidth:H,borderBottomWidth:H,borderLeftWidth:H,borderRadius:H,radius:H,borderTopLeftRadius:H,borderTopRightRadius:H,borderBottomRightRadius:H,borderBottomLeftRadius:H,width:H,maxWidth:H,height:H,maxHeight:H,top:H,right:H,bottom:H,left:H,padding:H,paddingTop:H,paddingRight:H,paddingBottom:H,paddingLeft:H,margin:H,marginTop:H,marginRight:H,marginBottom:H,marginLeft:H,backgroundPositionX:H,backgroundPositionY:H,...{rotate:wt,rotateX:wt,rotateY:wt,rotateZ:wt,scale:pi,scaleX:pi,scaleY:pi,scaleZ:pi,skew:wt,skewX:wt,skewY:wt,distance:H,translateX:H,translateY:H,translateZ:H,x:H,y:H,z:H,perspective:H,transformPerspective:H,opacity:Tn,originX:Ea,originY:Ea,originZ:H},zIndex:rc,fillOpacity:Tn,strokeOpacity:Tn,numOctaves:rc},Hf={...Qs,color:ye,backgroundColor:ye,outlineColor:ye,fill:ye,stroke:ye,borderColor:ye,borderTopColor:ye,borderRightColor:ye,borderBottomColor:ye,borderLeftColor:ye,filter:Js,WebkitFilter:Js},oc=t=>Hf[t];function ac(t,e){let n=oc(t);return n!==Js&&(n=xt),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const Gf=new Set(["auto","none","0"]);function zf(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!Gf.has(o)&&In(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=ac(n,s)}class Wf extends Xs{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 c=0;c<e.length;c++){let l=e[c];if(typeof l=="string"&&(l=l.trim(),Ts(l))){const u=ec(l,n.current);u!==void 0&&(e[c]=u),c===e.length-1&&(this.finalKeyframe=l)}}if(this.resolveNoneKeyframes(),!tc.has(i)||e.length!==2)return;const[s,o]=e,r=sc(s),a=sc(o);if(r!==a)if(Ga(r)&&Ga(a))for(let c=0;c<e.length;c++){const l=e[c];typeof l=="string"&&(e[c]=parseFloat(l))}else Lt[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||Bf(e[s]))&&i.push(s);i.length&&zf(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=Lt[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]=Lt[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(([c,l])=>{e.getValue(c).set(l)}),this.resolveNoneKeyframes()}}function qf(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 cc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,lc=30,Kf=t=>!isNaN(parseFloat(t));class Xf{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Ve.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 c of this.dependents)c.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=Ve.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Kf(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 ws);const i=this.events[e].add(n);return e==="change"?()=>{i(),de.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=Ve.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>lc)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,lc);return ua(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 en(t,e){return new Xf(t,e)}const{schedule:er}=ka(queueMicrotask,!1),Ze={x:!1,y:!1};function dc(){return Ze.x||Ze.y}function Yf(t){return t==="x"||t==="y"?Ze[t]?null:(Ze[t]=!0,()=>{Ze[t]=!1}):Ze.x||Ze.y?null:(Ze.x=Ze.y=!0,()=>{Ze.x=Ze.y=!1})}function uc(t,e){const n=qf(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function hc(t){return!(t.pointerType==="touch"||dc())}function Zf(t,e,n={}){const[i,s,o]=uc(t,n),r=a=>{if(!hc(a))return;const{target:c}=a,l=e(c,a);if(typeof l!="function"||!c)return;const u=d=>{hc(d)&&(l(d),c.removeEventListener("pointerleave",u))};c.addEventListener("pointerleave",u,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const fc=(t,e)=>e?t===e?!0:fc(t,e.parentElement):!1,tr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Jf=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Qf(t){return Jf.has(t.tagName)||t.tabIndex!==-1}const _i=new WeakSet;function pc(t){return e=>{e.key==="Enter"&&t(e)}}function nr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const ep=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=pc(()=>{if(_i.has(n))return;nr(n,"down");const s=pc(()=>{nr(n,"up")}),o=()=>nr(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 mc(t){return tr(t)&&!dc()}function tp(t,e,n={}){const[i,s,o]=uc(t,n),r=a=>{const c=a.currentTarget;if(!mc(a))return;_i.add(c);const l=e(c,a),u=(g,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",p),_i.has(c)&&_i.delete(c),mc(g)&&typeof l=="function"&&l(g,{success:y})},d=g=>{u(g,c===window||c===document||n.useGlobalTarget||fc(c,g.target))},p=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",p,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Ys(a)&&(a.addEventListener("focus",l=>ep(l,s)),!Qf(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function gc(t){return la(t)&&"ownerSVGElement"in t}function np(t){return gc(t)&&t.tagName==="svg"}const Ae=t=>!!(t&&t.getVelocity),ip=[...ic,ye,xt],sp=t=>ip.find(nc(t)),Mn=Pt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class rp extends Ye{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=Ys(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 op({children:t,isPresent:e,anchorX:n,root:i}){const s=ns(),o=ke(null),r=ke({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=we(Mn);return $o(()=>{const{width:c,height:l,top:u,left:d,right:p}=r.current;if(e||!o.current||!c||!l)return;const g=n==="left"?`left: ${d}`:`right: ${p}`;o.current.dataset.motionPopId=s;const y=document.createElement("style");a&&(y.nonce=a);const k=i??document.head;return k.appendChild(y),y.sheet&&y.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${c}px !important;
@@ -6,14 +6,14 @@
6
6
  ${g}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{k.removeChild(y),k.contains(y)&&k.removeChild(y)}},[e]),E(rp,{isPresent:e,childRef:o,sizeRef:r,children:rh(t,{ref:o})})}const ap=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:c})=>{const l=di(cp),u=ns();let d=!0,m=it(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:g=>{l.set(g,!0);for(const y of l.values())if(!y)return;i&&i()},register:g=>(l.set(g,!1),()=>l.delete(g))}),[n,l,i]);return o&&d&&(m={...m}),it(()=>{l.forEach((g,y)=>l.set(y,!1))},[n]),Ne(()=>{!n&&!l.size&&i&&i()},[n]),r==="popLayout"&&(t=E(op,{isPresent:n,anchorX:a,root:c,children:t})),E(ui.Provider,{value:m,children:t})};function cp(){return new Map}function vc(t=!0){const e=we(ui);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=ns();Ne(()=>{if(t)return s(o)},[t]);const r=si(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const yi=t=>t.key||"";function _c(t){const e=[];return Ku.forEach(t,n=>{ta(n)&&e.push(n)}),e}const lp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:c})=>{const[l,u]=vc(r),d=it(()=>_c(t),[t]),m=r&&!l?[]:d.map(yi),g=ke(!0),y=ke(d),k=di(()=>new Map),[x,b]=Re(d),[S,C]=Re(d);aa(()=>{g.current=!1,y.current=d;for(let O=0;O<S.length;O++){const _=yi(S[O]);m.includes(_)?k.delete(_):k.get(_)!==!0&&k.set(_,!1)}},[S,m.length,m.join("-")]);const A=[];if(d!==x){let O=[...d];for(let _=0;_<S.length;_++){const w=S[_],f=yi(w);m.includes(f)||(O.splice(_,0,w),A.push(w))}return o==="wait"&&A.length&&(O=A),C(_c(O)),b(d),null}const{forceRender:M}=we(ms);return E(Xe,{children:S.map(O=>{const _=yi(O),w=r&&!l?!1:d===S||m.includes(_),f=()=>{if(k.has(_))k.set(_,!0);else return;let p=!0;k.forEach(h=>{h||(p=!1)}),p&&(M==null||M(),C(y.current),r&&(u==null||u()),i&&i())};return E(ap,{isPresent:w,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:c,onExitComplete:w?void 0:f,anchorX:a,children:O},_)})})},yc=Pt({strict:!1}),bc={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"]},tn={};for(const t in bc)tn[t]={isEnabled:e=>bc[t].some(n=>!!e[n])};function dp(t){for(const e in t)tn[e]={...tn[e],...t[e]}}const up=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 bi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||up.has(t)}let wc=t=>!bi(t);function xc(t){typeof t=="function"&&(wc=e=>e.startsWith("on")?!bi(e):t(e))}try{xc(require("@emotion/is-prop-valid").default)}catch{}function hp(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(wc(s)||n===!0&&bi(s)||!e&&!bi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function fp({children:t,isValidProp:e,...n}){e&&xc(e),n={...we(Mn),...n},n.isStatic=di(()=>n.isStatic);const i=it(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return E(Mn.Provider,{value:i,children:t})}function pp(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 wi=Pt({});function xi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ln(t){return typeof t=="string"||Array.isArray(t)}const ir=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],sr=["initial",...ir];function Si(t){return xi(t.animate)||sr.some(e=>Ln(t[e]))}function Sc(t){return!!(Si(t)||t.variants)}function mp(t,e){if(Si(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Ln(n)?n:void 0,animate:Ln(i)?i:void 0}}return t.inherit!==!1?e:{}}function gp(t){const{initial:e,animate:n}=mp(t,we(wi));return it(()=>({initial:e,animate:n}),[kc(e),kc(n)])}function kc(t){return Array.isArray(t)?t.join(" "):t}const vp=Symbol.for("motionComponentSymbol");function nn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function _p(t,e,n){return si(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):nn(n)&&(n.current=i))},[e])}const rr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Cc="data-"+rr("framerAppearId"),Tc=Pt({});function yp(t,e,n,i,s){var k,x;const{visualElement:o}=we(wi),r=we(yc),a=we(ui),c=we(Mn).reducedMotion,l=ke(null);i=i||r.renderer,!l.current&&i&&(l.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=we(Tc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&bp(l.current,n,s,d);const m=ke(!1);$o(()=>{u&&m.current&&u.update(n,a)});const g=n[Cc],y=ke(!!g&&!((k=window.MotionHandoffIsComplete)!=null&&k.call(window,g))&&((x=window.MotionHasOptimisedAnimation)==null?void 0:x.call(window,g)));return aa(()=>{u&&(m.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),er.render(u.render),y.current&&u.animationState&&u.animationState.animateChanges())}),Ne(()=>{u&&(!y.current&&u.animationState&&u.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,g)}),y.current=!1))}),u}function bp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Ec(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&nn(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function Ec(t){if(t)return t.options.allowProjection!==!1?t.projection:Ec(t.parent)}function wp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&dp(t);function o(a,c){let l;const u={...we(Mn),...a,layoutId:xp(a)},{isStatic:d}=u,m=gp(a),g=i(a,d);if(!d&&gs){Sp();const y=kp(u);l=y.MeasureLayout,m.visualElement=yp(s,g,u,e,y.ProjectionNode)}return E(wi.Provider,{value:m,children:[l&&m.visualElement?E(l,{visualElement:m.visualElement,...u}):null,n(s,a,_p(g,m.visualElement,c),g,d,m.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=qu(o);return r[vp]=s,r}function xp({layoutId:t}){const e=we(ms).id;return e&&t!==void 0?e+"-"+t:t}function Sp(t,e){we(yc).strict}function kp(t){const{drag:e,layout:n}=tn;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 Dn={};function Cp(t){for(const e in t)Dn[e]=t[e],Cs(e)&&(Dn[e].isCSSVariable=!0)}function Ac(t,{layout:e,layoutId:n}){return Qt.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Dn[t]||t==="opacity")}const Tp={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Ep=Jt.length;function Ap(t,e,n){let i="",s=!0;for(let o=0;o<Ep;o++){const r=Jt[o],a=t[r];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(r.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const l=cc(a,Qs[r]);if(!c){s=!1;const u=Tp[r]||r;i+=`${u}(${l}) `}n&&(e[r]=l)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function or(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const c in e){const l=e[c];if(Qt.has(c)){r=!0;continue}else if(Cs(c)){s[c]=l;continue}else{const u=cc(l,Qs[c]);c.startsWith("origin")?(a=!0,o[c]=u):i[c]=u}}if(e.transform||(r||n?i.transform=Ap(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:u=0}=o;i.transformOrigin=`${c} ${l} ${u}`}}const ar=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ic(t,e,n){for(const i in e)!Ae(e[i])&&!Ac(i,n)&&(t[i]=e[i])}function Ip({transformTemplate:t},e){return it(()=>{const n=ar();return or(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Pp(t,e){const n=t.style||{},i={};return Ic(i,n,t),Object.assign(i,Ip(t,e)),i}function Rp(t,e){const n={},i=Pp(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 Mp={offset:"stroke-dashoffset",array:"stroke-dasharray"},Lp={offset:"strokeDashoffset",array:"strokeDasharray"};function Dp(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?Mp:Lp;t[o.offset]=H.transform(-i);const r=H.transform(e),a=H.transform(n);t[o.array]=`${r} ${a}`}function Pc(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},c,l,u){if(or(t,a,l),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:m}=t;d.transform&&(m.transform=d.transform,delete d.transform),(m.transform||d.transformOrigin)&&(m.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),m.transform&&(m.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&&Dp(d,s,o,r,!1)}const Rc=()=>({...ar(),attrs:{}}),Mc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Op(t,e,n,i){const s=it(()=>{const o=Rc();return Pc(o,e,Mc(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Ic(o,t.style,t),s.style={...o,...s.style}}return s}const Np=["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 cr(t){return typeof t!="string"||t.includes("-")?!1:!!(Np.indexOf(t)>-1||/[A-Z]/u.test(t))}function Vp(t=!1){return(n,i,s,{latestValues:o},r)=>{const c=(cr(n)?Op:Rp)(i,o,r,n),l=hp(i,typeof n=="string",t),u=n!==Xe?{...l,...c,ref:s}:{},{children:d}=i,m=it(()=>Ae(d)?d.get():d,[d]);return He(n,{...u,children:m})}}function Lc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function lr(t,e,n,i){if(typeof e=="function"){const[s,o]=Lc(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]=Lc(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function ki(t){return Ae(t)?t.get():t}function Fp({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Bp(n,i,s,t),renderState:e()}}const Dc=t=>(e,n)=>{const i=we(wi),s=we(ui),o=()=>Fp(t,e,i,s);return n?o():di(o)};function Bp(t,e,n,i){const s={},o=i(t,{});for(const m in o)s[m]=ki(o[m]);let{initial:r,animate:a}=t;const c=Si(t),l=Sc(t);e&&l&&!c&&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"&&!xi(d)){const m=Array.isArray(d)?d:[d];for(let g=0;g<m.length;g++){const y=lr(t,m[g]);if(y){const{transitionEnd:k,transition:x,...b}=y;for(const S in b){let C=b[S];if(Array.isArray(C)){const A=u?C.length-1:0;C=C[A]}C!==null&&(s[S]=C)}for(const S in k)s[S]=k[S]}}}return s}function dr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Ae(i[r])||e.style&&Ae(e.style[r])||Ac(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const jp={useVisualState:Dc({scrapeMotionValuesFromProps:dr,createRenderState:ar})};function Oc(t,e,n){const i=dr(t,e,n);for(const s in t)if(Ae(t[s])||Ae(e[s])){const o=Jt.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const $p={useVisualState:Dc({scrapeMotionValuesFromProps:Oc,createRenderState:Rc})};function Up(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...cr(i)?$p:jp,preloadedFeatures:t,useRender:Vp(s),createVisualElement:e,Component:i};return wp(r)}}function On(t,e,n){const i=t.getProps();return lr(i,e,n!==void 0?n:i.custom,t)}const ur=t=>Array.isArray(t);function Hp(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,en(n))}function Gp(t){return ur(t)?t[t.length-1]||0:t}function zp(t,e){const n=On(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=Gp(o[r]);Hp(t,r,a)}}function Wp(t){return!!(Ae(t)&&t.add)}function hr(t,e){const n=t.getValue("willChange");if(Wp(n))return n.add(e);if(!n&&ft.WillChange){const i=new ft.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Nc(t){return t.props[Cc]}const qp=t=>t!==null;function Kp(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(qp),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Xp={type:"spring",stiffness:500,damping:25,restSpeed:10},Yp=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Zp={type:"keyframes",duration:.8},Jp={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Qp=(t,{keyframes:e})=>e.length>2?Zp:Qt.has(t)?t.startsWith("scale")?Yp(e[1]):Xp:Jp;function em({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const fr=(t,e,n,i={},s,o)=>r=>{const a=Zs(i,t)||{},c=a.delay||i.delay||0;let{elapsed:l=0}=i;l=l-st(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-l,onUpdate:m=>{e.set(m),a.onUpdate&&a.onUpdate(m)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};em(a)||Object.assign(u,Qp(t,u)),u.duration&&(u.duration=st(u.duration)),u.repeatDelay&&(u.repeatDelay=st(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)),(ft.instantAnimations||ft.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const m=Kp(u.keyframes,a);if(m!==void 0){de.update(()=>{u.onUpdate(m),u.onComplete()});return}}return a.isSync?new $s(u):new Of(u)};function tm({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 c=[],l=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),m=a[u];if(m===void 0||l&&tm(l,u))continue;const g={delay:n,...Zs(o||{},u)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(m)&&m===y&&!g.velocity)continue;let k=!1;if(window.MotionHandoffAnimation){const b=Nc(t);if(b){const S=window.MotionHandoffAnimation(b,u,de);S!==null&&(g.startTime=S,k=!0)}}hr(t,u),d.start(fr(u,d,m,t.shouldReduceMotion&&tc.has(u)?{type:!1}:g,t,k));const x=d.animation;x&&c.push(x)}return r&&Promise.all(c).then(()=>{de.update(()=>{r&&zp(t,r)})}),c}function pr(t,e,n={}){var c;const i=On(t,e,n.type==="exit"?(c=t.presenceContext)==null?void 0:c.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?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:m}=s;return nm(t,e,l,u,d,m,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[l,u]=a==="beforeChildren"?[o,r]:[r,o];return l().then(()=>u())}else return Promise.all([o(),r(n.delay)])}function nm(t,e,n=0,i=0,s=0,o=1,r){const a=[],c=t.variantChildren.size,l=(c-1)*s,u=typeof i=="function",d=u?m=>i(m,c):o===1?(m=0)=>m*s:(m=0)=>l-m*s;return Array.from(t.variantChildren).sort(im).forEach((m,g)=>{m.notify("AnimationStart",e),a.push(pr(m,e,{...r,delay:n+(u?0:i)+d(g)}).then(()=>m.notify("AnimationComplete",e)))}),Promise.all(a)}function im(t,e){return t.sortNodePosition(e)}function sm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>pr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=pr(t,e,n);else{const s=typeof e=="function"?On(t,e,n.custom):e;i=Promise.all(Vc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Fc(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 rm=sr.length;function Bc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Bc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<rm;n++){const i=sr[n],s=t.props[i];(Ln(s)||s===!1)&&(e[i]=s)}return e}const om=[...ir].reverse(),am=ir.length;function cm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>sm(t,n,i)))}function lm(t){let e=cm(t),n=jc(),i=!0;const s=c=>(l,u)=>{var m;const d=On(t,u,c==="exit"?(m=t.presenceContext)==null?void 0:m.custom:void 0);if(d){const{transition:g,transitionEnd:y,...k}=d;l={...l,...k,...y}}return l};function o(c){e=c(t)}function r(c){const{props:l}=t,u=Bc(t.parent)||{},d=[],m=new Set;let g={},y=1/0;for(let x=0;x<am;x++){const b=om[x],S=n[b],C=l[b]!==void 0?l[b]:u[b],A=Ln(C),M=b===c?S.isActive:null;M===!1&&(y=x);let O=C===u[b]&&C!==l[b]&&A;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),S.protectedKeys={...g},!S.isActive&&M===null||!C&&!S.prevProp||xi(C)||typeof C=="boolean")continue;const _=dm(S.prevProp,C);let w=_||b===c&&S.isActive&&!O&&A||x>y&&A,f=!1;const p=Array.isArray(C)?C:[C];let h=p.reduce(s(b),{});M===!1&&(h={});const{prevResolvedValues:v={}}=S,T={...v,...h},P=R=>{w=!0,m.has(R)&&(f=!0,m.delete(R)),S.needsAnimating[R]=!0;const V=t.getValue(R);V&&(V.liveStyle=!1)};for(const R in T){const V=h[R],X=v[R];if(g.hasOwnProperty(R))continue;let B=!1;ur(V)&&ur(X)?B=!Fc(V,X):B=V!==X,B?V!=null?P(R):m.add(R):V!==void 0&&m.has(R)?P(R):S.protectedKeys[R]=!0}S.prevProp=C,S.prevResolvedValues=h,S.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(w=!1),w&&(!(O&&_)||f)&&d.push(...p.map(R=>({animation:R,options:{type:b}})))}if(m.size){const x={};if(typeof l.initial!="boolean"){const b=On(t,Array.isArray(l.initial)?l.initial[0]:l.initial);b&&b.transition&&(x.transition=b.transition)}m.forEach(b=>{const S=t.getBaseTarget(b),C=t.getValue(b);C&&(C.liveStyle=!0),x[b]=S??null}),d.push({animation:x})}let k=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!t.manuallyAnimateOnMount&&(k=!1),i=!1,k?e(d):Promise.resolve()}function a(c,l){var d;if(n[c].isActive===l)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(m=>{var g;return(g=m.animationState)==null?void 0:g.setActive(c,l)}),n[c].isActive=l;const u=r(c);for(const m in n)n[m].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=jc(),i=!0}}}function dm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Fc(e,t):!1}function Ot(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function jc(){return{animate:Ot(!0),whileInView:Ot(),whileHover:Ot(),whileTap:Ot(),whileDrag:Ot(),whileFocus:Ot(),exit:Ot()}}class St{constructor(e){this.isMounted=!1,this.node=e}update(){}}class um extends St{constructor(e){super(e),e.animationState||(e.animationState=lm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();xi(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 hm=0;class fm extends St{constructor(){super(...arguments),this.id=hm++}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 pm={animation:{Feature:um},exit:{Feature:fm}};function Nn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Vn(t){return{point:{x:t.pageX,y:t.pageY}}}const mm=t=>e=>tr(e)&&t(e,Vn(e));function Fn(t,e,n,i){return Nn(t,e,mm(n),i)}function $c({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 vm(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,_m=1-Uc,ym=1+Uc,Hc=.01,bm=0-Hc,wm=0+Hc;function Me(t){return t.max-t.min}function xm(t,e,n){return Math.abs(t-e)<=n}function Gc(t,e,n,i=.5){t.origin=i,t.originPoint=me(e.min,e.max,t.origin),t.scale=Me(n)/Me(e),t.translate=me(n.min,n.max,t.origin)-t.originPoint,(t.scale>=_m&&t.scale<=ym||isNaN(t.scale))&&(t.scale=1),(t.translate>=bm&&t.translate<=wm||isNaN(t.translate))&&(t.translate=0)}function Bn(t,e,n,i){Gc(t.x,e.x,n.x,i?i.originX:void 0),Gc(t.y,e.y,n.y,i?i.originY:void 0)}function zc(t,e,n){t.min=n.min+e.min,t.max=t.min+Me(e)}function Sm(t,e,n){zc(t.x,e.x,n.x),zc(t.y,e.y,n.y)}function Wc(t,e,n){t.min=e.min-n.min,t.max=t.min+Me(e)}function jn(t,e,n){Wc(t.x,e.x,n.x),Wc(t.y,e.y,n.y)}const qc=()=>({translate:0,scale:1,origin:0,originPoint:0}),sn=()=>({x:qc(),y:qc()}),Kc=()=>({min:0,max:0}),_e=()=>({x:Kc(),y:Kc()});function ze(t){return[t("x"),t("y")]}function mr(t){return t===void 0||t===1}function gr({scale:t,scaleX:e,scaleY:n}){return!mr(t)||!mr(e)||!mr(n)}function Nt(t){return gr(t)||Xc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Xc(t){return Yc(t.x)||Yc(t.y)}function Yc(t){return t&&t!=="0%"}function Ci(t,e,n){const i=t-n,s=e*i;return n+s}function Zc(t,e,n,i,s){return s!==void 0&&(t=Ci(t,s,i)),Ci(t,n,i)+e}function vr(t,e=0,n=1,i,s){t.min=Zc(t.min,e,n,i,s),t.max=Zc(t.max,e,n,i,s)}function Jc(t,{x:e,y:n}){vr(t.x,e.translate,e.scale,e.originPoint),vr(t.y,n.translate,n.scale,n.originPoint)}const Qc=.999999999999,el=1.0000000000001;function km(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:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&on(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Jc(t,r)),i&&Nt(o.latestValues)&&on(t,o.latestValues))}e.x<el&&e.x>Qc&&(e.x=1),e.y<el&&e.y>Qc&&(e.y=1)}function rn(t,e){t.min=t.min+e,t.max=t.max+e}function tl(t,e,n,i,s=.5){const o=me(t.min,t.max,s);vr(t,e,n,o,i)}function on(t,e){tl(t.x,e.x,e.scaleX,e.scale,e.originX),tl(t.y,e.y,e.scaleY,e.scale,e.originY)}function nl(t,e){return $c(vm(t.getBoundingClientRect(),e))}function Cm(t,e,n){const i=nl(t,n),{scroll:s}=e;return s&&(rn(i.x,s.offset.x),rn(i.y,s.offset.y)),i}const il=({current:t})=>t?t.ownerDocument.defaultView:null,sl=(t,e)=>Math.abs(t-e);function Tm(t,e){const n=sl(t.x,e.x),i=sl(t.y,e.y);return Math.sqrt(n**2+i**2)}class rl{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 m=yr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=Tm(m.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:k}=m,{timestamp:x}=Ce;this.history.push({...k,timestamp:x});const{onStart:b,onMove:S}=this.handlers;g||(b&&b(this.lastMoveEvent,m),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,m)},this.handlePointerMove=(m,g)=>{this.lastMoveEvent=m,this.lastMoveEventInfo=_r(g,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(m,g)=>{this.end();const{onEnd:y,onSessionEnd:k,resumeAnimation:x}=this.handlers;if(this.dragSnapToOrigin&&x&&x(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=yr(m.type==="pointercancel"?this.lastMoveEventInfo:_r(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(m,b),k&&k(m,b)},!tr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Vn(e),c=_r(a,this.transformPagePoint),{point:l}=c,{timestamp:u}=Ce;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,yr(c,this.history)),this.removeListeners=Sn(Fn(this.contextWindow,"pointermove",this.handlePointerMove),Fn(this.contextWindow,"pointerup",this.handlePointerUp),Fn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),bt(this.updatePoint)}}function _r(t,e){return e?{point:e(t.point)}:t}function ol(t,e){return{x:t.x-e.x,y:t.y-e.y}}function yr({point:t},e){return{point:t,delta:ol(t,al(e)),offset:ol(t,Em(e)),velocity:Am(e,.1)}}function Em(t){return t[0]}function al(t){return t[t.length-1]}function Am(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=al(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>st(e)));)n--;if(!i)return{x:0,y:0};const o=rt(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 Im(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?me(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?me(n,t,i.max):Math.min(t,n)),t}function cl(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 Pm(t,{top:e,left:n,bottom:i,right:s}){return{x:cl(t.x,n,s),y:cl(t.y,e,i)}}function ll(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:ll(t.x,e.x),y:ll(t.y,e.y)}}function Mm(t,e){let n=.5;const i=Me(t),s=Me(e);return s>i?n=kn(e.min,e.max-i,t.min):i>s&&(n=kn(t.min,t.max-s,e.min)),ht(0,1,n)}function Lm(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const br=.35;function Dm(t=br){return t===!1?t=0:t===!0&&(t=br),{x:dl(t,"left","right"),y:dl(t,"top","bottom")}}function dl(t,e,n){return{min:ul(t,e),max:ul(t,n)}}function ul(t,e){return typeof t=="number"?t:t[e]||0}const Om=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=_e(),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:m}=this.getProps();m?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Vn(d).point)},r=(d,m)=>{const{drag:g,dragPropagation:y,onDragStart:k}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Yf(g),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ze(b=>{let S=this.getAxisMotionValue(b).get()||0;if(ot.test(S)){const{projection:C}=this.visualElement;if(C&&C.layout){const A=C.layout.layoutBox[b];A&&(S=Me(A)*(parseFloat(S)/100))}}this.originPoint[b]=S}),k&&de.postRender(()=>k(d,m)),hr(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},a=(d,m)=>{this.latestPointerEvent=d,this.latestPanInfo=m;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:k,onDrag:x}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:b}=m;if(y&&this.currentDirection===null){this.currentDirection=Vm(b),this.currentDirection!==null&&k&&k(this.currentDirection);return}this.updateAxis("x",m.point,b),this.updateAxis("y",m.point,b),this.visualElement.render(),x&&x(d,m)},c=(d,m)=>{this.latestPointerEvent=d,this.latestPanInfo=m,this.stop(d,m),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>ze(d=>{var m;return this.getAnimationState(d)==="paused"&&((m=this.getAxisMotionValue(d).animation)==null?void 0:m.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new rl(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:il(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&&de.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||!Ti(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Im(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&&nn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Pm(i.layoutBox,e):this.constraints=!1,this.elastic=Dm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Lm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!nn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Cm(i,s.root,this.visualElement.getTransformPagePoint());let r=Rm(s.layout.layoutBox,o);if(n){const a=n(gm(r));this.hasMutatedConstraints=!!a,a&&(r=$c(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=ze(u=>{if(!Ti(u,n,this.currentDirection))return;let d=c&&c[u]||{};r&&(d={min:0,max:0});const m=s?200:1e6,g=s?40:1e7,y={type:"inertia",velocity:i?e[u]:0,bounceStiffness:m,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,y)});return Promise.all(l).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return hr(this.visualElement,e),i.start(fr(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(!Ti(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]-me(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!nn(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 c=a.get();s[r]=Mm({min:c,max:c},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(!Ti(r,e,null))return;const a=this.getAxisMotionValue(r),{min:c,max:l}=this.constraints[r];a.set(me(c,l,s[r]))})}addListeners(){if(!this.visualElement.current)return;Om.set(this.visualElement,this);const e=this.visualElement.current,n=Fn(e,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps();l&&u&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();nn(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),de.read(i);const r=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(ze(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[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=br,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Ti(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Vm(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 St{constructor(e){super(e),this.removeGroupControls=Ge,this.removeListeners=Ge,this.controls=new Nm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ge}unmount(){this.removeGroupControls(),this.removeListeners()}}const hl=t=>(e,n)=>{t&&de.postRender(()=>t(e,n))};class Bm extends St{constructor(){super(...arguments),this.removePointerDownListener=Ge}onPointerDown(e){this.session=new rl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:il(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:hl(e),onStart:hl(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&de.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=Fn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ei={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function fl(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const $n={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(H.test(t))t=parseFloat(t);else return t;const n=fl(t,e.target.x),i=fl(t,e.target.y);return`${n}% ${i}%`}},jm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=xt.parse(t);if(s.length>5)return i;const o=xt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=c;const l=me(a,c,.5);return typeof s[2+r]=="number"&&(s[2+r]/=l),typeof s[3+r]=="number"&&(s[3+r]/=l),o(s)}};let pl=!1;class $m extends Ye{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Cp(Um),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),pl&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Ei.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,pl=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||de.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),er.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 ml(t){const[e,n]=vc(),i=we(ms);return E($m,{...t,layoutGroup:i,switchLayoutGroup:we(Tc),isPresent:e,safeToRemove:n})}const Um={borderRadius:{...$n,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:$n,borderTopRightRadius:$n,borderBottomLeftRadius:$n,borderBottomRightRadius:$n,boxShadow:jm};function Hm(t,e,n){const i=Ae(t)?t:en(t);return i.start(fr("",i,e,n)),i.animation}const Gm=(t,e)=>t.depth-e.depth;class zm{constructor(){this.children=[],this.isDirty=!1}add(e){vs(this.children,e),this.isDirty=!0}remove(e){_s(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Gm),this.isDirty=!1,this.children.forEach(e)}}function Wm(t,e){const n=Ve.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(bt(i),t(o-e))};return de.setup(i,!0),()=>bt(i)}const gl=["TopLeft","TopRight","BottomLeft","BottomRight"],qm=gl.length,vl=t=>typeof t=="string"?parseFloat(t):t,_l=t=>typeof t=="number"||H.test(t);function Km(t,e,n,i,s,o){s?(t.opacity=me(0,n.opacity??1,Xm(i)),t.opacityExit=me(e.opacity??1,0,Ym(i))):o&&(t.opacity=me(e.opacity??1,n.opacity??1,i));for(let r=0;r<qm;r++){const a=`border${gl[r]}Radius`;let c=yl(e,a),l=yl(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||_l(c)===_l(l)?(t[a]=Math.max(me(vl(c),vl(l),i),0),(ot.test(l)||ot.test(c))&&(t[a]+="%")):t[a]=l}(e.rotate||n.rotate)&&(t.rotate=me(e.rotate||0,n.rotate||0,i))}function yl(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Xm=bl(0,.5,_a),Ym=bl(.5,.95,Ge);function bl(t,e,n){return i=>i<t?0:i>e?1:n(kn(t,e,i))}function wl(t,e){t.min=e.min,t.max=e.max}function We(t,e){wl(t.x,e.x),wl(t.y,e.y)}function xl(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Sl(t,e,n,i,s){return t-=e,t=Ci(t,1/n,i),s!==void 0&&(t=Ci(t,1/s,i)),t}function Zm(t,e=0,n=1,i=.5,s,o=t,r=t){if(ot.test(e)&&(e=parseFloat(e),e=me(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=me(o.min,o.max,i);t===o&&(a-=e),t.min=Sl(t.min,e,n,a,s),t.max=Sl(t.max,e,n,a,s)}function kl(t,e,[n,i,s],o,r){Zm(t,e[n],e[i],e[s],e.scale,o,r)}const Jm=["x","scaleX","originX"],Qm=["y","scaleY","originY"];function Cl(t,e,n,i){kl(t.x,e,Jm,n?n.x:void 0,i?i.x:void 0),kl(t.y,e,Qm,n?n.y:void 0,i?i.y:void 0)}function Tl(t){return t.translate===0&&t.scale===1}function El(t){return Tl(t.x)&&Tl(t.y)}function Al(t,e){return t.min===e.min&&t.max===e.max}function eg(t,e){return Al(t.x,e.x)&&Al(t.y,e.y)}function Il(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Pl(t,e){return Il(t.x,e.x)&&Il(t.y,e.y)}function Rl(t){return Me(t.x)/Me(t.y)}function Ml(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class tg{constructor(){this.members=[]}add(e){vs(this.members,e),e.scheduleRender()}remove(e){if(_s(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 ng(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:l,rotate:u,rotateX:d,rotateY:m,skewX:g,skewY:y}=n;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),m&&(i+=`rotateY(${m}deg) `),g&&(i+=`skewX(${g}deg) `),y&&(i+=`skewY(${y}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const wr=["","X","Y","Z"],ig=1e3;let sg=0;function xr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function Ll(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Nc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&Ll(i)}function Dl({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=sg++,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(ag),this.nodes.forEach(ug),this.nodes.forEach(hg),this.nodes.forEach(cg)},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 c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new zm)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new ws),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const c=this.eventHandlers.get(r);c&&c.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=gc(r)&&!np(r),this.instance=r;const{layoutId:a,layout:c,visualElement:l}=this.options;if(l&&!l.current&&l.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const m=()=>this.root.updateBlockedByResize=!1;de.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=Wm(m,250),Ei.hasAnimatedSinceResize&&(Ei.hasAnimatedSinceResize=!1,this.nodes.forEach(Vl)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:m,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||l.getDefaultTransition()||vg,{onLayoutAnimationStart:k,onLayoutAnimationComplete:x}=l.getProps(),b=!this.targetLayout||!Pl(this.targetLayout,g),S=!d&&m;if(this.options.layoutRoot||this.resumeFrom||S||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...Zs(y,"layout"),onPlay:k,onComplete:x};(l.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(u,S)}else d||Vl(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(),bt(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(fg),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&&Ll(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:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Ol);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Nl);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(dg),this.nodes.forEach(rg),this.nodes.forEach(og)):this.nodes.forEach(Nl),this.clearAllSnapshots();const a=Ve.now();Ce.delta=ht(0,1e3/60,a-Ce.timestamp),Ce.timestamp=a,Ce.isProcessing=!0,ks.update.process(Ce),ks.preRender.process(Ce),ks.render.process(Ce),Ce.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,er.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(lg),this.sharedNodes.forEach(pg)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Me(this.snapshot.measuredBox.x)&&!Me(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 c=0;c<this.path.length;c++)this.path[c].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=_e(),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 c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!El(this.projectionDelta),c=this.getTransformTemplate(),l=c?c(this.latestValues,""):void 0,u=l!==this.prevTransformTemplateValue;r&&this.instance&&(a||Nt(this.latestValues)||u)&&(s(this.instance,l),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return r&&(c=this.removeTransform(c)),_g(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var l;const{visualElement:r}=this.options;if(!r)return _e();const a=r.measureViewportBox();if(!(((l=this.scroll)==null?void 0:l.wasRoot)||this.path.some(yg))){const{scroll:u}=this.root;u&&(rn(a.x,u.offset.x),rn(a.y,u.offset.y))}return a}removeElementScroll(r){var c;const a=_e();if(We(a,r),(c=this.scroll)!=null&&c.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:m}=u;u!==this.root&&d&&m.layoutScroll&&(d.wasRoot&&We(a,r),rn(a.x,d.offset.x),rn(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const c=_e();We(c,r);for(let l=0;l<this.path.length;l++){const u=this.path[l];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&on(c,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Nt(u.latestValues)&&on(c,u.latestValues)}return Nt(this.latestValues)&&on(c,this.latestValues),c}removeTransform(r){const a=_e();We(a,r);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!Nt(l.latestValues))continue;gr(l.latestValues)&&l.updateSnapshot();const u=_e(),d=l.measurePageBox();We(u,d),Cl(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,u)}return Nt(this.latestValues)&&Cl(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!==Ce.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var m;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(r||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Ce.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=_e(),this.relativeTargetOrigin=_e(),jn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),We(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=_e(),this.targetWithTransforms=_e()),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):We(this.target,this.layout.layoutBox),Jc(this.target,this.targetDelta)):We(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=_e(),this.relativeTargetOrigin=_e(),jn(this.relativeTargetOrigin,this.target,g.target),We(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||gr(this.parent.latestValues)||Xc(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 c=!0;if((this.isProjectionDirty||(y=this.parent)!=null&&y.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Ce.timestamp&&(c=!1),c)return;const{layout:l,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||!(l||u))return;We(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,m=this.treeScale.y;km(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=_e());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(xl(this.prevProjectionDelta.x,this.projectionDelta.x),xl(this.prevProjectionDelta.y,this.projectionDelta.y)),Bn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==m||!Ml(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ml(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 c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=sn(),this.projectionDelta=sn(),this.projectionDeltaWithTransform=sn()}setAnimationOrigin(r,a=!1){const c=this.snapshot,l=c?c.latestValues:{},u={...this.latestValues},d=sn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const m=_e(),g=c?c.source:void 0,y=this.layout?this.layout.source:void 0,k=g!==y,x=this.getStack(),b=!x||x.members.length<=1,S=!!(k&&!b&&this.options.crossfade===!0&&!this.path.some(gg));this.animationProgress=0;let C;this.mixTargetDelta=A=>{const M=A/1e3;Fl(d.x,r.x,M),Fl(d.y,r.y,M),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(jn(m,this.layout.layoutBox,this.relativeParent.layout.layoutBox),mg(this.relativeTarget,this.relativeTargetOrigin,m,M),C&&eg(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=_e()),We(C,this.relativeTarget)),k&&(this.animationValues=u,Km(u,l,this.latestValues,M,S,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=M},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,c,l;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(l=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||l.stop(),this.pendingAnimation&&(bt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{Ei.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=en(0)),this.currentAnimation=Hm(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(ig),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:c,layout:l,latestValues:u}=r;if(!(!a||!c||!l)){if(this!==r&&this.layout&&l&&Hl(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||_e();const d=Me(this.layout.layoutBox.x);c.x.min=r.target.x.min,c.x.max=c.x.min+d;const m=Me(this.layout.layoutBox.y);c.y.min=r.target.y.min,c.y.max=c.y.min+m}We(a,c),on(a,u),Bn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new tg),this.sharedNodes.get(r).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.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:c}={}){const l=this.getStack();l&&l.promote(this,c),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:c}=r;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const l={};c.z&&xr("z",r,l,this.animationValues);for(let u=0;u<wr.length;u++)xr(`rotate${wr[u]}`,r,l,this.animationValues),xr(`skew${wr[u]}`,r,l,this.animationValues);r.render();for(const u in l)r.setStaticValue(u,l[u]),this.animationValues&&(this.animationValues[u]=l[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=ki(a==null?void 0:a.pointerEvents)||"",r.transform=c?c(this.latestValues,""):"none";return}const l=this.getLead();if(!this.projectionDelta||!this.layout||!l.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=ki(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Nt(this.latestValues)&&(r.transform=c?c({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=l.animationValues||l.latestValues;this.applyTransformsToTarget();let d=ng(this.projectionDeltaWithTransform,this.treeScale,u);c&&(d=c(u,d)),r.transform=d;const{x:m,y:g}=this.projectionDelta;r.transformOrigin=`${m.origin*100}% ${g.origin*100}% 0`,l.animationValues?r.opacity=l===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=l===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const y in Dn){if(u[y]===void 0)continue;const{correct:k,applyTo:x,isCSSVariable:b}=Dn[y],S=d==="none"?u[y]:k(u[y],l);if(x){const C=x.length;for(let A=0;A<C;A++)r[x[A]]=S}else b?this.options.visualElement.renderState.vars[y]=S:r[y]=S}this.options.layoutId&&(r.pointerEvents=l===this?ki(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(Ol),this.root.sharedNodes.clear()}}}function rg(t){t.updateLayout()}function og(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 m=r?e.measuredBox[d]:e.layoutBox[d],g=Me(m);m.min=i[d].min,m.max=m.min+g}):Hl(o,e.layoutBox,i)&&ze(d=>{const m=r?e.measuredBox[d]:e.layoutBox[d],g=Me(i[d]);m.max=m.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=sn();Bn(a,i,e.layoutBox);const c=sn();r?Bn(c,t.applyTransform(s,!0),e.measuredBox):Bn(c,i,e.layoutBox);const l=!El(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:m,layout:g}=d;if(m&&g){const y=_e();jn(y,e.layoutBox,m.layoutBox);const k=_e();jn(k,i,g.layoutBox),Pl(y,k)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=k,t.relativeTargetOrigin=y,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:c,layoutDelta:a,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function ag(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 cg(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function lg(t){t.clearSnapshot()}function Ol(t){t.clearMeasurements()}function Nl(t){t.isLayoutDirty=!1}function dg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Vl(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ug(t){t.resolveTargetDelta()}function hg(t){t.calcProjection()}function fg(t){t.resetSkewAndRotation()}function pg(t){t.removeLeadSnapshot()}function Fl(t,e,n){t.translate=me(e.translate,0,n),t.scale=me(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Bl(t,e,n,i){t.min=me(e.min,n.min,i),t.max=me(e.max,n.max,i)}function mg(t,e,n,i){Bl(t.x,e.x,n.x,i),Bl(t.y,e.y,n.y,i)}function gg(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const vg={duration:.45,ease:[.4,0,.1,1]},jl=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),$l=jl("applewebkit/")&&!jl("chrome/")?Math.round:Ge;function Ul(t){t.min=$l(t.min),t.max=$l(t.max)}function _g(t){Ul(t.x),Ul(t.y)}function Hl(t,e,n){return t==="position"||t==="preserve-aspect"&&!xm(Rl(e),Rl(n),.2)}function yg(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const bg=Dl({attachResizeListener:(t,e)=>Nn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Sr={current:void 0},Gl=Dl({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Sr.current){const t=new bg({});t.mount(window),t.setOptions({layoutScroll:!0}),Sr.current=t}return Sr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),wg={pan:{Feature:Bm},drag:{Feature:Fm,ProjectionNode:Gl,MeasureLayout:ml}};function zl(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&&de.postRender(()=>o(e,Vn(e)))}class xg extends St{mount(){const{current:e}=this.node;e&&(this.unmount=Zf(e,(n,i)=>(zl(this.node,i,"Start"),s=>zl(this.node,s,"End"))))}unmount(){}}class Sg extends St{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Sn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Wl(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&&de.postRender(()=>o(e,Vn(e)))}class kg extends St{mount(){const{current:e}=this.node;e&&(this.unmount=tp(e,(n,i)=>(Wl(this.node,i,"Start"),(s,{success:o})=>Wl(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const kr=new WeakMap,Cr=new WeakMap,Cg=t=>{const e=kr.get(t.target);e&&e(t)},Tg=t=>{t.forEach(Cg)};function Eg({root:t,...e}){const n=t||document;Cr.has(n)||Cr.set(n,{});const i=Cr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Tg,{root:t,...e})),i[s]}function Ag(t,e,n){const i=Eg(e);return kr.set(t,n),i.observe(t),()=>{kr.delete(t),i.unobserve(t)}}const Ig={some:0,all:1};class Pg extends St{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:Ig[s]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,o&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),m=l?u:d;m&&m(c)};return Ag(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(Rg(e,n))&&this.startObserver()}unmount(){}}function Rg({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Mg={inView:{Feature:Pg},tap:{Feature:kg},focus:{Feature:Sg},hover:{Feature:xg}},Lg={layout:{ProjectionNode:Gl,MeasureLayout:ml}},Tr={current:null},ql={current:!1};function Dg(){if(ql.current=!0,!!gs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Tr.current=t.matches;t.addEventListener("change",e),e()}else Tr.current=!1}const Og=new WeakMap;function Ng(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Ae(s))t.addValue(i,s);else if(Ae(o))t.addValue(i,en(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,en(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const Kl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Vg{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=Xs,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 m=Ve.now();this.renderScheduledAt<m&&(this.renderScheduledAt=m,de.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=r;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,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=Si(n),this.isVariantNode=Sc(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const m in d){const g=d[m];c[m]!==void 0&&Ae(g)&&g.set(c[m],!1)}}mount(e){this.current=e,Og.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)),ql.current||Dg(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Tr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),bt(this.notifyUpdate),bt(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=Qt.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&de.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 tn){const n=tn[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):_e()}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<Kl.length;i++){const s=Kl[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=Ng(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=en(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"&&(ca(i)||da(i))?i=parseFloat(i):!sp(i)&&xt.test(n)&&(i=ac(e,n)),this.setBaseTarget(e,Ae(i)?i.get():i)),Ae(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=lr(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&&!Ae(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 ws),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class Xl extends Vg{constructor(){super(...arguments),this.KeyframeResolver=Wf}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;Ae(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Yl(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 Fg(t){return window.getComputedStyle(t)}class Bg extends Xl{constructor(){super(...arguments),this.type="html",this.renderInstance=Yl}readValueFromInstance(e,n){var i;if(Qt.has(n))return(i=this.projection)!=null&&i.isProjecting?Gs(n):hf(e,n);{const s=Fg(e),o=(Cs(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return nl(e,n)}build(e,n,i){or(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return dr(e,n,i)}}const Zl=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 jg(t,e,n,i){Yl(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(Zl.has(s)?s:rr(s),e.attrs[s])}class $g extends Xl{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=_e}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Qt.has(n)){const i=oc(n);return i&&i.default||0}return n=Zl.has(n)?n:rr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Oc(e,n,i)}build(e,n,i){Pc(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){jg(e,n,i,s)}mount(e){this.isSVGTag=Mc(e.tagName),super.mount(e)}}const Ug=(t,e)=>cr(t)?new $g(e):new Bg(e,{allowProjection:t!==Xe}),Hg=Up({...pm,...Mg,...wg,...Lg},Ug),Un=pp(Hg),Gg=["agent-id","environment","position","version-id","call-destination-number","call-caller-number","call-caller-name","call-custom-headers"],Ai="widget-layout-id";function Jl(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=Jl(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function pt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=Jl(t))&&(i&&(i+=" "),i+=e);return i}const zg=ls("waiting"),Er=()=>oa(zg),Ii={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},Ql=ls(Ii),Wg=()=>{const t=ps(Ql);return si(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Ii.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Ii.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Ii.speak_to_interrupt_text),n}),[t])},Vt=()=>ra(Ql),ed=({size:t="large",className:e})=>{const n=Vt(),[i]=Er();return E("h1",{className:pt({"text-xs":t==="small"},e),children:i==="waiting"?n.speak_to_interrupt_text:i==="processing_image"?"Processing image...":n.agent_thinking_text})},td=({stream:t})=>{const e=ke(null);return Ne(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),E("audio",{muted:!0,ref:e,autoPlay:!0})};/**!
9
+ `),()=>{k.removeChild(y),k.contains(y)&&k.removeChild(y)}},[e]),E(rp,{isPresent:e,childRef:o,sizeRef:r,children:rh(t,{ref:o})})}const ap=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:c})=>{const l=di(cp),u=ns();let d=!0,p=it(()=>(d=!1,{id:u,initial:e,isPresent:n,custom:s,onExitComplete:g=>{l.set(g,!0);for(const y of l.values())if(!y)return;i&&i()},register:g=>(l.set(g,!1),()=>l.delete(g))}),[n,l,i]);return o&&d&&(p={...p}),it(()=>{l.forEach((g,y)=>l.set(y,!1))},[n]),Ne(()=>{!n&&!l.size&&i&&i()},[n]),r==="popLayout"&&(t=E(op,{isPresent:n,anchorX:a,root:c,children:t})),E(ui.Provider,{value:p,children:t})};function cp(){return new Map}function vc(t=!0){const e=we(ui);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=ns();Ne(()=>{if(t)return s(o)},[t]);const r=si(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const yi=t=>t.key||"";function _c(t){const e=[];return Ku.forEach(t,n=>{ta(n)&&e.push(n)}),e}const lp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:c})=>{const[l,u]=vc(r),d=it(()=>_c(t),[t]),p=r&&!l?[]:d.map(yi),g=ke(!0),y=ke(d),k=di(()=>new Map),[x,b]=Re(d),[S,C]=Re(d);aa(()=>{g.current=!1,y.current=d;for(let O=0;O<S.length;O++){const _=yi(S[O]);p.includes(_)?k.delete(_):k.get(_)!==!0&&k.set(_,!1)}},[S,p.length,p.join("-")]);const I=[];if(d!==x){let O=[...d];for(let _=0;_<S.length;_++){const w=S[_],f=yi(w);p.includes(f)||(O.splice(_,0,w),I.push(w))}return o==="wait"&&I.length&&(O=I),C(_c(O)),b(d),null}const{forceRender:M}=we(ms);return E(Xe,{children:S.map(O=>{const _=yi(O),w=r&&!l?!1:d===S||p.includes(_),f=()=>{if(k.has(_))k.set(_,!0);else return;let m=!0;k.forEach(h=>{h||(m=!1)}),m&&(M==null||M(),C(y.current),r&&(u==null||u()),i&&i())};return E(ap,{isPresent:w,initial:!g.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:c,onExitComplete:w?void 0:f,anchorX:a,children:O},_)})})},yc=Pt({strict:!1}),bc={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"]},tn={};for(const t in bc)tn[t]={isEnabled:e=>bc[t].some(n=>!!e[n])};function dp(t){for(const e in t)tn[e]={...tn[e],...t[e]}}const up=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 bi(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||up.has(t)}let wc=t=>!bi(t);function xc(t){typeof t=="function"&&(wc=e=>e.startsWith("on")?!bi(e):t(e))}try{xc(require("@emotion/is-prop-valid").default)}catch{}function hp(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(wc(s)||n===!0&&bi(s)||!e&&!bi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function fp({children:t,isValidProp:e,...n}){e&&xc(e),n={...we(Mn),...n},n.isStatic=di(()=>n.isStatic);const i=it(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return E(Mn.Provider,{value:i,children:t})}function pp(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 wi=Pt({});function xi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ln(t){return typeof t=="string"||Array.isArray(t)}const ir=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],sr=["initial",...ir];function Si(t){return xi(t.animate)||sr.some(e=>Ln(t[e]))}function Sc(t){return!!(Si(t)||t.variants)}function mp(t,e){if(Si(t)){const{initial:n,animate:i}=t;return{initial:n===!1||Ln(n)?n:void 0,animate:Ln(i)?i:void 0}}return t.inherit!==!1?e:{}}function gp(t){const{initial:e,animate:n}=mp(t,we(wi));return it(()=>({initial:e,animate:n}),[kc(e),kc(n)])}function kc(t){return Array.isArray(t)?t.join(" "):t}const vp=Symbol.for("motionComponentSymbol");function nn(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function _p(t,e,n){return si(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):nn(n)&&(n.current=i))},[e])}const rr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Cc="data-"+rr("framerAppearId"),Tc=Pt({});function yp(t,e,n,i,s){var k,x;const{visualElement:o}=we(wi),r=we(yc),a=we(ui),c=we(Mn).reducedMotion,l=ke(null);i=i||r.renderer,!l.current&&i&&(l.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:c}));const u=l.current,d=we(Tc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&bp(l.current,n,s,d);const p=ke(!1);$o(()=>{u&&p.current&&u.update(n,a)});const g=n[Cc],y=ke(!!g&&!((k=window.MotionHandoffIsComplete)!=null&&k.call(window,g))&&((x=window.MotionHasOptimisedAnimation)==null?void 0:x.call(window,g)));return aa(()=>{u&&(p.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),er.render(u.render),y.current&&u.animationState&&u.animationState.animateChanges())}),Ne(()=>{u&&(!y.current&&u.animationState&&u.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{var b;(b=window.MotionHandoffMarkAsComplete)==null||b.call(window,g)}),y.current=!1))}),u}function bp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:c,layoutRoot:l,layoutCrossfade:u}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Ec(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&nn(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:u,layoutScroll:c,layoutRoot:l})}function Ec(t){if(t)return t.options.allowProjection!==!1?t.projection:Ec(t.parent)}function wp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&dp(t);function o(a,c){let l;const u={...we(Mn),...a,layoutId:xp(a)},{isStatic:d}=u,p=gp(a),g=i(a,d);if(!d&&gs){Sp();const y=kp(u);l=y.MeasureLayout,p.visualElement=yp(s,g,u,e,y.ProjectionNode)}return E(wi.Provider,{value:p,children:[l&&p.visualElement?E(l,{visualElement:p.visualElement,...u}):null,n(s,a,_p(g,p.visualElement,c),g,d,p.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=qu(o);return r[vp]=s,r}function xp({layoutId:t}){const e=we(ms).id;return e&&t!==void 0?e+"-"+t:t}function Sp(t,e){we(yc).strict}function kp(t){const{drag:e,layout:n}=tn;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 Dn={};function Cp(t){for(const e in t)Dn[e]=t[e],Cs(e)&&(Dn[e].isCSSVariable=!0)}function Ac(t,{layout:e,layoutId:n}){return Qt.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Dn[t]||t==="opacity")}const Tp={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Ep=Jt.length;function Ap(t,e,n){let i="",s=!0;for(let o=0;o<Ep;o++){const r=Jt[o],a=t[r];if(a===void 0)continue;let c=!0;if(typeof a=="number"?c=a===(r.startsWith("scale")?1:0):c=parseFloat(a)===0,!c||n){const l=cc(a,Qs[r]);if(!c){s=!1;const u=Tp[r]||r;i+=`${u}(${l}) `}n&&(e[r]=l)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function or(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const c in e){const l=e[c];if(Qt.has(c)){r=!0;continue}else if(Cs(c)){s[c]=l;continue}else{const u=cc(l,Qs[c]);c.startsWith("origin")?(a=!0,o[c]=u):i[c]=u}}if(e.transform||(r||n?i.transform=Ap(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:c="50%",originY:l="50%",originZ:u=0}=o;i.transformOrigin=`${c} ${l} ${u}`}}const ar=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ic(t,e,n){for(const i in e)!Ae(e[i])&&!Ac(i,n)&&(t[i]=e[i])}function Ip({transformTemplate:t},e){return it(()=>{const n=ar();return or(n,e,t),Object.assign({},n.vars,n.style)},[e])}function Pp(t,e){const n=t.style||{},i={};return Ic(i,n,t),Object.assign(i,Ip(t,e)),i}function Rp(t,e){const n={},i=Pp(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 Mp={offset:"stroke-dashoffset",array:"stroke-dasharray"},Lp={offset:"strokeDashoffset",array:"strokeDasharray"};function Dp(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?Mp:Lp;t[o.offset]=H.transform(-i);const r=H.transform(e),a=H.transform(n);t[o.array]=`${r} ${a}`}function Pc(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},c,l,u){if(or(t,a,l),c){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:p}=t;d.transform&&(p.transform=d.transform,delete d.transform),(p.transform||d.transformOrigin)&&(p.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),p.transform&&(p.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&&Dp(d,s,o,r,!1)}const Rc=()=>({...ar(),attrs:{}}),Mc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function Op(t,e,n,i){const s=it(()=>{const o=Rc();return Pc(o,e,Mc(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Ic(o,t.style,t),s.style={...o,...s.style}}return s}const Np=["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 cr(t){return typeof t!="string"||t.includes("-")?!1:!!(Np.indexOf(t)>-1||/[A-Z]/u.test(t))}function Vp(t=!1){return(n,i,s,{latestValues:o},r)=>{const c=(cr(n)?Op:Rp)(i,o,r,n),l=hp(i,typeof n=="string",t),u=n!==Xe?{...l,...c,ref:s}:{},{children:d}=i,p=it(()=>Ae(d)?d.get():d,[d]);return He(n,{...u,children:p})}}function Lc(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function lr(t,e,n,i){if(typeof e=="function"){const[s,o]=Lc(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]=Lc(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function ki(t){return Ae(t)?t.get():t}function Fp({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:Bp(n,i,s,t),renderState:e()}}const Dc=t=>(e,n)=>{const i=we(wi),s=we(ui),o=()=>Fp(t,e,i,s);return n?o():di(o)};function Bp(t,e,n,i){const s={},o=i(t,{});for(const p in o)s[p]=ki(o[p]);let{initial:r,animate:a}=t;const c=Si(t),l=Sc(t);e&&l&&!c&&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"&&!xi(d)){const p=Array.isArray(d)?d:[d];for(let g=0;g<p.length;g++){const y=lr(t,p[g]);if(y){const{transitionEnd:k,transition:x,...b}=y;for(const S in b){let C=b[S];if(Array.isArray(C)){const I=u?C.length-1:0;C=C[I]}C!==null&&(s[S]=C)}for(const S in k)s[S]=k[S]}}}return s}function dr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Ae(i[r])||e.style&&Ae(e.style[r])||Ac(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const jp={useVisualState:Dc({scrapeMotionValuesFromProps:dr,createRenderState:ar})};function Oc(t,e,n){const i=dr(t,e,n);for(const s in t)if(Ae(t[s])||Ae(e[s])){const o=Jt.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const $p={useVisualState:Dc({scrapeMotionValuesFromProps:Oc,createRenderState:Rc})};function Up(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...cr(i)?$p:jp,preloadedFeatures:t,useRender:Vp(s),createVisualElement:e,Component:i};return wp(r)}}function On(t,e,n){const i=t.getProps();return lr(i,e,n!==void 0?n:i.custom,t)}const ur=t=>Array.isArray(t);function Hp(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,en(n))}function Gp(t){return ur(t)?t[t.length-1]||0:t}function zp(t,e){const n=On(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=Gp(o[r]);Hp(t,r,a)}}function Wp(t){return!!(Ae(t)&&t.add)}function hr(t,e){const n=t.getValue("willChange");if(Wp(n))return n.add(e);if(!n&&ft.WillChange){const i=new ft.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Nc(t){return t.props[Cc]}const qp=t=>t!==null;function Kp(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(qp),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Xp={type:"spring",stiffness:500,damping:25,restSpeed:10},Yp=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Zp={type:"keyframes",duration:.8},Jp={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Qp=(t,{keyframes:e})=>e.length>2?Zp:Qt.has(t)?t.startsWith("scale")?Yp(e[1]):Xp:Jp;function em({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:c,elapsed:l,...u}){return!!Object.keys(u).length}const fr=(t,e,n,i={},s,o)=>r=>{const a=Zs(i,t)||{},c=a.delay||i.delay||0;let{elapsed:l=0}=i;l=l-st(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-l,onUpdate:p=>{e.set(p),a.onUpdate&&a.onUpdate(p)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};em(a)||Object.assign(u,Qp(t,u)),u.duration&&(u.duration=st(u.duration)),u.repeatDelay&&(u.repeatDelay=st(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)),(ft.instantAnimations||ft.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const p=Kp(u.keyframes,a);if(p!==void 0){de.update(()=>{u.onUpdate(p),u.onComplete()});return}}return a.isSync?new $s(u):new Of(u)};function tm({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 c=[],l=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),p=a[u];if(p===void 0||l&&tm(l,u))continue;const g={delay:n,...Zs(o||{},u)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(p)&&p===y&&!g.velocity)continue;let k=!1;if(window.MotionHandoffAnimation){const b=Nc(t);if(b){const S=window.MotionHandoffAnimation(b,u,de);S!==null&&(g.startTime=S,k=!0)}}hr(t,u),d.start(fr(u,d,p,t.shouldReduceMotion&&tc.has(u)?{type:!1}:g,t,k));const x=d.animation;x&&c.push(x)}return r&&Promise.all(c).then(()=>{de.update(()=>{r&&zp(t,r)})}),c}function pr(t,e,n={}){var c;const i=On(t,e,n.type==="exit"?(c=t.presenceContext)==null?void 0:c.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?(l=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:p}=s;return nm(t,e,l,u,d,p,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[l,u]=a==="beforeChildren"?[o,r]:[r,o];return l().then(()=>u())}else return Promise.all([o(),r(n.delay)])}function nm(t,e,n=0,i=0,s=0,o=1,r){const a=[],c=t.variantChildren.size,l=(c-1)*s,u=typeof i=="function",d=u?p=>i(p,c):o===1?(p=0)=>p*s:(p=0)=>l-p*s;return Array.from(t.variantChildren).sort(im).forEach((p,g)=>{p.notify("AnimationStart",e),a.push(pr(p,e,{...r,delay:n+(u?0:i)+d(g)}).then(()=>p.notify("AnimationComplete",e)))}),Promise.all(a)}function im(t,e){return t.sortNodePosition(e)}function sm(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>pr(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=pr(t,e,n);else{const s=typeof e=="function"?On(t,e,n.custom):e;i=Promise.all(Vc(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Fc(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 rm=sr.length;function Bc(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Bc(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<rm;n++){const i=sr[n],s=t.props[i];(Ln(s)||s===!1)&&(e[i]=s)}return e}const om=[...ir].reverse(),am=ir.length;function cm(t){return e=>Promise.all(e.map(({animation:n,options:i})=>sm(t,n,i)))}function lm(t){let e=cm(t),n=jc(),i=!0;const s=c=>(l,u)=>{var p;const d=On(t,u,c==="exit"?(p=t.presenceContext)==null?void 0:p.custom:void 0);if(d){const{transition:g,transitionEnd:y,...k}=d;l={...l,...k,...y}}return l};function o(c){e=c(t)}function r(c){const{props:l}=t,u=Bc(t.parent)||{},d=[],p=new Set;let g={},y=1/0;for(let x=0;x<am;x++){const b=om[x],S=n[b],C=l[b]!==void 0?l[b]:u[b],I=Ln(C),M=b===c?S.isActive:null;M===!1&&(y=x);let O=C===u[b]&&C!==l[b]&&I;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),S.protectedKeys={...g},!S.isActive&&M===null||!C&&!S.prevProp||xi(C)||typeof C=="boolean")continue;const _=dm(S.prevProp,C);let w=_||b===c&&S.isActive&&!O&&I||x>y&&I,f=!1;const m=Array.isArray(C)?C:[C];let h=m.reduce(s(b),{});M===!1&&(h={});const{prevResolvedValues:v={}}=S,T={...v,...h},P=R=>{w=!0,p.has(R)&&(f=!0,p.delete(R)),S.needsAnimating[R]=!0;const V=t.getValue(R);V&&(V.liveStyle=!1)};for(const R in T){const V=h[R],X=v[R];if(g.hasOwnProperty(R))continue;let B=!1;ur(V)&&ur(X)?B=!Fc(V,X):B=V!==X,B?V!=null?P(R):p.add(R):V!==void 0&&p.has(R)?P(R):S.protectedKeys[R]=!0}S.prevProp=C,S.prevResolvedValues=h,S.isActive&&(g={...g,...h}),i&&t.blockInitialAnimation&&(w=!1),w&&(!(O&&_)||f)&&d.push(...m.map(R=>({animation:R,options:{type:b}})))}if(p.size){const x={};if(typeof l.initial!="boolean"){const b=On(t,Array.isArray(l.initial)?l.initial[0]:l.initial);b&&b.transition&&(x.transition=b.transition)}p.forEach(b=>{const S=t.getBaseTarget(b),C=t.getValue(b);C&&(C.liveStyle=!0),x[b]=S??null}),d.push({animation:x})}let k=!!d.length;return i&&(l.initial===!1||l.initial===l.animate)&&!t.manuallyAnimateOnMount&&(k=!1),i=!1,k?e(d):Promise.resolve()}function a(c,l){var d;if(n[c].isActive===l)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(p=>{var g;return(g=p.animationState)==null?void 0:g.setActive(c,l)}),n[c].isActive=l;const u=r(c);for(const p in n)n[p].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=jc(),i=!0}}}function dm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Fc(e,t):!1}function Ot(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function jc(){return{animate:Ot(!0),whileInView:Ot(),whileHover:Ot(),whileTap:Ot(),whileDrag:Ot(),whileFocus:Ot(),exit:Ot()}}class St{constructor(e){this.isMounted=!1,this.node=e}update(){}}class um extends St{constructor(e){super(e),e.animationState||(e.animationState=lm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();xi(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 hm=0;class fm extends St{constructor(){super(...arguments),this.id=hm++}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 pm={animation:{Feature:um},exit:{Feature:fm}};function Nn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function Vn(t){return{point:{x:t.pageX,y:t.pageY}}}const mm=t=>e=>tr(e)&&t(e,Vn(e));function Fn(t,e,n,i){return Nn(t,e,mm(n),i)}function $c({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 vm(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,_m=1-Uc,ym=1+Uc,Hc=.01,bm=0-Hc,wm=0+Hc;function Me(t){return t.max-t.min}function xm(t,e,n){return Math.abs(t-e)<=n}function Gc(t,e,n,i=.5){t.origin=i,t.originPoint=me(e.min,e.max,t.origin),t.scale=Me(n)/Me(e),t.translate=me(n.min,n.max,t.origin)-t.originPoint,(t.scale>=_m&&t.scale<=ym||isNaN(t.scale))&&(t.scale=1),(t.translate>=bm&&t.translate<=wm||isNaN(t.translate))&&(t.translate=0)}function Bn(t,e,n,i){Gc(t.x,e.x,n.x,i?i.originX:void 0),Gc(t.y,e.y,n.y,i?i.originY:void 0)}function zc(t,e,n){t.min=n.min+e.min,t.max=t.min+Me(e)}function Sm(t,e,n){zc(t.x,e.x,n.x),zc(t.y,e.y,n.y)}function Wc(t,e,n){t.min=e.min-n.min,t.max=t.min+Me(e)}function jn(t,e,n){Wc(t.x,e.x,n.x),Wc(t.y,e.y,n.y)}const qc=()=>({translate:0,scale:1,origin:0,originPoint:0}),sn=()=>({x:qc(),y:qc()}),Kc=()=>({min:0,max:0}),_e=()=>({x:Kc(),y:Kc()});function ze(t){return[t("x"),t("y")]}function mr(t){return t===void 0||t===1}function gr({scale:t,scaleX:e,scaleY:n}){return!mr(t)||!mr(e)||!mr(n)}function Nt(t){return gr(t)||Xc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Xc(t){return Yc(t.x)||Yc(t.y)}function Yc(t){return t&&t!=="0%"}function Ci(t,e,n){const i=t-n,s=e*i;return n+s}function Zc(t,e,n,i,s){return s!==void 0&&(t=Ci(t,s,i)),Ci(t,n,i)+e}function vr(t,e=0,n=1,i,s){t.min=Zc(t.min,e,n,i,s),t.max=Zc(t.max,e,n,i,s)}function Jc(t,{x:e,y:n}){vr(t.x,e.translate,e.scale,e.originPoint),vr(t.y,n.translate,n.scale,n.originPoint)}const Qc=.999999999999,el=1.0000000000001;function km(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:c}=o.options;c&&c.props.style&&c.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&on(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Jc(t,r)),i&&Nt(o.latestValues)&&on(t,o.latestValues))}e.x<el&&e.x>Qc&&(e.x=1),e.y<el&&e.y>Qc&&(e.y=1)}function rn(t,e){t.min=t.min+e,t.max=t.max+e}function tl(t,e,n,i,s=.5){const o=me(t.min,t.max,s);vr(t,e,n,o,i)}function on(t,e){tl(t.x,e.x,e.scaleX,e.scale,e.originX),tl(t.y,e.y,e.scaleY,e.scale,e.originY)}function nl(t,e){return $c(vm(t.getBoundingClientRect(),e))}function Cm(t,e,n){const i=nl(t,n),{scroll:s}=e;return s&&(rn(i.x,s.offset.x),rn(i.y,s.offset.y)),i}const il=({current:t})=>t?t.ownerDocument.defaultView:null,sl=(t,e)=>Math.abs(t-e);function Tm(t,e){const n=sl(t.x,e.x),i=sl(t.y,e.y);return Math.sqrt(n**2+i**2)}class rl{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 p=yr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=Tm(p.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:k}=p,{timestamp:x}=Ce;this.history.push({...k,timestamp:x});const{onStart:b,onMove:S}=this.handlers;g||(b&&b(this.lastMoveEvent,p),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,p)},this.handlePointerMove=(p,g)=>{this.lastMoveEvent=p,this.lastMoveEventInfo=_r(g,this.transformPagePoint),de.update(this.updatePoint,!0)},this.handlePointerUp=(p,g)=>{this.end();const{onEnd:y,onSessionEnd:k,resumeAnimation:x}=this.handlers;if(this.dragSnapToOrigin&&x&&x(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=yr(p.type==="pointercancel"?this.lastMoveEventInfo:_r(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(p,b),k&&k(p,b)},!tr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=Vn(e),c=_r(a,this.transformPagePoint),{point:l}=c,{timestamp:u}=Ce;this.history=[{...l,timestamp:u}];const{onSessionStart:d}=n;d&&d(e,yr(c,this.history)),this.removeListeners=Sn(Fn(this.contextWindow,"pointermove",this.handlePointerMove),Fn(this.contextWindow,"pointerup",this.handlePointerUp),Fn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),bt(this.updatePoint)}}function _r(t,e){return e?{point:e(t.point)}:t}function ol(t,e){return{x:t.x-e.x,y:t.y-e.y}}function yr({point:t},e){return{point:t,delta:ol(t,al(e)),offset:ol(t,Em(e)),velocity:Am(e,.1)}}function Em(t){return t[0]}function al(t){return t[t.length-1]}function Am(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=al(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>st(e)));)n--;if(!i)return{x:0,y:0};const o=rt(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 Im(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?me(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?me(n,t,i.max):Math.min(t,n)),t}function cl(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 Pm(t,{top:e,left:n,bottom:i,right:s}){return{x:cl(t.x,n,s),y:cl(t.y,e,i)}}function ll(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:ll(t.x,e.x),y:ll(t.y,e.y)}}function Mm(t,e){let n=.5;const i=Me(t),s=Me(e);return s>i?n=kn(e.min,e.max-i,t.min):i>s&&(n=kn(t.min,t.max-s,e.min)),ht(0,1,n)}function Lm(t,e){const n={};return e.min!==void 0&&(n.min=e.min-t.min),e.max!==void 0&&(n.max=e.max-t.min),n}const br=.35;function Dm(t=br){return t===!1?t=0:t===!0&&(t=br),{x:dl(t,"left","right"),y:dl(t,"top","bottom")}}function dl(t,e,n){return{min:ul(t,e),max:ul(t,n)}}function ul(t,e){return typeof t=="number"?t:t[e]||0}const Om=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=_e(),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:p}=this.getProps();p?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Vn(d).point)},r=(d,p)=>{const{drag:g,dragPropagation:y,onDragStart:k}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Yf(g),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ze(b=>{let S=this.getAxisMotionValue(b).get()||0;if(ot.test(S)){const{projection:C}=this.visualElement;if(C&&C.layout){const I=C.layout.layoutBox[b];I&&(S=Me(I)*(parseFloat(S)/100))}}this.originPoint[b]=S}),k&&de.postRender(()=>k(d,p)),hr(this.visualElement,"transform");const{animationState:x}=this.visualElement;x&&x.setActive("whileDrag",!0)},a=(d,p)=>{this.latestPointerEvent=d,this.latestPanInfo=p;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:k,onDrag:x}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:b}=p;if(y&&this.currentDirection===null){this.currentDirection=Vm(b),this.currentDirection!==null&&k&&k(this.currentDirection);return}this.updateAxis("x",p.point,b),this.updateAxis("y",p.point,b),this.visualElement.render(),x&&x(d,p)},c=(d,p)=>{this.latestPointerEvent=d,this.latestPanInfo=p,this.stop(d,p),this.latestPointerEvent=null,this.latestPanInfo=null},l=()=>ze(d=>{var p;return this.getAnimationState(d)==="paused"&&((p=this.getAxisMotionValue(d).animation)==null?void 0:p.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new rl(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:c,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:i,contextWindow:il(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&&de.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||!Ti(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=Im(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&&nn(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=Pm(i.layoutBox,e):this.constraints=!1,this.elastic=Dm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Lm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!nn(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Cm(i,s.root,this.visualElement.getTransformPagePoint());let r=Rm(s.layout.layoutBox,o);if(n){const a=n(gm(r));this.hasMutatedConstraints=!!a,a&&(r=$c(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),c=this.constraints||{},l=ze(u=>{if(!Ti(u,n,this.currentDirection))return;let d=c&&c[u]||{};r&&(d={min:0,max:0});const p=s?200:1e6,g=s?40:1e7,y={type:"inertia",velocity:i?e[u]:0,bounceStiffness:p,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,y)});return Promise.all(l).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return hr(this.visualElement,e),i.start(fr(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(!Ti(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]-me(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!nn(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 c=a.get();s[r]=Mm({min:c,max:c},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(!Ti(r,e,null))return;const a=this.getAxisMotionValue(r),{min:c,max:l}=this.constraints[r];a.set(me(c,l,s[r]))})}addListeners(){if(!this.visualElement.current)return;Om.set(this.visualElement,this);const e=this.visualElement.current,n=Fn(e,"pointerdown",c=>{const{drag:l,dragListener:u=!0}=this.getProps();l&&u&&this.start(c)}),i=()=>{const{dragConstraints:c}=this.getProps();nn(c)&&c.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),de.read(i);const r=Nn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:c,hasLayoutChanged:l})=>{this.isDragging&&l&&(ze(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=c[u].translate,d.set(d.get()+c[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=br,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Ti(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function Vm(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 St{constructor(e){super(e),this.removeGroupControls=Ge,this.removeListeners=Ge,this.controls=new Nm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ge}unmount(){this.removeGroupControls(),this.removeListeners()}}const hl=t=>(e,n)=>{t&&de.postRender(()=>t(e,n))};class Bm extends St{constructor(){super(...arguments),this.removePointerDownListener=Ge}onPointerDown(e){this.session=new rl(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:il(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:hl(e),onStart:hl(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&de.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=Fn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Ei={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function fl(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const $n={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(H.test(t))t=parseFloat(t);else return t;const n=fl(t,e.target.x),i=fl(t,e.target.y);return`${n}% ${i}%`}},jm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=xt.parse(t);if(s.length>5)return i;const o=xt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,c=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=c;const l=me(a,c,.5);return typeof s[2+r]=="number"&&(s[2+r]/=l),typeof s[3+r]=="number"&&(s[3+r]/=l),o(s)}};let pl=!1;class $m extends Ye{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;Cp(Um),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),pl&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Ei.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,pl=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||de.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),er.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 ml(t){const[e,n]=vc(),i=we(ms);return E($m,{...t,layoutGroup:i,switchLayoutGroup:we(Tc),isPresent:e,safeToRemove:n})}const Um={borderRadius:{...$n,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:$n,borderTopRightRadius:$n,borderBottomLeftRadius:$n,borderBottomRightRadius:$n,boxShadow:jm};function Hm(t,e,n){const i=Ae(t)?t:en(t);return i.start(fr("",i,e,n)),i.animation}const Gm=(t,e)=>t.depth-e.depth;class zm{constructor(){this.children=[],this.isDirty=!1}add(e){vs(this.children,e),this.isDirty=!0}remove(e){_s(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(Gm),this.isDirty=!1,this.children.forEach(e)}}function Wm(t,e){const n=Ve.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(bt(i),t(o-e))};return de.setup(i,!0),()=>bt(i)}const gl=["TopLeft","TopRight","BottomLeft","BottomRight"],qm=gl.length,vl=t=>typeof t=="string"?parseFloat(t):t,_l=t=>typeof t=="number"||H.test(t);function Km(t,e,n,i,s,o){s?(t.opacity=me(0,n.opacity??1,Xm(i)),t.opacityExit=me(e.opacity??1,0,Ym(i))):o&&(t.opacity=me(e.opacity??1,n.opacity??1,i));for(let r=0;r<qm;r++){const a=`border${gl[r]}Radius`;let c=yl(e,a),l=yl(n,a);if(c===void 0&&l===void 0)continue;c||(c=0),l||(l=0),c===0||l===0||_l(c)===_l(l)?(t[a]=Math.max(me(vl(c),vl(l),i),0),(ot.test(l)||ot.test(c))&&(t[a]+="%")):t[a]=l}(e.rotate||n.rotate)&&(t.rotate=me(e.rotate||0,n.rotate||0,i))}function yl(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Xm=bl(0,.5,_a),Ym=bl(.5,.95,Ge);function bl(t,e,n){return i=>i<t?0:i>e?1:n(kn(t,e,i))}function wl(t,e){t.min=e.min,t.max=e.max}function We(t,e){wl(t.x,e.x),wl(t.y,e.y)}function xl(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Sl(t,e,n,i,s){return t-=e,t=Ci(t,1/n,i),s!==void 0&&(t=Ci(t,1/s,i)),t}function Zm(t,e=0,n=1,i=.5,s,o=t,r=t){if(ot.test(e)&&(e=parseFloat(e),e=me(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=me(o.min,o.max,i);t===o&&(a-=e),t.min=Sl(t.min,e,n,a,s),t.max=Sl(t.max,e,n,a,s)}function kl(t,e,[n,i,s],o,r){Zm(t,e[n],e[i],e[s],e.scale,o,r)}const Jm=["x","scaleX","originX"],Qm=["y","scaleY","originY"];function Cl(t,e,n,i){kl(t.x,e,Jm,n?n.x:void 0,i?i.x:void 0),kl(t.y,e,Qm,n?n.y:void 0,i?i.y:void 0)}function Tl(t){return t.translate===0&&t.scale===1}function El(t){return Tl(t.x)&&Tl(t.y)}function Al(t,e){return t.min===e.min&&t.max===e.max}function eg(t,e){return Al(t.x,e.x)&&Al(t.y,e.y)}function Il(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Pl(t,e){return Il(t.x,e.x)&&Il(t.y,e.y)}function Rl(t){return Me(t.x)/Me(t.y)}function Ml(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class tg{constructor(){this.members=[]}add(e){vs(this.members,e),e.scheduleRender()}remove(e){if(_s(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 ng(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:l,rotate:u,rotateX:d,rotateY:p,skewX:g,skewY:y}=n;l&&(i=`perspective(${l}px) ${i}`),u&&(i+=`rotate(${u}deg) `),d&&(i+=`rotateX(${d}deg) `),p&&(i+=`rotateY(${p}deg) `),g&&(i+=`skewX(${g}deg) `),y&&(i+=`skewY(${y}deg) `)}const a=t.x.scale*e.x,c=t.y.scale*e.y;return(a!==1||c!==1)&&(i+=`scale(${a}, ${c})`),i||"none"}const wr=["","X","Y","Z"],ig=1e3;let sg=0;function xr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function Ll(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Nc(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",de,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&Ll(i)}function Dl({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=sg++,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(ag),this.nodes.forEach(ug),this.nodes.forEach(hg),this.nodes.forEach(cg)},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 c=0;c<this.path.length;c++)this.path[c].shouldResetTransform=!0;this.root===this&&(this.nodes=new zm)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new ws),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const c=this.eventHandlers.get(r);c&&c.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=gc(r)&&!np(r),this.instance=r;const{layoutId:a,layout:c,visualElement:l}=this.options;if(l&&!l.current&&l.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(c||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const p=()=>this.root.updateBlockedByResize=!1;de.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=Wm(p,250),Ei.hasAnimatedSinceResize&&(Ei.hasAnimatedSinceResize=!1,this.nodes.forEach(Vl)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&l&&(a||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:p,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||l.getDefaultTransition()||vg,{onLayoutAnimationStart:k,onLayoutAnimationComplete:x}=l.getProps(),b=!this.targetLayout||!Pl(this.targetLayout,g),S=!d&&p;if(this.options.layoutRoot||this.resumeFrom||S||d&&(b||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const C={...Zs(y,"layout"),onPlay:k,onComplete:x};(l.shouldReduceMotion||this.options.layoutRoot)&&(C.delay=0,C.type=!1),this.startAnimation(C),this.setAnimationOrigin(u,S)}else d||Vl(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(),bt(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(fg),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&&Ll(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:c}=this.options;if(a===void 0&&!c)return;const l=this.getTransformTemplate();this.prevTransformTemplateValue=l?l(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Ol);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Nl);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(dg),this.nodes.forEach(rg),this.nodes.forEach(og)):this.nodes.forEach(Nl),this.clearAllSnapshots();const a=Ve.now();Ce.delta=ht(0,1e3/60,a-Ce.timestamp),Ce.timestamp=a,Ce.isProcessing=!0,ks.update.process(Ce),ks.preRender.process(Ce),ks.render.process(Ce),Ce.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,er.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(lg),this.sharedNodes.forEach(pg)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,de.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){de.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Me(this.snapshot.measuredBox.x)&&!Me(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 c=0;c<this.path.length;c++)this.path[c].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=_e(),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 c=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:c,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:c}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!El(this.projectionDelta),c=this.getTransformTemplate(),l=c?c(this.latestValues,""):void 0,u=l!==this.prevTransformTemplateValue;r&&this.instance&&(a||Nt(this.latestValues)||u)&&(s(this.instance,l),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let c=this.removeElementScroll(a);return r&&(c=this.removeTransform(c)),_g(c),{animationId:this.root.animationId,measuredBox:a,layoutBox:c,latestValues:{},source:this.id}}measurePageBox(){var l;const{visualElement:r}=this.options;if(!r)return _e();const a=r.measureViewportBox();if(!(((l=this.scroll)==null?void 0:l.wasRoot)||this.path.some(yg))){const{scroll:u}=this.root;u&&(rn(a.x,u.offset.x),rn(a.y,u.offset.y))}return a}removeElementScroll(r){var c;const a=_e();if(We(a,r),(c=this.scroll)!=null&&c.wasRoot)return a;for(let l=0;l<this.path.length;l++){const u=this.path[l],{scroll:d,options:p}=u;u!==this.root&&d&&p.layoutScroll&&(d.wasRoot&&We(a,r),rn(a.x,d.offset.x),rn(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const c=_e();We(c,r);for(let l=0;l<this.path.length;l++){const u=this.path[l];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&on(c,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Nt(u.latestValues)&&on(c,u.latestValues)}return Nt(this.latestValues)&&on(c,this.latestValues),c}removeTransform(r){const a=_e();We(a,r);for(let c=0;c<this.path.length;c++){const l=this.path[c];if(!l.instance||!Nt(l.latestValues))continue;gr(l.latestValues)&&l.updateSnapshot();const u=_e(),d=l.measurePageBox();We(u,d),Cl(a,l.latestValues,l.snapshot?l.snapshot.layoutBox:void 0,u)}return Nt(this.latestValues)&&Cl(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!==Ce.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var p;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const c=!!this.resumingFrom||this!==a;if(!(r||c&&this.isSharedProjectionDirty||this.isProjectionDirty||(p=this.parent)!=null&&p.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Ce.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=_e(),this.relativeTargetOrigin=_e(),jn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),We(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=_e(),this.targetWithTransforms=_e()),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):We(this.target,this.layout.layoutBox),Jc(this.target,this.targetDelta)):We(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=_e(),this.relativeTargetOrigin=_e(),jn(this.relativeTargetOrigin,this.target,g.target),We(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||gr(this.parent.latestValues)||Xc(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 c=!0;if((this.isProjectionDirty||(y=this.parent)!=null&&y.isProjectionDirty)&&(c=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(c=!1),this.resolvedRelativeTargetAt===Ce.timestamp&&(c=!1),c)return;const{layout:l,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||!(l||u))return;We(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,p=this.treeScale.y;km(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=_e());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(xl(this.prevProjectionDelta.x,this.projectionDelta.x),xl(this.prevProjectionDelta.y,this.projectionDelta.y)),Bn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==p||!Ml(this.projectionDelta.x,this.prevProjectionDelta.x)||!Ml(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 c=this.getStack();c&&c.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=sn(),this.projectionDelta=sn(),this.projectionDeltaWithTransform=sn()}setAnimationOrigin(r,a=!1){const c=this.snapshot,l=c?c.latestValues:{},u={...this.latestValues},d=sn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const p=_e(),g=c?c.source:void 0,y=this.layout?this.layout.source:void 0,k=g!==y,x=this.getStack(),b=!x||x.members.length<=1,S=!!(k&&!b&&this.options.crossfade===!0&&!this.path.some(gg));this.animationProgress=0;let C;this.mixTargetDelta=I=>{const M=I/1e3;Fl(d.x,r.x,M),Fl(d.y,r.y,M),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(jn(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox),mg(this.relativeTarget,this.relativeTargetOrigin,p,M),C&&eg(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=_e()),We(C,this.relativeTarget)),k&&(this.animationValues=u,Km(u,l,this.latestValues,M,S,b)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=M},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,c,l;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(l=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||l.stop(),this.pendingAnimation&&(bt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=de.update(()=>{Ei.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=en(0)),this.currentAnimation=Hm(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(ig),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:c,layout:l,latestValues:u}=r;if(!(!a||!c||!l)){if(this!==r&&this.layout&&l&&Hl(this.options.animationType,this.layout.layoutBox,l.layoutBox)){c=this.target||_e();const d=Me(this.layout.layoutBox.x);c.x.min=r.target.x.min,c.x.max=c.x.min+d;const p=Me(this.layout.layoutBox.y);c.y.min=r.target.y.min,c.y.max=c.y.min+p}We(a,c),on(a,u),Bn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new tg),this.sharedNodes.get(r).add(a);const l=a.options.initialPromotionConfig;a.promote({transition:l?l.transition:void 0,preserveFollowOpacity:l&&l.shouldPreserveFollowOpacity?l.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:c}={}){const l=this.getStack();l&&l.promote(this,c),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:c}=r;if((c.z||c.rotate||c.rotateX||c.rotateY||c.rotateZ||c.skewX||c.skewY)&&(a=!0),!a)return;const l={};c.z&&xr("z",r,l,this.animationValues);for(let u=0;u<wr.length;u++)xr(`rotate${wr[u]}`,r,l,this.animationValues),xr(`skew${wr[u]}`,r,l,this.animationValues);r.render();for(const u in l)r.setStaticValue(u,l[u]),this.animationValues&&(this.animationValues[u]=l[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const c=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=ki(a==null?void 0:a.pointerEvents)||"",r.transform=c?c(this.latestValues,""):"none";return}const l=this.getLead();if(!this.projectionDelta||!this.layout||!l.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=ki(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Nt(this.latestValues)&&(r.transform=c?c({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=l.animationValues||l.latestValues;this.applyTransformsToTarget();let d=ng(this.projectionDeltaWithTransform,this.treeScale,u);c&&(d=c(u,d)),r.transform=d;const{x:p,y:g}=this.projectionDelta;r.transformOrigin=`${p.origin*100}% ${g.origin*100}% 0`,l.animationValues?r.opacity=l===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=l===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const y in Dn){if(u[y]===void 0)continue;const{correct:k,applyTo:x,isCSSVariable:b}=Dn[y],S=d==="none"?u[y]:k(u[y],l);if(x){const C=x.length;for(let I=0;I<C;I++)r[x[I]]=S}else b?this.options.visualElement.renderState.vars[y]=S:r[y]=S}this.options.layoutId&&(r.pointerEvents=l===this?ki(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(Ol),this.root.sharedNodes.clear()}}}function rg(t){t.updateLayout()}function og(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 p=r?e.measuredBox[d]:e.layoutBox[d],g=Me(p);p.min=i[d].min,p.max=p.min+g}):Hl(o,e.layoutBox,i)&&ze(d=>{const p=r?e.measuredBox[d]:e.layoutBox[d],g=Me(i[d]);p.max=p.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=sn();Bn(a,i,e.layoutBox);const c=sn();r?Bn(c,t.applyTransform(s,!0),e.measuredBox):Bn(c,i,e.layoutBox);const l=!El(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:p,layout:g}=d;if(p&&g){const y=_e();jn(y,e.layoutBox,p.layoutBox);const k=_e();jn(k,i,g.layoutBox),Pl(y,k)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=k,t.relativeTargetOrigin=y,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:c,layoutDelta:a,hasLayoutChanged:l,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function ag(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 cg(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function lg(t){t.clearSnapshot()}function Ol(t){t.clearMeasurements()}function Nl(t){t.isLayoutDirty=!1}function dg(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Vl(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function ug(t){t.resolveTargetDelta()}function hg(t){t.calcProjection()}function fg(t){t.resetSkewAndRotation()}function pg(t){t.removeLeadSnapshot()}function Fl(t,e,n){t.translate=me(e.translate,0,n),t.scale=me(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Bl(t,e,n,i){t.min=me(e.min,n.min,i),t.max=me(e.max,n.max,i)}function mg(t,e,n,i){Bl(t.x,e.x,n.x,i),Bl(t.y,e.y,n.y,i)}function gg(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const vg={duration:.45,ease:[.4,0,.1,1]},jl=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),$l=jl("applewebkit/")&&!jl("chrome/")?Math.round:Ge;function Ul(t){t.min=$l(t.min),t.max=$l(t.max)}function _g(t){Ul(t.x),Ul(t.y)}function Hl(t,e,n){return t==="position"||t==="preserve-aspect"&&!xm(Rl(e),Rl(n),.2)}function yg(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const bg=Dl({attachResizeListener:(t,e)=>Nn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Sr={current:void 0},Gl=Dl({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Sr.current){const t=new bg({});t.mount(window),t.setOptions({layoutScroll:!0}),Sr.current=t}return Sr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),wg={pan:{Feature:Bm},drag:{Feature:Fm,ProjectionNode:Gl,MeasureLayout:ml}};function zl(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&&de.postRender(()=>o(e,Vn(e)))}class xg extends St{mount(){const{current:e}=this.node;e&&(this.unmount=Zf(e,(n,i)=>(zl(this.node,i,"Start"),s=>zl(this.node,s,"End"))))}unmount(){}}class Sg extends St{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=Sn(Nn(this.node.current,"focus",()=>this.onFocus()),Nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Wl(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&&de.postRender(()=>o(e,Vn(e)))}class kg extends St{mount(){const{current:e}=this.node;e&&(this.unmount=tp(e,(n,i)=>(Wl(this.node,i,"Start"),(s,{success:o})=>Wl(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const kr=new WeakMap,Cr=new WeakMap,Cg=t=>{const e=kr.get(t.target);e&&e(t)},Tg=t=>{t.forEach(Cg)};function Eg({root:t,...e}){const n=t||document;Cr.has(n)||Cr.set(n,{});const i=Cr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(Tg,{root:t,...e})),i[s]}function Ag(t,e,n){const i=Eg(e);return kr.set(t,n),i.observe(t),()=>{kr.delete(t),i.unobserve(t)}}const Ig={some:0,all:1};class Pg extends St{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:Ig[s]},a=c=>{const{isIntersecting:l}=c;if(this.isInView===l||(this.isInView=l,o&&!l&&this.hasEnteredView))return;l&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",l);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),p=l?u:d;p&&p(c)};return Ag(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(Rg(e,n))&&this.startObserver()}unmount(){}}function Rg({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const Mg={inView:{Feature:Pg},tap:{Feature:kg},focus:{Feature:Sg},hover:{Feature:xg}},Lg={layout:{ProjectionNode:Gl,MeasureLayout:ml}},Tr={current:null},ql={current:!1};function Dg(){if(ql.current=!0,!!gs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Tr.current=t.matches;t.addEventListener("change",e),e()}else Tr.current=!1}const Og=new WeakMap;function Ng(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Ae(s))t.addValue(i,s);else if(Ae(o))t.addValue(i,en(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,en(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const Kl=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class Vg{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=Xs,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 p=Ve.now();this.renderScheduledAt<p&&(this.renderScheduledAt=p,de.render(this.render,!1,!0))};const{latestValues:c,renderState:l}=r;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=l,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=Si(n),this.isVariantNode=Sc(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(n,{},this);for(const p in d){const g=d[p];c[p]!==void 0&&Ae(g)&&g.set(c[p],!1)}}mount(e){this.current=e,Og.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)),ql.current||Dg(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Tr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),bt(this.notifyUpdate),bt(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=Qt.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&de.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 tn){const n=tn[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):_e()}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<Kl.length;i++){const s=Kl[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=Ng(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=en(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"&&(ca(i)||da(i))?i=parseFloat(i):!sp(i)&&xt.test(n)&&(i=ac(e,n)),this.setBaseTarget(e,Ae(i)?i.get():i)),Ae(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=lr(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&&!Ae(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 ws),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class Xl extends Vg{constructor(){super(...arguments),this.KeyframeResolver=Wf}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;Ae(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function Yl(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 Fg(t){return window.getComputedStyle(t)}class Bg extends Xl{constructor(){super(...arguments),this.type="html",this.renderInstance=Yl}readValueFromInstance(e,n){var i;if(Qt.has(n))return(i=this.projection)!=null&&i.isProjecting?Gs(n):hf(e,n);{const s=Fg(e),o=(Cs(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return nl(e,n)}build(e,n,i){or(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return dr(e,n,i)}}const Zl=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 jg(t,e,n,i){Yl(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(Zl.has(s)?s:rr(s),e.attrs[s])}class $g extends Xl{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=_e}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(Qt.has(n)){const i=oc(n);return i&&i.default||0}return n=Zl.has(n)?n:rr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Oc(e,n,i)}build(e,n,i){Pc(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){jg(e,n,i,s)}mount(e){this.isSVGTag=Mc(e.tagName),super.mount(e)}}const Ug=(t,e)=>cr(t)?new $g(e):new Bg(e,{allowProjection:t!==Xe}),Hg=Up({...pm,...Mg,...wg,...Lg},Ug),Un=pp(Hg),Gg=["agent-id","environment","position","version-id","call-destination-number","call-caller-number","call-caller-name","call-custom-headers"],Ai="widget-layout-id";function Jl(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=Jl(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function pt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=Jl(t))&&(i&&(i+=" "),i+=e);return i}const zg=ls("waiting"),Er=()=>oa(zg),Ii={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},Ql=ls(Ii),Wg=()=>{const t=ps(Ql);return si(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Ii.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Ii.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Ii.speak_to_interrupt_text),n}),[t])},Vt=()=>ra(Ql),ed=({size:t="large",className:e})=>{const n=Vt(),[i]=Er();return E("h1",{className:pt({"text-xs":t==="small"},e),children:i==="waiting"?n.speak_to_interrupt_text:i==="processing_image"?"Processing image...":n.agent_thinking_text})},td=({stream:t})=>{const e=ke(null);return Ne(()=>{!e.current||!t||(e.current.srcObject=t)},[t]),E("audio",{muted:!0,ref:e,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 qg="4.5.1",Ar=Math.PI,an=2*Ar,Ir=Ar/2,nd=8.17579892,id="dual-combined",Pi="dual-horizontal",mt="single",at="dual-vertical",sd="bar-index",rd="bar-level",Ri="gradient",od=60,ad="click",Kg="fullscreenchange",cd="resize",Xg="#111",ld="",dd="A",ud="B",hd="C",fd="D",pd="468",Mi="sans-serif",Yg="#0f0",Zg="#7f7f7f22",cn=10,md="create",gd="fschange",Jg="lores",Qg=cd,Pr="user",ev="#000c",vd="#fff",tv="#4f4",_d="#888",nv="#555",Rr="bark",Hn="linear",ln="log",Mr="mel",yd=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],bd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:yd}],["rainbow",{dir:"h",colorStops:["#817",...yd,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Gn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:mt,colorMode:Ri,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:ln,gradient:bd[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:ld,width:void 0},iv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],sv=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],rv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Lr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],ov=["ERR_INVALID_MODE","Invalid mode"],av=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],cv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],lv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],dv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],uv=["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 wd=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),xd=t=>{for(const e in t)return!1;return!0},Li=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],hv=(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 fv{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||(xd(n)&&!xd(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,m]of bd)this.registerGradient(d,m);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(iv)}}if(!s.createGain)throw new qe(sv);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 c=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Qg),this._fsTimeout=0)},od))};window.ResizeObserver&&(this._observer=new ResizeObserver(c),this._observer.observe(this._container)),this._controller=new AbortController;const l=this._controller.signal;window.addEventListener(cd,c,{signal:l}),i.addEventListener(Kg,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(gd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},od)},{signal:l});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(ad,u))};window.addEventListener(ad,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:l}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(md)}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=Li(e,[mt,Pi,at,id]),this._input.disconnect(),this._input.connect(this._chLayout!=mt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=mt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Li(e,[Ri,sd,rd])}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=Li(e,[ln,Rr,Mr,Hn]),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||Gn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Pr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(Jg)}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(Lr);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(Lr);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(ov,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||Gn.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(av);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=-Ir),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return wd("stereo","channelLayout"),this._chLayout!=mt}set stereo(e){wd("stereo","channelLayout"),this.channelLayout=e?at:mt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=Li(e,[ld,dd,ud,hd,fd,pd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Pr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return qg}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new qe(cv);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==mt&&!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:c,_splitter:l}=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(),l.disconnect(),o.disconnect(),c&&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==mt?1:2;let r=0;for(let a=0;a<o;a++)for(let c=i;c<=s;c++)r+=this._normalizedB(this._fftData[a][c]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Gn))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(lv);if(typeof n!="object")throw new qe(dv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new qe(uv);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const c=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:c,color:r}:o(r.pos)&&(r.pos=c),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||Xg,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Pr)}setFreqRange(e,n){if(e<1||n<1)throw new qe(Lr);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:c,_mode:l,_radial:u,_radialInvert:d,_reflexRatio:m}=this,g=s.width>>1,y=s.height>>1,k=o==at&&!u,x=o==Pi,b=l%10!=0,S=b&&this._frequencyScale==ln,C=this._showLeds&&b&&!u,A=this._lumiBars&&b&&!u,M=this._alphaBars&&!A&&l!=cn,O=this._outlineBars&&b&&!A&&!C,_=this._roundBars&&b&&!A&&!C,w=o!=at||m>0&&!A,f=s.height-(k&&!C?.5:0)>>k,p=f*(A||u?1:1-m)|0,h=s.width-g*(x||c!=0),v=k?s.height-f*2:0,T=g*(c==-1&&!x&&!u);let P=Math.min(s.width,s.height)*.375*(o==at?1:this._radius)|0,I=Math.min(g,y);d&&o!=at&&([P,I]=[I,P]);const L=W=>e.push({...W,peak:[0,0],hold:[0],alpha:[0],value:[0]}),R=W=>{const Z=this._freqToBin(W,"floor"),J=this._binToFreq(Z),ee=this._binToFreq(Z+1),ue=Math.log2(W/J)/Math.log2(ee/J);return[Z,ue]};let V,X,B;if(S){const W=(se,fe,ie)=>+se.toPrecision(ie?Math.max(fe,1+Math.log10(se)|0):fe),Z=se=>{const fe=[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],ie=Math.log10(se)|0,ct=se/10**ie;let Qe=1;for(;Qe<fe.length&&ct>fe[Qe];)Qe++;return ct-fe[Qe-1]<fe[Qe]-ct&&Qe--,(fe[Qe]*10**(ie+5)|0)/1e5},J=[0,24,12,8,6,4,3,2,1][l],ee=n?10**(3/(J*10)):2**(1/J),ue=ee**.5;let De=n?7.94328235/(J%2?1:ue):nd;do{let se=De;const fe=W(se/ue,4,!0),ie=W(se*ue,4,!0),[ct,Qe]=R(fe),[Zn,lt]=R(ie);n?se=J<4?Z(se):W(se,se.toString()[0]<5?3:2):se=W(se,4,!0),se>=a&&L({posX:0,freq:se,freqLo:fe,freqHi:ie,binLo:ct,binHi:Zn,ratioLo:Qe,ratioHi:lt}),De*=ee}while(De<=r);V=h/e.length,e.forEach((se,fe)=>se.posX=T+fe*V);const he=e[0],Pe=e[e.length-1];X=this._freqScaling(he.freqLo),B=h/(this._freqScaling(Pe.freqHi)-X),he.freqLo<a&&(he.freqLo=a,[he.binLo,he.ratioLo]=R(a)),Pe.freqHi>r&&(Pe.freqHi=r,[Pe.binHi,Pe.ratioHi]=R(r))}else if(b){const W=[0,24,12,8,6,4,3,2,1][l]*10,Z=J=>{switch(this._frequencyScale){case Rr:return 1960/(26.81/(J+.53)-1);case Mr:return 700*(2**J-1);case Hn:return J}};V=h/W,X=this._freqScaling(a),B=h/(this._freqScaling(r)-X);for(let J=0,ee=0;J<W;J++,ee+=V){const ue=Z(X+ee/B),De=Z(X+(ee+V/2)/B),he=Z(X+(ee+V)/B),[Pe,se]=R(ue),[fe,ie]=R(he);L({posX:T+ee,freq:De,freqLo:ue,freqHi:he,binLo:Pe,binHi:fe,ratioLo:se,ratioHi:ie})}}else{V=1,X=this._freqScaling(a),B=h/(this._freqScaling(r)-X);const W=this._freqToBin(a,"floor"),Z=this._freqToBin(r);let J=-999;for(let ee=W;ee<=Z;ee++){const ue=this._binToFreq(ee),De=T+Math.round(B*(this._freqScaling(ue)-X));if(De>J)L({posX:De,freq:ue,freqLo:ue,freqHi:ue,binLo:ee,binHi:ee,ratioLo:0,ratioHi:0}),J=De;else if(e.length){const he=e[e.length-1];he.binHi=ee,he.freqHi=ue,he.freq=(he.freqLo*ue)**.5}}}let re=0,Q=0;if(C){const W=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]],J=this._ledParams,[ee,ue,De]=J||Z[l];let he,Pe=p;if(J){const se=2*W;let fe;he=ee+1;do he--,fe=Pe/he/(1+ue),Q=fe*ue;while((fe<se||Q<se)&&he>1)}else{const se=540/ue;Q=Math.min(ue*W,Math.max(2,Pe/se+.1|0))}w&&(Pe+=Q),J||(he=Math.min(ee,Pe/(Q*2)|0)),re=De>=1?De:V*De,this._leds=[he,re,Q,Pe/he-Q]}const $=Math.min(V-1,i*(i>0&&i<1?V:1));b&&(V-=Math.max(C?re:0,$)),e.forEach((W,Z)=>{let J=W.posX,ee=V;b&&(i==0&&!C?(J|=0,ee|=0,Z>0&&J>e[Z-1].posX+e[Z-1].width&&(J--,ee++)):J+=Math.max(C?re:0,$)/2,W.posX=J),W.barCenter=J+(V==1?0:ee/2),W.width=ee});const ce=[];for(const W of[0,1]){const Z=o==at?(f+v)*W:0,J=Z+f,ee=Z+p-(!C||w?0:Q);ce.push({channelTop:Z,channelBottom:J,analyzerBottom:ee})}this._aux={analyzerHeight:p,analyzerWidth:h,centerX:g,centerY:y,channelCoords:ce,channelHeight:f,channelGap:v,initialX:T,innerRadius:P,outerRadius:I,scaleMin:X,unitWidth:B},this._flg={isAlpha:M,isBands:b,isLeds:C,isLumi:A,isOctaves:S,isOutline:O,isRound:_,noLedGap:w},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:c,_noteLabels:l,_radial:u,_scaleX:d,_scaleR:m}=this,g=d.canvas,y=m.canvas,k=[],x=this._chLayout==Pi,b=this._chLayout==at,S=Math.min(r.width,r.height),C=["C",,"D",,"E","F",,"G",,"A",,"B"],A=S/34|0,M=g.height>>1,O=A>>1,_=M*(l?.7:1.5),w=O*(l?1:2),f=2**(1/12);if(!l&&(this._ansiBands||a!=ln))k.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Hn?k.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):k.push(8e3,16e3);else{let I=nd;for(let L=-1;L<11;L++)for(let R=0;R<12;R++){if(I>=this._minFreq&&I<=this._maxFreq){const V=C[R],X=V=="C";(V&&l&&!c&&!x||X)&&k.push(l?[I,V+(X?L:"")]:I)}I*=f}}y.width=y.height=Math.max(S*.15,(i<<1)+b*A);const p=y.width>>1,h=p-A*.7,v=(I,L)=>{const R=an*(I/r.width),V=R-Ir,X=h*Math.cos(V),B=h*Math.sin(V);m.save(),m.translate(p+X,p+B),m.rotate(R),m.fillText(L,0,0),m.restore()};g.width|=0,d.fillStyle=m.strokeStyle=ev,d.fillRect(0,0,g.width,g.height),m.arc(p,p,p-A/2,0,an),m.lineWidth=A,m.stroke(),d.fillStyle=m.fillStyle=vd,d.font=`${M}px ${Mi}`,m.font=`${O}px ${Mi}`,d.textAlign=m.textAlign="center";let T=-_/4,P=-w;for(const I of k){const[L,R]=Array.isArray(I)?I:[I,I<1e3?I|0:`${(I/100|0)/10}k`],V=o*(this._freqScaling(L)-s),X=g.height*.75,B=R[0]=="C",re=M*(l&&!c&&!x?B?1.2:.6:3);if(d.fillStyle=m.fillStyle=B&&!c&&!x?tv:vd,l){const Q=a==ln,$=a==Hn;let ce=["C"];if((Q||L>2e3||!$&&L>250||(!u||b)&&(!$&&L>125||L>1e3))&&ce.push("G"),(Q||L>4e3||!$&&L>500||(!u||b)&&(!$&&L>250||L>2e3))&&ce.push("E"),($&&L>4e3||(!u||b)&&(Q||L>2e3||!$&&L>500))&&ce.push("D","F","A","B"),!ce.includes(R[0]))continue}V>=T+_/2&&V<=e&&(d.fillText(R,x&&c==-1?e-V:n+V,X,re),(x||c&&(V>_||c==1))&&d.fillText(R,x&&c!=1?e+V:(n||r.width)-V,X,re),T=V+Math.min(re,d.measureText(R).width)/2),V>=P+w&&V<e-w&&(v(x&&c==1?e-V:V,R),(x||c&&(V>w||c==1))&&v(x&&c!=-1?e+V:-V,R),P=V)}}_draw(e){this._runId=requestAnimationFrame(N=>this._draw(N));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:c,isOctaves:l,isOutline:u,isRound:d,noLedGap:m}=this._flg,{analyzerHeight:g,centerX:y,centerY:k,channelCoords:x,channelHeight:b,channelGap:S,initialX:C,innerRadius:A,outerRadius:M}=this._aux,{_bars:O,canvas:_,_canvasGradients:w,_chLayout:f,_colorMode:p,_ctx:h,_energy:v,_fadePeaks:T,fillAlpha:P,_fps:I,_linearAmplitude:L,_lineWidth:R,maxDecibels:V,minDecibels:X,_mirror:B,_mode:re,overlay:Q,_radial:$,showBgColor:ce,showPeaks:W,useCanvas:Z,_weightingFilter:J}=this,ee=this._scaleX.canvas,ue=this._scaleR.canvas,De=I*this._peakFadeTime/1e3,he=I**2,Pe=this._gravity*1e3,se=I*this._peakHoldTime/1e3,fe=f==id,ie=f==Pi,ct=f==at,Qe=f==mt,Zn=a&&this._trueLeds&&p==Ri,lt=$?_.width:this._aux.analyzerWidth,Wr=C+lt,Jn=W&&this._peakLine&&re==cn,Ct=$?M-A:g,H_=Ct/this._pixelRatio,[G_,J_,Qn,qr]=this._leds||[];v.val>0&&I>0&&(this._spinAngle+=this._spinSpeed*an/60/I);const z_=N=>{if(this._reflexRatio>0&&!c&&!$){let ne,dt;this.reflexFit||ct?(ne=ct&&N==0?b+S:0,dt=b-g):(ne=_.height-g*2,dt=g),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,_.height),h.drawImage(_,0,x[N].channelTop,_.width,g,0,ne,_.width,dt),h.restore()}},W_=()=>{this.showScaleX&&($?(h.save(),h.translate(y,k),this._spinSpeed&&h.rotate(this._spinAngle+Ir),h.drawImage(ue,-ue.width>>1,-ue.width>>1),h.restore()):h.drawImage(ee,0,_.height-ee.height))},q_=N=>{const ne=N**2,dt=424.36,Ee=11599.29,Ui=25122.25,Tt=544496.41,_t=148693636,Ht=Gt=>20*Math.log10(Gt);switch(J){case dd:const Gt=_t*ne**2/((ne+dt)*Math.sqrt((ne+Ee)*(ne+Tt))*(ne+_t));return 2+Ht(Gt);case ud:const zt=_t*ne*N/((ne+dt)*Math.sqrt(ne+Ui)*(ne+_t));return .17+Ht(zt);case hd:const Yr=_t*ne/((ne+dt)*(ne+_t));return .06+Ht(Yr);case fd:const Hi=((103791848e-2-ne)**2+108076816e-2*ne)/((9837328-ne)**2+11723776*ne),Zr=N/68966888496476e-18*Math.sqrt(Hi/((ne+79919.29)*(ne+1345600)));return Ht(Zr);case pd:const Gi=-4737338981378384e-39*N**6+2043828333606125e-30*N**4-1363894795463638e-22*ne+1,Wt=1306612257412824e-34*N**5-2118150887518656e-26*N**3+.0005559488023498642*N,Ue=.0001246332637532143*N/Math.hypot(Gi,Wt);return 18.2+Ht(Ue)}return 0},Kr=(N,ne,dt)=>{h.beginPath(),h.moveTo(N,ne),h.lineTo(N,dt),h.stroke()},Xr=N=>{if(N&&R){const ne=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ne}},Ut=N=>Math.max(0,(N*G_|0)*(qr+Qn)-Qn),K_=N=>{v.val=N,v.peak>0&&(v.hold--,v.hold<0&&(v.peak+=v.hold*Pe/he/_.height*this._pixelRatio)),N>=v.peak&&(v.peak=N,v.hold=se)};Q&&h.clearRect(0,0,_.width,_.height);let mu=0;const gu=O.length,vu=Qe?1:2;for(let N=0;N<vu;N++){const{channelTop:ne,channelBottom:dt,analyzerBottom:Ee}=x[N],Ui=this._gradients[this._selectedGrads[N]],Tt=Ui.colorStops,_t=Tt.length,Ht=!ce||a&&!Q?"#000":Ui.bgColor,Gt=ct&&$&&N?-1:1,zt=!N&&B==-1||N&&B==1,Yr=!ie||N&&B!=1?0:lt>>(N||!zt),Hi=ie&&zt?-1:1,Zr=()=>{const U=ee.height,G=U>>1,q=L?100:V,le=L?0:X,be=L?20:5,je=g/(q-le),ut=B!=-1&&(!ie||N==0||B==1),Et=B!=1&&(!ie||N!=B);h.save(),h.fillStyle=_d,h.font=`${G}px ${Mi}`,h.textAlign="right",h.lineWidth=1;for(let At=q;At>le;At-=be){const pn=ne+(q-At)*je,Se=At%2==0|0;if(Se){const Oe=pn+G*(pn==ne?.8:.35);ut&&h.fillText(At,U*.85,Oe),Et&&h.fillText(At,(ie?lt:_.width)-U*.1,Oe),h.strokeStyle=_d,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=nv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(C+U*Se*ut,~~pn+.5),h.lineTo(Wr-U*Se*Et,~~pn+.5),h.stroke()}h.restore()},Gi=(U,G)=>{const q=et[U]+(U<et.length-1?(et[U+1]-et[U])*G:0);return isNaN(q)?-1/0:q},Wt=(U,G=Hi)=>G*an*((U+Yr)/_.width)+this._spinAngle,Ue=(U,G,q)=>{const le=A+G*Gt,be=Wt(U,q);return[y+le*Math.cos(be),k+le*Math.sin(be)]},Jr=(U,G,q,le,be)=>{h.beginPath();for(const je of B&&!ie?[1,-1]:[Hi]){const[ut,Et]=d?[Wt(U,je),Wt(U+q,je)]:[];h.moveTo(...Ue(U,G,je)),h.lineTo(...Ue(U,G+le,je)),d?h.arc(y,k,A+(G+le)*Gt,ut,Et,je!=1):h.lineTo(...Ue(U+q,G+le,je)),h.lineTo(...Ue(U+q,G,je)),d&&!be&&h.arc(y,k,A+G*Gt,Et,ut,je==1)}Xr(be),h.fill()},Qr=(U=0,G=0)=>{let q;if(p==Ri&&!Zn||re==cn)q=w[N];else{const le=p==sd?G%_t:Tt.findLastIndex(be=>a?Ut(U)<=Ut(be.level):U<=be.level);q=Tt[le].color}h.fillStyle=h.strokeStyle=q};if(Z){if(ie&&!$){const U=lt*(N+zt),G=zt?-1:1;h.setTransform(G,0,0,1,U,0)}if((!Q||ce)&&(Q&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Ht,(N==0||!$&&!fe)&&h.fillRect(C,ne-S,lt,(Q&&this.reflexAlpha==1?g:b)+S),h.globalAlpha=1),this.showScaleY&&!c&&!$&&(N==0||!fe)&&Zr(),a?(h.setLineDash([qr,Qn]),h.lineWidth=O[0].width):h.lineWidth=u?Math.min(R,O[0].width/2):R,h.save(),!$){const U=new Path2D;U.rect(0,ne,_.width,g),h.clip(U)}}let et=this._fftData[N];this._analyzer[N].getFloatFrequencyData(et),J&&(et=et.map((U,G)=>U+q_(this._binToFreq(G)))),h.beginPath();let ei=[];for(let U=0;U<gu;U++){const G=O[U],{posX:q,barCenter:le,width:be,freq:je,binLo:ut,binHi:Et,ratioLo:At,ratioHi:pn}=G;let Se=Math.max(Gi(ut,At),Gi(Et,pn));for(let oe=ut+1;oe<Et;oe++)et[oe]>Se&&(Se=et[oe]);if(Se=this._normalizedB(Se),G.value[N]=Se,mu+=Se,G.peak[N]>0&&G.alpha[N]>0&&(G.hold[N]--,G.hold[N]<0)){if(T&&!Jn){const oe=!o||u&&R>0?1:o?G.peak[N]:P;G.alpha[N]=oe*(1+G.hold[N]/De)}else G.peak[N]+=G.hold[N]*Pe/he/H_;G.alpha[N]<=0&&(G.peak[N]=0)}if(Se>=G.peak[N]&&(G.peak[N]=Se,G.hold[N]=se,G.alpha[N]=!o||u&&R>0?1:o?Se:P),!Z)continue;h.globalAlpha=c||o?Se:u?P:1,Qr(Se,U);const Oe=c?Ct:a?Ut(Se):Se*Ct|0;if(re==cn){const oe=U?0:(this._normalizedB(et[O[1].binLo])*Ct+Oe)/2;if($){if(U==0&&(ie&&h.moveTo(...Ue(0,0)),h.lineTo(...Ue(0,q<0?oe:Oe))),q>=0){const Ke=[q,Oe];h.lineTo(...Ue(...Ke)),ei.push(Ke)}}else{if(U==0)if(B==-1&&!ie)h.moveTo(C,Ee-(q<C?oe:Oe));else{const Ke=ut?this._normalizedB(et[ut-1])*Ct:Oe;h.moveTo(C-R,Ee-Ke)}(ie||B!=-1||q>=C)&&h.lineTo(q,Ee-Oe)}}else if(a){if(ce&&!Q&&(N==0||!fe)){const oe=h.globalAlpha;h.strokeStyle=Zg,h.globalAlpha=1,Kr(le,ne,Ee),h.strokeStyle=h.fillStyle,h.globalAlpha=oe}if(Zn){const oe=c?0:Tt.findLastIndex(qt=>Ut(Se)<=Ut(qt.level));let Ke=Ee;for(let qt=_t-1;qt>=oe;qt--){h.strokeStyle=Tt[qt].color;let yu=Ee-(qt==oe?Oe:Ut(Tt[qt].level));Kr(le,Ke,yu),Ke=yu-Qn}}else Kr(le,Ee,Ee-Oe)}else if(q>=C)if($)Jr(q,0,be,Oe,u);else if(d){const oe=be/2,Ke=Ee+oe;h.beginPath(),h.moveTo(q,Ke),h.lineTo(q,Ke-Oe),h.arc(le,Ke-Oe,oe,Ar,an),h.lineTo(q+be,Ke),Xr(u),h.fill()}else{const oe=u?h.lineWidth:0;h.beginPath(),h.rect(q,Ee+oe,be,-Oe-oe),Xr(u),h.fill()}const mn=G.peak[N],_u=G.alpha[N];if(mn>0&&_u>0&&W&&!Jn&&!c&&q>=C&&q<Wr){if(T?h.globalAlpha=_u:u&&R>0?h.globalAlpha=1:o&&(h.globalAlpha=mn),(p==rd||Zn)&&Qr(mn),a){const oe=Ut(mn);oe>=Qn&&h.fillRect(q,Ee-oe,be,qr)}else if(!$)h.fillRect(q,Ee-mn*Ct,be,2);else if(re!=cn){const oe=mn*Ct;Jr(q,oe,be,!this._radialInvert||ct||oe+A>=2?-2:2)}}}if(Z){if(h.globalAlpha=1,re==cn){if(Qr(),$&&!ie){if(B){let U;for(;U=ei.pop();)h.lineTo(...Ue(...U,-1))}h.closePath()}if(R>0&&h.stroke(),P>0){if($){const U=ie?Wt(lt>>1):0,G=ie?Wt(lt):an;h.moveTo(...Ue(ie?lt>>1:0,0)),h.arc(y,k,A,U,G,ie?!zt:!0)}else h.lineTo(Wr,Ee),h.lineTo(C,Ee);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((Jn||$&&W)&&(ei=[],h.beginPath(),O.forEach((U,G)=>{let q=U.posX,le=U.peak[N],be=G?"lineTo":"moveTo";if($&&q<0){const je=O[G+1];le=hv(q,le,je.posX,je.peak[N],0),q=0}le*=Ct,Jn?(h[be](...$?Ue(q,le):[q,Ee-le]),$&&B&&!ie&&ei.push([q,le])):le>0&&Jr(q,le,1,-2)}),Jn)){let U;for(;U=ei.pop();)h.lineTo(...Ue(...U,-1));h.lineWidth=1,h.stroke()}}h.restore(),ie&&!$&&h.setTransform(1,0,0,1,0,0),(!ie&&!fe||N)&&z_(N)}}if(K_(mu/(gu<<vu-1)),Z&&(B&&!$&&!ie&&(h.setTransform(-1,0,0,1,_.width-C,0),h.drawImage(_,C,0,y,_.height,0,0,y,_.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),W_()),this.showFPS){const N=ee.height;h.font=`bold ${N}px ${Mi}`,h.fillStyle=Yg,h.textAlign="right",h.fillText(Math.round(I),_.width-N,N*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=w[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:w}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case ln:return Math.log2(e);case Rr:return 26.81*e/(1960+e)-.53;case Mr:return Math.log2(1+e/700);case Hn: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:c,innerRadius:l,outerRadius:u}=this._aux,{isLumi:d}=this._flg,m=this._chLayout==at,g=1-s,y=d?e.height:e.height*(1-s*!m)|0;for(const k of[0,1]){const x=this._gradients[this._selectedGrads[k]],b=x.colorStops,S=x.dir=="h";let C;if(i?C=n.createRadialGradient(r,a,u,r,a,l-(u-l)*m):C=n.createLinearGradient(...S?[c,0,c+o,0]:[0,0,0,y]),b){const A=m&&!this._splitGradient&&(!S||i);for(let M=0;M<1+A;M++){const O=b.length-1;b.forEach((_,w)=>{let f=_.pos;if(A&&(f/=2),m&&!d&&!i&&!S&&(f*=g,!A&&f>.5*g&&(f+=.5*s)),M==1)if(i||d){const p=O-w;_=b[p],f=1-_.pos/2}else w==0&&f>0&&C.addColorStop(.5,_.color),f+=.5;C.addColorStop(f,_.color),m&&w==O&&f<.5&&C.addColorStop(.5,_.color)})}}this._canvasGradients[k]=C}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(c,l,u)=>c<=l?l:c>=u?u:c,o=c=>10**(c/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 c=this.isFullscreen,l=c&&this._fsEl==n,u=l?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=l?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=md&&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!==c&&(e=gd),this._fsStatus=c,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new qe(rv,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(Gn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Gn,...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 pv={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}]}},Sd=({stream:t,className:e,onClick:n})=>{var o;const i=ke(null),s=Vt();return Ne(()=>{var l;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),c=new fv(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 c.registerGradient("gradient",pv[((l=s.audio_visualizer_config)==null?void 0:l.color)||"verdant"]),c.gradient="gradient",()=>{c.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),E("div",{onClick:n,className:pt("w-full",e),ref:i})};/**
16
+ */const qg="4.5.1",Ar=Math.PI,an=2*Ar,Ir=Ar/2,nd=8.17579892,id="dual-combined",Pi="dual-horizontal",mt="single",at="dual-vertical",sd="bar-index",rd="bar-level",Ri="gradient",od=60,ad="click",Kg="fullscreenchange",cd="resize",Xg="#111",ld="",dd="A",ud="B",hd="C",fd="D",pd="468",Mi="sans-serif",Yg="#0f0",Zg="#7f7f7f22",cn=10,md="create",gd="fschange",Jg="lores",Qg=cd,Pr="user",ev="#000c",vd="#fff",tv="#4f4",_d="#888",nv="#555",Rr="bark",Hn="linear",ln="log",Mr="mel",yd=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],bd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:yd}],["rainbow",{dir:"h",colorStops:["#817",...yd,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Gn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:mt,colorMode:Ri,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:ln,gradient:bd[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:ld,width:void 0},iv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],sv=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],rv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Lr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],ov=["ERR_INVALID_MODE","Invalid mode"],av=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],cv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],lv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],dv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],uv=["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 wd=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),xd=t=>{for(const e in t)return!1;return!0},Li=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],hv=(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 fv{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||(xd(n)&&!xd(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,p]of bd)this.registerGradient(d,p);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(iv)}}if(!s.createGain)throw new qe(sv);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 c=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Qg),this._fsTimeout=0)},od))};window.ResizeObserver&&(this._observer=new ResizeObserver(c),this._observer.observe(this._container)),this._controller=new AbortController;const l=this._controller.signal;window.addEventListener(cd,c,{signal:l}),i.addEventListener(Kg,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(gd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},od)},{signal:l});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(ad,u))};window.addEventListener(ad,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:l}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(md)}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=Li(e,[mt,Pi,at,id]),this._input.disconnect(),this._input.connect(this._chLayout!=mt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=mt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Li(e,[Ri,sd,rd])}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=Li(e,[ln,Rr,Mr,Hn]),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||Gn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Pr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(Jg)}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(Lr);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(Lr);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(ov,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||Gn.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(av);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=-Ir),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return wd("stereo","channelLayout"),this._chLayout!=mt}set stereo(e){wd("stereo","channelLayout"),this.channelLayout=e?at:mt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=Li(e,[ld,dd,ud,hd,fd,pd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Pr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return qg}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new qe(cv);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==mt&&!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:c,_splitter:l}=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(),l.disconnect(),o.disconnect(),c&&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==mt?1:2;let r=0;for(let a=0;a<o;a++)for(let c=i;c<=s;c++)r+=this._normalizedB(this._fftData[a][c]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Gn))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(lv);if(typeof n!="object")throw new qe(dv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new qe(uv);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const c=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:c,color:r}:o(r.pos)&&(r.pos=c),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||Xg,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Pr)}setFreqRange(e,n){if(e<1||n<1)throw new qe(Lr);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:c,_mode:l,_radial:u,_radialInvert:d,_reflexRatio:p}=this,g=s.width>>1,y=s.height>>1,k=o==at&&!u,x=o==Pi,b=l%10!=0,S=b&&this._frequencyScale==ln,C=this._showLeds&&b&&!u,I=this._lumiBars&&b&&!u,M=this._alphaBars&&!I&&l!=cn,O=this._outlineBars&&b&&!I&&!C,_=this._roundBars&&b&&!I&&!C,w=o!=at||p>0&&!I,f=s.height-(k&&!C?.5:0)>>k,m=f*(I||u?1:1-p)|0,h=s.width-g*(x||c!=0),v=k?s.height-f*2:0,T=g*(c==-1&&!x&&!u);let P=Math.min(s.width,s.height)*.375*(o==at?1:this._radius)|0,A=Math.min(g,y);d&&o!=at&&([P,A]=[A,P]);const L=W=>e.push({...W,peak:[0,0],hold:[0],alpha:[0],value:[0]}),R=W=>{const Z=this._freqToBin(W,"floor"),J=this._binToFreq(Z),ee=this._binToFreq(Z+1),ue=Math.log2(W/J)/Math.log2(ee/J);return[Z,ue]};let V,X,B;if(S){const W=(se,fe,ie)=>+se.toPrecision(ie?Math.max(fe,1+Math.log10(se)|0):fe),Z=se=>{const fe=[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],ie=Math.log10(se)|0,ct=se/10**ie;let Qe=1;for(;Qe<fe.length&&ct>fe[Qe];)Qe++;return ct-fe[Qe-1]<fe[Qe]-ct&&Qe--,(fe[Qe]*10**(ie+5)|0)/1e5},J=[0,24,12,8,6,4,3,2,1][l],ee=n?10**(3/(J*10)):2**(1/J),ue=ee**.5;let De=n?7.94328235/(J%2?1:ue):nd;do{let se=De;const fe=W(se/ue,4,!0),ie=W(se*ue,4,!0),[ct,Qe]=R(fe),[Zn,lt]=R(ie);n?se=J<4?Z(se):W(se,se.toString()[0]<5?3:2):se=W(se,4,!0),se>=a&&L({posX:0,freq:se,freqLo:fe,freqHi:ie,binLo:ct,binHi:Zn,ratioLo:Qe,ratioHi:lt}),De*=ee}while(De<=r);V=h/e.length,e.forEach((se,fe)=>se.posX=T+fe*V);const he=e[0],Pe=e[e.length-1];X=this._freqScaling(he.freqLo),B=h/(this._freqScaling(Pe.freqHi)-X),he.freqLo<a&&(he.freqLo=a,[he.binLo,he.ratioLo]=R(a)),Pe.freqHi>r&&(Pe.freqHi=r,[Pe.binHi,Pe.ratioHi]=R(r))}else if(b){const W=[0,24,12,8,6,4,3,2,1][l]*10,Z=J=>{switch(this._frequencyScale){case Rr:return 1960/(26.81/(J+.53)-1);case Mr:return 700*(2**J-1);case Hn:return J}};V=h/W,X=this._freqScaling(a),B=h/(this._freqScaling(r)-X);for(let J=0,ee=0;J<W;J++,ee+=V){const ue=Z(X+ee/B),De=Z(X+(ee+V/2)/B),he=Z(X+(ee+V)/B),[Pe,se]=R(ue),[fe,ie]=R(he);L({posX:T+ee,freq:De,freqLo:ue,freqHi:he,binLo:Pe,binHi:fe,ratioLo:se,ratioHi:ie})}}else{V=1,X=this._freqScaling(a),B=h/(this._freqScaling(r)-X);const W=this._freqToBin(a,"floor"),Z=this._freqToBin(r);let J=-999;for(let ee=W;ee<=Z;ee++){const ue=this._binToFreq(ee),De=T+Math.round(B*(this._freqScaling(ue)-X));if(De>J)L({posX:De,freq:ue,freqLo:ue,freqHi:ue,binLo:ee,binHi:ee,ratioLo:0,ratioHi:0}),J=De;else if(e.length){const he=e[e.length-1];he.binHi=ee,he.freqHi=ue,he.freq=(he.freqLo*ue)**.5}}}let re=0,Q=0;if(C){const W=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]],J=this._ledParams,[ee,ue,De]=J||Z[l];let he,Pe=m;if(J){const se=2*W;let fe;he=ee+1;do he--,fe=Pe/he/(1+ue),Q=fe*ue;while((fe<se||Q<se)&&he>1)}else{const se=540/ue;Q=Math.min(ue*W,Math.max(2,Pe/se+.1|0))}w&&(Pe+=Q),J||(he=Math.min(ee,Pe/(Q*2)|0)),re=De>=1?De:V*De,this._leds=[he,re,Q,Pe/he-Q]}const $=Math.min(V-1,i*(i>0&&i<1?V:1));b&&(V-=Math.max(C?re:0,$)),e.forEach((W,Z)=>{let J=W.posX,ee=V;b&&(i==0&&!C?(J|=0,ee|=0,Z>0&&J>e[Z-1].posX+e[Z-1].width&&(J--,ee++)):J+=Math.max(C?re:0,$)/2,W.posX=J),W.barCenter=J+(V==1?0:ee/2),W.width=ee});const ce=[];for(const W of[0,1]){const Z=o==at?(f+v)*W:0,J=Z+f,ee=Z+m-(!C||w?0:Q);ce.push({channelTop:Z,channelBottom:J,analyzerBottom:ee})}this._aux={analyzerHeight:m,analyzerWidth:h,centerX:g,centerY:y,channelCoords:ce,channelHeight:f,channelGap:v,initialX:T,innerRadius:P,outerRadius:A,scaleMin:X,unitWidth:B},this._flg={isAlpha:M,isBands:b,isLeds:C,isLumi:I,isOctaves:S,isOutline:O,isRound:_,noLedGap:w},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:c,_noteLabels:l,_radial:u,_scaleX:d,_scaleR:p}=this,g=d.canvas,y=p.canvas,k=[],x=this._chLayout==Pi,b=this._chLayout==at,S=Math.min(r.width,r.height),C=["C",,"D",,"E","F",,"G",,"A",,"B"],I=S/34|0,M=g.height>>1,O=I>>1,_=M*(l?.7:1.5),w=O*(l?1:2),f=2**(1/12);if(!l&&(this._ansiBands||a!=ln))k.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Hn?k.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):k.push(8e3,16e3);else{let A=nd;for(let L=-1;L<11;L++)for(let R=0;R<12;R++){if(A>=this._minFreq&&A<=this._maxFreq){const V=C[R],X=V=="C";(V&&l&&!c&&!x||X)&&k.push(l?[A,V+(X?L:"")]:A)}A*=f}}y.width=y.height=Math.max(S*.15,(i<<1)+b*I);const m=y.width>>1,h=m-I*.7,v=(A,L)=>{const R=an*(A/r.width),V=R-Ir,X=h*Math.cos(V),B=h*Math.sin(V);p.save(),p.translate(m+X,m+B),p.rotate(R),p.fillText(L,0,0),p.restore()};g.width|=0,d.fillStyle=p.strokeStyle=ev,d.fillRect(0,0,g.width,g.height),p.arc(m,m,m-I/2,0,an),p.lineWidth=I,p.stroke(),d.fillStyle=p.fillStyle=vd,d.font=`${M}px ${Mi}`,p.font=`${O}px ${Mi}`,d.textAlign=p.textAlign="center";let T=-_/4,P=-w;for(const A of k){const[L,R]=Array.isArray(A)?A:[A,A<1e3?A|0:`${(A/100|0)/10}k`],V=o*(this._freqScaling(L)-s),X=g.height*.75,B=R[0]=="C",re=M*(l&&!c&&!x?B?1.2:.6:3);if(d.fillStyle=p.fillStyle=B&&!c&&!x?tv:vd,l){const Q=a==ln,$=a==Hn;let ce=["C"];if((Q||L>2e3||!$&&L>250||(!u||b)&&(!$&&L>125||L>1e3))&&ce.push("G"),(Q||L>4e3||!$&&L>500||(!u||b)&&(!$&&L>250||L>2e3))&&ce.push("E"),($&&L>4e3||(!u||b)&&(Q||L>2e3||!$&&L>500))&&ce.push("D","F","A","B"),!ce.includes(R[0]))continue}V>=T+_/2&&V<=e&&(d.fillText(R,x&&c==-1?e-V:n+V,X,re),(x||c&&(V>_||c==1))&&d.fillText(R,x&&c!=1?e+V:(n||r.width)-V,X,re),T=V+Math.min(re,d.measureText(R).width)/2),V>=P+w&&V<e-w&&(v(x&&c==1?e-V:V,R),(x||c&&(V>w||c==1))&&v(x&&c!=-1?e+V:-V,R),P=V)}}_draw(e){this._runId=requestAnimationFrame(N=>this._draw(N));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:c,isOctaves:l,isOutline:u,isRound:d,noLedGap:p}=this._flg,{analyzerHeight:g,centerX:y,centerY:k,channelCoords:x,channelHeight:b,channelGap:S,initialX:C,innerRadius:I,outerRadius:M}=this._aux,{_bars:O,canvas:_,_canvasGradients:w,_chLayout:f,_colorMode:m,_ctx:h,_energy:v,_fadePeaks:T,fillAlpha:P,_fps:A,_linearAmplitude:L,_lineWidth:R,maxDecibels:V,minDecibels:X,_mirror:B,_mode:re,overlay:Q,_radial:$,showBgColor:ce,showPeaks:W,useCanvas:Z,_weightingFilter:J}=this,ee=this._scaleX.canvas,ue=this._scaleR.canvas,De=A*this._peakFadeTime/1e3,he=A**2,Pe=this._gravity*1e3,se=A*this._peakHoldTime/1e3,fe=f==id,ie=f==Pi,ct=f==at,Qe=f==mt,Zn=a&&this._trueLeds&&m==Ri,lt=$?_.width:this._aux.analyzerWidth,Wr=C+lt,Jn=W&&this._peakLine&&re==cn,Ct=$?M-I:g,H_=Ct/this._pixelRatio,[G_,J_,Qn,qr]=this._leds||[];v.val>0&&A>0&&(this._spinAngle+=this._spinSpeed*an/60/A);const z_=N=>{if(this._reflexRatio>0&&!c&&!$){let ne,dt;this.reflexFit||ct?(ne=ct&&N==0?b+S:0,dt=b-g):(ne=_.height-g*2,dt=g),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,_.height),h.drawImage(_,0,x[N].channelTop,_.width,g,0,ne,_.width,dt),h.restore()}},W_=()=>{this.showScaleX&&($?(h.save(),h.translate(y,k),this._spinSpeed&&h.rotate(this._spinAngle+Ir),h.drawImage(ue,-ue.width>>1,-ue.width>>1),h.restore()):h.drawImage(ee,0,_.height-ee.height))},q_=N=>{const ne=N**2,dt=424.36,Ee=11599.29,Ui=25122.25,Tt=544496.41,_t=148693636,Ht=Gt=>20*Math.log10(Gt);switch(J){case dd:const Gt=_t*ne**2/((ne+dt)*Math.sqrt((ne+Ee)*(ne+Tt))*(ne+_t));return 2+Ht(Gt);case ud:const zt=_t*ne*N/((ne+dt)*Math.sqrt(ne+Ui)*(ne+_t));return .17+Ht(zt);case hd:const Yr=_t*ne/((ne+dt)*(ne+_t));return .06+Ht(Yr);case fd:const Hi=((103791848e-2-ne)**2+108076816e-2*ne)/((9837328-ne)**2+11723776*ne),Zr=N/68966888496476e-18*Math.sqrt(Hi/((ne+79919.29)*(ne+1345600)));return Ht(Zr);case pd:const Gi=-4737338981378384e-39*N**6+2043828333606125e-30*N**4-1363894795463638e-22*ne+1,Wt=1306612257412824e-34*N**5-2118150887518656e-26*N**3+.0005559488023498642*N,Ue=.0001246332637532143*N/Math.hypot(Gi,Wt);return 18.2+Ht(Ue)}return 0},Kr=(N,ne,dt)=>{h.beginPath(),h.moveTo(N,ne),h.lineTo(N,dt),h.stroke()},Xr=N=>{if(N&&R){const ne=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ne}},Ut=N=>Math.max(0,(N*G_|0)*(qr+Qn)-Qn),K_=N=>{v.val=N,v.peak>0&&(v.hold--,v.hold<0&&(v.peak+=v.hold*Pe/he/_.height*this._pixelRatio)),N>=v.peak&&(v.peak=N,v.hold=se)};Q&&h.clearRect(0,0,_.width,_.height);let mu=0;const gu=O.length,vu=Qe?1:2;for(let N=0;N<vu;N++){const{channelTop:ne,channelBottom:dt,analyzerBottom:Ee}=x[N],Ui=this._gradients[this._selectedGrads[N]],Tt=Ui.colorStops,_t=Tt.length,Ht=!ce||a&&!Q?"#000":Ui.bgColor,Gt=ct&&$&&N?-1:1,zt=!N&&B==-1||N&&B==1,Yr=!ie||N&&B!=1?0:lt>>(N||!zt),Hi=ie&&zt?-1:1,Zr=()=>{const U=ee.height,G=U>>1,q=L?100:V,le=L?0:X,be=L?20:5,je=g/(q-le),ut=B!=-1&&(!ie||N==0||B==1),Et=B!=1&&(!ie||N!=B);h.save(),h.fillStyle=_d,h.font=`${G}px ${Mi}`,h.textAlign="right",h.lineWidth=1;for(let At=q;At>le;At-=be){const pn=ne+(q-At)*je,Se=At%2==0|0;if(Se){const Oe=pn+G*(pn==ne?.8:.35);ut&&h.fillText(At,U*.85,Oe),Et&&h.fillText(At,(ie?lt:_.width)-U*.1,Oe),h.strokeStyle=_d,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=nv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(C+U*Se*ut,~~pn+.5),h.lineTo(Wr-U*Se*Et,~~pn+.5),h.stroke()}h.restore()},Gi=(U,G)=>{const q=et[U]+(U<et.length-1?(et[U+1]-et[U])*G:0);return isNaN(q)?-1/0:q},Wt=(U,G=Hi)=>G*an*((U+Yr)/_.width)+this._spinAngle,Ue=(U,G,q)=>{const le=I+G*Gt,be=Wt(U,q);return[y+le*Math.cos(be),k+le*Math.sin(be)]},Jr=(U,G,q,le,be)=>{h.beginPath();for(const je of B&&!ie?[1,-1]:[Hi]){const[ut,Et]=d?[Wt(U,je),Wt(U+q,je)]:[];h.moveTo(...Ue(U,G,je)),h.lineTo(...Ue(U,G+le,je)),d?h.arc(y,k,I+(G+le)*Gt,ut,Et,je!=1):h.lineTo(...Ue(U+q,G+le,je)),h.lineTo(...Ue(U+q,G,je)),d&&!be&&h.arc(y,k,I+G*Gt,Et,ut,je==1)}Xr(be),h.fill()},Qr=(U=0,G=0)=>{let q;if(m==Ri&&!Zn||re==cn)q=w[N];else{const le=m==sd?G%_t:Tt.findLastIndex(be=>a?Ut(U)<=Ut(be.level):U<=be.level);q=Tt[le].color}h.fillStyle=h.strokeStyle=q};if(Z){if(ie&&!$){const U=lt*(N+zt),G=zt?-1:1;h.setTransform(G,0,0,1,U,0)}if((!Q||ce)&&(Q&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Ht,(N==0||!$&&!fe)&&h.fillRect(C,ne-S,lt,(Q&&this.reflexAlpha==1?g:b)+S),h.globalAlpha=1),this.showScaleY&&!c&&!$&&(N==0||!fe)&&Zr(),a?(h.setLineDash([qr,Qn]),h.lineWidth=O[0].width):h.lineWidth=u?Math.min(R,O[0].width/2):R,h.save(),!$){const U=new Path2D;U.rect(0,ne,_.width,g),h.clip(U)}}let et=this._fftData[N];this._analyzer[N].getFloatFrequencyData(et),J&&(et=et.map((U,G)=>U+q_(this._binToFreq(G)))),h.beginPath();let ei=[];for(let U=0;U<gu;U++){const G=O[U],{posX:q,barCenter:le,width:be,freq:je,binLo:ut,binHi:Et,ratioLo:At,ratioHi:pn}=G;let Se=Math.max(Gi(ut,At),Gi(Et,pn));for(let oe=ut+1;oe<Et;oe++)et[oe]>Se&&(Se=et[oe]);if(Se=this._normalizedB(Se),G.value[N]=Se,mu+=Se,G.peak[N]>0&&G.alpha[N]>0&&(G.hold[N]--,G.hold[N]<0)){if(T&&!Jn){const oe=!o||u&&R>0?1:o?G.peak[N]:P;G.alpha[N]=oe*(1+G.hold[N]/De)}else G.peak[N]+=G.hold[N]*Pe/he/H_;G.alpha[N]<=0&&(G.peak[N]=0)}if(Se>=G.peak[N]&&(G.peak[N]=Se,G.hold[N]=se,G.alpha[N]=!o||u&&R>0?1:o?Se:P),!Z)continue;h.globalAlpha=c||o?Se:u?P:1,Qr(Se,U);const Oe=c?Ct:a?Ut(Se):Se*Ct|0;if(re==cn){const oe=U?0:(this._normalizedB(et[O[1].binLo])*Ct+Oe)/2;if($){if(U==0&&(ie&&h.moveTo(...Ue(0,0)),h.lineTo(...Ue(0,q<0?oe:Oe))),q>=0){const Ke=[q,Oe];h.lineTo(...Ue(...Ke)),ei.push(Ke)}}else{if(U==0)if(B==-1&&!ie)h.moveTo(C,Ee-(q<C?oe:Oe));else{const Ke=ut?this._normalizedB(et[ut-1])*Ct:Oe;h.moveTo(C-R,Ee-Ke)}(ie||B!=-1||q>=C)&&h.lineTo(q,Ee-Oe)}}else if(a){if(ce&&!Q&&(N==0||!fe)){const oe=h.globalAlpha;h.strokeStyle=Zg,h.globalAlpha=1,Kr(le,ne,Ee),h.strokeStyle=h.fillStyle,h.globalAlpha=oe}if(Zn){const oe=c?0:Tt.findLastIndex(qt=>Ut(Se)<=Ut(qt.level));let Ke=Ee;for(let qt=_t-1;qt>=oe;qt--){h.strokeStyle=Tt[qt].color;let yu=Ee-(qt==oe?Oe:Ut(Tt[qt].level));Kr(le,Ke,yu),Ke=yu-Qn}}else Kr(le,Ee,Ee-Oe)}else if(q>=C)if($)Jr(q,0,be,Oe,u);else if(d){const oe=be/2,Ke=Ee+oe;h.beginPath(),h.moveTo(q,Ke),h.lineTo(q,Ke-Oe),h.arc(le,Ke-Oe,oe,Ar,an),h.lineTo(q+be,Ke),Xr(u),h.fill()}else{const oe=u?h.lineWidth:0;h.beginPath(),h.rect(q,Ee+oe,be,-Oe-oe),Xr(u),h.fill()}const mn=G.peak[N],_u=G.alpha[N];if(mn>0&&_u>0&&W&&!Jn&&!c&&q>=C&&q<Wr){if(T?h.globalAlpha=_u:u&&R>0?h.globalAlpha=1:o&&(h.globalAlpha=mn),(m==rd||Zn)&&Qr(mn),a){const oe=Ut(mn);oe>=Qn&&h.fillRect(q,Ee-oe,be,qr)}else if(!$)h.fillRect(q,Ee-mn*Ct,be,2);else if(re!=cn){const oe=mn*Ct;Jr(q,oe,be,!this._radialInvert||ct||oe+I>=2?-2:2)}}}if(Z){if(h.globalAlpha=1,re==cn){if(Qr(),$&&!ie){if(B){let U;for(;U=ei.pop();)h.lineTo(...Ue(...U,-1))}h.closePath()}if(R>0&&h.stroke(),P>0){if($){const U=ie?Wt(lt>>1):0,G=ie?Wt(lt):an;h.moveTo(...Ue(ie?lt>>1:0,0)),h.arc(y,k,I,U,G,ie?!zt:!0)}else h.lineTo(Wr,Ee),h.lineTo(C,Ee);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((Jn||$&&W)&&(ei=[],h.beginPath(),O.forEach((U,G)=>{let q=U.posX,le=U.peak[N],be=G?"lineTo":"moveTo";if($&&q<0){const je=O[G+1];le=hv(q,le,je.posX,je.peak[N],0),q=0}le*=Ct,Jn?(h[be](...$?Ue(q,le):[q,Ee-le]),$&&B&&!ie&&ei.push([q,le])):le>0&&Jr(q,le,1,-2)}),Jn)){let U;for(;U=ei.pop();)h.lineTo(...Ue(...U,-1));h.lineWidth=1,h.stroke()}}h.restore(),ie&&!$&&h.setTransform(1,0,0,1,0,0),(!ie&&!fe||N)&&z_(N)}}if(K_(mu/(gu<<vu-1)),Z&&(B&&!$&&!ie&&(h.setTransform(-1,0,0,1,_.width-C,0),h.drawImage(_,C,0,y,_.height,0,0,y,_.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),W_()),this.showFPS){const N=ee.height;h.font=`bold ${N}px ${Mi}`,h.fillStyle=Yg,h.textAlign="right",h.fillText(Math.round(A),_.width-N,N*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=w[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:w}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case ln:return Math.log2(e);case Rr:return 26.81*e/(1960+e)-.53;case Mr:return Math.log2(1+e/700);case Hn: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:c,innerRadius:l,outerRadius:u}=this._aux,{isLumi:d}=this._flg,p=this._chLayout==at,g=1-s,y=d?e.height:e.height*(1-s*!p)|0;for(const k of[0,1]){const x=this._gradients[this._selectedGrads[k]],b=x.colorStops,S=x.dir=="h";let C;if(i?C=n.createRadialGradient(r,a,u,r,a,l-(u-l)*p):C=n.createLinearGradient(...S?[c,0,c+o,0]:[0,0,0,y]),b){const I=p&&!this._splitGradient&&(!S||i);for(let M=0;M<1+I;M++){const O=b.length-1;b.forEach((_,w)=>{let f=_.pos;if(I&&(f/=2),p&&!d&&!i&&!S&&(f*=g,!I&&f>.5*g&&(f+=.5*s)),M==1)if(i||d){const m=O-w;_=b[m],f=1-_.pos/2}else w==0&&f>0&&C.addColorStop(.5,_.color),f+=.5;C.addColorStop(f,_.color),p&&w==O&&f<.5&&C.addColorStop(.5,_.color)})}}this._canvasGradients[k]=C}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(c,l,u)=>c<=l?l:c>=u?u:c,o=c=>10**(c/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 c=this.isFullscreen,l=c&&this._fsEl==n,u=l?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=l?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=md&&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!==c&&(e=gd),this._fsStatus=c,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new qe(rv,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(Gn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Gn,...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 pv={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}]}},Sd=({stream:t,className:e,onClick:n})=>{var o;const i=ke(null),s=Vt();return Ne(()=>{var l;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),c=new fv(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 c.registerGradient("gradient",pv[((l=s.audio_visualizer_config)==null?void 0:l.color)||"verdant"]),c.gradient="gradient",()=>{c.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),E("div",{onClick:n,className:pt("w-full",e),ref:i})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
@@ -103,12 +103,12 @@
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 Dr=Fe("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ad=ls(!1),Pv=()=>oa(Ad),gt=({children:t,className:e,onClick:n,tooltip:i})=>E("button",{title:i,onClick:n,className:pt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Id=({call:t})=>{const[e,n]=Pv(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return E("div",{className:"flex items-center justify-center gap-2",children:[E(gt,{tooltip:e?"Unmute":"Mute",onClick:i,className:pt(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?E(xv,{className:"w-5 h-5 text-black dark:text-white"}):E(Sv,{className:"w-5 h-5 text-black dark:text-white"})}),E(gt,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:E(Cv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Pd=({call:t,onExpand:e})=>E(Un.div,{layoutId:Ai,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:[E(Sd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),E(td,{stream:t.remoteStream}),E(ed,{size:"small"}),E(Id,{call:t})]});function Rv(){const[t,e]=Re(!1),n=Vt();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 E("div",{children:[E(gt,{tooltip:"More",onClick:()=>e(!t),children:E(Ed,{className:"text-black dark:text-white"})}),t&&E("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:[E(gt,{tooltip:"More",onClick:()=>e(!t),children:E(Ed,{className:"text-black dark:text-white"})}),E("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&E("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",E(Av,{className:"w-4 h-4"})]}),n.report_issue_url&&E("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",E(Iv,{className:"w-4 h-4"})]}),n.view_history_url&&E("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",E(bv,{className:"w-4 h-4"})]})]})]})]})}function Mv({onCapture:t,onClose:e}){const n=ke(null),i=ke(null),s=ke(null),[o,r]=Re(null),[a,c]=Re(!0);Ne(()=>((async()=>{try{const m=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=m,n.current&&(n.current.srcObject=m,c(!1))}catch(m){console.error("Error accessing camera:",m),m instanceof Error?m.name==="NotAllowedError"||m.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):m.name==="NotFoundError"||m.name==="DevicesNotFoundError"?r("No camera found on this device."):m.name==="NotReadableError"||m.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."),c(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(m=>m.stop())}),[]);const l=()=>{if(!n.current||!i.current)return;const d=n.current,m=i.current,g=m.getContext("2d");if(!g)return;m.width=d.videoWidth,m.height=d.videoHeight,g.drawImage(d,0,0,m.width,m.height);const y=m.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(k=>k.stop()),t(y),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return E("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:[E("div",{className:"absolute top-2 right-2 z-10",children:E(gt,{tooltip:"Close",onClick:u,children:E(Dr,{className:"text-white w-5 h-5"})})}),E("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&E("div",{className:"absolute text-white text-center",children:E("p",{className:"text-sm",children:"Loading camera..."})}),o&&E("div",{className:"text-white text-center max-w-xs",children:[E("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),E("p",{className:"text-xs",children:o}),E("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&&E(Xe,{children:[E("video",{ref:n,autoPlay:!0,playsInline:!0,className:pt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),E("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&E("div",{className:"p-3 flex justify-center",children:E("button",{onClick:l,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:[E(Td,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function Lv({item:t,containerRef:e}){const n=ke(null);return Ne(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),E("li",{className:pt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[E("span",{className:"text-xs text-[#969696]",children:t.timestamp.toLocaleTimeString()}),E("div",{className:pt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&E("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&E("img",{src:i.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},s))}),t.content&&E("p",{className:pt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const Dv=({transcript:t,call:e})=>{const n=ke(null),i=ke(null),s=ke(null),[o,r]=Re([]),[a,c]=Re(!1),[l,u]=Re([]),[,d]=Er();Ne(()=>()=>{o.forEach(_=>URL.revokeObjectURL(_.preview))},[o]),Ne(()=>{if(l.length===0)return;const _=t.filter(w=>w.role==="user"&&!w.id.startsWith("optimistic-"));if(_.length>0){const w=_[_.length-1];u(f=>f.filter(p=>p.timestamp>w.timestamp))}},[t,l]);const m=_=>new Promise((w,f)=>{const p=new FileReader;p.onload=()=>w(p.result),p.onerror=f,p.readAsDataURL(_)}),g=async _=>{if(_.type.startsWith("image/"))try{const w=await m(_),f=URL.createObjectURL(_),p={id:Date.now().toString(),file:_,base64:w,preview:f};r(h=>[...h,p])}catch(w){console.error("Error processing image:",w)}},y=_=>{r(w=>{const f=w.find(p=>p.id===_);return f&&URL.revokeObjectURL(f.preview),w.filter(p=>p.id!==_)})},k=_=>{const w=_.target,f=w.files;f&&f.length>0&&(Array.from(f).forEach(g),w.value="")},x=_=>{var f;const w=(f=_.clipboardData)==null?void 0:f.items;w&&Array.from(w).forEach(p=>{if(p.type.startsWith("image/")){const h=p.getAsFile();h&&g(h)}})},b=()=>{var _;(_=i.current)==null||_.click()},S=()=>{c(!0)},C=_=>{fetch(_).then(w=>w.blob()).then(w=>{const f=new File([w],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(f)}).catch(w=>{console.error("Error processing camera capture:",w)})},A=async()=>{var f;const _=n.current&&n.current.value.trim()!=="",w=o.length>0;if(_||w){const p=((f=n.current)==null?void 0:f.value)||"",h=new Date,v={id:`optimistic-${h.getTime()}`,role:"user",content:p,timestamp:h,attachments:o.map(T=>({type:"image",url:T.base64}))};u(T=>[...T,v]),w&&d("processing_image"),e.sendConversationMessage(p,o.map(T=>T.base64)),n.current&&(n.current.value=""),o.forEach(T=>URL.revokeObjectURL(T.preview)),r([])}},M=_=>{_.key==="Enter"&&(_.preventDefault(),A())},O=[...t,...l];return E("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:[E("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((_,w)=>E(Lv,{item:_,containerRef:s},_.id+w))}),o.length>0&&E("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(_=>E("div",{className:"relative",children:[E("img",{src:_.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),E("button",{onClick:()=>y(_.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:E(Dr,{className:"w-3 h-3"})})]},_.id))}),E("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:[E("input",{ref:n,type:"text",onKeyDown:M,onPaste:x,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),E("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:k,className:"hidden"}),E(gt,{tooltip:"Attach image",onClick:b,children:E(kv,{className:"text-[#969696] w-4 h-4"})}),E(gt,{tooltip:"Take photo",onClick:S,children:E(Td,{className:"text-[#969696] w-4 h-4"})}),E(gt,{tooltip:"Send",children:E(Tv,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&E(Mv,{onCapture:C,onClose:()=>c(!1)})]})};function Ov({onCollapse:t}){return E("div",{className:"flex items-center justify-between w-full",children:[E(Rv,{}),E(gt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:E(Dr,{className:"text-black dark:text-white"})})]})}const Nv=({call:t,onCollapse:e,transcript:n})=>E(lp,{children:E(Un.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:[E("div",{className:"p-4 text-center",children:[E(Ov,{onCollapse:e}),E(Sd,{className:"h-[144px]",stream:t.remoteStream}),E(ed,{size:"large",className:"mb-4"}),E(Id,{call:t})]}),E(td,{stream:t.remoteStream}),E(Dv,{call:t,transcript:n})]})});function Rd(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 j(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(l){try{c(i.next(l))}catch(u){o(u)}}function a(l){try{c(i.throw(l))}catch(u){o(u)}}function c(l){var u;l.done?s(l.value):(u=l.value,u instanceof n?u:new n(function(d){d(u)})).then(r,a)}c((i=i.apply(t,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var Md=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Vv=new Uint8Array(16);function Fv(){if(!Md)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Md(Vv)}for(var Ld=[],Di=0;Di<256;++Di)Ld[Di]=(Di+256).toString(16).substr(1);function dn(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||Fv)();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 c=0,l=Ld;return[l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]]].join("")}(s)}const Dd="wss://rtc.telnyx.com",Bv={urls:"stun:stun.l.google.com:19302"},jv={urls:"stun:stun.telnyx.com:3478"},Od={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",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"})(F||(F={}));var $v=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Nd(t,e){return t(e={exports:{}},e.exports),e.exports}var Uv=Nd(function(t){var e,n;e=$v,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(x,b){var S=x[b];if(typeof S.bind=="function")return S.bind(x);try{return Function.prototype.bind.call(S,x)}catch{return function(){return Function.prototype.apply.apply(S,[x,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(x,b){for(var S=0;S<r.length;S++){var C=r[S];this[C]=S<x?i:this.methodFactory(C,x,b)}this.log=this.debug}function u(x,b,S){return function(){typeof console!==s&&(l.call(this,b,S),this[x].apply(this,arguments))}}function d(x,b,S){return function(C){return C==="debug"&&(C="log"),typeof console!==s&&(C==="trace"&&o?c:console[C]!==void 0?a(console,C):console.log!==void 0?a(console,"log"):i)}(x)||u.apply(this,arguments)}function m(x,b,S){var C,A=this;b=b??"WARN";var M="loglevel";function O(){var w;if(typeof window!==s&&M){try{w=window.localStorage[M]}catch{}if(typeof w===s)try{var f=window.document.cookie,p=f.indexOf(encodeURIComponent(M)+"=");p!==-1&&(w=/^([^;]+)/.exec(f.slice(p))[1])}catch{}return A.levels[w]===void 0&&(w=void 0),w}}typeof x=="string"?M+=":"+x:typeof x=="symbol"&&(M=void 0),A.name=x,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=S||d,A.getLevel=function(){return C},A.setLevel=function(w,f){if(typeof w=="string"&&A.levels[w.toUpperCase()]!==void 0&&(w=A.levels[w.toUpperCase()]),!(typeof w=="number"&&w>=0&&w<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+w;if(C=w,f!==!1&&function(p){var h=(r[p]||"silent").toUpperCase();if(typeof window!==s&&M){try{return void(window.localStorage[M]=h)}catch{}try{window.document.cookie=encodeURIComponent(M)+"="+h+";"}catch{}}}(w),l.call(A,w,x),typeof console===s&&w<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(w){b=w,O()||A.setLevel(w,!1)},A.resetLevel=function(){A.setLevel(b,!1),function(){if(typeof window!==s&&M){try{return void window.localStorage.removeItem(M)}catch{}try{window.document.cookie=encodeURIComponent(M)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(w){A.setLevel(A.levels.TRACE,w)},A.disableAll=function(w){A.setLevel(A.levels.SILENT,w)};var _=O();_==null&&(_=b),A.setLevel(_,!1)}var g=new m,y={};g.getLogger=function(x){if(typeof x!="symbol"&&typeof x!="string"||x==="")throw new TypeError("You must supply a name when creating a logger.");var b=y[x];return b||(b=y[x]=new m(x,g.getLevel(),g.methodFactory)),b};var k=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=k),g},g.getLoggers=function(){return y},g.default=g,g},t.exports?t.exports=n():e.log=n()});const D=Uv.getLogger("telnyx"),Hv=D.methodFactory;D.methodFactory=(t,e,n)=>{const i=Hv(t,e,n);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);i.apply(void 0,s)}},D.setLevel(D.getLevel());const Oi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{D.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Vd=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},un=t=>t instanceof Function||typeof t=="function",Ni=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Gv=/^(ws|wss):\/\//,Fd=(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?Fd(a,r):{result:s}},Bd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Vi=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),zn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Or=t=>{var e,n,i,s,o,r;let a="",c="";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&&(c=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||c};function jd({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?zv(i,t):i,n=s}),resolve:e,reject:n}}const zv=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Nr="telnyx-voice-sdk-id";function Ft(){return sessionStorage.getItem(Nr)}var Te,kt,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Nr)}),function(t){t.Offer="offer",t.Answer="answer"}(Te||(Te={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(kt||(kt={})),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 Je={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError"},Wv={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}};var z,Vr,$e,vt,Le;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(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"}($e||($e={})),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"}(Le||(Le={}));const hn="GLOBAL",Be={},Wn=(t,e)=>`${t}|${e}`,$d=(t,e=hn)=>Wn(t,e)in Be,Bt=(t,e,n=hn)=>{const i=Wn(t,n);i in Be||(Be[i]=[]),Be[i].push(e)},Ud=(t,e,n=hn)=>{const i=function(s){jt(t,i,n),e(s)};return i.prototype.targetRef=e,Bt(t,i,n)},jt=(t,e,n=hn)=>{if(!$d(t,n))return!1;const i=Wn(t,n);if(un(e))for(let s=Be[i].length-1;s>=0;s--){const o=Be[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Be[i].splice(s,1)}else Be[i]=[];return Be[i].length===0&&delete Be[i],!0},Y=(t,e,n=hn,i=!0)=>{const s=i&&n!==hn;if(!$d(t,n))return s&&Y(t,e),!1;const o=Wn(t,n),r=Be[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)Be[o][a](e);return s&&Y(t,e),!0},Fr=t=>{const e=Wn(t,"");Object.keys(Be).filter(n=>n.indexOf(e)===0).forEach(n=>delete Be[n])};let qv=typeof WebSocket<"u"?WebSocket:null;const Kv=0,Xv=1,Yv=2,Zv=3;class Hd{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Dd,this._timers={},this._hasTrickleIceCanaryBeenUsed=!1,this._trickleIceCanaryEnabled=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Dd),n&&(this._host=(r=>`${Gv.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._trickleIceCanaryEnabled=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===Xv}get connecting(){return this._wsClient&&this._wsClient.readyState===Kv}get closing(){return this._wsClient&&this._wsClient.readyState===Yv}get closed(){return this._wsClient&&this._wsClient.readyState===Zv}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=Ft();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._trickleIceCanaryEnabled=!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._trickleIceCanaryEnabled&&(e.searchParams.set("canary","true"),n&&!this._hasTrickleIceCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),D.debug("first trickle ice canary connection. Refreshing voice_sdk_id")),this.session.options.trickleIce=!0,this._hasTrickleIceCanaryBeenUsed=!0),this._wsClient=new qv(e.toString()),this._wsClient.onopen=i=>Y(F.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Y(F.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Y(F.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=Vd(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(Nr,a)),this._unsetTimer(r.id),D.debug(`RECV:
106
+ */const Dr=Fe("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ad=ls(!1),Pv=()=>oa(Ad),gt=({children:t,className:e,onClick:n,tooltip:i})=>E("button",{title:i,onClick:n,className:pt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Id=({call:t})=>{const[e,n]=Pv(),i=()=>{n(o=>{const r=!o;return r?t.muteAudio():t.unmuteAudio(),r})},s=()=>{t.hangup()};return E("div",{className:"flex items-center justify-center gap-2",children:[E(gt,{tooltip:e?"Unmute":"Mute",onClick:i,className:pt(e?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:e?E(xv,{className:"w-5 h-5 text-black dark:text-white"}):E(Sv,{className:"w-5 h-5 text-black dark:text-white"})}),E(gt,{tooltip:"End Call",onClick:s,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:E(Cv,{className:"w-4 h-4 text-black dark:text-white"})})]})},Pd=({call:t,onExpand:e})=>E(Un.div,{layoutId:Ai,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:[E(Sd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),E(td,{stream:t.remoteStream}),E(ed,{size:"small"}),E(Id,{call:t})]});function Rv(){const[t,e]=Re(!1),n=Vt();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 E("div",{children:[E(gt,{tooltip:"More",onClick:()=>e(!t),children:E(Ed,{className:"text-black dark:text-white"})}),t&&E("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:[E(gt,{tooltip:"More",onClick:()=>e(!t),children:E(Ed,{className:"text-black dark:text-white"})}),E("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&E("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",E(Av,{className:"w-4 h-4"})]}),n.report_issue_url&&E("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",E(Iv,{className:"w-4 h-4"})]}),n.view_history_url&&E("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",E(bv,{className:"w-4 h-4"})]})]})]})]})}function Mv({onCapture:t,onClose:e}){const n=ke(null),i=ke(null),s=ke(null),[o,r]=Re(null),[a,c]=Re(!0);Ne(()=>((async()=>{try{const p=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=p,n.current&&(n.current.srcObject=p,c(!1))}catch(p){console.error("Error accessing camera:",p),p instanceof Error?p.name==="NotAllowedError"||p.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):p.name==="NotFoundError"||p.name==="DevicesNotFoundError"?r("No camera found on this device."):p.name==="NotReadableError"||p.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."),c(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(p=>p.stop())}),[]);const l=()=>{if(!n.current||!i.current)return;const d=n.current,p=i.current,g=p.getContext("2d");if(!g)return;p.width=d.videoWidth,p.height=d.videoHeight,g.drawImage(d,0,0,p.width,p.height);const y=p.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(k=>k.stop()),t(y),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return E("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:[E("div",{className:"absolute top-2 right-2 z-10",children:E(gt,{tooltip:"Close",onClick:u,children:E(Dr,{className:"text-white w-5 h-5"})})}),E("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&E("div",{className:"absolute text-white text-center",children:E("p",{className:"text-sm",children:"Loading camera..."})}),o&&E("div",{className:"text-white text-center max-w-xs",children:[E("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),E("p",{className:"text-xs",children:o}),E("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&&E(Xe,{children:[E("video",{ref:n,autoPlay:!0,playsInline:!0,className:pt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),E("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&E("div",{className:"p-3 flex justify-center",children:E("button",{onClick:l,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:[E(Td,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function Lv({item:t,containerRef:e}){const n=ke(null);return Ne(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),E("li",{className:pt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[E("span",{className:"text-xs text-[#969696]",children:t.timestamp.toLocaleTimeString()}),E("div",{className:pt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&E("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&E("img",{src:i.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},s))}),t.content&&E("p",{className:pt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const Dv=({transcript:t,call:e})=>{const n=ke(null),i=ke(null),s=ke(null),[o,r]=Re([]),[a,c]=Re(!1),[l,u]=Re([]),[,d]=Er();Ne(()=>()=>{o.forEach(_=>URL.revokeObjectURL(_.preview))},[o]),Ne(()=>{if(l.length===0)return;const _=t.filter(w=>w.role==="user"&&!w.id.startsWith("optimistic-"));if(_.length>0){const w=_[_.length-1];u(f=>f.filter(m=>m.timestamp>w.timestamp))}},[t,l]);const p=_=>new Promise((w,f)=>{const m=new FileReader;m.onload=()=>w(m.result),m.onerror=f,m.readAsDataURL(_)}),g=async _=>{if(_.type.startsWith("image/"))try{const w=await p(_),f=URL.createObjectURL(_),m={id:Date.now().toString(),file:_,base64:w,preview:f};r(h=>[...h,m])}catch(w){console.error("Error processing image:",w)}},y=_=>{r(w=>{const f=w.find(m=>m.id===_);return f&&URL.revokeObjectURL(f.preview),w.filter(m=>m.id!==_)})},k=_=>{const w=_.target,f=w.files;f&&f.length>0&&(Array.from(f).forEach(g),w.value="")},x=_=>{var f;const w=(f=_.clipboardData)==null?void 0:f.items;w&&Array.from(w).forEach(m=>{if(m.type.startsWith("image/")){const h=m.getAsFile();h&&g(h)}})},b=()=>{var _;(_=i.current)==null||_.click()},S=()=>{c(!0)},C=_=>{fetch(_).then(w=>w.blob()).then(w=>{const f=new File([w],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(f)}).catch(w=>{console.error("Error processing camera capture:",w)})},I=async()=>{var f;const _=n.current&&n.current.value.trim()!=="",w=o.length>0;if(_||w){const m=((f=n.current)==null?void 0:f.value)||"",h=new Date,v={id:`optimistic-${h.getTime()}`,role:"user",content:m,timestamp:h,attachments:o.map(T=>({type:"image",url:T.base64}))};u(T=>[...T,v]),w&&d("processing_image"),e.sendConversationMessage(m,o.map(T=>T.base64)),n.current&&(n.current.value=""),o.forEach(T=>URL.revokeObjectURL(T.preview)),r([])}},M=_=>{_.key==="Enter"&&(_.preventDefault(),I())},O=[...t,...l];return E("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:[E("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((_,w)=>E(Lv,{item:_,containerRef:s},_.id+w))}),o.length>0&&E("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(_=>E("div",{className:"relative",children:[E("img",{src:_.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),E("button",{onClick:()=>y(_.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:E(Dr,{className:"w-3 h-3"})})]},_.id))}),E("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:[E("input",{ref:n,type:"text",onKeyDown:M,onPaste:x,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),E("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:k,className:"hidden"}),E(gt,{tooltip:"Attach image",onClick:b,children:E(kv,{className:"text-[#969696] w-4 h-4"})}),E(gt,{tooltip:"Take photo",onClick:S,children:E(Td,{className:"text-[#969696] w-4 h-4"})}),E(gt,{tooltip:"Send",children:E(Tv,{onClick:I,className:"text-[#969696] w-4 h-4"})})]}),a&&E(Mv,{onCapture:C,onClose:()=>c(!1)})]})};function Ov({onCollapse:t}){return E("div",{className:"flex items-center justify-between w-full",children:[E(Rv,{}),E(gt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:E(Dr,{className:"text-black dark:text-white"})})]})}const Nv=({call:t,onCollapse:e,transcript:n})=>E(lp,{children:E(Un.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:[E("div",{className:"p-4 text-center",children:[E(Ov,{onCollapse:e}),E(Sd,{className:"h-[144px]",stream:t.remoteStream}),E(ed,{size:"large",className:"mb-4"}),E(Id,{call:t})]}),E(td,{stream:t.remoteStream}),E(Dv,{call:t,transcript:n})]})});function Rd(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 j(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(l){try{c(i.next(l))}catch(u){o(u)}}function a(l){try{c(i.throw(l))}catch(u){o(u)}}function c(l){var u;l.done?s(l.value):(u=l.value,u instanceof n?u:new n(function(d){d(u)})).then(r,a)}c((i=i.apply(t,[])).next())})}typeof SuppressedError=="function"&&SuppressedError;var Md=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Vv=new Uint8Array(16);function Fv(){if(!Md)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Md(Vv)}for(var Ld=[],Di=0;Di<256;++Di)Ld[Di]=(Di+256).toString(16).substr(1);function dn(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||Fv)();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 c=0,l=Ld;return[l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],"-",l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]],l[r[c++]]].join("")}(s)}const Dd="wss://rtc.telnyx.com",Bv={urls:"stun:stun.l.google.com:19302"},jv={urls:"stun:stun.telnyx.com:3478"},Od={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"};var F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.Ready="telnyx.ready",t.Error="telnyx.error",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"})(F||(F={}));var $v=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Nd(t,e){return t(e={exports:{}},e.exports),e.exports}var Uv=Nd(function(t){var e,n;e=$v,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(x,b){var S=x[b];if(typeof S.bind=="function")return S.bind(x);try{return Function.prototype.bind.call(S,x)}catch{return function(){return Function.prototype.apply.apply(S,[x,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(x,b){for(var S=0;S<r.length;S++){var C=r[S];this[C]=S<x?i:this.methodFactory(C,x,b)}this.log=this.debug}function u(x,b,S){return function(){typeof console!==s&&(l.call(this,b,S),this[x].apply(this,arguments))}}function d(x,b,S){return function(C){return C==="debug"&&(C="log"),typeof console!==s&&(C==="trace"&&o?c:console[C]!==void 0?a(console,C):console.log!==void 0?a(console,"log"):i)}(x)||u.apply(this,arguments)}function p(x,b,S){var C,I=this;b=b??"WARN";var M="loglevel";function O(){var w;if(typeof window!==s&&M){try{w=window.localStorage[M]}catch{}if(typeof w===s)try{var f=window.document.cookie,m=f.indexOf(encodeURIComponent(M)+"=");m!==-1&&(w=/^([^;]+)/.exec(f.slice(m))[1])}catch{}return I.levels[w]===void 0&&(w=void 0),w}}typeof x=="string"?M+=":"+x:typeof x=="symbol"&&(M=void 0),I.name=x,I.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},I.methodFactory=S||d,I.getLevel=function(){return C},I.setLevel=function(w,f){if(typeof w=="string"&&I.levels[w.toUpperCase()]!==void 0&&(w=I.levels[w.toUpperCase()]),!(typeof w=="number"&&w>=0&&w<=I.levels.SILENT))throw"log.setLevel() called with invalid level: "+w;if(C=w,f!==!1&&function(m){var h=(r[m]||"silent").toUpperCase();if(typeof window!==s&&M){try{return void(window.localStorage[M]=h)}catch{}try{window.document.cookie=encodeURIComponent(M)+"="+h+";"}catch{}}}(w),l.call(I,w,x),typeof console===s&&w<I.levels.SILENT)return"No console available for logging"},I.setDefaultLevel=function(w){b=w,O()||I.setLevel(w,!1)},I.resetLevel=function(){I.setLevel(b,!1),function(){if(typeof window!==s&&M){try{return void window.localStorage.removeItem(M)}catch{}try{window.document.cookie=encodeURIComponent(M)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},I.enableAll=function(w){I.setLevel(I.levels.TRACE,w)},I.disableAll=function(w){I.setLevel(I.levels.SILENT,w)};var _=O();_==null&&(_=b),I.setLevel(_,!1)}var g=new p,y={};g.getLogger=function(x){if(typeof x!="symbol"&&typeof x!="string"||x==="")throw new TypeError("You must supply a name when creating a logger.");var b=y[x];return b||(b=y[x]=new p(x,g.getLevel(),g.methodFactory)),b};var k=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=k),g},g.getLoggers=function(){return y},g.default=g,g},t.exports?t.exports=n():e.log=n()});const D=Uv.getLogger("telnyx"),Hv=D.methodFactory;D.methodFactory=(t,e,n)=>{const i=Hv(t,e,n);return function(){const s=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(let o=0;o<arguments.length;o++)s.push(arguments[o]);i.apply(void 0,s)}},D.setLevel(D.getLevel());const Oi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{D.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},Vd=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},un=t=>t instanceof Function||typeof t=="function",Ni=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Gv=/^(ws|wss):\/\//,Fd=(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?Fd(a,r):{result:s}},Bd=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Vi=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),zn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Or=t=>{var e,n,i,s,o,r;let a="",c="";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&&(c=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||c};function jd({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?zv(i,t):i,n=s}),resolve:e,reject:n}}const zv=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Nr="telnyx-voice-sdk-id";function Ft(){return sessionStorage.getItem(Nr)}var Te,kt,te;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Nr)}),function(t){t.Offer="offer",t.Answer="answer"}(Te||(Te={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(kt||(kt={})),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 Je={generic:"event",[te.Display]:"participantData",[te.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError"},Wv={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}};var z,Vr,$e,vt,Le;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(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"}($e||($e={})),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"}(Le||(Le={}));const hn="GLOBAL",Be={},Wn=(t,e)=>`${t}|${e}`,$d=(t,e=hn)=>Wn(t,e)in Be,Bt=(t,e,n=hn)=>{const i=Wn(t,n);i in Be||(Be[i]=[]),Be[i].push(e)},Ud=(t,e,n=hn)=>{const i=function(s){jt(t,i,n),e(s)};return i.prototype.targetRef=e,Bt(t,i,n)},jt=(t,e,n=hn)=>{if(!$d(t,n))return!1;const i=Wn(t,n);if(un(e))for(let s=Be[i].length-1;s>=0;s--){const o=Be[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Be[i].splice(s,1)}else Be[i]=[];return Be[i].length===0&&delete Be[i],!0},Y=(t,e,n=hn,i=!0)=>{const s=i&&n!==hn;if(!$d(t,n))return s&&Y(t,e),!1;const o=Wn(t,n),r=Be[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)Be[o][a](e);return s&&Y(t,e),!0},Fr=t=>{const e=Wn(t,"");Object.keys(Be).filter(n=>n.indexOf(e)===0).forEach(n=>delete Be[n])};let qv=typeof WebSocket<"u"?WebSocket:null;const Kv=0,Xv=1,Yv=2,Zv=3;class Hd{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Dd,this._timers={},this._hasTrickleIceCanaryBeenUsed=!1,this._trickleIceCanaryEnabled=!1,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,trickleIce:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Dd),n&&(this._host=(r=>`${Gv.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._trickleIceCanaryEnabled=!0)}get connected(){return this._wsClient&&this._wsClient.readyState===Xv}get connecting(){return this._wsClient&&this._wsClient.readyState===Kv}get closing(){return this._wsClient&&this._wsClient.readyState===Yv}get closed(){return this._wsClient&&this._wsClient.readyState===Zv}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}connect(){const e=new URL(this._host);let n=Ft();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._trickleIceCanaryEnabled=!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._trickleIceCanaryEnabled&&(e.searchParams.set("canary","true"),n&&!this._hasTrickleIceCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),D.debug("first trickle ice canary connection. Refreshing voice_sdk_id")),this.session.options.trickleIce=!0,this._hasTrickleIceCanaryBeenUsed=!0),this._wsClient=new qv(e.toString()),this._wsClient.onopen=i=>Y(F.SocketOpen,i,this.session.uuid),this._wsClient.onclose=i=>Y(F.SocketClose,i,this.session.uuid),this._wsClient.onerror=i=>Y(F.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid),this._wsClient.onmessage=i=>{var s,o;const r=Vd(i.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(a=r.voice_sdk_id,sessionStorage.setItem(Nr,a)),this._unsetTimer(r.id),D.debug(`RECV:
107
107
  `,JSON.stringify(r,null,2),`
108
108
  `),Le[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!Y(r.id,r)){const c=Or(r);Y(F.SocketMessage,r,this.session.uuid),c&&(this.previousGatewayState=c)}}else this._handleStringResponse(r)}}sendRawText(e){this._wsClient.send(e)}send(e){const{request:n}=e,i=new Promise((s,o)=>{if(n.hasOwnProperty("result"))return s();Ud(n.id,r=>{const{result:a,error:c}=Fd(r);return c?o(c):s(a)})});return D.debug(`SEND:
109
109
  `,JSON.stringify(n,null,2),`
110
- `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(un(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_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)),Y(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else D.warn("Unknown message from socket",e)}}class qn{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:dn()},e)}}const Gd={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 Ie extends qn{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Rd(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Gd)i&&n.hasOwnProperty(i)&&(n[Gd[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class zd extends Ie{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Jv{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>j(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Or(n))}),this.getIsRegistered=()=>j(this,void 0,void 0,function*(){const n=new zd(Ft());this.pendingRequestId=n.request.id,this.gatewayStateTask=jd({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Le.REGISTER,Le.REGED].includes(i)}),this.session=e,this.gatewayStateTask=jd({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Wd extends Ie{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Qv{constructor(e){if(this.options=e,this.uuid=dn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new Hd(this),this.registerAgent=new Jv(this)}get __logger(){return D}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return j(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Bd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Vi(this.options)||zn(this.options)}broadcast(e){}disconnect(){return j(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners()})}on(e,n){return Bt(e,n,this.uuid),this}off(e,n){return jt(e,n,this.uuid),this}connect(){return j(this,void 0,void 0,function*(){this.connection||(this.connection=new Hd(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){Y(F.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return j(this,void 0,void 0,function*(){this.options.keepConnectionAliveOnSocketClose&&this._emptyExecuteQueues()})}onNetworkClose(){this.relayProtocol&&Fr(this.relayProtocol);for(const e in this.subscriptions)Fr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],jt(e,null,n)):(delete this.subscriptions[e],Fr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},un(n)&&Bt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.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&&(D.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Wd(Ft()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){D.debug("Ping received"),this._pong=!0}static on(e,n){Bt(e,n)}static off(e){jt(e)}static uuid(){return dn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Br=t=>navigator.mediaDevices.getUserMedia(t),Fi=t=>t&&t instanceof MediaStream,Kn=(t,e)=>{const n=Ni(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},qd=(t,e)=>j(void 0,void 0,void 0,function*(){const n=Ni(t);if(n===null)return D.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return D.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),e_=t=>{t&&t.readyState==="live"&&t.stop()},Xn=t=>{Fi(t)&&t.getTracks().forEach(e_),t=null},Bi=t=>j(void 0,void 0,void 0,function*(){D.info("RTCService.getUserMedia",t);const{audio:e}=t;if(!e)return null;try{return yield Br(t)}catch(n){throw D.error("getUserMedia error: ",n),n}}),Yn=(t=null,e=!1)=>j(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=>(console.error(s),null));if(i){if(Xn(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}),Kd=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],jr=(t,e,n)=>j(void 0,void 0,void 0,function*(){const i=yield Yn(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}),t_=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},$r=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=Ur(t);return n.includes(e)||i.includes(e)},Ur=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},fn=(t,e=null,n=null)=>{if(!Fi(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}})},Xd=t=>{fn(t,"audio",!0)},Yd=t=>{fn(t,"audio",!1)},Zd=t=>{fn(t,"audio",null)};function n_(){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],m=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:m,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],m=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:m,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("/"),m=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:m,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],m=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:m,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,c=window.navigator&&window.navigator.mediaDevices,l=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&l),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!Bi}}catch(t){return t.message}}var ve;function Jd(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 Qd(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),t._playFulfilled=!0}))}function eu(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"})(ve||(ve={}));var tu="2.25.6",ji=tu;class nu extends Ie{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:ji,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class i_ extends Ie{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class iu extends Ie{toString(){return te.Invite}}class su extends Ie{toString(){return te.Answer}}class Hr extends Ie{toString(){return te.Attach}}class s_ extends Ie{toString(){return te.Bye}}class ru extends Ie{toString(){return te.Candidate}}class r_ extends Ie{toString(){return te.EndOfCandidates}}class Gr extends Ie{toString(){return te.Modify}}class ou extends Ie{toString(){return te.Info}}class o_ extends Ie{toString(){return te.Broadcast}}class a_ extends Ie{toString(){return te.Subscribe}}class c_ extends Ie{toString(){return te.Unsubscribe}}class l_ extends qn{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:dn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}const au=(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:Je.conferenceUpdate,call:t.calls[s],canvasInfo:d_(o),currentLayerIdx:r};switch(n){case"layer-info":{const c=Object.assign({action:$e.LayerInfo},a);Y(F.Notification,c,t.uuid);break}case"layout-info":{const c=Object.assign({action:$e.LayoutInfo},a);Y(F.Notification,c,t.uuid);break}}},d_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Vd(e)};var $i,cu=Nd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,p,h,v){var T,P,I;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=f._events)?(P.newListener&&(f.emit("newListener",p,h.listener?h.listener:h),P=f._events),I=P[p]):(P=f._events=new i,f._eventsCount=0),I){if(typeof I=="function"?I=P[p]=v?[h,I]:[I,h]:v?I.unshift(h):I.push(h),!I.warned&&(T=o(f))&&0<T&&I.length>T){I.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+I.length+" "+p+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=f,L.type=p,L.count=I.length,function(R){typeof console.warn=="function"?console.warn(R):console.log(R)}(L)}}else I=P[p]=h,++f._eventsCount;return f}function a(f,p,h){function v(){f.removeListener(p,v),T||(T=!0,h.apply(f,arguments))}var T=!1;return v.listener=h,v}function c(f){var p=this._events;if(p){var h=p[f];if(typeof h=="function")return 1;if(h)return h.length}return 0}function l(f,p){for(var h=Array(p);p--;)h[p]=f[p];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(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var p,h,v,T,P,I,L,R=f==="error";if(I=this._events)R=R&&I.error==null;else if(!R)return!1;if(L=this.domain,R){if(p=arguments[1],!L){if(p instanceof Error)throw p;var V=new Error('Uncaught, unspecified "error" event. ('+p+")");throw V.context=p,V}return p||(p=new Error('Uncaught, unspecified "error" event')),p.domainEmitter=this,p.domain=L,p.domainThrown=!1,L.emit("error",p),!1}if(!(h=I[f]))return!1;var X=typeof h=="function";switch(v=arguments.length){case 1:(function(B,re,Q){if(re)B.call(Q);else for(var $=B.length,ce=l(B,$),W=0;W<$;++W)ce[W].call(Q)})(h,X,this);break;case 2:(function(B,re,Q,$){if(re)B.call(Q,$);else for(var ce=B.length,W=l(B,ce),Z=0;Z<ce;++Z)W[Z].call(Q,$)})(h,X,this,arguments[1]);break;case 3:(function(B,re,Q,$,ce){if(re)B.call(Q,$,ce);else for(var W=B.length,Z=l(B,W),J=0;J<W;++J)Z[J].call(Q,$,ce)})(h,X,this,arguments[1],arguments[2]);break;case 4:(function(B,re,Q,$,ce,W){if(re)B.call(Q,$,ce,W);else for(var Z=B.length,J=l(B,Z),ee=0;ee<Z;++ee)J[ee].call(Q,$,ce,W)})(h,X,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(v-1),P=1;P<v;P++)T[P-1]=arguments[P];(function(B,re,Q,$){if(re)B.apply(Q,$);else for(var ce=B.length,W=l(B,ce),Z=0;Z<ce;++Z)W[Z].apply(Q,$)})(h,X,this,T)}return!0},s.prototype.addListener=function(f,p){return r(this,f,p,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,p){return r(this,f,p,!0)},s.prototype.once=function(f,p){if(typeof p!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,p)),this},s.prototype.prependOnceListener=function(f,p){if(typeof p!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,p)),this},s.prototype.removeListener=function(f,p){var h,v,T,P,I;if(typeof p!="function")throw new TypeError('"listener" argument must be a function');if(!(v=this._events))return this;if(!(h=v[f]))return this;if(h===p||h.listener&&h.listener===p)--this._eventsCount==0?this._events=new i:(delete v[f],v.removeListener&&this.emit("removeListener",f,h.listener||p));else if(typeof h!="function"){for(T=-1,P=h.length;0<P--;)if(h[P]===p||h[P].listener&&h[P].listener===p){I=h[P].listener,T=P;break}if(0>T)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete v[f]}else(function(L,R){for(var V=R,X=V+1,B=L.length;X<B;V+=1,X+=1)L[V]=L[X];L.pop()})(h,T);v.removeListener&&this.emit("removeListener",f,I||p)}return this},s.prototype.removeAllListeners=function(f){var p,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[f]&&(--this._eventsCount==0?this._events=new i:delete h[f]),this;if(arguments.length===0){for(var v,T=Object.keys(h),P=0;P<T.length;++P)(v=T[P])!=="removeListener"&&this.removeAllListeners(v);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(p=h[f])=="function")this.removeListener(f,p);else if(p)do this.removeListener(f,p[p.length-1]);while(p[0]);return this},s.prototype.listeners=function(f){var p,h,v=this._events;return v?h=(p=v[f])?typeof p=="function"?[p.listener||p]:function(T){for(var P=Array(T.length),I=0;I<P.length;++I)P[I]=T[I].listener||T[I];return P}(p):[]:h=[],h},s.listenerCount=function(f,p){return typeof f.listenerCount=="function"?f.listenerCount(p):c.call(f,p)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function m(){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=[],k=0;256>k;++k)y.push((k+256).toString(16).substr(1));function x(f){var p=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(y[f[p+0]]+y[f[p+1]]+y[f[p+2]]+y[f[p+3]]+"-"+y[f[p+4]]+y[f[p+5]]+"-"+y[f[p+6]]+y[f[p+7]]+"-"+y[f[p+8]]+y[f[p+9]]+"-"+y[f[p+10]]+y[f[p+11]]+y[f[p+12]]+y[f[p+13]]+y[f[p+14]]+y[f[p+15]]).toLowerCase();if(!function(v){return typeof v=="string"&&g.test(v)}(h))throw TypeError("Stringified UUID is invalid");return h}function b(f,p,h){var v=(f=f||{}).random||(f.rng||m)();return v[6]=64|15&v[6],v[8]=128|63&v[8],x(v)}function S(f,p){if(!f||!p)return{};const h={...f};if(h.localCandidateId){const v=p.get(h.localCandidateId);h.local={...v}}if(h.remoteCandidateId){const v=p.get(h.remoteCandidateId);h.remote={...v}}return h}function C(f,p,h){return 8*function(v,T,P){const I=v[P],L=T?T[P]:null;return I===null||L===null?null:(I-L)/(v.timestamp-T.timestamp)*1e3}(f,p,h)}function A(f){if(!f.entries)return f;const p={};return f.forEach(function(h,v){p[v]=h}),p}function M(f,p,h={}){if(!f)return null;let v={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(v.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const T of f.values())switch(T.type){case"outbound-rtp":{const P=T.mediaType||T.kind,I={};let L={};if(!["audio","video"].includes(P))continue;if(T.codecId){const R=f.get(T.codecId);R&&(I.clockRate=R.clockRate,I.mimeType=R.mimeType,I.payloadType=R.payloadType)}L=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[P].outbound.push({...T,...I,track:{...L}});break}case"inbound-rtp":{let P=T.mediaType||T.kind,I={};const L={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const R=f.get(T.codecId);R&&(L.clockRate=R.clockRate,L.mimeType=R.mimeType,L.payloadType=R.payloadType)}if(!v.connection.id&&T.transportId){const R=f.get(T.transportId);if(R&&R.selectedCandidatePairId){const V=f.get(R.selectedCandidatePairId);v.connection=S(V,f)}}I=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[P].inbound.push({...T,...L,track:{...I}});break}case"peer-connection":v.connection.dataChannelsClosed=T.dataChannelsClosed,v.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=T.mediaType||T.kind;const I={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const L=f.get(T.codecId);L&&(I.clockRate=L.clockRate,I.mimeType=L.mimeType,I.payloadType=L.payloadType)}if(!v.connection.id&&T.transportId){const L=f.get(T.transportId);if(L&&L.selectedCandidatePairId){const R=f.get(L.selectedCandidatePairId);v.connection=S(R,f)}}v.remote[P].inbound.push({...T,...I});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=T.mediaType||T.kind,I={};if(!["audio","video"].includes(P))continue;if(T.codecId){const L=f.get(T.codecId);L&&(I.clockRate=L.clockRate,I.mimeType=L.mimeType,I.payloadType=L.payloadType)}v.remote[P].outbound.push({...T,...I});break}}if(!v.connection.id)for(const T of f.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(v.connection=S(T,f));return v=function(T,P){return P&&(T.audio.inbound.map(I=>{let L=P.audio.inbound.find(R=>R.id===I.id);I.bitrate=C(I,L,"bytesReceived"),I.packetRate=C(I,L,"packetsReceived")}),T.audio.outbound.map(I=>{let L=P.audio.outbound.find(R=>R.id===I.id);I.bitrate=C(I,L,"bytesSent"),I.packetRate=C(I,L,"packetsSent")}),T.video.inbound.map(I=>{let L=P.video.inbound.find(R=>R.id===I.id);I.bitrate=C(I,L,"bytesReceived"),I.packetRate=C(I,L,"packetsReceived")}),T.video.outbound.map(I=>{let L=P.video.outbound.find(R=>R.id===I.id);I.bitrate=C(I,L,"bytesSent"),I.packetRate=C(I,L,"packetsSent")})),T}(v,p),v}let O,_={},w=[];e.WebRTCStats=class extends s{constructor(f){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const p={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=p.getStatsInterval||1e3,this.rawStats=!!p.rawStats,this.statsObject=!!p.statsObject,this.filteredStats=!!p.filteredStats,this.shouldWrapGetUserMedia=!!p.wrapGetUserMedia,typeof p.remote=="boolean"&&(this.remote=p.remote),this.debug=!!p.debug,this.logLevel=p.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,p){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:p})}async addConnection(f){const{pc:p,peerId:h}=f;let{connectionId:v,remote:T}=f;if(T=typeof T=="boolean"?T:this.remote,!(p&&p instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(v&&v in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${v}.`);for(let I in this.peersToMonitor[h]){const L=this.peersToMonitor[h][I];if(L.pc===p)throw new Error(`We are already monitoring peer with id ${h}.`);L.pc.connectionState==="closed"&&this.removeConnection({pc:L.pc})}}const P=p.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(I){delete I.credential}),v||(v=b()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:v,data:{options:f,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:v,pc:p,remote:T}),{connectionId:v}}getTimeline(f){return this.timeline=this.timeline.sort((p,h)=>p.timestamp.getTime()-h.timestamp.getTime()),f?this.timeline.filter(p=>p.tag===f):this.timeline}get logger(){const f=p=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(p)>-1};return{error(...p){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",...p)},warn(...p){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",...p)},info(...p){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",...p)},debug(...p){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",...p)}}}removeConnection(f){let p,{connectionId:h,pc:v}=f;if(!v&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let T in this.peersToMonitor)h in this.peersToMonitor[T]&&(v=this.peersToMonitor[T][h].pc,p=T)}else if(v){if(!(v instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let P in this.peersToMonitor[T])this.peersToMonitor[T][P].pc===v&&(h=P,p=T)}if(!v||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,v),delete this.peersToMonitor[p][h],Object.values(this.peersToMonitor[p]).length===0&&delete this.peersToMonitor[p],{connectionId:h}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let p in this.peersToMonitor[f]){let h=this.peersToMonitor[f][p].pc;this.removePeerConnectionEventListeners(p,h)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),w.forEach(f=>{this.removeTrackEventListeners(f)}),w=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(f){let{peerId:p,connectionId:h,pc:v,remote:T}=f;if(!v)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:v,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};if(this.peersToMonitor[p]){if(h in this.peersToMonitor[p])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[p][h]=P}else this.peersToMonitor[p]={[h]:P};this.addPeerConnectionEventListeners(p,h,v),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(p=>{this.emitEvent(p)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let p={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);p[f]=this.peersToMonitor[f]}else p=this.peersToMonitor;let h=[];for(const v in p)for(const T in p[v]){const P=p[v][T],I=P.pc;if(I&&!this.checkIfConnectionIsClosed(v,T,I))try{const L=this.getTimestamp(),R=I.getStats(null);if(R){const V=await R,X=this.getTimestamp(),B=A(V),re={remote:P.options.remote},Q=M(V,P.stats.parsed,re),$={event:"stats",tag:"stats",peerId:v,connectionId:T,timeTaken:X-L,data:Q};this.rawStats===!0&&($.rawStats=V),this.statsObject===!0&&($.statsObject=B),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(B)),h.push($),P.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${v} did not return any stats data`)}catch(L){this.logger.error(L)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const p in this.peersToMonitor[f]){const h=this.peersToMonitor[f][p].pc;this.checkIfConnectionIsClosed(f,p,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,p,h){const v=this.isConnectionClosed(h);if(v){this.removeConnection({pc:h});let T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,peerId:f,connectionId:p,tag:"connection",data:"closed"})}return v}isConnectionClosed(f){return f.connectionState==="closed"||f.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(p=>(f({stream:p}),p),p=>(f({error:p}),Promise.reject(p)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const p={...f};for(const v in p){var h=p[v];this.statsToMonitor.includes(h.type)||delete p[v]}return p}get peerConnectionListeners(){return{icecandidate:(f,p,h,v)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",v),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:p,data:v.candidate})},track:(f,p,h,v)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,v);const T=v.track,P=v.streams[0];f in this.peersToMonitor&&p in this.peersToMonitor[f]&&(this.peersToMonitor[f][p].stream=P),this.addTrackEventListeners(T,p),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:p,data:{stream:P?this.getStreamDetails(P):null,track:T?this.getMediaTrackDetails(T):null,title:v.track.kind+":"+v.track.id+" "+v.streams.map(function(I){return"stream:"+I.id})}})},signalingstatechange:(f,p,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:p,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(f,p,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:p,data:h.iceConnectionState})},icegatheringstatechange:(f,p,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:p,data:h.iceGatheringState})},icecandidateerror:(f,p,h,v)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:p,error:{errorCode:v.errorCode}})},connectionstatechange:(f,p,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:p,data:h.connectionState})},negotiationneeded:(f,p,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:p})},datachannel:(f,p,h,v)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,v),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:p,data:v.channel})}}}addPeerConnectionEventListeners(f,p,h){this.logger.debug(`Adding event listeners for peer ${f} and connection ${p}.`),_[p]={},Object.keys(this.peerConnectionListeners).forEach(v=>{_[p][v]=this.peerConnectionListeners[v].bind(this,f,p,h),h.addEventListener(v,_[p][v],!1)})}parseGetUserMedia(f){try{const p={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(p.data.details=this.parseStream(f.stream),f.stream.getTracks().map(h=>{this.addTrackEventListeners(h),w.push(h)})),this.emitEvent(p)}catch{}}parseStream(f){const p={audio:[],video:[]};return f.getTracks().forEach(h=>{p[h.kind].push(this.getMediaTrackDetails(h))}),p}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:p=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:p}})},unmute:p=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:p}})},overconstrained:p=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:p}})},ended:p=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:p}}),this.removeTrackEventListeners(p.target)}}}addTrackEventListeners(f,p){_[f.id]={};const h=this.getTrackEventObject(p);Object.keys(h).forEach(v=>{_[f.id][v]=h[v].bind(this),f.addEventListener(v,_[f.id][v])}),_[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let v=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(v)}},1e3)}removeTrackEventListeners(f){if(f.id in _){const p=this.getTrackEventObject();Object.keys(p).forEach(h=>{f.removeEventListener(h,_[f.id][h])}),clearInterval(_[f.id].readyState),delete _[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const p={...f,timestamp:new Date};this.addToTimeline(p),p.tag&&this.emit(p.tag,p)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,p){f in _&&(Object.keys(this.peerConnectionListeners).forEach(h=>{p.removeEventListener(h,_[f][h],!1)}),delete _[f]),p.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),p.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const p=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),p.apply(navigator.mediaDevices,arguments).then(function(v){return v},function(v){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,v.name),Promise.reject(v)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});($i=cu)&&$i.__esModule&&Object.prototype.hasOwnProperty.call($i,"default")&&$i.default;var u_=cu.WebRTCStats;function h_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(l){const{jitter:u,rtt:d}=l,m=u+d/2;return .024*m+.11*(m-177.3)*(m>177.3?1:0)}({rtt:s,jitter:i}),r=function(l){const{packetsLost:u,packetsReceived:d}=l,m=u/(d+u)*100;return 20*Math.log(1+m)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function f_(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 p_ extends qn{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class m_ extends qn{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class g_ extends qn{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function v_(t){const e=dn(),n=new u_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>j(this,void 0,void 0,function*(){s.event==="stats"&&Y(F.StatsFrame,function({data:o}){var r,a,c,l,u,d,m,g;const{audio:y,remote:k}=o,{audio:x}=k,b=(a=(r=x.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,S=(l=(c=x.inbound[0])===null||c===void 0?void 0:c.roundTripTime)!==null&&l!==void 0?l:1/0,C=(d=(u=y.inbound[0])===null||u===void 0?void 0:u.packetsReceived)!==null&&d!==void 0?d:-1,A=(g=(m=y.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&g!==void 0?g:-1,M=h_({jitter:1e3*b,rtt:1e3*S,packetsLost:A,packetsReceived:C});return{jitter:b,rtt:S,mos:M,quality:f_(M),inboundAudio:y.inbound[0],outboundAudio:y.outbound[0],remoteInboundAudio:x.inbound[0],remoteOutboundAudio:x.outbound[0]}}(s),t.uuid),yield t.execute(new g_(e,s))});return{start:(s,o,r)=>j(this,void 0,void 0,function*(){yield t.execute(new p_(e)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>j(this,void 0,void 0,function*(){const o=n.getTimeline();Y(F.StatsReport,o,t.uuid),s==="file"&&function(r,a){const c=new Blob([JSON.stringify(r)],{type:"application/json"}),l=URL.createObjectURL(c),u=document.createElement("a");u.href=l,u.download=`${a}.json`,u.click(),URL.revokeObjectURL(l)}(o,`webrtc-stats-${e}-${Date.now()}`),yield t.execute(new m_(e)),n.removeAllPeers(),n.destroy()})}}class lu{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this.handleConnectionStateChange=r=>j(this,void 0,void 0,function*(){const{connectionState:a}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${a}`),a==="failed"||a==="disconnected"){const c=()=>j(this,void 0,void 0,function*(){this._isOffer()&&!this._restartedIceOnConnectionStateFailed?(this.instance.restartIce(),D.debug(`Peer Connection ${a}. Restarting ICE gathering.`),a==="failed"&&(this._restartedIceOnConnectionStateFailed=!0,D.debug("ICE has been restarted on connection state failed.")),this._isTrickleIce()?yield this.startTrickleIceNegotiation():this.startNegotiation()):this._restartedIceOnConnectionStateFailed&&(D.debug("Peer Connection failed again after ICE restart. Recovering call via peer reconnection through error handling."),Y(F.PeerConnectionFailureError,{error:new Error(`Peer Connection failed twice. previous state: ${this._prevConnectionState}, current state: ${a}`),sessionId:this._session.sessionid},this.options.id)),window.removeEventListener("online",c)});navigator.onLine?c():window.addEventListener("online",c)}this._prevConnectionState==="connected"&&a==="disconnected"&&(yield this._resetJitterBuffer()),this._prevConnectionState==="disconnected"&&a==="connected"&&(yield this._resetJitterBuffer()),this._prevConnectionState=a,this._isTrickleIce()&&(a==="connecting"&&performance.mark("peer-connection-connecting"),a==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=r=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return r.setCodecPreferences?r.setCodecPreferences(this.options.preferred_codecs):void 0},D.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Te.Offer}get isAnswer(){return this.type===Te.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get keepConnectionAliveOnSocketClose(){return this.options.keepConnectionAliveOnSocketClose||this._session.options.keepConnectionAliveOnSocketClose}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return j(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){D.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{D.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),D.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=c=>`${c.toFixed(2)}ms`;return{"New Call":{duration:a(e.duration)},"Peer Creation":{duration:a(n.duration)},"ICE Gathering":{duration:a(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:a(o.duration)},"SDP Send":{duration:a(s.duration)},"Total Duration":{duration:a(r.duration)}}}handleSignalingStateChangeEvent(e){switch(D.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){D.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?D.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Kn(i,o)}createPeerConnection(){return j(this,void 0,void 0,function*(){var e;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",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Te.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(F.MediaError,n,this.options.id),null)),performance.mark("peer-creation-end")})}init(){var e;return j(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=v_(this._session)),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(Fi(i)){const o=i.getAudioTracks();if(D.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(r=>{D.info("Local audio tracks constraints: ",r.getConstraints())}),this.isOffer&&typeof this.instance.addTransceiver=="function"){const r={direction:"sendrecv",streams:[i]};o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label;const c=this.instance.addTransceiver(a,r);this._setAudioCodec(c)})}else typeof this.instance.addTrack=="function"?(o.forEach(r=>{this.options.userVariables.microphoneLabel=r.label,this.instance.addTrack(r,i)}),this.instance.getTransceivers().forEach(r=>this._setAudioCodec(r))):this.instance.addStream(i);s===!1&&Kn(n,i)}this.isOffer?this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"):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);D.info("Add transceiver",e,n)}}_createOffer(){return j(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!!this.options.audio,D.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){D.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return j(this,void 0,void 0,function*(){D.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return j(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return D.debug("Skipping negotiation, state:",this.instance.signalingState),console.log(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Te.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){D.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return j(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){un(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return j(this,void 0,void 0,function*(){if(Fi(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,j(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s}=n;const{micLabel:o=""}=n;return s&&(s=yield jr(s,o,vt.AudioIn).catch(r=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),{audio:i}}));var n;return Bi(e)})}_resetJitterBuffer(){return j(this,void 0,void 0,function*(){try{const e=this.instance.getReceivers().find(n=>n.track&&n.track.kind==="audio");e&&"jitterBufferTarget"in e&&(e.jitterBufferTarget=20,D.debug("[jitter] target set to",e.jitterBufferTarget,"ms"))}catch(e){D.error("Peer _resetJitterBuffer error:",e)}})}_isOffer(){return this.type===Te.Offer}_isAnswer(){return this.type===Te.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n}=this.options,i={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:[Bv,Od],iceTransportPolicy:n?"relay":"all"};return D.info("RTC config",i),i}close(){var e;return j(this,void 0,void 0,function*(){yield(e=this.statsReporter)===null||e===void 0?void 0:e.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const du=ji;class uu{constructor(e,n){this.session=e,this.id="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Vr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._checkConferenceSerno=k=>{const x=k<0||!this._lastSerno||this._lastSerno&&k===this._lastSerno+1;return x&&k>=0&&(this._lastSerno=k),x},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(k=>{k.forEach(x=>{this._statsBindings.forEach(b=>{if(b.callback){if(b.constraints){for(var S in b.constraints)if(b.constraints.hasOwnProperty(S)&&b.constraints[S]!==x[S])return}b.callback(x)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:l,remoteElement:u,options:d,mediaConstraints:{audio:m},ringtoneFile:g,ringbackFile:y}=e;this.options=Object.assign({},Wv,{audio:m,iceServers:i,localElement:l,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:g,ringbackFile:y,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.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=Jd(this.options.ringtoneFile,"_ringtone"),this._ringback=Jd(this.options.ringbackFile,"_ringback"))}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),n=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("total-duration","peer-creation-start","sdp-send-end"),o=r=>`${r.toFixed(2)}ms`;return{"Peer Creation":{duration:o(e.duration)},"ICE Gathering":{duration:o(n.duration)},"SDP Send":{duration:o(i.duration)},"Total Duration":{duration:o(s.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){return j(this,void 0,void 0,function*(){this.direction=kt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new lu(Te.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init()})}answer(e={}){var n;return j(this,void 0,void 0,function*(){performance.mark("new-call-start"),this.stopRingtone(),this.direction=kt.Inbound,((n=e==null?void 0:e.customHeaders)===null||n===void 0?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new lu(Te.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end")})}playRingtone(){Qd(this._ringtone)}stopRingtone(){eu(this._ringtone)}playRingback(){Qd(this._ringback)}stopRingback(){eu(this._ringback)}hangup(e,n){var i,s,o;let r=e||{},a=n!==!1;this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],this.setState(z.Hangup);const c=()=>{var l;return(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const l=new s_({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(l).catch(u=>{D.error("telnyx_rtc.bye failed!",u),Y(F.Error,{error:u,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new Gr({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 Gr({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 Gr({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 ou({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 ou({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Yd(this.options.localStream)}unmuteAudio(){Xd(this.options.localStream)}toggleAudioMute(){Zd(this.options.localStream)}setAudioInDevice(e){return j(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="audio");if(i){const s=yield Br({audio:{deviceId:{exact:e}}}),o=s.getAudioTracks()[0];i.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach(a=>a.stop()),r.getVideoTracks().forEach(a=>s.addTrack(a)),this.options.localStream=s}})}muteVideo(){var e;e=this.options.localStream,fn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,fn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,fn(e,"video",null)}setVideoDevice(e){return j(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 Br({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Kn(r,s),this.options.camId=e,a.getAudioTracks().forEach(c=>s.addTrack(c)),a.getVideoTracks().forEach(c=>c.stop()),this.options.localStream=s}})}deaf(){Yd(this.options.remoteStream)}undeaf(){Xd(this.options.remoteStream)}toggleDeaf(){Zd(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return j(this,void 0,void 0,function*(){if(!this||!this.peer)return void D.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 D.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"}]),D.info("Parameters: ",r),D.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{D.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>console.error(a))}else D.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){switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),D.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case z.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case z.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&qd(n,i)},0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(this.gotAnswer=!0,this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:case te.Attach:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const c=a===kt.Inbound?kt.Outbound:kt.Inbound,l={type:Je[n],call:this,displayName:o,displayNumber:r,displayDirection:c};Y(F.Notification,l,this.id)||Y(F.Notification,l,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const o=Object.assign(Object.assign({},i),{type:Je.generic,call:this});Y(F.Notification,o,this.id)||Y(F.Notification,o,this.session.uuid);break}case te.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 j(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return D.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:c,modChannel:l,laName:u,conferenceMemberID:d,role:m}=n;this._dispatchConferenceUpdate({action:$e.Join,conferenceName:u,participantId:Number(d),role:m}),a&&(yield this._subscribeConferenceChat(a)),c&&(yield this._subscribeConferenceInfo(c));const g=[];for(const y in s)g.push(Object.assign({callId:s[y][0],index:Number(y)},Oi(s[y][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:o,index:r},Oi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:o,index:r},Oi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:o,index:r},Oi(s)));break;case"clear":this._dispatchConferenceUpdate({action:$e.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 j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:c,type:l}=s.data;this._dispatchConferenceUpdate({action:$e.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:c,messageType:l,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{D.error("ConfChat subscription error:",s)});$r(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 j(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,au(this.session,o)):D.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{D.error("ConfInfo subscription error:",s)});$r(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){return D.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return j(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Te.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(i=>{D.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){un(this.peer.onSdpReadyTwice)?Y(F.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;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return D.info(`No candidate - retry
110
+ `),this._wsClient.send(JSON.stringify(n)),i}close(){this._wsClient&&(un(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close()),this._wsClient=null}_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)),Y(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else D.warn("Unknown message from socket",e)}}class qn{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:dn()},e)}}const Gd={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 Ie extends qn{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Rd(e.dialogParams,["remoteSdp","localStream","remoteStream","onNotification","camId","micId","speakerId"]);for(const i in Gd)i&&n.hasOwnProperty(i)&&(n[Gd[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class zd extends Ie{constructor(e){super(),this.method=te.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Jv{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>j(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Or(n))}),this.getIsRegistered=()=>j(this,void 0,void 0,function*(){const n=new zd(Ft());this.pendingRequestId=n.request.id,this.gatewayStateTask=jd({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Le.REGISTER,Le.REGED].includes(i)}),this.session=e,this.gatewayStateTask=jd({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Wd extends Ie{constructor(e){super(),this.method=te.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Qv{constructor(e){if(this.options=e,this.uuid=dn(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new Hd(this),this.registerAgent=new Jv(this)}get __logger(){return D}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return j(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Bd(2,6)}execute(e){return this._idle?new Promise(n=>this._executeQueue.push({resolve:n,msg:e})):this.connected?this.connection.send(e):new Promise(n=>{this._executeQueue.push({resolve:n,msg:e}),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Vi(this.options)||zn(this.options)}broadcast(e){}disconnect(){return j(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this.subscriptions={},this._autoReconnect=!1,this.relayProtocol=null,this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners()})}on(e,n){return Bt(e,n,this.uuid),this}off(e,n){return jt(e,n,this.uuid),this}connect(){return j(this,void 0,void 0,function*(){this.connection||(this.connection=new Hd(this)),this._attachListeners(),this.connection.isAlive||this.connection.connect()})}_handleLoginError(e){Y(F.Error,{error:e,sessionId:this.sessionid},this.uuid)}_onSocketOpen(){return j(this,void 0,void 0,function*(){this.options.keepConnectionAliveOnSocketClose&&this._emptyExecuteQueues()})}onNetworkClose(){this.relayProtocol&&Fr(this.relayProtocol);for(const e in this.subscriptions)Fr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>this.connect(),this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],jt(e,null,n)):(delete this.subscriptions[e],Fr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},un(n)&&Bt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.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&&(D.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Wd(Ft()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){D.debug("Ping received"),this._pong=!0}static on(e,n){Bt(e,n)}static off(e){jt(e)}static uuid(){return dn()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Br=t=>navigator.mediaDevices.getUserMedia(t),Fi=t=>t&&t instanceof MediaStream,Kn=(t,e)=>{const n=Ni(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},qd=(t,e)=>j(void 0,void 0,void 0,function*(){const n=Ni(t);if(n===null)return D.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return D.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),e_=t=>{t&&t.readyState==="live"&&t.stop()},Xn=t=>{Fi(t)&&t.getTracks().forEach(e_),t=null},Bi=t=>j(void 0,void 0,void 0,function*(){D.info("RTCService.getUserMedia",t);const{audio:e}=t;if(!e)return null;try{return yield Br(t)}catch(n){throw D.error("getUserMedia error: ",n),n}}),Yn=(t=null,e=!1)=>j(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=>(console.error(s),null));if(i){if(Xn(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}),Kd=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],jr=(t,e,n)=>j(void 0,void 0,void 0,function*(){const i=yield Yn(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}),t_=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},$r=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=Ur(t);return n.includes(e)||i.includes(e)},Ur=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},fn=(t,e=null,n=null)=>{if(!Fi(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}})},Xd=t=>{fn(t,"audio",!0)},Yd=t=>{fn(t,"audio",!1)},Zd=t=>{fn(t,"audio",null)};function n_(){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],p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),p=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:p,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],p=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:p,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,c=window.navigator&&window.navigator.mediaDevices,l=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&c&&l),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!c,supportGetUserMedia:!!Bi}}catch(t){return t.message}}var ve;function Jd(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 Qd(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{console.error("playAudio",e),t._playFulfilled=!0}))}function eu(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"})(ve||(ve={}));var tu="2.25.6",ji=tu;class nu extends Ie{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:ji,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class i_ extends Ie{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class iu extends Ie{toString(){return te.Invite}}class su extends Ie{toString(){return te.Answer}}class Hr extends Ie{toString(){return te.Attach}}class s_ extends Ie{toString(){return te.Bye}}class ru extends Ie{toString(){return te.Candidate}}class r_ extends Ie{toString(){return te.EndOfCandidates}}class Gr extends Ie{toString(){return te.Modify}}class ou extends Ie{toString(){return te.Info}}class o_ extends Ie{toString(){return te.Broadcast}}class a_ extends Ie{toString(){return te.Subscribe}}class c_ extends Ie{toString(){return te.Unsubscribe}}class l_ extends qn{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:dn(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}const au=(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:Je.conferenceUpdate,call:t.calls[s],canvasInfo:d_(o),currentLayerIdx:r};switch(n){case"layer-info":{const c=Object.assign({action:$e.LayerInfo},a);Y(F.Notification,c,t.uuid);break}case"layout-info":{const c=Object.assign({action:$e.LayoutInfo},a);Y(F.Notification,c,t.uuid);break}}},d_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Vd(e)};var $i,cu=Nd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,m,h,v){var T,P,A;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=f._events)?(P.newListener&&(f.emit("newListener",m,h.listener?h.listener:h),P=f._events),A=P[m]):(P=f._events=new i,f._eventsCount=0),A){if(typeof A=="function"?A=P[m]=v?[h,A]:[A,h]:v?A.unshift(h):A.push(h),!A.warned&&(T=o(f))&&0<T&&A.length>T){A.warned=!0;var L=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");L.name="MaxListenersExceededWarning",L.emitter=f,L.type=m,L.count=A.length,function(R){typeof console.warn=="function"?console.warn(R):console.log(R)}(L)}}else A=P[m]=h,++f._eventsCount;return f}function a(f,m,h){function v(){f.removeListener(m,v),T||(T=!0,h.apply(f,arguments))}var T=!1;return v.listener=h,v}function c(f){var m=this._events;if(m){var h=m[f];if(typeof h=="function")return 1;if(h)return h.length}return 0}function l(f,m){for(var h=Array(m);m--;)h[m]=f[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(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var m,h,v,T,P,A,L,R=f==="error";if(A=this._events)R=R&&A.error==null;else if(!R)return!1;if(L=this.domain,R){if(m=arguments[1],!L){if(m instanceof Error)throw m;var V=new Error('Uncaught, unspecified "error" event. ('+m+")");throw V.context=m,V}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=L,m.domainThrown=!1,L.emit("error",m),!1}if(!(h=A[f]))return!1;var X=typeof h=="function";switch(v=arguments.length){case 1:(function(B,re,Q){if(re)B.call(Q);else for(var $=B.length,ce=l(B,$),W=0;W<$;++W)ce[W].call(Q)})(h,X,this);break;case 2:(function(B,re,Q,$){if(re)B.call(Q,$);else for(var ce=B.length,W=l(B,ce),Z=0;Z<ce;++Z)W[Z].call(Q,$)})(h,X,this,arguments[1]);break;case 3:(function(B,re,Q,$,ce){if(re)B.call(Q,$,ce);else for(var W=B.length,Z=l(B,W),J=0;J<W;++J)Z[J].call(Q,$,ce)})(h,X,this,arguments[1],arguments[2]);break;case 4:(function(B,re,Q,$,ce,W){if(re)B.call(Q,$,ce,W);else for(var Z=B.length,J=l(B,Z),ee=0;ee<Z;++ee)J[ee].call(Q,$,ce,W)})(h,X,this,arguments[1],arguments[2],arguments[3]);break;default:for(T=Array(v-1),P=1;P<v;P++)T[P-1]=arguments[P];(function(B,re,Q,$){if(re)B.apply(Q,$);else for(var ce=B.length,W=l(B,ce),Z=0;Z<ce;++Z)W[Z].apply(Q,$)})(h,X,this,T)}return!0},s.prototype.addListener=function(f,m){return r(this,f,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,m){return r(this,f,m,!0)},s.prototype.once=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,m)),this},s.prototype.prependOnceListener=function(f,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,m)),this},s.prototype.removeListener=function(f,m){var h,v,T,P,A;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(v=this._events))return this;if(!(h=v[f]))return this;if(h===m||h.listener&&h.listener===m)--this._eventsCount==0?this._events=new i:(delete v[f],v.removeListener&&this.emit("removeListener",f,h.listener||m));else if(typeof h!="function"){for(T=-1,P=h.length;0<P--;)if(h[P]===m||h[P].listener&&h[P].listener===m){A=h[P].listener,T=P;break}if(0>T)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete v[f]}else(function(L,R){for(var V=R,X=V+1,B=L.length;X<B;V+=1,X+=1)L[V]=L[X];L.pop()})(h,T);v.removeListener&&this.emit("removeListener",f,A||m)}return this},s.prototype.removeAllListeners=function(f){var m,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[f]&&(--this._eventsCount==0?this._events=new i:delete h[f]),this;if(arguments.length===0){for(var v,T=Object.keys(h),P=0;P<T.length;++P)(v=T[P])!=="removeListener"&&this.removeAllListeners(v);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(m=h[f])=="function")this.removeListener(f,m);else if(m)do this.removeListener(f,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(f){var m,h,v=this._events;return v?h=(m=v[f])?typeof m=="function"?[m.listener||m]:function(T){for(var P=Array(T.length),A=0;A<P.length;++A)P[A]=T[A].listener||T[A];return P}(m):[]:h=[],h},s.listenerCount=function(f,m){return typeof f.listenerCount=="function"?f.listenerCount(m):c.call(f,m)},s.prototype.listenerCount=c,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function p(){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=[],k=0;256>k;++k)y.push((k+256).toString(16).substr(1));function x(f){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(y[f[m+0]]+y[f[m+1]]+y[f[m+2]]+y[f[m+3]]+"-"+y[f[m+4]]+y[f[m+5]]+"-"+y[f[m+6]]+y[f[m+7]]+"-"+y[f[m+8]]+y[f[m+9]]+"-"+y[f[m+10]]+y[f[m+11]]+y[f[m+12]]+y[f[m+13]]+y[f[m+14]]+y[f[m+15]]).toLowerCase();if(!function(v){return typeof v=="string"&&g.test(v)}(h))throw TypeError("Stringified UUID is invalid");return h}function b(f,m,h){var v=(f=f||{}).random||(f.rng||p)();return v[6]=64|15&v[6],v[8]=128|63&v[8],x(v)}function S(f,m){if(!f||!m)return{};const h={...f};if(h.localCandidateId){const v=m.get(h.localCandidateId);h.local={...v}}if(h.remoteCandidateId){const v=m.get(h.remoteCandidateId);h.remote={...v}}return h}function C(f,m,h){return 8*function(v,T,P){const A=v[P],L=T?T[P]:null;return A===null||L===null?null:(A-L)/(v.timestamp-T.timestamp)*1e3}(f,m,h)}function I(f){if(!f.entries)return f;const m={};return f.forEach(function(h,v){m[v]=h}),m}function M(f,m,h={}){if(!f)return null;let v={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(v.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const T of f.values())switch(T.type){case"outbound-rtp":{const P=T.mediaType||T.kind,A={};let L={};if(!["audio","video"].includes(P))continue;if(T.codecId){const R=f.get(T.codecId);R&&(A.clockRate=R.clockRate,A.mimeType=R.mimeType,A.payloadType=R.payloadType)}L=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[P].outbound.push({...T,...A,track:{...L}});break}case"inbound-rtp":{let P=T.mediaType||T.kind,A={};const L={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const R=f.get(T.codecId);R&&(L.clockRate=R.clockRate,L.mimeType=R.mimeType,L.payloadType=R.payloadType)}if(!v.connection.id&&T.transportId){const R=f.get(T.transportId);if(R&&R.selectedCandidatePairId){const V=f.get(R.selectedCandidatePairId);v.connection=S(V,f)}}A=f.get(T.mediaSourceId)||f.get(T.trackId)||{},v[P].inbound.push({...T,...L,track:{...A}});break}case"peer-connection":v.connection.dataChannelsClosed=T.dataChannelsClosed,v.connection.dataChannelsOpened=T.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=T.mediaType||T.kind;const A={};if(!["audio","video"].includes(P))if(T.id.includes("Video"))P="video";else{if(!T.id.includes("Audio"))continue;P="audio"}if(T.codecId){const L=f.get(T.codecId);L&&(A.clockRate=L.clockRate,A.mimeType=L.mimeType,A.payloadType=L.payloadType)}if(!v.connection.id&&T.transportId){const L=f.get(T.transportId);if(L&&L.selectedCandidatePairId){const R=f.get(L.selectedCandidatePairId);v.connection=S(R,f)}}v.remote[P].inbound.push({...T,...A});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=T.mediaType||T.kind,A={};if(!["audio","video"].includes(P))continue;if(T.codecId){const L=f.get(T.codecId);L&&(A.clockRate=L.clockRate,A.mimeType=L.mimeType,A.payloadType=L.payloadType)}v.remote[P].outbound.push({...T,...A});break}}if(!v.connection.id)for(const T of f.values())T.type==="candidate-pair"&&T.nominated&&T.state==="succeeded"&&(v.connection=S(T,f));return v=function(T,P){return P&&(T.audio.inbound.map(A=>{let L=P.audio.inbound.find(R=>R.id===A.id);A.bitrate=C(A,L,"bytesReceived"),A.packetRate=C(A,L,"packetsReceived")}),T.audio.outbound.map(A=>{let L=P.audio.outbound.find(R=>R.id===A.id);A.bitrate=C(A,L,"bytesSent"),A.packetRate=C(A,L,"packetsSent")}),T.video.inbound.map(A=>{let L=P.video.inbound.find(R=>R.id===A.id);A.bitrate=C(A,L,"bytesReceived"),A.packetRate=C(A,L,"packetsReceived")}),T.video.outbound.map(A=>{let L=P.video.outbound.find(R=>R.id===A.id);A.bitrate=C(A,L,"bytesSent"),A.packetRate=C(A,L,"packetsSent")})),T}(v,m),v}let O,_={},w=[];e.WebRTCStats=class extends s{constructor(f){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:m})}async addConnection(f){const{pc:m,peerId:h}=f;let{connectionId:v,remote:T}=f;if(T=typeof T=="boolean"?T:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(v&&v in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${v}.`);for(let A in this.peersToMonitor[h]){const L=this.peersToMonitor[h][A];if(L.pc===m)throw new Error(`We are already monitoring peer with id ${h}.`);L.pc.connectionState==="closed"&&this.removeConnection({pc:L.pc})}}const P=m.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(A){delete A.credential}),v||(v=b()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:v,data:{options:f,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:v,pc:m,remote:T}),{connectionId:v}}getTimeline(f){return this.timeline=this.timeline.sort((m,h)=>m.timestamp.getTime()-h.timestamp.getTime()),f?this.timeline.filter(m=>m.tag===f):this.timeline}get logger(){const f=m=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(f){let m,{connectionId:h,pc:v}=f;if(!v&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let T in this.peersToMonitor)h in this.peersToMonitor[T]&&(v=this.peersToMonitor[T][h].pc,m=T)}else if(v){if(!(v instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let T in this.peersToMonitor)for(let P in this.peersToMonitor[T])this.peersToMonitor[T][P].pc===v&&(h=P,m=T)}if(!v||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,v),delete this.peersToMonitor[m][h],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:h}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let m in this.peersToMonitor[f]){let h=this.peersToMonitor[f][m].pc;this.removePeerConnectionEventListeners(m,h)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),w.forEach(f=>{this.removeTrackEventListeners(f)}),w=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(f){let{peerId:m,connectionId:h,pc:v,remote:T}=f;if(!v)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:v,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:T}};if(this.peersToMonitor[m]){if(h in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[m][h]=P}else this.peersToMonitor[m]={[h]:P};this.addPeerConnectionEventListeners(m,h,v),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let m={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);m[f]=this.peersToMonitor[f]}else m=this.peersToMonitor;let h=[];for(const v in m)for(const T in m[v]){const P=m[v][T],A=P.pc;if(A&&!this.checkIfConnectionIsClosed(v,T,A))try{const L=this.getTimestamp(),R=A.getStats(null);if(R){const V=await R,X=this.getTimestamp(),B=I(V),re={remote:P.options.remote},Q=M(V,P.stats.parsed,re),$={event:"stats",tag:"stats",peerId:v,connectionId:T,timeTaken:X-L,data:Q};this.rawStats===!0&&($.rawStats=V),this.statsObject===!0&&($.statsObject=B),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(B)),h.push($),P.stats.parsed=Q}else this.logger.error(`PeerConnection from peer ${v} did not return any stats data`)}catch(L){this.logger.error(L)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const m in this.peersToMonitor[f]){const h=this.peersToMonitor[f][m].pc;this.checkIfConnectionIsClosed(f,m,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,m,h){const v=this.isConnectionClosed(h);if(v){this.removeConnection({pc:h});let T=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:T,peerId:f,connectionId:m,tag:"connection",data:"closed"})}return v}isConnectionClosed(f){return f.connectionState==="closed"||f.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(m=>(f({stream:m}),m),m=>(f({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const m={...f};for(const v in m){var h=m[v];this.statsToMonitor.includes(h.type)||delete m[v]}return m}get peerConnectionListeners(){return{icecandidate:(f,m,h,v)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",v),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:m,data:v.candidate})},track:(f,m,h,v)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,v);const T=v.track,P=v.streams[0];f in this.peersToMonitor&&m in this.peersToMonitor[f]&&(this.peersToMonitor[f][m].stream=P),this.addTrackEventListeners(T,m),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:m,data:{stream:P?this.getStreamDetails(P):null,track:T?this.getMediaTrackDetails(T):null,title:v.track.kind+":"+v.track.id+" "+v.streams.map(function(A){return"stream:"+A.id})}})},signalingstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:m,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceConnectionState})},icegatheringstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:m,data:h.iceGatheringState})},icecandidateerror:(f,m,h,v)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:m,error:{errorCode:v.errorCode}})},connectionstatechange:(f,m,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:m,data:h.connectionState})},negotiationneeded:(f,m,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:m})},datachannel:(f,m,h,v)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,v),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:m,data:v.channel})}}}addPeerConnectionEventListeners(f,m,h){this.logger.debug(`Adding event listeners for peer ${f} and connection ${m}.`),_[m]={},Object.keys(this.peerConnectionListeners).forEach(v=>{_[m][v]=this.peerConnectionListeners[v].bind(this,f,m,h),h.addEventListener(v,_[m][v],!1)})}parseGetUserMedia(f){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(m.data.details=this.parseStream(f.stream),f.stream.getTracks().map(h=>{this.addTrackEventListeners(h),w.push(h)})),this.emitEvent(m)}catch{}}parseStream(f){const m={audio:[],video:[]};return f.getTracks().forEach(h=>{m[h.kind].push(this.getMediaTrackDetails(h))}),m}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(f,m){_[f.id]={};const h=this.getTrackEventObject(m);Object.keys(h).forEach(v=>{_[f.id][v]=h[v].bind(this),f.addEventListener(v,_[f.id][v])}),_[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let v=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(v)}},1e3)}removeTrackEventListeners(f){if(f.id in _){const m=this.getTrackEventObject();Object.keys(m).forEach(h=>{f.removeEventListener(h,_[f.id][h])}),clearInterval(_[f.id].readyState),delete _[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const m={...f,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,m){f in _&&(Object.keys(this.peerConnectionListeners).forEach(h=>{m.removeEventListener(h,_[f][h],!1)}),delete _[f]),m.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),m.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(v){return v},function(v){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,v.name),Promise.reject(v)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});($i=cu)&&$i.__esModule&&Object.prototype.hasOwnProperty.call($i,"default")&&$i.default;var u_=cu.WebRTCStats;function h_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(l){const{jitter:u,rtt:d}=l,p=u+d/2;return .024*p+.11*(p-177.3)*(p>177.3?1:0)}({rtt:s,jitter:i}),r=function(l){const{packetsLost:u,packetsReceived:d}=l,p=u/(d+u)*100;return 20*Math.log(1+p)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,c=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(c,1),5)}function f_(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 p_ extends qn{constructor(e){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1})}}class m_ extends qn{constructor(e){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1})}}class g_ extends qn{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function v_(t){const e=dn(),n=new u_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),i=s=>j(this,void 0,void 0,function*(){s.event==="stats"&&Y(F.StatsFrame,function({data:o}){var r,a,c,l,u,d,p,g;const{audio:y,remote:k}=o,{audio:x}=k,b=(a=(r=x.inbound[0])===null||r===void 0?void 0:r.jitter)!==null&&a!==void 0?a:1/0,S=(l=(c=x.inbound[0])===null||c===void 0?void 0:c.roundTripTime)!==null&&l!==void 0?l:1/0,C=(d=(u=y.inbound[0])===null||u===void 0?void 0:u.packetsReceived)!==null&&d!==void 0?d:-1,I=(g=(p=y.inbound[0])===null||p===void 0?void 0:p.packetsLost)!==null&&g!==void 0?g:-1,M=h_({jitter:1e3*b,rtt:1e3*S,packetsLost:I,packetsReceived:C});return{jitter:b,rtt:S,mos:M,quality:f_(M),inboundAudio:y.inbound[0],outboundAudio:y.outbound[0],remoteInboundAudio:x.inbound[0],remoteOutboundAudio:x.outbound[0]}}(s),t.uuid),yield t.execute(new g_(e,s))});return{start:(s,o,r)=>j(this,void 0,void 0,function*(){yield t.execute(new p_(e)),n.on("timeline",i),yield new Promise(a=>setTimeout(a,500)),n.addConnection({pc:s,peerId:o,connectionId:r})}),stop:s=>j(this,void 0,void 0,function*(){const o=n.getTimeline();Y(F.StatsReport,o,t.uuid),s==="file"&&function(r,a){const c=new Blob([JSON.stringify(r)],{type:"application/json"}),l=URL.createObjectURL(c),u=document.createElement("a");u.href=l,u.download=`${a}.json`,u.click(),URL.revokeObjectURL(l)}(o,`webrtc-stats-${e}-${Date.now()}`),yield t.execute(new m_(e)),n.removeAllPeers(),n.destroy()})}}class lu{constructor(e,n,i,s,o){this.type=e,this.options=n,this.onSdpReadyTwice=null,this.statsReporter=null,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this.handleConnectionStateChange=r=>j(this,void 0,void 0,function*(){const{connectionState:a}=this.instance;if(console.log(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${a}`),a==="failed"||a==="disconnected"){const c=()=>j(this,void 0,void 0,function*(){this._isOffer()&&!this._restartedIceOnConnectionStateFailed?(this.instance.restartIce(),D.debug(`Peer Connection ${a}. Restarting ICE gathering.`),a==="failed"&&(this._restartedIceOnConnectionStateFailed=!0,D.debug("ICE has been restarted on connection state failed.")),this._isTrickleIce()?yield this.startTrickleIceNegotiation():this.startNegotiation()):this._restartedIceOnConnectionStateFailed&&(D.debug("Peer Connection failed again after ICE restart. Recovering call via peer reconnection through error handling."),Y(F.PeerConnectionFailureError,{error:new Error(`Peer Connection failed twice. previous state: ${this._prevConnectionState}, current state: ${a}`),sessionId:this._session.sessionid},this.options.id)),window.removeEventListener("online",c)});navigator.onLine?c():window.addEventListener("online",c)}this._prevConnectionState==="connected"&&a==="disconnected"&&(yield this._resetJitterBuffer()),this._prevConnectionState==="disconnected"&&a==="connected"&&(yield this._resetJitterBuffer()),this._prevConnectionState=a,this._isTrickleIce()&&(a==="connecting"&&performance.mark("peer-connection-connecting"),a==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=r=>{console.log(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setAudioCodec=r=>{if(this.options.preferred_codecs&&this.options.preferred_codecs.length!==0)return r.setCodecPreferences?r.setCodecPreferences(this.options.preferred_codecs):void 0},D.info("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Te.Offer}get isAnswer(){return this.type===Te.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get keepConnectionAliveOnSocketClose(){return this.options.keepConnectionAliveOnSocketClose||this._session.options.keepConnectionAliveOnSocketClose}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return j(this,void 0,void 0,function*(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){D.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{D.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),D.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})}get trickleIcePerformanceMetrics(){const e=performance.measure("new-call","new-call-start","new-call-end"),n=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),i=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),s=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),o=performance.measure("invite-send","new-call-start","sdp-send-start"),r=performance.measure("total-duration","peer-creation-start","sdp-send-end"),a=c=>`${c.toFixed(2)}ms`;return{"New Call":{duration:a(e.duration)},"Peer Creation":{duration:a(n.duration)},"ICE Gathering":{duration:a(i.duration)},[this._isOffer()?"Invite Send":"Answer Send"]:{duration:a(o.duration)},"SDP Send":{duration:a(s.duration)},"Total Duration":{duration:a(r.duration)}}}handleSignalingStateChangeEvent(e){switch(D.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":this.instance=null;break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){D.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?D.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){const{streams:[n]}=e,{remoteElement:i,screenShare:s}=this.options;let{remoteStream:o}=this.options;o=n,s===!1&&Kn(i,o)}createPeerConnection(){return j(this,void 0,void 0,function*(){var e;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",n=>{this.options.remoteStream=n.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Te.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(F.MediaError,n,this.options.id),null)),performance.mark("peer-creation-end")})}init(){var e;return j(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=v_(this._session)),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(Fi(i)){const o=i.getAudioTracks();if(D.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(r=>{D.info("Local audio tracks constraints: ",r.getConstraints())}),this.isOffer&&typeof this.instance.addTransceiver=="function"){const r={direction:"sendrecv",streams:[i]};o.forEach(a=>{this.options.userVariables.microphoneLabel=a.label;const c=this.instance.addTransceiver(a,r);this._setAudioCodec(c)})}else typeof this.instance.addTrack=="function"?(o.forEach(r=>{this.options.userVariables.microphoneLabel=r.label,this.instance.addTrack(r,i)}),this.instance.getTransceivers().forEach(r=>this._setAudioCodec(r))):this.instance.addStream(i);s===!1&&Kn(n,i)}this.isOffer?this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"):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);D.info("Add transceiver",e,n)}}_createOffer(){return j(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=!!this.options.audio,D.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return yield this._setLocalDescription(e),this._isTrickleIce()||this._sdpReady(),e}catch(e){D.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return j(this,void 0,void 0,function*(){D.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return j(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return D.debug("Skipping negotiation, state:",this.instance.signalingState),console.log(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Te.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){D.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return j(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){un(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return j(this,void 0,void 0,function*(){if(Fi(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,j(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s}=n;const{micLabel:o=""}=n;return s&&(s=yield jr(s,o,vt.AudioIn).catch(r=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),{audio:i}}));var n;return Bi(e)})}_resetJitterBuffer(){return j(this,void 0,void 0,function*(){try{const e=this.instance.getReceivers().find(n=>n.track&&n.track.kind==="audio");e&&"jitterBufferTarget"in e&&(e.jitterBufferTarget=20,D.debug("[jitter] target set to",e.jitterBufferTarget,"ms"))}catch(e){D.error("Peer _resetJitterBuffer error:",e)}})}_isOffer(){return this.type===Te.Offer}_isAnswer(){return this.type===Te.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n}=this.options,i={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:[Bv,Od],iceTransportPolicy:n?"relay":"all"};return D.info("RTC config",i),i}close(){var e;return j(this,void 0,void 0,function*(){yield(e=this.statsReporter)===null||e===void 0?void 0:e.stop(this.debugOutput),this.instance&&(this.instance.close(),this.instance=null)})}}const du=ji;class uu{constructor(e,n){this.session=e,this.id="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Vr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._checkConferenceSerno=k=>{const x=k<0||!this._lastSerno||this._lastSerno&&k===this._lastSerno+1;return x&&k>=0&&(this._lastSerno=k),x},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(k=>{k.forEach(x=>{this._statsBindings.forEach(b=>{if(b.callback){if(b.constraints){for(var S in b.constraints)if(b.constraints.hasOwnProperty(S)&&b.constraints[S]!==x[S])return}b.callback(x)}})})})};const{iceServers:i,speaker:s,micId:o,micLabel:r,camId:a,camLabel:c,localElement:l,remoteElement:u,options:d,mediaConstraints:{audio:p},ringtoneFile:g,ringbackFile:y}=e;this.options=Object.assign({},Wv,{audio:p,iceServers:i,localElement:l,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:c,speakerId:s,ringtoneFile:g,ringbackFile:y,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.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=Jd(this.options.ringtoneFile,"_ringtone"),this._ringback=Jd(this.options.ringbackFile,"_ringback"))}get performanceMetrics(){const e=performance.measure("peer-creation","peer-creation-start","peer-creation-end"),n=performance.measure("ice-gathering","ice-gathering-start","ice-gathering-end"),i=performance.measure("sdp-send","sdp-send-start","sdp-send-end"),s=performance.measure("total-duration","peer-creation-start","sdp-send-end"),o=r=>`${r.toFixed(2)}ms`;return{"Peer Creation":{duration:o(e.duration)},"ICE Gathering":{duration:o(n.duration)},"SDP Send":{duration:o(i.duration)},"Total Duration":{duration:o(s.duration)}}}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}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}`}invite(){return j(this,void 0,void 0,function*(){this.direction=kt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new lu(Te.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init()})}answer(e={}){var n;return j(this,void 0,void 0,function*(){performance.mark("new-call-start"),this.stopRingtone(),this.direction=kt.Inbound,((n=e==null?void 0:e.customHeaders)===null||n===void 0?void 0:n.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new lu(Te.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end")})}playRingtone(){Qd(this._ringtone)}stopRingtone(){eu(this._ringtone)}playRingback(){Qd(this._ringback)}stopRingback(){eu(this._ringback)}hangup(e,n){var i,s,o;let r=e||{},a=n!==!1;this.cause=r.cause||"NORMAL_CLEARING",this.causeCode=r.causeCode||16,this.sipCode=r.sipCode||null,this.sipReason=r.sipReason||null,this.sipCallId=r.sip_call_id||null,this.options.customHeaders=[...(i=this.options.customHeaders)!==null&&i!==void 0?i:[],...(o=(s=r==null?void 0:r.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],this.setState(z.Hangup);const c=()=>{var l;return(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const l=new s_({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:"USER_BUSY",causeCode:17});this._execute(l).catch(u=>{D.error("telnyx_rtc.bye failed!",u),Y(F.Error,{error:u,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new Gr({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 Gr({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 Gr({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 ou({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 ou({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){Yd(this.options.localStream)}unmuteAudio(){Xd(this.options.localStream)}toggleAudioMute(){Zd(this.options.localStream)}setAudioInDevice(e){return j(this,void 0,void 0,function*(){const{instance:n}=this.peer,i=n.getSenders().find(({track:{kind:s}})=>s==="audio");if(i){const s=yield Br({audio:{deviceId:{exact:e}}}),o=s.getAudioTracks()[0];i.replaceTrack(o),this.options.micId=e;const{localStream:r}=this.options;r.getAudioTracks().forEach(a=>a.stop()),r.getVideoTracks().forEach(a=>s.addTrack(a)),this.options.localStream=s}})}muteVideo(){var e;e=this.options.localStream,fn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,fn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,fn(e,"video",null)}setVideoDevice(e){return j(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 Br({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Kn(r,s),this.options.camId=e,a.getAudioTracks().forEach(c=>s.addTrack(c)),a.getVideoTracks().forEach(c=>c.stop()),this.options.localStream=s}})}deaf(){Yd(this.options.remoteStream)}undeaf(){Xd(this.options.remoteStream)}toggleDeaf(){Zd(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return j(this,void 0,void 0,function*(){if(!this||!this.peer)return void D.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 D.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"}]),D.info("Parameters: ",r),D.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{D.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>console.error(a))}else D.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){switch(this._prevState=this._state,this._state=e,this.state=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),D.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case z.Purge:this.hangup({cause:"PURGE",causeCode:"01"},!1);break;case z.Active:setTimeout(()=>{const{remoteElement:n,speakerId:i}=this.options;n&&i&&qd(n,i)},0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case te.Answer:if(this.gotAnswer=!0,this._state>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case te.Media:if(this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case te.Display:case te.Attach:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const c=a===kt.Inbound?kt.Outbound:kt.Inbound,l={type:Je[n],call:this,displayName:o,displayNumber:r,displayDirection:c};Y(F.Notification,l,this.id)||Y(F.Notification,l,this.session.uuid);break}case te.Candidate:this._addIceCandidate(i);break;case te.Info:case te.Event:{const o=Object.assign(Object.assign({},i),{type:Je.generic,call:this});Y(F.Notification,o,this.id)||Y(F.Notification,o,this.session.uuid);break}case te.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 j(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return D.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:c,modChannel:l,laName:u,conferenceMemberID:d,role:p}=n;this._dispatchConferenceUpdate({action:$e.Join,conferenceName:u,participantId:Number(d),role:p}),a&&(yield this._subscribeConferenceChat(a)),c&&(yield this._subscribeConferenceInfo(c));const g=[];for(const y in s)g.push(Object.assign({callId:s[y][0],index:Number(y)},Oi(s[y][1])));this._dispatchConferenceUpdate({action:$e.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:$e.Add,callId:o,index:r},Oi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:$e.Modify,callId:o,index:r},Oi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:$e.Delete,callId:o,index:r},Oi(s)));break;case"clear":this._dispatchConferenceUpdate({action:$e.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 j(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:c,type:l}=s.data;this._dispatchConferenceUpdate({action:$e.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:c,messageType:l,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{D.error("ConfChat subscription error:",s)});$r(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 j(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,au(this.session,o)):D.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{D.error("ConfInfo subscription error:",s)});$r(i,e)&&this._addChannel(e)})}_confControl(e,n={}){const i=Object.assign({application:"conf-control",callID:this.id,value:null},n);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:i})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){return D.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return j(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Te.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this.setState(z.Active)}).catch(i=>{D.error("Call setRemoteDescription Error: ",i),this.hangup()})})}_requestAnotherLocalDescription(){un(this.peer.onSdpReadyTwice)?Y(F.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;this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._iceDone=!0;const{sdp:s,type:o}=e;if(s.indexOf("candidate")===-1)return D.info(`No candidate - retry
111
111
  `),void this._requestAnotherLocalDescription();(i=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||i===void 0||i.removeEventListener("icecandidate",this._onIce),performance.mark("ice-gathering-end");let r=null;const a={sessid:this.session.sessionid,sdp:s,dialogParams:this.options,"User-Agent":`Web-${du}`};switch(o){case Te.Offer:this.setState(z.Requesting),r=new iu(a);break;case Te.Answer:this.setState(z.Answering),r=this.options.attach===!0?new Hr(a):new su(a);break;default:return D.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(c=>{const{node_id:l=null}=c;this._targetNodeId=l,o===Te.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(c=>{D.error(`${this.id} - Sending ${o} error:`,c),this.hangup()}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return D.error("No SDP data provided"),this.hangup({},!1);const{sdp:n,type:i}=e;let s=null;const o={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${du}`};switch(i){case Te.Offer:this.setState(z.Requesting),s=new iu(o);break;case Te.Answer:this.setState(z.Answering),s=this.options.attach===!0?new Hr(o):new su(o);break;default:return D.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(s).then(r=>{const{node_id:a=null}=r;this._targetNodeId=a,i===Te.Offer?this.setState(z.Trying):this.setState(z.Active)}).catch(r=>{D.error(`${this.id} - Sending ${i} error:`,r),this.hangup()}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;this._iceTimeout===null&&(this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),1e3)),e.candidate?D.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(D.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new ru({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 D.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(()=>{D.debug("Successfully added ICE candidate:",e)}).catch(i=>{D.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new r_({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e),performance.mark("ice-gathering-end")}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!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.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&&Kn(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{D.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&D.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{D.debug("ICE candidate error:",n)},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&&Kn(i,s)})}_onMediaError(e){this._dispatchNotification({type:Je.userMediaError,error:e}),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),this.hangup({},!1)}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Je.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(Y(F.Notification,e,this.id,!1)||Y(F.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_init(){const{id:e,userVariables:n,remoteCallerNumber:i,onNotification:s}=this.options;var o;this.options.id=e?e.toString():dn(),this.id=this.options.id,n&&(o=n,Object.keys(o).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),i||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Bt(F.MediaError,this._onMediaError,this.id),Bt(F.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),un(s)&&Bt(F.Notification,s.bind(this),this.id),this.setState(z.New),D.info("New Call with Options:",this.options)}_finalize(){this._stopStats(),this.peer&&this.peer.instance&&(this.peer.instance.close(),this.peer=null);const{remoteStream:e,localStream:n}=this.options;Xn(e),Xn(n),jt(F.MediaError,null,this.id),jt(F.PeerConnectionFailureError,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id]}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),D.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),D.info("Stats stopped")}}uu.setStateTelnyx=t=>{if(t){switch(t._state){case z.Requesting:case z.Recovering:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class $t extends uu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new l_(e,n))}hangup(e={},n=!0){this.screenShare instanceof $t&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return j(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(l=>{l.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,c=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 $t(this.session,c),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof $t&&this.screenShare.hangup()}setAudioOutDevice(e){return j(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&qd(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);D.setLevel(2),this._statsInterval=window.setInterval(()=>j(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+=`
112
112
  ${r.type}
113
113
  `,Object.keys(r).forEach(a=>{o.includes(a)||(i+=` ${a}: ${r[a]}
114
- `)}))}),D.info(i)}),2e3)}}class __ extends Qv{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!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 j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield Bi({audio:e,video:n});return Xn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(z.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Ud(F.SpeedTest,r=>{const{upDur:a,downDur:c}=r,l=c?8*e/(c/1e3)/1024:0;n({upDur:a,downDur:c,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:l.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 Yn().catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getVideoDevices(){return Yn(vt.Video).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Yn(vt.AudioIn).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Yn(vt.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),Y(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return jr(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield Bi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<Kd.length;r++){const[a,c]=Kd[r];(yield o.applyConstraints({width:{exact:a},height:{exact:c}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${c}`,width:a,height:c})}return Xn(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints}}setAudioSettings(e){return j(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=Rd(e,["micId","micLabel"]);return t_(s),this._audioConstraints=yield((o,r,a,c)=>j(void 0,void 0,void 0,function*(){const{deviceId:l}=c;if(l===void 0&&(o||r)){const u=yield jr(o,r,a).catch(d=>null);u&&(c.deviceId={exact:u})}return c}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}set iceServers(e){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[n]:[]:e||[Od,jv,n]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ni(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ni(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 o_({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 j(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&!this._existsSubscription(this.relayProtocol,c))).length)return{};const s=new a_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Ur(o);return r.length&&r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),a.forEach(c=>this._addSubscription(this.relayProtocol,i,c)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new c_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Ur(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&&(this._closeConnection(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0},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 $t.setStateTelnyx(e)}}class hu{constructor(e,n){this.code=n,this.message=e}}class fu extends Ie{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:ji,data:navigator.userAgent}};r&&(c.sessid=r),s&&(c.target_version_id=s),this.buildRequest({method:this.method,params:c})}}const y_=ji;class xe{constructor(e){this.session=e,this.handleLogin=()=>j(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new nu(n,i||s,o,this.session.sessionid,r,!!Ft()),c=yield this.session.execute(a).catch(this.session.handleLoginError);c&&(this.session.sessionid=c.sessid)}),this.handleAnonymousLogin=()=>j(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new fu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!Ft()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new i_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Bd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,c=r==null?void 0:r.callID,l=r==null?void 0:r.eventChannel,u=r==null?void 0:r.eventType,d=o===te.Attach;let m=!1;if(u==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(c&&i.calls.hasOwnProperty(c)){if(!d)return i.calls[c].handleMessage(e),void this._ack(s,o);m=(i.calls[c].options.keepConnectionAliveOnSocketClose||i.options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[c].peer)===null||n===void 0)&&n.instance),m?D.info(`[${new Date().toISOString()}][${c}] re-attaching call due to ATTACH`):(D.debug(`Session Options: ${i.options}`),D.debug(`Call: ${i.calls[c]}`),D.info(`[${new Date().toISOString()}][${c}] Hanging up the call due to ATTACH`),i.calls[c].hangup({},!1))}const g=()=>{var x,b,S,C,A,M;const O={id:c,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:d,mediaSettings:r.mediaSettings,debug:(x=i.options.debug)!==null&&x!==void 0&&x,debugOutput:(b=i.options.debugOutput)!==null&&b!==void 0?b:"socket",trickleIce:(S=i.options.trickleIce)!==null&&S!==void 0&&S,prefetchIceCandidates:(C=i.options.prefetchIceCandidates)!==null&&C!==void 0&&C,forceRelayCandidate:(A=i.options.forceRelayCandidate)!==null&&A!==void 0&&A,keepConnectionAliveOnSocketClose:(M=i.options.keepConnectionAliveOnSocketClose)!==null&&M!==void 0&&M};r.telnyx_call_control_id&&(O.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(O.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(O.telnyxLegId=r.telnyx_leg_id),r.client_state&&(O.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(O.customHeaders=r.dialogParams.custom_headers);const _=new $t(i,O);return _.nodeId=this.nodeId,_},y=new zd(a),k=new Wd(a);switch(o){case te.Ping:this.session.setPingReceived(),this.session.execute(k).then(()=>{xe.receivedAuthenticationRequired=0}).catch(S=>j(this,void 0,void 0,function*(){S.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(D.warn("Ping failed twice with Authentication Required. Re-logging in..."),Vi(this.session.options)?this.handleLogin():zn(this.session.options)&&this.handleAnonymousLogin(),xe.receivedAuthenticationRequired=-1))}));break;case te.Punt:if(this.session.options.keepConnectionAliveOnSocketClose)return void D.info(`[${new Date().toISOString()}][${c}] Ignoring PUNT due to keepConnectionAliveOnSocketClose`);i.disconnect();break;case te.Invite:{const S=g();S.playRingtone(),S.setState(z.Ringing),S.direction=kt.Inbound,this._ack(s,o);break}case te.Attach:{if(m)return void this.session.execute(new Hr({sessid:this.session.sessionid,sdp:this.session.calls[c].peer.instance.localDescription.sdp,dialogParams:this.session.calls[c].options,"User-Agent":`Web-${y_}`}));D.info(`[${new Date().toISOString()}][${c}] Re-creating call instance.`);const S=g();this.session.autoRecoverCalls?S.answer():S.setState(z.Recovering),S.handleMessage(e);break}case te.Event:case"webrtc.event":if(!l)return void D.error("Verto received an unknown event:",r);const x=i.relayProtocol,b=l.split(".")[0];i._existsSubscription(x,l)?Y(x,r,l):l===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(x,b)?Y(x,r,b):i.calls.hasOwnProperty(l)?i.calls[l].handleMessage(e):Y(F.Notification,r,i.uuid);break;case te.Info:r.type=Je.generic,Y(F.Notification,r,i.uuid);break;case te.ClientReady:this.session.execute(y);break;default:{const S=Or(e);if(S){switch(S){case Le.REGISTER:case Le.REGED:i.connection.previousGatewayState!==Le.REGED&&i.connection.previousGatewayState!==Le.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=Je.vertoClientReady,Y(F.Ready,r,i.uuid),i.options.trickleIce&&(D.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new ru({candidate:""})).catch(C=>{C.code===this.session.invalidMethodErrorCode?(console.warn("Trickle ICE is not supported by the server, disabling it."),D.debug("Trickle ICE check error:",JSON.stringify(C,null,2)),i.options.trickleIce=!1):D.debug("Trickle ICE check:",JSON.stringify(C,null,2))})));break;case Le.UNREGED:case Le.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(F.Error,{error:new hu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(y)},this.reconnectDelay());break;case Le.FAILED:case Le.FAIL_WAIT:if(i.connection.previousGatewayState!==Le.FAILED&&i.connection.previousGatewayState!==Le.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(F.Error,{error:new hu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(F.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:D.warn("GatewayState message unknown method:",e)}break}D.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 j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:l,conferenceMemberID:u,role:d,callID:m}=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:x})=>{const b=m||this._retrieveCallId(x,o);if(b&&n.calls.hasOwnProperty(b)){const S=n.calls[b];S._addChannel(o),S.extension=r,S.handleConferenceUpdate(x,e).then(C=>{C==="INVALID_PACKET"&&g()})}}},k=yield n.vertoSubscribe(y).catch(x=>{D.error("liveArray subscription error:",x)});$r(k,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:k=null}=n.subscriptions[i][o];if(g=n.calls[k]||null,k!==null){const x={type:Je.conferenceUpdate,action:$e.Leave,conferenceName:r,participantId:Number(u),role:d};Y(F.Notification,x,k,!1)||Y(F.Notification,x,n.uuid),g===null&&jt(F.Notification,null,k)}}const y=[o,a,c,l];n.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:k=[]})=>{g&&(g.channels=g.channels.filter(x=>!k.includes(x)))}).catch(k=>{D.error("liveArray unsubscribe error:",k)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":au(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};Y(F.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class b_ extends __{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,c=new nu(n,i||s,o,this.sessionid,r,!!Ft()),l=yield this.execute(c).catch(this._handleLoginError);l&&(this._autoReconnect=a,this.sessionid=l.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new fu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Ft()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(D.info(`Hanging up call due to page unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Vi(this.options)||zn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new $t(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!zn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return Vi(this.options)?this.handleLoginOnSocketOpen():zn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class w_ extends b_{constructor(e){super(e),console.log(`SDK version: ${tu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return n_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ve.not_supported},{browserName:"Firefox",supported:ve.not_supported},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",features:["audio"],supported:ve.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",features:["audio"],supported:ve.partial}]}]}}function x_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function S_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function k_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}const C_=2e3;function T_(t){if(!k_(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}}function E_(t){const[e,n]=Re([]),[,i]=Er();return Ne(()=>{if(!t)return;const s=o=>{if(x_(o))switch(o.params.type){case"response.text.delta":{S_(o)&&n(r=>{const a=r[r.length-1];if(a&&a.id===o.params.item_id&&a.role==="assistant"){const c={...a,content:a.content+o.params.delta};return[...r.slice(0,-1),c]}else{const c={id:o.params.item_id,role:"assistant",content:o.params.delta,timestamp:new Date};return[...r,c]}}),i("waiting");return}case"conversation.item.created":{const r=T_(o);if(r){const a=r.attachments&&r.attachments.length>0;i(a?"processing_image":"thinking"),n(c=>{const l=c[c.length-1];if(l&&l.role==="user"&&r.role==="user"&&r.timestamp.getTime()-l.timestamp.getTime()<C_){const d={...l,id:r.id,content:l.content+" "+r.content,timestamp:r.timestamp,attachments:[...l.attachments||[],...r.attachments||[]]};return[...c.slice(0,-1),d]}return[...c,r]})}return}}};return t.on(F.SocketMessage,s),()=>{t.off(F.SocketMessage,s)}},[t,i]),e}const A_=({call:t,client:e})=>{const n=Vt(),[i,s]=Re(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),a=E_(e);switch(i){case"collapsed":return E(Pd,{onExpand:o,call:t,client:e});case"expanded":return E(Nv,{transcript:a,onCollapse:r,call:t});default:return E(Pd,{onExpand:o,call:t,client:e})}},zr=()=>E(Un.div,{layoutId:Ai,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:E("div",{className:"rounded-full animate-spin",children:E(wv,{})})}),I_=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return E(zr,{});case"done":case"purged":case"destroy":return null;case"active":return E(A_,{client:e,call:t});default:return E(zr,{})}},P_=(t,e,n,i)=>{const[s,o]=Re(null);return Ne(()=>{if(!t)return;const r=new w_({env:e||"production",anonymous_login:{target_id:t,target_type:"ai_assistant",target_version_id:n},debug:i||!1});o(r)},[t,e,n,i]),s},R_=(t,{onReady:e,onNotification:n,onError:i,onSocketMessage:s})=>(Ne(()=>{if(t)return t.connect().then().catch(console.error),t.on(F.Ready,e),t.on(F.Notification,n),t.on(F.Error,i),t.on(F.SocketMessage,s),()=>{t.off(F.Ready,e),t.off(F.Notification,n),t.off(F.Error,i),t.off(F.SocketMessage,s),t.disconnect()}},[t]),null),M_=({className:t})=>E("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:[E("g",{clipPath:"url(#:R5lfm:)",children:[E("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"}),E("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"}),E("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"}),E("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"}),E("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"})]}),E("defs",{children:E("clipPath",{id:":R5lfm:",children:E("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function L_(){const t=Vt();return t.logo_icon_url?E("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:E("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):E(M_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,versionId:e,callProps:n})=>{const i=Vt(),s=()=>{var u;if(!t){console.error("Client is not initialized.");return}const o=(u=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:u.codecs,r=o==null?void 0:o.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:a,...c}=n||{},l=a?[...a]:[];e&&l.push({name:"X-AI-Assistant-Version-ID",value:e}),t.newCall({destinationNumber:"xxx",...c,preferred_codecs:[r],customHeaders:l.length>0?l:void 0})};return E(Un.button,{layoutId:Ai,onClick:s,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:[E(L_,{}),i.start_call_text]})},O_='@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-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-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.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-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}.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-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)}}',N_=({children:t})=>E("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:E("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),V_={duration:.1,ease:"circOut"},F_=({children:t,position:e="fixed"})=>{const n=Vt(),s=(e??n.position??"fixed")==="fixed"?E(N_,{children:t}):t;return E("div",{className:pt(n.theme==="dark"&&"dark"),children:E(fp,{transition:V_,children:[E("style",{children:O_}),s]})})},B_=t=>E(Un.div,{layoutId:Ai,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:[E(yv,{className:"w-8 h-8 text-red-400"}),E("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),E("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[E("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),E("li",{children:["Make sure that the"," ",E("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"," ",E(Ev,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function j_(t){return Object.keys(t).length===0}function pu(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 $_=({client:t})=>{const e=Wg();return ts(()=>{if(!t)return;const n=i=>{if(pu(i)&&!j_(i.params.widget_settings)){const s=i.params.widget_settings;e(s)}};return t.on(F.SocketMessage,n),()=>{t.off(F.SocketMessage,n)}},[t,e]),null};function U_({"agent-id":t,debug:e,"call-destination-number":n,"call-caller-number":i,"call-caller-name":s,"call-custom-headers":o,"call-audio":r,environment:a,position:c="fixed","version-id":l}){const u=P_(t,a,l,e),[d,m]=Re(null),[g,y]=Re(!1),[k,x]=Re(!1),[b,S]=Re(!1),C=ps(Ad),A={};if(n&&(A.destinationNumber=n),i&&(A.callerNumber=i),s&&(A.callerName=s),o)try{A.customHeaders=JSON.parse(o)}catch(p){console.error("Invalid JSON for call-custom-headers attribute:",o,p)}if(r)try{A.audio=JSON.parse(r);const p=A.audio;if(typeof p=="object"){const h=navigator.mediaDevices.getSupportedConstraints();Object.keys(p).forEach(v=>{h[v]||console.warn(`Audio constraint not supported by browser: ${v}`)})}}catch(p){console.error("Invalid JSON for call-audio attribute:",r,p)}return R_(u,{onReady:()=>y(!1),onNotification:p=>{var h;if(((h=p.call)==null?void 0:h.state)==="destroy")return C(!1),m(null);m(p)},onError:()=>{y(!1),x(!0)},onSocketMessage:p=>{pu(p)&&S(!0)}}),E(Xe,{children:[E(F_,{position:c,children:t?k?E(B_,{agentId:t}):g?E(zr,{}):d!=null&&d.call?E(I_,{call:d.call,client:u}):b?E(D_,{versionId:l,client:u,callProps:A}):null:E("div",{children:"Please provide an assistant ID."})}),E($_,{client:u})]})}Ru(U_,"telnyx-ai-agent",Gg,{shadow:!0})})();
114
+ `)}))}),D.info(i)}),2e3)}}class __ extends Qv{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!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 j(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return j(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return j(this,void 0,void 0,function*(){try{const i=yield Bi({audio:e,video:n});return Xn(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return j(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(z.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(Ud(F.SpeedTest,r=>{const{upDur:a,downDur:c}=r,l=c?8*e/(c/1e3)/1024:0;n({upDur:a,downDur:c,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:l.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 Yn().catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getVideoDevices(){return Yn(vt.Video).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return Yn(vt.AudioIn).catch(e=>(Y(F.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return Yn(vt.AudioOut).catch(e=>(console.error("getAudioOutDevices",e),Y(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return jr(e,n,i)}getDeviceResolutions(e){return j(this,void 0,void 0,function*(){try{return yield(n=>j(void 0,void 0,void 0,function*(){const i=[],s=yield Bi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<Kd.length;r++){const[a,c]=Kd[r];(yield o.applyConstraints({width:{exact:a},height:{exact:c}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${c}`,width:a,height:c})}return Xn(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints}}setAudioSettings(e){return j(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=Rd(e,["micId","micLabel"]);return t_(s),this._audioConstraints=yield((o,r,a,c)=>j(void 0,void 0,void 0,function*(){const{deviceId:l}=c;if(l===void 0&&(o||r)){const u=yield jr(o,r,a).catch(d=>null);u&&(c.deviceId={exact:u})}return c}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=!0}set iceServers(e){const n={urls:["stun:stun.l.google.com:19302"]};this._iceServers=typeof e=="boolean"?e?[n]:[]:e||[Od,jv,n]}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ni(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ni(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 o_({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 j(this,void 0,void 0,function*(){if(!(n=n.filter(c=>c&&!this._existsSubscription(this.relayProtocol,c))).length)return{};const s=new a_({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Ur(o);return r.length&&r.forEach(c=>this._removeSubscription(this.relayProtocol,c)),a.forEach(c=>this._addSubscription(this.relayProtocol,i,c)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return j(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new c_({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=Ur(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&&(this._closeConnection(),this.connect()),this._wasOffline=!1},this._offlineHandler=()=>{this._wasOffline=!0},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 $t.setStateTelnyx(e)}}class hu{constructor(e,n){this.code=n,this.message=e}}class fu extends Ie{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,userVariables:o,sessionId:r,reconnection:a}=e,c={target_type:n,target_id:i,userVariables:o,reconnection:a,"User-Agent":{sdkVersion:ji,data:navigator.userAgent}};r&&(c.sessid=r),s&&(c.target_version_id=s),this.buildRequest({method:this.method,params:c})}}const y_=ji;class xe{constructor(e){this.session=e,this.handleLogin=()=>j(this,void 0,void 0,function*(){const{login:n,password:i,passwd:s,login_token:o,userVariables:r}=this.session.options,a=new nu(n,i||s,o,this.session.sessionid,r,!!Ft()),c=yield this.session.execute(a).catch(this.session.handleLoginError);c&&(this.session.sessionid=c.sessid)}),this.handleAnonymousLogin=()=>j(this,void 0,void 0,function*(){const{anonymous_login:n}=this.session.options,i=new fu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.session.sessionid,userVariables:this.session.options.userVariables,reconnection:!!Ft()}),s=yield this.session.execute(i).catch(this.session.handleLoginError);s&&(this.session.sessionid=s.sessid)})}_ack(e,n){const i=new i_(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*Bd(2,6)}handleMessage(e){var n;const{session:i}=this,{id:s,method:o,params:r={},voice_sdk_id:a}=e,c=r==null?void 0:r.callID,l=r==null?void 0:r.eventChannel,u=r==null?void 0:r.eventType,d=o===te.Attach;let p=!1;if(u==="channelPvtData")return this._handlePvtEvent(r.pvtData);if(c&&i.calls.hasOwnProperty(c)){if(!d)return i.calls[c].handleMessage(e),void this._ack(s,o);p=(i.calls[c].options.keepConnectionAliveOnSocketClose||i.options.keepConnectionAliveOnSocketClose)&&!!(!((n=this.session.calls[c].peer)===null||n===void 0)&&n.instance),p?D.info(`[${new Date().toISOString()}][${c}] re-attaching call due to ATTACH`):(D.debug(`Session Options: ${i.options}`),D.debug(`Call: ${i.calls[c]}`),D.info(`[${new Date().toISOString()}][${c}] Hanging up the call due to ATTACH`),i.calls[c].hangup({},!1))}const g=()=>{var x,b,S,C,I,M;const O={id:c,remoteSdp:r.sdp,destinationNumber:r.callee_id_number,remoteCallerName:r.caller_id_name,remoteCallerNumber:r.caller_id_number,callerName:r.callee_id_name,callerNumber:r.callee_id_number,attach:d,mediaSettings:r.mediaSettings,debug:(x=i.options.debug)!==null&&x!==void 0&&x,debugOutput:(b=i.options.debugOutput)!==null&&b!==void 0?b:"socket",trickleIce:(S=i.options.trickleIce)!==null&&S!==void 0&&S,prefetchIceCandidates:(C=i.options.prefetchIceCandidates)!==null&&C!==void 0&&C,forceRelayCandidate:(I=i.options.forceRelayCandidate)!==null&&I!==void 0&&I,keepConnectionAliveOnSocketClose:(M=i.options.keepConnectionAliveOnSocketClose)!==null&&M!==void 0&&M};r.telnyx_call_control_id&&(O.telnyxCallControlId=r.telnyx_call_control_id),r.telnyx_session_id&&(O.telnyxSessionId=r.telnyx_session_id),r.telnyx_leg_id&&(O.telnyxLegId=r.telnyx_leg_id),r.client_state&&(O.clientState=r.client_state),r.dialogParams&&r.dialogParams.custom_headers&&r.dialogParams.custom_headers.length&&(O.customHeaders=r.dialogParams.custom_headers);const _=new $t(i,O);return _.nodeId=this.nodeId,_},y=new zd(a),k=new Wd(a);switch(o){case te.Ping:this.session.setPingReceived(),this.session.execute(k).then(()=>{xe.receivedAuthenticationRequired=0}).catch(S=>j(this,void 0,void 0,function*(){S.code===this.session.authenticationRequiredErrorCode&&xe.receivedAuthenticationRequired>=0&&(xe.receivedAuthenticationRequired+=1,xe.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(D.warn("Ping failed twice with Authentication Required. Re-logging in..."),Vi(this.session.options)?this.handleLogin():zn(this.session.options)&&this.handleAnonymousLogin(),xe.receivedAuthenticationRequired=-1))}));break;case te.Punt:if(this.session.options.keepConnectionAliveOnSocketClose)return void D.info(`[${new Date().toISOString()}][${c}] Ignoring PUNT due to keepConnectionAliveOnSocketClose`);i.disconnect();break;case te.Invite:{const S=g();S.playRingtone(),S.setState(z.Ringing),S.direction=kt.Inbound,this._ack(s,o);break}case te.Attach:{if(p)return void this.session.execute(new Hr({sessid:this.session.sessionid,sdp:this.session.calls[c].peer.instance.localDescription.sdp,dialogParams:this.session.calls[c].options,"User-Agent":`Web-${y_}`}));D.info(`[${new Date().toISOString()}][${c}] Re-creating call instance.`);const S=g();this.session.autoRecoverCalls?S.answer():S.setState(z.Recovering),S.handleMessage(e);break}case te.Event:case"webrtc.event":if(!l)return void D.error("Verto received an unknown event:",r);const x=i.relayProtocol,b=l.split(".")[0];i._existsSubscription(x,l)?Y(x,r,l):l===i.sessionid?this._handleSessionEvent(r.eventData):i._existsSubscription(x,b)?Y(x,r,b):i.calls.hasOwnProperty(l)?i.calls[l].handleMessage(e):Y(F.Notification,r,i.uuid);break;case te.Info:r.type=Je.generic,Y(F.Notification,r,i.uuid);break;case te.ClientReady:this.session.execute(y);break;default:{const S=Or(e);if(S){switch(S){case Le.REGISTER:case Le.REGED:i.connection.previousGatewayState!==Le.REGED&&i.connection.previousGatewayState!==Le.REGISTER&&(this.session._triggerKeepAliveTimeoutCheck(),xe.retriedRegister=0,r.type=Je.vertoClientReady,Y(F.Ready,r,i.uuid),i.options.trickleIce&&(D.debug("Trickle ICE is enabled. Checking Gateway support"),this.session.execute(new ru({candidate:""})).catch(C=>{C.code===this.session.invalidMethodErrorCode?(console.warn("Trickle ICE is not supported by the server, disabling it."),D.debug("Trickle ICE check error:",JSON.stringify(C,null,2)),i.options.trickleIce=!1):D.debug("Trickle ICE check:",JSON.stringify(C,null,2))})));break;case Le.UNREGED:case Le.NOREG:if(xe.retriedRegister+=1,xe.retriedRegister===5){xe.retriedRegister=0,Y(F.Error,{error:new hu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.execute(y)},this.reconnectDelay());break;case Le.FAILED:case Le.FAIL_WAIT:if(i.connection.previousGatewayState!==Le.FAILED&&i.connection.previousGatewayState!==Le.FAIL_WAIT){if(!this.session.hasAutoReconnect()){xe.retriedConnect=0,Y(F.Error,{error:new hu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:i.sessionid},i.uuid);break}if(xe.retriedConnect+=1,xe.retriedConnect===5){xe.retriedConnect=0,Y(F.Error,{error:new Error("Connection Retry Failed"),sessionId:i.sessionid},i.uuid);break}setTimeout(()=>{this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:D.warn("GatewayState message unknown method:",e)}break}D.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 j(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:c,modChannel:l,conferenceMemberID:u,role:d,callID:p}=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:x})=>{const b=p||this._retrieveCallId(x,o);if(b&&n.calls.hasOwnProperty(b)){const S=n.calls[b];S._addChannel(o),S.extension=r,S.handleConferenceUpdate(x,e).then(C=>{C==="INVALID_PACKET"&&g()})}}},k=yield n.vertoSubscribe(y).catch(x=>{D.error("liveArray subscription error:",x)});$r(k,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&n._existsSubscription(i,o)){const{callId:k=null}=n.subscriptions[i][o];if(g=n.calls[k]||null,k!==null){const x={type:Je.conferenceUpdate,action:$e.Leave,conferenceName:r,participantId:Number(u),role:d};Y(F.Notification,x,k,!1)||Y(F.Notification,x,n.uuid),g===null&&jt(F.Notification,null,k)}}const y=[o,a,c,l];n.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:k=[]})=>{g&&(g.channels=g.channels.filter(x=>!k.includes(x)))}).catch(k=>{D.error("liveArray unsubscribe error:",k)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":au(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:$e.LogoInfo,logo:e.logoURL};Y(F.Notification,n,this.session.uuid);break}}}}xe.retriedConnect=0,xe.retriedRegister=0,xe.receivedAuthenticationRequired=0;class b_ extends __{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{login:n,password:i,passwd:s,login_token:o,userVariables:r,autoReconnect:a=!0}=this.options,c=new nu(n,i||s,o,this.sessionid,r,!!Ft()),l=yield this.execute(c).catch(this._handleLoginError);l&&(this._autoReconnect=a,this.sessionid=l.sessid)}),this.handleAnonymousLoginOnSocketOpen=()=>j(this,void 0,void 0,function*(){this._idle=!1;const{anonymous_login:n}=this.options,i=new fu({target_id:n.target_id,target_type:n.target_type,target_version_id:n.target_version_id,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Ft()}),s=yield this.execute(i).catch(this._handleLoginError);s&&(this.sessionid=s.sessid)}),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(D.info(`Hanging up call due to page unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Vi(this.options)||zn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw new Error("Verto.newCall() error: destinationNumber is required.");performance.mark("new-call-start");const n=new $t(this,e);return n.invite(),performance.mark("new-call-end"),n}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!zn(this.options)||!!e.destinationNumber}_onSocketOpen(){return j(this,void 0,void 0,function*(){return Vi(this.options)?this.handleLoginOnSocketOpen():zn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){new xe(this).handleMessage(e)}}class w_ extends b_{constructor(e){super(e),console.log(`SDK version: ${tu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return n_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ve.not_supported},{browserName:"Firefox",supported:ve.not_supported},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",supported:ve.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",features:["video","audio"],supported:ve.full},{browserName:"Edge",features:["audio"],supported:ve.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ve.full},{browserName:"Firefox",features:["audio"],supported:ve.partial},{browserName:"Safari",supported:ve.not_supported},{browserName:"Edge",features:["audio"],supported:ve.partial}]}]}}function x_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function S_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function k_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}const C_=2e3;function T_(t){if(!k_(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}}function E_(t){const[e,n]=Re([]),[,i]=Er();return Ne(()=>{if(!t)return;const s=o=>{if(x_(o))switch(o.params.type){case"response.text.delta":{S_(o)&&n(r=>{const a=r[r.length-1];if(a&&a.id===o.params.item_id&&a.role==="assistant"){const c={...a,content:a.content+o.params.delta};return[...r.slice(0,-1),c]}else{const c={id:o.params.item_id,role:"assistant",content:o.params.delta,timestamp:new Date};return[...r,c]}}),i("waiting");return}case"conversation.item.created":{const r=T_(o);if(r){const a=r.attachments&&r.attachments.length>0;i(a?"processing_image":"thinking"),n(c=>{const l=c[c.length-1];if(l&&l.role==="user"&&r.role==="user"&&r.timestamp.getTime()-l.timestamp.getTime()<C_){const d={...l,id:r.id,content:l.content+" "+r.content,timestamp:r.timestamp,attachments:[...l.attachments||[],...r.attachments||[]]};return[...c.slice(0,-1),d]}return[...c,r]})}return}}};return t.on(F.SocketMessage,s),()=>{t.off(F.SocketMessage,s)}},[t,i]),e}const A_=({call:t,client:e})=>{const n=Vt(),[i,s]=Re(n.default_state),o=()=>s("expanded"),r=()=>s("collapsed"),a=E_(e);switch(i){case"collapsed":return E(Pd,{onExpand:o,call:t,client:e});case"expanded":return E(Nv,{transcript:a,onCollapse:r,call:t});default:return E(Pd,{onExpand:o,call:t,client:e})}},zr=()=>E(Un.div,{layoutId:Ai,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:E("div",{className:"rounded-full animate-spin",children:E(wv,{})})}),I_=({call:t,client:e})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return E(zr,{});case"done":case"purged":case"destroy":return null;case"active":return E(A_,{client:e,call:t});default:return E(zr,{})}},P_=(t,e,n,i,s)=>{const[o,r]=Re(null);return Ne(()=>{if(!t)return;const a=new w_({env:e||"production",anonymous_login:{target_id:t,target_type:"ai_assistant",target_version_id:n},debug:i||!1,trickleIce:s||!1});r(a)},[t,e,n,i,s]),o},R_=(t,{onReady:e,onNotification:n,onError:i,onSocketMessage:s})=>(Ne(()=>{if(t)return t.connect().then().catch(console.error),t.on(F.Ready,e),t.on(F.Notification,n),t.on(F.Error,i),t.on(F.SocketMessage,s),()=>{t.off(F.Ready,e),t.off(F.Notification,n),t.off(F.Error,i),t.off(F.SocketMessage,s),t.disconnect()}},[t]),null),M_=({className:t})=>E("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:[E("g",{clipPath:"url(#:R5lfm:)",children:[E("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"}),E("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"}),E("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"}),E("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"}),E("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"})]}),E("defs",{children:E("clipPath",{id:":R5lfm:",children:E("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function L_(){const t=Vt();return t.logo_icon_url?E("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:E("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):E(M_,{className:"w-8 h-8 mr-2"})}const D_=({client:t,versionId:e,callProps:n})=>{const i=Vt(),s=()=>{var u;if(!t){console.error("Client is not initialized.");return}const o=(u=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:u.codecs,r=o==null?void 0:o.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:a,...c}=n||{},l=a?[...a]:[];e&&l.push({name:"X-AI-Assistant-Version-ID",value:e}),t.newCall({destinationNumber:"xxx",...c,preferred_codecs:[r],customHeaders:l.length>0?l:void 0})};return E(Un.button,{layoutId:Ai,onClick:s,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:[E(L_,{}),i.start_call_text]})},O_='@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-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-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.flex{display:flex}.hidden{display:none}.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-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}.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-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)}}',N_=({children:t})=>E("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:E("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),V_={duration:.1,ease:"circOut"},F_=({children:t,position:e="fixed"})=>{const n=Vt(),s=(e??n.position??"fixed")==="fixed"?E(N_,{children:t}):t;return E("div",{className:pt(n.theme==="dark"&&"dark"),children:E(fp,{transition:V_,children:[E("style",{children:O_}),s]})})},B_=t=>E(Un.div,{layoutId:Ai,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:[E(yv,{className:"w-8 h-8 text-red-400"}),E("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),E("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[E("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),E("li",{children:["Make sure that the"," ",E("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"," ",E(Ev,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function j_(t){return Object.keys(t).length===0}function pu(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 $_=({client:t})=>{const e=Wg();return ts(()=>{if(!t)return;const n=i=>{if(pu(i)&&!j_(i.params.widget_settings)){const s=i.params.widget_settings;e(s)}};return t.on(F.SocketMessage,n),()=>{t.off(F.SocketMessage,n)}},[t,e]),null};function U_({"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,environment:c,position:l="fixed","version-id":u}){const d=P_(t,c,u,e,n),[p,g]=Re(null),[y,k]=Re(!1),[x,b]=Re(!1),[S,C]=Re(!1),I=ps(Ad),M={};if(i&&(M.destinationNumber=i),s&&(M.callerNumber=s),o&&(M.callerName=o),r)try{M.customHeaders=JSON.parse(r)}catch(h){console.error("Invalid JSON for call-custom-headers attribute:",r,h)}if(a)try{M.audio=JSON.parse(a);const h=M.audio;if(typeof h=="object"){const v=navigator.mediaDevices.getSupportedConstraints();Object.keys(h).forEach(T=>{v[T]||console.warn(`Audio constraint not supported by browser: ${T}`)})}}catch(h){console.error("Invalid JSON for call-audio attribute:",a,h)}return R_(d,{onReady:()=>k(!1),onNotification:h=>{var v;if(((v=h.call)==null?void 0:v.state)==="destroy")return I(!1),g(null);g(h)},onError:()=>{k(!1),b(!0)},onSocketMessage:h=>{pu(h)&&C(!0)}}),E(Xe,{children:[E(F_,{position:l,children:t?x?E(B_,{agentId:t}):y?E(zr,{}):p!=null&&p.call?E(I_,{call:p.call,client:d}):S?E(D_,{versionId:u,client:d,callProps:M}):null:E("div",{children:"Please provide an assistant ID."})}),E($_,{client:d})]})}Ru(U_,"telnyx-ai-agent",Gg,{shadow:!0})})();