@telnyx/ai-agent-widget 0.32.1 → 0.32.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/bundle.min.js +23 -23
  2. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- var s0=Object.defineProperty;var r0=(Qe,G,Ft)=>G in Qe?s0(Qe,G,{enumerable:!0,configurable:!0,writable:!0,value:Ft}):Qe[G]=Ft;var Q=(Qe,G,Ft)=>r0(Qe,typeof G!="symbol"?G+"":G,Ft);(function(){"use strict";var Qe,G,Ft,Vt,go,mo,vo,yo,rs,os,as,_o,Tn={},bo=[],Xu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,En=Array.isArray;function st(t,e){for(var n in e)t[n]=e[n];return t}function ls(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function We(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?Qe.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 An(t,r,i,s,null)}function An(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??++Ft,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(o),o}function rt(t){return t.children}function et(t,e){this.props=t,this.context=e}function nn(t,e){if(e==null)return t.__?nn(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"?nn(t):null}function wo(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 wo(t)}}function cs(t){(!t.__d&&(t.__d=!0)&&Vt.push(t)&&!hi.__r++||go!=G.debounceRendering)&&((go=G.debounceRendering)||mo)(hi)}function hi(){for(var t,e,n,i,s,o,r,a=1;Vt.length;)Vt.length>a&&Vt.sort(vo),t=Vt.shift(),a=Vt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=st({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),ds(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??nn(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,To(o,n,r),n.__e!=s&&wo(n)));hi.__r=0}function So(t,e,n,i,s,o,r,a,l,c,d){var u,f,m,_,v,w,y=i&&i.__k||bo,C=e.length;for(l=Yu(n,e,y,l,C),u=0;u<C;u++)(m=n.__k[u])!=null&&(f=m.__i==-1?Tn:y[m.__i]||Tn,m.__i=u,w=ds(t,m,f,s,o,r,a,l,c,d),_=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&us(f.ref,null,m),d.push(m.ref,m.__c||_,m)),v==null&&_!=null&&(v=_),4&m.__u||f.__k===m.__k?l=Co(m,l,t):typeof m.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),m.__u&=-7);return n.__e=v,l}function Yu(t,e,n,i,s){var o,r,a,l,c,d=n.length,u=d,f=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+f,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?An(null,r,null,null,null):En(r)?An(rt,{children:r},null,null,null):r.constructor==null&&r.__b>0?An(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=Ju(r,n,l,u))!=-1&&(u--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>d?f--:s<d&&f++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,r.__u|=4))):t.__k[o]=null;if(u)for(o=0;o<d;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=nn(a)),Ao(a,a));return i}function Co(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=Co(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=nn(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ot(t,e){return e=e||[],t==null||typeof t=="boolean"||(En(t)?t.some(function(n){ot(n,e)}):e.push(t)),e}function Ju(t,e,n,i){var s,o,r=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function xo(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Xu.test(e)?n:n+"px"}function fi(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||xo(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||xo(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(yo,"$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=rs,t.addEventListener(e,o?as:os,o)):t.removeEventListener(e,o?as:os,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 ko(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=rs++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function ds(t,e,n,i,s,o,r,a,l,c){var d,u,f,m,_,v,w,y,C,k,E,R,O,S,x,p,g,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(d=G.__b)&&d(e);e:if(typeof h=="function")try{if(y=e.props,C="prototype"in h&&h.prototype.render,k=(d=h.contextType)&&i[d.__c],E=d?k?k.props.value:d.__:i,n.__c?w=(u=e.__c=n.__c).__=u.__E:(C?e.__c=u=new h(y,E):(e.__c=u=new et(y,E),u.constructor=h,u.render=Qu),k&&k.sub(u),u.props=y,u.state||(u.state={}),u.context=E,u.__n=i,f=u.__d=!0,u.__h=[],u._sb=[]),C&&u.__s==null&&(u.__s=u.state),C&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=st({},u.__s)),st(u.__s,h.getDerivedStateFromProps(y,u.__s))),m=u.props,_=u.state,u.__v=e,f)C&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),C&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(C&&h.getDerivedStateFromProps==null&&y!==m&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,E),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,E)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=y,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),R=0;R<u._sb.length;R++)u.__h.push(u._sb[R]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,E),C&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(m,_,v)})}if(u.context=E,u.props=y,u.__P=t,u.__e=!1,O=G.__r,S=0,C){for(u.state=u.__s,u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),x=0;x<u._sb.length;x++)u.__h.push(u._sb[x]);u._sb=[]}else do u.__d=!1,O&&O(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(i=st(st({},i),u.getChildContext())),C&&!f&&u.getSnapshotBeforeUpdate!=null&&(v=u.getSnapshotBeforeUpdate(m,_)),p=d,d!=null&&d.type===rt&&d.key==null&&(p=Eo(d.props.children)),a=So(t,En(p)?p:[p],e,n,i,s,o,r,a,l,c),u.base=e.__e,e.__u&=-161,u.__h.length&&r.push(u),w&&(u.__E=u.__=null)}catch(b){if(e.__v=null,l||o!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(g=o.length;g--;)ls(o[g]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Zu(n.__e,e,n,i,s,o,r,l,c);return(d=G.diffed)&&d(e),128&e.__u?void 0:a}function To(t,e,n){for(var i=0;i<n.length;i++)us(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){G.__e(o,s.__v)}})}function Eo(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:En(t)?t.map(Eo):st({},t)}function Zu(t,e,n,i,s,o,r,a,l){var c,d,u,f,m,_,v,w=n.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((m=o[c])&&"setAttribute"in m==!!C&&(C?m.localName==C:m.nodeType==3)){t=m,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(G.__m&&G.__m(e,o),a=!1),o=null}if(C==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&Qe.call(t.childNodes),w=n.props||Tn,!a&&o!=null)for(w={},c=0;c<t.attributes.length;c++)w[(m=t.attributes[c]).name]=m.value;for(c in w)if(m=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=m;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;fi(t,c,null,m,s)}}for(c in y)m=y[c],c=="children"?f=m:c=="dangerouslySetInnerHTML"?d=m:c=="value"?_=m:c=="checked"?v=m:a&&typeof m!="function"||w[c]===m||fi(t,c,m,w[c],s);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),So(e.type=="template"?t.content:t,En(f)?f:[f],e,n,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&nn(n,0),a,l),o!=null)for(c=o.length;c--;)ls(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=w[c])&&fi(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&fi(t,c,v,w[c],s))}return t}function us(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){G.__e(s,n)}}function Ao(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||us(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){G.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Ao(i[s],e,n||typeof t.type!="function");n||ls(t.__e),t.__c=t.__=t.__e=void 0}function Qu(t,e,n){return this.constructor(t,n)}function pi(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],ds(e,t=(!i&&n||e).__k=We(rt,null,[t]),s||Tn,Tn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?Qe.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),To(o,t,r)}function Io(t,e){pi(t,e,Io)}function hs(t,e,n){var i,s,o,r,a=st({},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?Qe.call(arguments,2):n),An(t.type,a,i||t.key,s||t.ref,null)}function vt(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,cs(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"+_o++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}Qe=bo.slice,G={__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}},Ft=0,et.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=st({},this.state),typeof t=="function"&&(t=t(st({},n),this.props)),t&&st(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),cs(this))},et.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),cs(this))},et.prototype.render=rt,Vt=[],mo=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,vo=function(t,e){return t.__v.__b-e.__v.__b},hi.__r=0,yo=/(PointerCapture)$|Capture$/i,rs=0,os=ko(!1),as=ko(!0),_o=0;var eh=0;function I(t,e,n,i,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--eh,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return G.vnode&&G.vnode(c),c}function fs(){return(fs=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}var th=["context","children"];function nh(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(t,th);return hs(e,n)}function ih(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=We(nh,fs({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Ro(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),d=l[r].slot;d?o[d]=We(Lo,{name:d},c):s[r]=c}var u=i?We(Lo,null,s):s;return We(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Io:pi)(this._vdom,this._root)}function Ro(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function sh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Ro(t)]=n,this._vdom=hs(this._vdom,i),pi(this._vdom,this._root)}}function rh(){pi(this._vdom=null,this._root)}function Lo(t,e){var n=this;return We("slot",fs({},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 oh(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=ih,s.prototype.attributeChangedCallback=sh,s.prototype.disconnectedCallback=rh,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 Tt,ce,ps,Po,In=0,Mo=[],ge=G,Do=ge.__b,Oo=ge.__r,No=ge.diffed,Fo=ge.__c,Vo=ge.unmount,Bo=ge.__;function sn(t,e){ge.__h&&ge.__h(ce,t,In||e),In=0;var n=ce.__H||(ce.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function Ce(t){return In=1,jo(Ho,t)}function jo(t,e,n){var i=sn(Tt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Ho(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=ce,!ce.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!o||o.call(this,a,l,c);var u=i.__c.props!==a;return d.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};ce.__f=!0;var o=ce.shouldComponentUpdate,r=ce.componentWillUpdate;ce.componentWillUpdate=function(a,l,c){if(this.__e){var d=o;o=void 0,s(a,l,c),o=d}r&&r.call(this,a,l,c)},ce.shouldComponentUpdate=s}return i.__N||i.__}function xe(t,e){var n=sn(Tt++,3);!ge.__s&&vs(n.__H,e)&&(n.__=t,n.u=e,ce.__H.__h.push(n))}function Uo(t,e){var n=sn(Tt++,4);!ge.__s&&vs(n.__H,e)&&(n.__=t,n.u=e,ce.__h.push(n))}function me(t){return In=5,ze(function(){return{current:t}},[])}function ze(t,e){var n=sn(Tt++,7);return vs(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function yt(t,e){return In=8,ze(function(){return t},e)}function ke(t){var e=ce.context[t.__c],n=sn(Tt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ce)),e.props.value):t.__}function ah(t,e){ge.useDebugValue&&ge.useDebugValue(e?e(t):t)}function gs(){var t=sn(Tt++,11);if(!t.__){for(var e=ce.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function lh(){for(var t;t=Mo.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(gi),t.__H.__h.forEach(ms),t.__H.__h=[]}catch(e){t.__H.__h=[],ge.__e(e,t.__v)}}ge.__b=function(t){ce=null,Do&&Do(t)},ge.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Bo&&Bo(t,e)},ge.__r=function(t){Oo&&Oo(t),Tt=0;var e=(ce=t.__c).__H;e&&(ps===ce?(e.__h=[],ce.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(gi),e.__h.forEach(ms),e.__h=[],Tt=0)),ps=ce},ge.diffed=function(t){No&&No(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Mo.push(e)!==1&&Po===ge.requestAnimationFrame||((Po=ge.requestAnimationFrame)||ch)(lh)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ps=ce=null},ge.__c=function(t,e){e.some(function(n){try{n.__h.forEach(gi),n.__h=n.__h.filter(function(i){return!i.__||ms(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ge.__e(i,n.__v)}}),Fo&&Fo(t,e)},ge.unmount=function(t){Vo&&Vo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{gi(i)}catch(s){e=s}}),n.__H=void 0,e&&ge.__e(e,n.__v))};var $o=typeof requestAnimationFrame=="function";function ch(t){var e,n=function(){clearTimeout(i),$o&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);$o&&(e=requestAnimationFrame(n))}function gi(t){var e=ce,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ce=e}function ms(t){var e=ce;t.__c=t.__(),ce=e}function vs(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Ho(t,e){return typeof e=="function"?e(t):e}const Rn={},Go=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Wo=t=>"init"in t,ys=t=>!!t.write,zo=t=>"v"in t||"e"in t,mi=t=>{if("e"in t)throw t.e;if((Rn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},vi=new WeakMap,qo=t=>{var e;return yi(t)&&!!((e=vi.get(t))!=null&&e[0])},dh=t=>{const e=vi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Ko=(t,e)=>{let n=vi.get(t);if(!n){n=[!0,new Set],vi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},yi=t=>typeof(t==null?void 0:t.then)=="function",Xo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},_s=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(yi(e))for(const r of i.d.keys())Xo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,yi(o)&&dh(o))},Yo=(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},uh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},bs=()=>{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},hh=t=>(t.c||(t.c=bs()),t.m||(t.m=bs()),t.u||(t.u=bs()),t.f||(t.f=uh()),t),fh=Symbol(),Jo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...m)=>f.read(...m),l=(f,...m)=>f.write(...m),c=(f,m)=>{var _;return(_=f.unstable_onInit)==null?void 0:_.call(f,m)},d=(f,m)=>{var _;return(_=f.onMount)==null?void 0:_.call(f,m)},...u)=>{const f=u[0]||(S=>{if((Rn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let x=t.get(S);return x||(x={d:new Map,p:new Set,n:0},t.set(S,x),c==null||c(S,O)),x}),m=u[1]||(()=>{const S=[],x=p=>{try{p()}catch(g){S.push(g)}};do{r.f&&x(r.f);const p=new Set,g=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(g)}),i.clear(),o.forEach(g),o.clear(),s.forEach(g),s.clear(),p.forEach(x),i.size&&_()}while(i.size||o.size||s.size);if(S.length)throw new AggregateError(S)}),_=u[2]||(()=>{const S=[],x=new WeakSet,p=new WeakSet,g=Array.from(i);for(;g.length;){const h=g[g.length-1],b=f(h);if(p.has(h)){g.pop();continue}if(x.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Rn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),g.pop();continue}x.add(h);for(const A of Yo(h,b,e))x.has(A)||g.push(A)}for(let h=S.length-1;h>=0;--h){const[b,A]=S[h];let P=!1;for(const L of A.d.keys())if(L!==b&&i.has(L)){P=!0;break}P&&(v(b),C(b)),n.delete(b)}}),v=u[3]||(S=>{var x;const p=f(S);if(zo(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([M,N])=>v(M).n===N)))return p;p.d.clear();let g=!0;const h=()=>{e.has(S)&&(C(S),_(),m())},b=M=>{var N;if(Go(S,M)){const j=f(M);if(!zo(j))if(Wo(M))_s(M,M.init,f);else throw new Error("no atom init");return mi(j)}const W=v(M);try{return mi(W)}finally{p.d.set(M,W.n),qo(p.v)&&Xo(S,p.v,W),(N=e.get(M))==null||N.t.add(S),g||h()}};let A,P;const L={get signal(){return A||(A=new AbortController),A.signal},get setSelf(){return(Rn?"production":void 0)!=="production"&&!ys(S)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&ys(S)&&(P=(...M)=>{if((Rn?"production":void 0)!=="production"&&g&&console.warn("setSelf function cannot be called in sync"),!g)try{return y(S,...M)}finally{_(),m()}}),P}},D=p.n;try{const M=a(S,b,L);return _s(S,M,f),yi(M)&&(Ko(M,()=>A==null?void 0:A.abort()),M.then(h,h)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{g=!1,D!==p.n&&n.get(S)===D&&(n.set(S,p.n),i.add(S),(x=r.c)==null||x.call(r,S))}}),w=u[4]||(S=>{const x=[S];for(;x.length;){const p=x.pop(),g=f(p);for(const h of Yo(p,g,e)){const b=f(h);n.set(h,b.n),x.push(h)}}}),y=u[5]||((S,...x)=>{let p=!0;const g=b=>mi(v(b)),h=(b,...A)=>{var P;const L=f(b);try{if(Go(S,b)){if(!Wo(b))throw new Error("atom not writable");const D=L.n,M=A[0];_s(b,M,f),C(b),D!==L.n&&(i.add(b),(P=r.c)==null||P.call(r,b),w(b));return}else return y(b,...A)}finally{p||(_(),m())}};try{return l(S,g,h,...x)}finally{p=!1}}),C=u[6]||(S=>{var x;const p=f(S),g=e.get(S);if(g&&!qo(p.v)){for(const[h,b]of p.d)if(!g.d.has(h)){const A=f(h);k(h).t.add(S),g.d.add(h),b!==A.n&&(i.add(h),(x=r.c)==null||x.call(r,h),w(h))}for(const h of g.d||[])if(!p.d.has(h)){g.d.delete(h);const b=E(h);b==null||b.t.delete(S)}}}),k=u[7]||(S=>{var x;const p=f(S);let g=e.get(S);if(!g){v(S);for(const h of p.d.keys())k(h).t.add(S);if(g={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,g),(x=r.m)==null||x.call(r,S),ys(S)){const h=()=>{let b=!0;const A=(...P)=>{try{return y(S,...P)}finally{b||(_(),m())}};try{const P=d(S,A);P&&(g.u=()=>{b=!0;try{P()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return g}),E=u[8]||(S=>{var x;const p=f(S);let g=e.get(S);if(g&&!g.l.size&&!Array.from(g.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){g.u&&o.add(g.u),g=void 0,e.delete(S),(x=r.u)==null||x.call(r,S);for(const h of p.d.keys()){const b=E(h);b==null||b.t.delete(S)}return}return g}),R=[t,e,n,i,s,o,r,a,l,c,d,f,m,_,v,w,y,C,k,E],O={get:S=>mi(v(S)),set:(S,...x)=>{try{return y(S,...x)}finally{_(),m()}},sub:(S,x)=>{const g=k(S).l;return g.add(x),m(),()=>{g.delete(x),E(S),m()}}};return Object.defineProperty(O,fh,{value:R}),O},ph=hh,Zo=Ko,ws={};let gh=0;function Ss(t,e){const n=`atom${++gh}`,i={toString(){return(ws?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?i.read=t:(i.init=t,i.read=mh,i.write=vh),i}function mh(t){return t(this)}function vh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const yh=()=>{let t=0;const e=ph({}),n=new WeakMap,i=new WeakMap,s=Jo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...d)=>t?c(a,...d):a.write(l,c,...d)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,d)=>{++t;try{for(const[u,f]of a)"init"in u&&d(u,f)}finally{--t}}};s.set(l)}})};function _h(){return(ws?"production":void 0)!=="production"?yh():Jo()}let Ln;function bh(){return Ln||(Ln=_h(),(ws?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Ln),globalThis.__JOTAI_DEFAULT_STORE__!==Ln&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Ln}function Qo(t,e){for(var n in e)t[n]=e[n];return t}function ea(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 ta=Uo;function na(t,e){this.props=t,this.context=e}(na.prototype=new et).isPureReactComponent=!0,na.prototype.shouldComponentUpdate=function(t,e){return ea(this.props,t)||ea(this.state,e)};var ia=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ia&&ia(t)};var wh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Sh(t){function e(n){var i=Qo({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=wh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var sa=function(t,e){return t==null?null:ot(ot(t).map(e))},Ch={map:sa,forEach:sa,count:function(t){return t?ot(t).length:0},only:function(t){var e=ot(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ot},xh=G.__e;G.__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)}xh(t,e,n,i)};var ra=G.unmount;function oa(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=Qo({},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 oa(i,e,n)})),t}function aa(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return aa(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 Cs(){this.__u=0,this.o=null,this.__b=null}function la(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function _i(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),ra&&ra(t)},(Cs.prototype=new et).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=la(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=aa(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},Cs.prototype.componentWillUnmount=function(){this.o=[]},Cs.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]=oa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&We(rt,null,t.fallback);return s&&(s.__u&=-33),[We(rt,null,e.__a?null:t.children),s]};var ca=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]}};(_i.prototype=new et).__a=function(t){var e=this,n=la(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),ca(e,t,i)):s()};n?n(o):o()}},_i.prototype.render=function(t){this.i=null,this.l=new Map;var e=ot(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},_i.prototype.componentDidUpdate=_i.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){ca(t,n,e)})};var da=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,kh=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Th=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Eh=/[A-Z0-9]/g,Ah=typeof document<"u",Ih=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};et.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(et.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var ua=G.event;function Rh(){}function Lh(){return this.cancelBubble}function Ph(){return this.defaultPrevented}G.event=function(t){return ua&&(t=ua(t)),t.persist=Rh,t.isPropagationStopped=Lh,t.isDefaultPrevented=Ph,t.nativeEvent=t};var Mh={enumerable:!1,configurable:!0,get:function(){return this.class}},ha=G.vnode;G.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||Ah&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Ih(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Th.test(r)&&(r=l):l=r="oninput":o&&kh.test(r)?r=r.replace(Eh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",Mh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=da,ha&&ha(t)};var fa=G.__r;G.__r=function(t){fa&&fa(t),t.__c};var pa=G.diffed;G.diffed=function(t){pa&&pa(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 ga(t){return!!t&&t.$$typeof===da}function Dh(t){return ga(t)?hs.apply(null,arguments):t}var ma={};const Oh={},Nh=vt(void 0);function va(t){return ke(Nh)||bh()}const xs=t=>typeof(t==null?void 0:t.then)=="function",ks=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Fh=ma.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(ks(t),t)}),Ts=new WeakMap,ya=(t,e)=>{let n=Ts.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=c=>d=>{o===c&&i(d)},a=c=>d=>{o===c&&s(d)},l=()=>{try{const c=e();xs(c)?(Ts.set(c,n),o=c,c.then(r(c),a(c)),Zo(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),Zo(t,l)}),Ts.set(t,n)),n};function _a(t,e){const{delay:n,unstable_promiseStatus:i=!ma.use}={},s=va(),[[o,r,a],l]=jo(d=>{const u=s.get(t);return Object.is(d[0],u)&&d[1]===s&&d[2]===t?d:[u,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),xe(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);xs(u)&&ks(ya(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),d},[s,t,n,i]),ah(c),xs(c)){const d=ya(c,()=>s.get(t));return i&&ks(d),Fh(d)}return c}function Es(t,e){const n=va();return yt((...s)=>{if((Oh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function ba(t,e){return[_a(t),Es(t)]}const As=vt({});function bi(t){const e=me(null);return e.current===null&&(e.current=t()),e.current}const Is=typeof window<"u",wa=Is?Uo:xe,wi=vt(null);function Rs(t,e){t.indexOf(e)===-1&&t.push(e)}function Ls(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const _t=(t,e,n)=>n>e?e:n<t?t:n;let Ps=()=>{};const bt={},Sa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Ca(t){return typeof t=="object"&&t!==null}const xa=t=>/^0[^.\s]+$/u.test(t);function Ms(t){let e;return()=>(e===void 0&&(e=t()),e)}const qe=t=>t,Vh=(t,e)=>n=>e(t(n)),Pn=(...t)=>t.reduce(Vh),Mn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Ds{constructor(){this.subscriptions=[]}add(e){return Rs(this.subscriptions,e),()=>Ls(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 at=t=>t*1e3,lt=t=>t/1e3;function ka(t,e){return e?t*(1e3/e):0}const Ta=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,Bh=1e-7,jh=12;function Uh(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=Ta(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>Bh&&++a<jh);return r}function Dn(t,e,n,i){if(t===e&&n===i)return qe;const s=o=>Uh(o,0,1,t,n);return o=>o===0||o===1?o:Ta(s(o),e,i)}const Ea=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Aa=t=>e=>1-t(1-e),Ia=Dn(.33,1.53,.69,.99),Os=Aa(Ia),Ra=Ea(Os),La=t=>(t*=2)<1?.5*Os(t):.5*(2-Math.pow(2,-10*(t-1))),Ns=t=>1-Math.sin(Math.acos(t)),Pa=Aa(Ns),Ma=Ea(Ns),$h=Dn(.42,0,1,1),Hh=Dn(0,0,.58,1),Da=Dn(.42,0,.58,1),Gh=t=>Array.isArray(t)&&typeof t[0]!="number",Oa=t=>Array.isArray(t)&&typeof t[0]=="number",Wh={linear:qe,easeIn:$h,easeInOut:Da,easeOut:Hh,circIn:Ns,circInOut:Ma,circOut:Pa,backIn:Os,backInOut:Ra,backOut:Ia,anticipate:La},zh=t=>typeof t=="string",Na=t=>{if(Oa(t)){Ps(t.length===4);const[e,n,i,s]=t;return Dn(e,n,i,s)}else if(zh(t))return Wh[t];return t},Si=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Fa={value:null};function qh(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(u){r.has(u)&&(d.schedule(u),t()),l++,u(a)}const d={schedule:(u,f=!1,m=!1)=>{const v=m&&s?n:i;return f&&r.add(u),v.has(u)||v.add(u),u},cancel:u=>{i.delete(u),r.delete(u)},process:u=>{if(a=u,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&Fa.value&&Fa.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,d.process(u))}};return d}const Kh=40;function Va(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=Si.reduce((k,E)=>(k[E]=qh(o,e?E:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:f,render:m,postRender:_}=r,v=()=>{const k=bt.useManualTiming?s.timestamp:performance.now();n=!1,bt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(k-s.timestamp,Kh),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),d.process(s),u.process(s),f.process(s),m.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},w=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:Si.reduce((k,E)=>{const R=r[E];return k[E]=(O,S=!1,x=!1)=>(n||w(),R.schedule(O,S,x)),k},{}),cancel:k=>{for(let E=0;E<Si.length;E++)r[Si[E]].cancel(k)},state:s,steps:r}}const{schedule:ue,cancel:Et,state:Ae,steps:Fs}=Va(typeof requestAnimationFrame<"u"?requestAnimationFrame:qe,!0);let Ci;function Xh(){Ci=void 0}const Be={now:()=>(Ci===void 0&&Be.set(Ae.isProcessing||bt.useManualTiming?Ae.timestamp:performance.now()),Ci),set:t=>{Ci=t,queueMicrotask(Xh)}},Ba=t=>e=>typeof e=="string"&&e.startsWith(t),Vs=Ba("--"),Yh=Ba("var(--"),Bs=t=>Yh(t)?Jh.test(t.split("/*")[0].trim()):!1,Jh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},On={...rn,transform:t=>_t(0,1,t)},xi={...rn,default:1},Nn=t=>Math.round(t*1e5)/1e5,js=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Zh(t){return t==null}const Qh=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Us=(t,e)=>n=>!!(typeof n=="string"&&Qh.test(n)&&n.startsWith(t)||e&&!Zh(n)&&Object.prototype.hasOwnProperty.call(n,e)),ja=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(js);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},ef=t=>_t(0,255,t),$s={...rn,transform:t=>Math.round(ef(t))},Bt={test:Us("rgb","red"),parse:ja("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+$s.transform(t)+", "+$s.transform(e)+", "+$s.transform(n)+", "+Nn(On.transform(i))+")"};function tf(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 Hs={test:Us("#"),parse:tf,transform:Bt.transform},Fn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),At=Fn("deg"),ct=Fn("%"),z=Fn("px"),nf=Fn("vh"),sf=Fn("vw"),Ua={...ct,parse:t=>ct.parse(t)/100,transform:t=>ct.transform(t*100)},on={test:Us("hsl","hue"),parse:ja("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ct.transform(Nn(e))+", "+ct.transform(Nn(n))+", "+Nn(On.transform(i))+")"},we={test:t=>Bt.test(t)||Hs.test(t)||on.test(t),parse:t=>Bt.test(t)?Bt.parse(t):on.test(t)?on.parse(t):Hs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Bt.transform(t):on.transform(t),getAnimatableNone:t=>{const e=we.parse(t);return e.alpha=0,we.transform(e)}},rf=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function of(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(js))==null?void 0:e.length)||0)+(((n=t.match(rf))==null?void 0:n.length)||0)>0}const $a="number",Ha="color",af="var",lf="var(",Ga="${}",cf=/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 Vn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(cf,l=>(we.test(l)?(i.color.push(o),s.push(Ha),n.push(we.parse(l))):l.startsWith(lf)?(i.var.push(o),s.push(af),n.push(l)):(i.number.push(o),s.push($a),n.push(parseFloat(l))),++o,Ga)).split(Ga);return{values:n,split:a,indexes:i,types:s}}function Wa(t){return Vn(t).values}function za(t){const{split:e,types:n}=Vn(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===$a?o+=Nn(s[r]):a===Ha?o+=we.transform(s[r]):o+=s[r]}return o}}const df=t=>typeof t=="number"?0:we.test(t)?we.getAnimatableNone(t):t;function uf(t){const e=Wa(t);return za(t)(e.map(df))}const It={test:of,parse:Wa,createTransformer:za,getAnimatableNone:uf};function Gs(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 hf({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Gs(l,a,t+1/3),o=Gs(l,a,t),r=Gs(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function ki(t,e){return n=>n>0?e:t}const ve=(t,e,n)=>t+(e-t)*n,Ws=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},ff=[Hs,Bt,on],pf=t=>ff.find(e=>e.test(t));function qa(t){const e=pf(t);if(!e)return!1;let n=e.parse(t);return e===on&&(n=hf(n)),n}const Ka=(t,e)=>{const n=qa(t),i=qa(e);if(!n||!i)return ki(t,e);const s={...n};return o=>(s.red=Ws(n.red,i.red,o),s.green=Ws(n.green,i.green,o),s.blue=Ws(n.blue,i.blue,o),s.alpha=ve(n.alpha,i.alpha,o),Bt.transform(s))},zs=new Set(["none","hidden"]);function gf(t,e){return zs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function mf(t,e){return n=>ve(t,e,n)}function qs(t){return typeof t=="number"?mf:typeof t=="string"?Bs(t)?ki:we.test(t)?Ka:_f:Array.isArray(t)?Xa:typeof t=="object"?we.test(t)?Ka:vf:ki}function Xa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>qs(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function vf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=qs(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function yf(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 _f=(t,e)=>{const n=It.createTransformer(e),i=Vn(t),s=Vn(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?zs.has(t)&&!s.values.length||zs.has(e)&&!i.values.length?gf(t,e):Pn(Xa(yf(i,s),s.values),n):ki(t,e)};function Ya(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ve(t,e,n):qs(t)(t,e)}const bf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ue.update(e,n),stop:()=>Et(e),now:()=>Ae.isProcessing?Ae.timestamp:Be.now()}},Ja=(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)})`},Ti=2e4;function Ks(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ti;)e+=n,i=t.next(e);return e>=Ti?1/0:e}function wf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Ks(i),Ti);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:lt(s)}}const Sf=5;function Za(t,e,n){const i=Math.max(e-Sf,0);return ka(n-t(i),e-i)}const ye={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},Xs=.001;function Cf({duration:t=ye.duration,bounce:e=ye.bounce,velocity:n=ye.velocity,mass:i=ye.mass}){let s,o,r=1-e;r=_t(ye.minDamping,ye.maxDamping,r),t=_t(ye.minDuration,ye.maxDuration,lt(t)),r<1?(s=c=>{const d=c*r,u=d*t,f=d-n,m=Ys(c,r),_=Math.exp(-u);return Xs-f/m*_},o=c=>{const u=c*r*t,f=u*n+n,m=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-u),v=Ys(Math.pow(c,2),r);return(-s(c)+Xs>0?-1:1)*((f-m)*_)/v}):(s=c=>{const d=Math.exp(-c*t),u=(c-n)*t+1;return-Xs+d*u},o=c=>{const d=Math.exp(-c*t),u=(n-c)*(t*t);return d*u});const a=5/t,l=kf(s,o,a);if(t=at(t),isNaN(l))return{stiffness:ye.stiffness,damping:ye.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const xf=12;function kf(t,e,n){let i=n;for(let s=1;s<xf;s++)i=i-t(i)/e(i);return i}function Ys(t,e){return t*Math.sqrt(1-e*e)}const Tf=["duration","bounce"],Ef=["stiffness","damping","mass"];function Qa(t,e){return e.some(n=>t[n]!==void 0)}function Af(t){let e={velocity:ye.velocity,stiffness:ye.stiffness,damping:ye.damping,mass:ye.mass,isResolvedFromDuration:!1,...t};if(!Qa(t,Ef)&&Qa(t,Tf))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*_t(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ye.mass,stiffness:s,damping:o}}else{const n=Cf(t);e={...e,...n,mass:ye.mass},e.isResolvedFromDuration=!0}return e}function Ei(t=ye.visualDuration,e=ye.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:d,duration:u,velocity:f,isResolvedFromDuration:m}=Af({...n,velocity:-lt(n.velocity||0)}),_=f||0,v=c/(2*Math.sqrt(l*d)),w=r-o,y=lt(Math.sqrt(l/d)),C=Math.abs(w)<5;i||(i=C?ye.restSpeed.granular:ye.restSpeed.default),s||(s=C?ye.restDelta.granular:ye.restDelta.default);let k;if(v<1){const R=Ys(y,v);k=O=>{const S=Math.exp(-v*y*O);return r-S*((_+v*y*w)/R*Math.sin(R*O)+w*Math.cos(R*O))}}else if(v===1)k=R=>r-Math.exp(-y*R)*(w+(_+y*w)*R);else{const R=y*Math.sqrt(v*v-1);k=O=>{const S=Math.exp(-v*y*O),x=Math.min(R*O,300);return r-S*((_+v*y*w)*Math.sinh(x)+R*w*Math.cosh(x))/R}}const E={calculatedDuration:m&&u||null,next:R=>{const O=k(R);if(m)a.done=R>=u;else{let S=R===0?_:0;v<1&&(S=R===0?at(_):Za(k,R,O));const x=Math.abs(S)<=i,p=Math.abs(r-O)<=s;a.done=x&&p}return a.value=a.done?r:O,a},toString:()=>{const R=Math.min(Ks(E),Ti),O=Ja(S=>E.next(R*S).value,R,30);return R+"ms "+O},toTransition:()=>{}};return E}Ei.applyToOptions=t=>{const e=wf(t,100,Ei);return t.ease=e.ease,t.duration=at(e.duration),t.type="keyframes",t};function Js({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:d}){const u=t[0],f={done:!1,value:u},m=x=>a!==void 0&&x<a||l!==void 0&&x>l,_=x=>a===void 0?l:l===void 0||Math.abs(a-x)<Math.abs(l-x)?a:l;let v=n*e;const w=u+v,y=r===void 0?w:r(w);y!==w&&(v=y-u);const C=x=>-v*Math.exp(-x/i),k=x=>y+C(x),E=x=>{const p=C(x),g=k(x);f.done=Math.abs(p)<=c,f.value=f.done?y:g};let R,O;const S=x=>{m(f.value)&&(R=x,O=Ei({keyframes:[f.value,_(f.value)],velocity:Za(k,x,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return S(0),{calculatedDuration:null,next:x=>{let p=!1;return!O&&R===void 0&&(p=!0,E(x),S(x)),R!==void 0&&x>=R?O.next(x-R):(!p&&E(x),f)}}}function If(t,e,n){const i=[],s=n||bt.mix||Ya,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||qe:e;a=Pn(l,a)}i.push(a)}return i}function Rf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Ps(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=If(e,i,s),l=a.length,c=d=>{if(r&&d<t[0])return e[0];let u=0;if(l>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const f=Mn(t[u],t[u+1],d);return a[u](f)};return n?d=>c(_t(t[0],t[o-1],d)):c}function Lf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Mn(0,e,i);t.push(ve(n,1,s))}}function Pf(t){const e=[0];return Lf(e,t.length-1),e}function Mf(t,e){return t.map(n=>n*e)}function Df(t,e){return t.map(()=>e||Da).splice(0,t.length-1)}function Bn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Gh(i)?i.map(Na):Na(i),o={done:!1,value:e[0]},r=Mf(n&&n.length===e.length?n:Pf(e),t),a=Rf(r,e,{ease:Array.isArray(s)?s:Df(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Of=t=>t!==null;function Zs(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 Nf={decay:Js,inertia:Js,tween:Bn,keyframes:Bn,spring:Ei};function el(t){typeof t.type=="string"&&(t.type=Nf[t.type])}class Qs{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 Ff=t=>t/100;class er extends Qs{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!==Be.now()&&this.tick(Be.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;el(e);const{type:n=Bn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||Bn;l!==Bn&&typeof a[0]!="number"&&(this.mixKeyframes=Pn(Ff,Ya(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=Ks(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:d,repeat:u,repeatType:f,repeatDelay:m,type:_,onUpdate:v,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,E=i;if(u){const x=Math.min(this.currentTime,s)/a;let p=Math.floor(x),g=x%1;!g&&x>=1&&(g=1),g===1&&p--,p=Math.min(p,u+1),!!(p%2)&&(f==="reverse"?(g=1-g,m&&(g-=m/a)):f==="mirror"&&(E=r)),k=_t(0,1,g)*a}const R=C?{done:!1,value:d[0]}:E.next(k);o&&(R.value=o(R.value));let{done:O}=R;!C&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return S&&_!==Js&&(R.value=Zs(d,this.options,w,this.speed)),v&&v(R.value),S&&this.finish(),R}then(e,n){return this.finished.then(e,n)}get duration(){return lt(this.calculatedDuration)}get time(){return lt(this.currentTime)}set time(e){var n;e=at(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(Be.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=lt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=bf,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(Be.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 Vf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const jt=t=>t*180/Math.PI,tr=t=>{const e=jt(Math.atan2(t[1],t[0]));return nr(e)},Bf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:tr,rotateZ:tr,skewX:t=>jt(Math.atan(t[1])),skewY:t=>jt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},nr=t=>(t=t%360,t<0&&(t+=360),t),tl=tr,nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),il=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),jf={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:nl,scaleY:il,scale:t=>(nl(t)+il(t))/2,rotateX:t=>nr(jt(Math.atan2(t[6],t[5]))),rotateY:t=>nr(jt(Math.atan2(-t[2],t[0]))),rotateZ:tl,rotate:tl,skewX:t=>jt(Math.atan(t[4])),skewY:t=>jt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ir(t){return t.includes("scale")?1:0}function sr(t,e){if(!t||t==="none")return ir(e);const n=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let i,s;if(n)i=jf,s=n;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);i=Bf,s=a}if(!s)return ir(e);const o=i[e],r=s[1].split(",").map($f);return typeof o=="function"?o(r):r[o]}const Uf=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return sr(n,e)};function $f(t){return parseFloat(t.trim())}const an=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ln=new Set(an),sl=t=>t===rn||t===z,Hf=new Set(["x","y","z"]),Gf=an.filter(t=>!Hf.has(t));function Wf(t){const e=[];return Gf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ut={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})=>sr(e,"x"),y:(t,{transform:e})=>sr(e,"y")};Ut.translateX=Ut.x,Ut.translateY=Ut.y;const $t=new Set;let rr=!1,or=!1,ar=!1;function rl(){if(or){const t=Array.from($t).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=Wf(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)})}or=!1,rr=!1,$t.forEach(t=>t.complete(ar)),$t.clear()}function ol(){$t.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(or=!0)})}function zf(){ar=!0,ol(),rl(),ar=!1}class lr{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?($t.add(this),rr||(rr=!0,ue.read(ol),ue.resolveKeyframes(rl))):(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])}Vf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),$t.delete(this)}cancel(){this.state==="scheduled"&&($t.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const qf=t=>t.startsWith("--");function Kf(t,e,n){qf(e)?t.style.setProperty(e,n):t.style[e]=n}const Xf=Ms(()=>window.ScrollTimeline!==void 0),Yf={};function Jf(t,e){const n=Ms(t);return()=>Yf[e]??n()}const al=Jf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),jn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,ll={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:jn([0,.65,.55,1]),circOut:jn([.55,0,1,.45]),backIn:jn([.31,.01,.66,-.59]),backOut:jn([.33,1.53,.69,.99])};function cl(t,e){if(t)return typeof t=="function"?al()?Ja(t,e):"ease-out":Oa(t)?jn(t):Array.isArray(t)?t.map(n=>cl(n,e)||ll.easeOut):ll[t]}function Zf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[e]:n};l&&(d.offset=l);const u=cl(a,s);Array.isArray(u)&&(d.easing=u);const f={delay:i,duration:s,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(d,f)}function dl(t){return typeof t=="function"&&"applyToOptions"in t}function Qf({type:t,...e}){return dl(t)&&al()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class ep extends Qs{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Ps(typeof e.type!="string");const c=Qf(e);this.animation=Zf(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Zs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Kf(n,i,d),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return lt(Number(e))}get time(){return lt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=at(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&&Xf()?(this.animation.timeline=e,qe):n(this)}}const ul={anticipate:La,backInOut:Ra,circInOut:Ma};function tp(t){return t in ul}function np(t){typeof t.ease=="string"&&tp(t.ease)&&(t.ease=ul[t.ease])}const hl=10;class ip extends ep{constructor(e){np(e),el(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 er({...r,autoplay:!1}),l=at(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-hl).value,a.sample(l).value,hl),a.stop()}}const fl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(It.test(t)||t==="0")&&!t.startsWith("url("));function sp(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 rp(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=fl(s,e),a=fl(o,e);return!r||!a?!1:sp(t)||(n==="spring"||dl(n))&&i}function cr(t){return Ca(t)&&"offsetHeight"in t}const op=new Set(["opacity","clipPath","filter","transform"]),ap=Ms(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function lp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!cr((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return ap()&&n&&op.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const cp=40;class dp extends Qs{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:d,...u}){var _;super(),this.stop=()=>{var v,w;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=Be.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},m=(d==null?void 0:d.KeyframeResolver)||lr;this.keyframeResolver=new m(a,(v,w,y)=>this.onKeyframesResolved(v,w,f,!y),l,c,d),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:d}=i;this.resolvedAt=Be.now(),rp(e,o,r,a)||((bt.instantAnimations||!l)&&(d==null||d(Zs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>cp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},m=!c&&lp(f)?new ip({...f,element:f.motionValue.owner.current}):new er(f);m.finished.then(()=>this.notifyFinished()).catch(qe),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),zf()),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 up=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hp(t){const e=up.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function pl(t,e,n=1){const[i,s]=hp(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Sa(r)?parseFloat(r):r}return Bs(s)?pl(s,e,n+1):s}function dr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const gl=new Set(["width","height","top","left","right","bottom",...an]),fp={test:t=>t==="auto",parse:t=>t},ml=t=>e=>e.test(t),vl=[rn,z,ct,At,sf,nf,fp],yl=t=>vl.find(ml(t));function pp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xa(t):!0}const gp=new Set(["brightness","contrast","saturate","opacity"]);function mp(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(js)||[];if(!i)return t;const s=n.replace(i,"");let o=gp.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const vp=/\b([a-z-]*)\(.*?\)/gu,ur={...It,getAnimatableNone:t=>{const e=t.match(vp);return e?e.map(mp).join(" "):t}},_l={...rn,transform:Math.round},hr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...{rotate:At,rotateX:At,rotateY:At,rotateZ:At,scale:xi,scaleX:xi,scaleY:xi,scaleZ:xi,skew:At,skewX:At,skewY:At,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:On,originX:Ua,originY:Ua,originZ:z},zIndex:_l,fillOpacity:On,strokeOpacity:On,numOctaves:_l},yp={...hr,color:we,backgroundColor:we,outlineColor:we,fill:we,stroke:we,borderColor:we,borderTopColor:we,borderRightColor:we,borderBottomColor:we,borderLeftColor:we,filter:ur,WebkitFilter:ur},bl=t=>yp[t];function wl(t,e){let n=bl(t);return n!==ur&&(n=It),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const _p=new Set(["auto","none","0"]);function bp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!_p.has(o)&&Vn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=wl(n,s)}class wp extends lr{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),Bs(c))){const d=pl(c,n.current);d!==void 0&&(e[l]=d),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!gl.has(i)||e.length!==2)return;const[s,o]=e,r=yl(s),a=yl(o);if(r!==a)if(sl(r)&&sl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Ut[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||pp(e[s]))&&i.push(s);i.length&&bp(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=Ut[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]=Ut[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function Sp(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 Sl=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Cl=30,Cp=t=>!isNaN(parseFloat(t));class xp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Be.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Be.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Cp(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 Ds);const i=this.events[e].add(n);return e==="change"?()=>{i(),ue.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=Be.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Cl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Cl);return ka(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 cn(t,e){return new xp(t,e)}const{schedule:fr}=Va(queueMicrotask,!1),tt={x:!1,y:!1};function xl(){return tt.x||tt.y}function kp(t){return t==="x"||t==="y"?tt[t]?null:(tt[t]=!0,()=>{tt[t]=!1}):tt.x||tt.y?null:(tt.x=tt.y=!0,()=>{tt.x=tt.y=!1})}function kl(t,e){const n=Sp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Tl(t){return!(t.pointerType==="touch"||xl())}function Tp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{if(!Tl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const d=u=>{Tl(u)&&(c(u),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const El=(t,e)=>e?t===e?!0:El(t,e.parentElement):!1,pr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ep=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ap(t){return Ep.has(t.tagName)||t.tabIndex!==-1}const Ai=new WeakSet;function Al(t){return e=>{e.key==="Enter"&&t(e)}}function gr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Ip=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=Al(()=>{if(Ai.has(n))return;gr(n,"down");const s=Al(()=>{gr(n,"up")}),o=()=>gr(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 Il(t){return pr(t)&&!xl()}function Rp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{const l=a.currentTarget;if(!Il(a))return;Ai.add(l);const c=e(l,a),d=(m,_)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),Ai.has(l)&&Ai.delete(l),Il(m)&&typeof c=="function"&&c(m,{success:_})},u=m=>{d(m,l===window||l===document||n.useGlobalTarget||El(l,m.target))},f=m=>{d(m,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),cr(a)&&(a.addEventListener("focus",c=>Ip(c,s)),!Ap(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Rl(t){return Ca(t)&&"ownerSVGElement"in t}function Lp(t){return Rl(t)&&t.tagName==="svg"}const Pe=t=>!!(t&&t.getVelocity),Pp=[...vl,we,It],Mp=t=>Pp.find(ml(t)),Un=vt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Dp extends et{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=cr(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=gs(),o=me(null),r=me({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=ke(Un);return ta(()=>{const{width:l,height:c,top:d,left:u,right:f}=r.current;if(e||!o.current||!l||!c)return;const m=n==="left"?`left: ${u}`:`right: ${f}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=i??document.head;return v.appendChild(_),_.sheet&&_.sheet.insertRule(`
1
+ var o0=Object.defineProperty;var a0=(Qe,G,Bt)=>G in Qe?o0(Qe,G,{enumerable:!0,configurable:!0,writable:!0,value:Bt}):Qe[G]=Bt;var Y=(Qe,G,Bt)=>a0(Qe,typeof G!="symbol"?G+"":G,Bt);(function(){"use strict";var Qe,G,Bt,jt,mo,vo,yo,_o,as,ls,cs,bo,Tn={},wo=[],Yu=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,An=Array.isArray;function st(t,e){for(var n in e)t[n]=e[n];return t}function ds(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function We(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?Qe.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 En(t,r,i,s,null)}function En(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??++Bt,__i:-1,__u:0};return s==null&&G.vnode!=null&&G.vnode(o),o}function rt(t){return t.children}function et(t,e){this.props=t,this.context=e}function nn(t,e){if(e==null)return t.__?nn(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"?nn(t):null}function So(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 So(t)}}function us(t){(!t.__d&&(t.__d=!0)&&jt.push(t)&&!hi.__r++||mo!=G.debounceRendering)&&((mo=G.debounceRendering)||vo)(hi)}function hi(){for(var t,e,n,i,s,o,r,a=1;jt.length;)jt.length>a&&jt.sort(yo),t=jt.shift(),a=jt.length,t.__d&&(n=void 0,s=(i=(e=t).__v).__e,o=[],r=[],e.__P&&((n=st({},i)).__v=i.__v+1,G.vnode&&G.vnode(n),hs(e.__P,n,i,e.__n,e.__P.namespaceURI,32&i.__u?[s]:null,o,s??nn(i),!!(32&i.__u),r),n.__v=i.__v,n.__.__k[n.__i]=n,Ao(o,n,r),n.__e!=s&&So(n)));hi.__r=0}function Co(t,e,n,i,s,o,r,a,l,c,d){var u,f,m,_,v,w,y=i&&i.__k||wo,C=e.length;for(l=Ju(n,e,y,l,C),u=0;u<C;u++)(m=n.__k[u])!=null&&(f=m.__i==-1?Tn:y[m.__i]||Tn,m.__i=u,w=hs(t,m,f,s,o,r,a,l,c,d),_=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&fs(f.ref,null,m),d.push(m.ref,m.__c||_,m)),v==null&&_!=null&&(v=_),4&m.__u||f.__k===m.__k?l=xo(m,l,t):typeof m.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),m.__u&=-7);return n.__e=v,l}function Ju(t,e,n,i,s){var o,r,a,l,c,d=n.length,u=d,f=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+f,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?En(null,r,null,null,null):An(r)?En(rt,{children:r},null,null,null):r.constructor==null&&r.__b>0?En(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=Zu(r,n,l,u))!=-1&&(u--,(a=n[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>d?f--:s<d&&f++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?f--:c==l+1?f++:(c>l?f--:f++,r.__u|=4))):t.__k[o]=null;if(u)for(o=0;o<d;o++)(a=n[o])!=null&&(2&a.__u)==0&&(a.__e==i&&(i=nn(a)),Io(a,a));return i}function xo(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=xo(i[s],e,n));return e}t.__e!=e&&(e&&t.type&&!n.contains(e)&&(e=nn(t)),n.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ot(t,e){return e=e||[],t==null||typeof t=="boolean"||(An(t)?t.some(function(n){ot(n,e)}):e.push(t)),e}function Zu(t,e,n,i){var s,o,r=t.key,a=t.type,l=e[n];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return n;if(i>(l!=null&&(2&l.__u)==0?1:0))for(s=n-1,o=n+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function ko(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Yu.test(e)?n:n+"px"}function fi(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||ko(t.style,e,"");if(n)for(e in n)i&&n[e]==i[e]||ko(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(_o,"$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=as,t.addEventListener(e,o?cs:ls,o)):t.removeEventListener(e,o?cs:ls,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 To(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=as++;else if(e.t<n.u)return;return n(G.event?G.event(e):e)}}}function hs(t,e,n,i,s,o,r,a,l,c){var d,u,f,m,_,v,w,y,C,k,T,E,D,S,x,p,g,h=e.type;if(e.constructor!=null)return null;128&n.__u&&(l=!!(32&n.__u),o=[a=e.__e=n.__e]),(d=G.__b)&&d(e);e:if(typeof h=="function")try{if(y=e.props,C="prototype"in h&&h.prototype.render,k=(d=h.contextType)&&i[d.__c],T=d?k?k.props.value:d.__:i,n.__c?w=(u=e.__c=n.__c).__=u.__E:(C?e.__c=u=new h(y,T):(e.__c=u=new et(y,T),u.constructor=h,u.render=eh),k&&k.sub(u),u.props=y,u.state||(u.state={}),u.context=T,u.__n=i,f=u.__d=!0,u.__h=[],u._sb=[]),C&&u.__s==null&&(u.__s=u.state),C&&h.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=st({},u.__s)),st(u.__s,h.getDerivedStateFromProps(y,u.__s))),m=u.props,_=u.state,u.__v=e,f)C&&h.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),C&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(C&&h.getDerivedStateFromProps==null&&y!==m&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(y,T),!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(y,u.__s,T)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(u.props=y,u.state=u.__s,u.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(b){b&&(b.__=e)}),E=0;E<u._sb.length;E++)u.__h.push(u._sb[E]);u._sb=[],u.__h.length&&r.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(y,u.__s,T),C&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(m,_,v)})}if(u.context=T,u.props=y,u.__P=t,u.__e=!1,D=G.__r,S=0,C){for(u.state=u.__s,u.__d=!1,D&&D(e),d=u.render(u.props,u.state,u.context),x=0;x<u._sb.length;x++)u.__h.push(u._sb[x]);u._sb=[]}else do u.__d=!1,D&&D(e),d=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(i=st(st({},i),u.getChildContext())),C&&!f&&u.getSnapshotBeforeUpdate!=null&&(v=u.getSnapshotBeforeUpdate(m,_)),p=d,d!=null&&d.type===rt&&d.key==null&&(p=Eo(d.props.children)),a=Co(t,An(p)?p:[p],e,n,i,s,o,r,a,l,c),u.base=e.__e,e.__u&=-161,u.__h.length&&r.push(u),w&&(u.__E=u.__=null)}catch(b){if(e.__v=null,l||o!=null)if(b.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(g=o.length;g--;)ds(o[g]);else e.__e=n.__e,e.__k=n.__k;G.__e(b,e,n)}else o==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):a=e.__e=Qu(n.__e,e,n,i,s,o,r,l,c);return(d=G.diffed)&&d(e),128&e.__u?void 0:a}function Ao(t,e,n){for(var i=0;i<n.length;i++)fs(n[i],n[++i],n[++i]);G.__c&&G.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){G.__e(o,s.__v)}})}function Eo(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:An(t)?t.map(Eo):st({},t)}function Qu(t,e,n,i,s,o,r,a,l){var c,d,u,f,m,_,v,w=n.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((m=o[c])&&"setAttribute"in m==!!C&&(C?m.localName==C:m.nodeType==3)){t=m,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(G.__m&&G.__m(e,o),a=!1),o=null}if(C==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&Qe.call(t.childNodes),w=n.props||Tn,!a&&o!=null)for(w={},c=0;c<t.attributes.length;c++)w[(m=t.attributes[c]).name]=m.value;for(c in w)if(m=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")u=m;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;fi(t,c,null,m,s)}}for(c in y)m=y[c],c=="children"?f=m:c=="dangerouslySetInnerHTML"?d=m:c=="value"?_=m:c=="checked"?v=m:a&&typeof m!="function"||w[c]===m||fi(t,c,m,w[c],s);if(d)a||u&&(d.__html==u.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(u&&(t.innerHTML=""),Co(e.type=="template"?t.content:t,An(f)?f:[f],e,n,i,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:n.__k&&nn(n,0),a,l),o!=null)for(c=o.length;c--;)ds(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=w[c])&&fi(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&fi(t,c,v,w[c],s))}return t}function fs(t,e,n){try{if(typeof t=="function"){var i=typeof t.__u=="function";i&&t.__u(),i&&e==null||(t.__u=t(e))}else t.current=e}catch(s){G.__e(s,n)}}function Io(t,e,n){var i,s;if(G.unmount&&G.unmount(t),(i=t.ref)&&(i.current&&i.current!=t.__e||fs(i,null,e)),(i=t.__c)!=null){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(o){G.__e(o,e)}i.base=i.__P=null}if(i=t.__k)for(s=0;s<i.length;s++)i[s]&&Io(i[s],e,n||typeof t.type!="function");n||ds(t.__e),t.__c=t.__=t.__e=void 0}function eh(t,e,n){return this.constructor(t,n)}function pi(t,e,n){var i,s,o,r;e==document&&(e=document.documentElement),G.__&&G.__(t,e),s=(i=typeof n=="function")?null:n&&n.__k||e.__k,o=[],r=[],hs(e,t=(!i&&n||e).__k=We(rt,null,[t]),s||Tn,Tn,e.namespaceURI,!i&&n?[n]:s?null:e.firstChild?Qe.call(e.childNodes):null,o,!i&&n?n:s?s.__e:e.firstChild,i,r),Ao(o,t,r)}function Ro(t,e){pi(t,e,Ro)}function ps(t,e,n){var i,s,o,r,a=st({},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?Qe.call(arguments,2):n),En(t.type,a,i||t.key,s||t.ref,null)}function vt(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,us(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"+bo++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,i){return n.children(i)}).contextType=e,e}Qe=wo.slice,G={__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}},Bt=0,et.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=st({},this.state),typeof t=="function"&&(t=t(st({},n),this.props)),t&&st(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),us(this))},et.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),us(this))},et.prototype.render=rt,jt=[],vo=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,yo=function(t,e){return t.__v.__b-e.__v.__b},hi.__r=0,_o=/(PointerCapture)$|Capture$/i,as=0,ls=To(!1),cs=To(!0),bo=0;var th=0;function R(t,e,n,i,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--th,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return G.vnode&&G.vnode(c),c}function gs(){return(gs=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 nh=["context","children"];function ih(t){this.getChildContext=function(){return t.context};var e=t.children,n=function(i,s){if(i==null)return{};var o,r,a={},l=Object.keys(i);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=i[o]);return a}(t,nh);return ps(e,n)}function sh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=We(ih,gs({},this._props,{context:t.detail.context}),function e(n,i){if(n.nodeType===3)return n.data;if(n.nodeType!==1)return null;var s=[],o={},r=0,a=n.attributes,l=n.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[Lo(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),d=l[r].slot;d?o[d]=We(Po,{name:d},c):s[r]=c}var u=i?We(Po,null,s):s;return We(i||n.nodeName.toLowerCase(),o,u)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ro:pi)(this._vdom,this._root)}function Lo(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function rh(t,e,n){if(this._vdom){var i={};i[t]=n=n??void 0,i[Lo(t)]=n,this._vdom=ps(this._vdom,i),pi(this._vdom,this._root)}}function oh(){pi(this._vdom=null,this._root)}function Po(t,e){var n=this;return We("slot",gs({},t,{ref:function(i){i?(n.ref=i,n._listener||(n._listener=function(s){s.stopPropagation(),s.detail.context=e},i.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function ah(t,e,n,i){function s(){var 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=sh,s.prototype.attributeChangedCallback=rh,s.prototype.disconnectedCallback=oh,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 Tt,ce,ms,Mo,In=0,Do=[],ge=G,Oo=ge.__b,No=ge.__r,Fo=ge.diffed,Vo=ge.__c,Bo=ge.unmount,jo=ge.__;function sn(t,e){ge.__h&&ge.__h(ce,t,In||e),In=0;var n=ce.__H||(ce.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function xe(t){return In=1,Uo(Go,t)}function Uo(t,e,n){var i=sn(Tt++,2);if(i.t=t,!i.__c&&(i.__=[n?n(e):Go(void 0,e),function(a){var l=i.__N?i.__N[0]:i.__[0],c=i.t(l,a);l!==c&&(i.__N=[c,i.__[1]],i.__c.setState({}))}],i.__c=ce,!ce.__f)){var s=function(a,l,c){if(!i.__c.__H)return!0;var d=i.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!o||o.call(this,a,l,c);var u=i.__c.props!==a;return d.forEach(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(u=!0)}}),o&&o.call(this,a,l,c)||u};ce.__f=!0;var o=ce.shouldComponentUpdate,r=ce.componentWillUpdate;ce.componentWillUpdate=function(a,l,c){if(this.__e){var d=o;o=void 0,s(a,l,c),o=d}r&&r.call(this,a,l,c)},ce.shouldComponentUpdate=s}return i.__N||i.__}function ke(t,e){var n=sn(Tt++,3);!ge.__s&&_s(n.__H,e)&&(n.__=t,n.u=e,ce.__H.__h.push(n))}function $o(t,e){var n=sn(Tt++,4);!ge.__s&&_s(n.__H,e)&&(n.__=t,n.u=e,ce.__h.push(n))}function me(t){return In=5,ze(function(){return{current:t}},[])}function ze(t,e){var n=sn(Tt++,7);return _s(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function yt(t,e){return In=8,ze(function(){return t},e)}function Te(t){var e=ce.context[t.__c],n=sn(Tt++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(ce)),e.props.value):t.__}function lh(t,e){ge.useDebugValue&&ge.useDebugValue(e?e(t):t)}function vs(){var t=sn(Tt++,11);if(!t.__){for(var e=ce.__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 ch(){for(var t;t=Do.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(gi),t.__H.__h.forEach(ys),t.__H.__h=[]}catch(e){t.__H.__h=[],ge.__e(e,t.__v)}}ge.__b=function(t){ce=null,Oo&&Oo(t)},ge.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),jo&&jo(t,e)},ge.__r=function(t){No&&No(t),Tt=0;var e=(ce=t.__c).__H;e&&(ms===ce?(e.__h=[],ce.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(gi),e.__h.forEach(ys),e.__h=[],Tt=0)),ms=ce},ge.diffed=function(t){Fo&&Fo(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Do.push(e)!==1&&Mo===ge.requestAnimationFrame||((Mo=ge.requestAnimationFrame)||dh)(ch)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),ms=ce=null},ge.__c=function(t,e){e.some(function(n){try{n.__h.forEach(gi),n.__h=n.__h.filter(function(i){return!i.__||ys(i)})}catch(i){e.some(function(s){s.__h&&(s.__h=[])}),e=[],ge.__e(i,n.__v)}}),Vo&&Vo(t,e)},ge.unmount=function(t){Bo&&Bo(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(i){try{gi(i)}catch(s){e=s}}),n.__H=void 0,e&&ge.__e(e,n.__v))};var Ho=typeof requestAnimationFrame=="function";function dh(t){var e,n=function(){clearTimeout(i),Ho&&cancelAnimationFrame(e),setTimeout(t)},i=setTimeout(n,35);Ho&&(e=requestAnimationFrame(n))}function gi(t){var e=ce,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),ce=e}function ys(t){var e=ce;t.__c=t.__(),ce=e}function _s(t,e){return!t||t.length!==e.length||e.some(function(n,i){return n!==t[i]})}function Go(t,e){return typeof e=="function"?e(t):e}const Rn={},Wo=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,zo=t=>"init"in t,bs=t=>!!t.write,qo=t=>"v"in t||"e"in t,mi=t=>{if("e"in t)throw t.e;if((Rn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},vi=new WeakMap,Ko=t=>{var e;return yi(t)&&!!((e=vi.get(t))!=null&&e[0])},uh=t=>{const e=vi.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(n=>n()))},Xo=(t,e)=>{let n=vi.get(t);if(!n){n=[!0,new Set],vi.set(t,n);const i=()=>{n[0]=!1};t.then(i,i)}n[1].add(e)},yi=t=>typeof(t==null?void 0:t.then)=="function",Yo=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},ws=(t,e,n)=>{const i=n(t),s="v"in i,o=i.v;if(yi(e))for(const r of i.d.keys())Yo(t,e,n(r));i.v=e,delete i.e,(!s||!Object.is(o,i.v))&&(++i.n,yi(o)&&uh(o))},Jo=(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},hh=()=>{const t=new Set,e=()=>{t.forEach(n=>n())};return e.add=n=>(t.add(n),()=>{t.delete(n)}),e},Ss=()=>{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},fh=t=>(t.c||(t.c=Ss()),t.m||(t.m=Ss()),t.u||(t.u=Ss()),t.f||(t.f=hh()),t),ph=Symbol(),Zo=(t=new WeakMap,e=new WeakMap,n=new WeakMap,i=new Set,s=new Set,o=new Set,r={},a=(f,...m)=>f.read(...m),l=(f,...m)=>f.write(...m),c=(f,m)=>{var _;return(_=f.unstable_onInit)==null?void 0:_.call(f,m)},d=(f,m)=>{var _;return(_=f.onMount)==null?void 0:_.call(f,m)},...u)=>{const f=u[0]||(S=>{if((Rn?"production":void 0)!=="production"&&!S)throw new Error("Atom is undefined or null");let x=t.get(S);return x||(x={d:new Map,p:new Set,n:0},t.set(S,x),c==null||c(S,D)),x}),m=u[1]||(()=>{const S=[],x=p=>{try{p()}catch(g){S.push(g)}};do{r.f&&x(r.f);const p=new Set,g=p.add.bind(p);i.forEach(h=>{var b;return(b=e.get(h))==null?void 0:b.l.forEach(g)}),i.clear(),o.forEach(g),o.clear(),s.forEach(g),s.clear(),p.forEach(x),i.size&&_()}while(i.size||o.size||s.size);if(S.length)throw new AggregateError(S)}),_=u[2]||(()=>{const S=[],x=new WeakSet,p=new WeakSet,g=Array.from(i);for(;g.length;){const h=g[g.length-1],b=f(h);if(p.has(h)){g.pop();continue}if(x.has(h)){if(n.get(h)===b.n)S.push([h,b]);else if((Rn?"production":void 0)!=="production"&&n.has(h))throw new Error("[Bug] invalidated atom exists");p.add(h),g.pop();continue}x.add(h);for(const I of Jo(h,b,e))x.has(I)||g.push(I)}for(let h=S.length-1;h>=0;--h){const[b,I]=S[h];let P=!1;for(const L of I.d.keys())if(L!==b&&i.has(L)){P=!0;break}P&&(v(b),C(b)),n.delete(b)}}),v=u[3]||(S=>{var x;const p=f(S);if(qo(p)&&(e.has(S)&&n.get(S)!==p.n||Array.from(p.d).every(([M,N])=>v(M).n===N)))return p;p.d.clear();let g=!0;const h=()=>{e.has(S)&&(C(S),_(),m())},b=M=>{var N;if(Wo(S,M)){const j=f(M);if(!qo(j))if(zo(M))ws(M,M.init,f);else throw new Error("no atom init");return mi(j)}const W=v(M);try{return mi(W)}finally{p.d.set(M,W.n),Ko(p.v)&&Yo(S,p.v,W),(N=e.get(M))==null||N.t.add(S),g||h()}};let I,P;const L={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Rn?"production":void 0)!=="production"&&!bs(S)&&console.warn("setSelf function cannot be used with read-only atom"),!P&&bs(S)&&(P=(...M)=>{if((Rn?"production":void 0)!=="production"&&g&&console.warn("setSelf function cannot be called in sync"),!g)try{return y(S,...M)}finally{_(),m()}}),P}},O=p.n;try{const M=a(S,b,L);return ws(S,M,f),yi(M)&&(Xo(M,()=>I==null?void 0:I.abort()),M.then(h,h)),p}catch(M){return delete p.v,p.e=M,++p.n,p}finally{g=!1,O!==p.n&&n.get(S)===O&&(n.set(S,p.n),i.add(S),(x=r.c)==null||x.call(r,S))}}),w=u[4]||(S=>{const x=[S];for(;x.length;){const p=x.pop(),g=f(p);for(const h of Jo(p,g,e)){const b=f(h);n.set(h,b.n),x.push(h)}}}),y=u[5]||((S,...x)=>{let p=!0;const g=b=>mi(v(b)),h=(b,...I)=>{var P;const L=f(b);try{if(Wo(S,b)){if(!zo(b))throw new Error("atom not writable");const O=L.n,M=I[0];ws(b,M,f),C(b),O!==L.n&&(i.add(b),(P=r.c)==null||P.call(r,b),w(b));return}else return y(b,...I)}finally{p||(_(),m())}};try{return l(S,g,h,...x)}finally{p=!1}}),C=u[6]||(S=>{var x;const p=f(S),g=e.get(S);if(g&&!Ko(p.v)){for(const[h,b]of p.d)if(!g.d.has(h)){const I=f(h);k(h).t.add(S),g.d.add(h),b!==I.n&&(i.add(h),(x=r.c)==null||x.call(r,h),w(h))}for(const h of g.d||[])if(!p.d.has(h)){g.d.delete(h);const b=T(h);b==null||b.t.delete(S)}}}),k=u[7]||(S=>{var x;const p=f(S);let g=e.get(S);if(!g){v(S);for(const h of p.d.keys())k(h).t.add(S);if(g={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(S,g),(x=r.m)==null||x.call(r,S),bs(S)){const h=()=>{let b=!0;const I=(...P)=>{try{return y(S,...P)}finally{b||(_(),m())}};try{const P=d(S,I);P&&(g.u=()=>{b=!0;try{P()}finally{b=!1}})}finally{b=!1}};s.add(h)}}return g}),T=u[8]||(S=>{var x;const p=f(S);let g=e.get(S);if(g&&!g.l.size&&!Array.from(g.t).some(h=>{var b;return(b=e.get(h))==null?void 0:b.d.has(S)})){g.u&&o.add(g.u),g=void 0,e.delete(S),(x=r.u)==null||x.call(r,S);for(const h of p.d.keys()){const b=T(h);b==null||b.t.delete(S)}return}return g}),E=[t,e,n,i,s,o,r,a,l,c,d,f,m,_,v,w,y,C,k,T],D={get:S=>mi(v(S)),set:(S,...x)=>{try{return y(S,...x)}finally{_(),m()}},sub:(S,x)=>{const g=k(S).l;return g.add(x),m(),()=>{g.delete(x),T(S),m()}}};return Object.defineProperty(D,ph,{value:E}),D},gh=fh,Qo=Xo,Cs={};let mh=0;function _i(t,e){const n=`atom${++mh}`,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=vh,i.write=yh),i}function vh(t){return t(this)}function yh(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}const _h=()=>{let t=0;const e=gh({}),n=new WeakMap,i=new WeakMap,s=Zo(n,i,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...d)=>t?c(a,...d):a.write(l,c,...d)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=n.get(a);l.m=i.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=n.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),n),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,d)=>{++t;try{for(const[u,f]of a)"init"in u&&d(u,f)}finally{--t}}};s.set(l)}})};function bh(){return(Cs?"production":void 0)!=="production"?_h():Zo()}let Ln;function wh(){return Ln||(Ln=bh(),(Cs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Ln),globalThis.__JOTAI_DEFAULT_STORE__!==Ln&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Ln}function ea(t,e){for(var n in e)t[n]=e[n];return t}function ta(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 na=$o;function ia(t,e){this.props=t,this.context=e}(ia.prototype=new et).isPureReactComponent=!0,ia.prototype.shouldComponentUpdate=function(t,e){return ta(this.props,t)||ta(this.state,e)};var sa=G.__b;G.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),sa&&sa(t)};var Sh=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Ch(t){function e(n){var i=ea({},n);return delete i.ref,t(i,n.ref||null)}return e.$$typeof=Sh,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var ra=function(t,e){return t==null?null:ot(ot(t).map(e))},xh={map:ra,forEach:ra,count:function(t){return t?ot(t).length:0},only:function(t){var e=ot(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ot},kh=G.__e;G.__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)}kh(t,e,n,i)};var oa=G.unmount;function aa(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=ea({},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 aa(i,e,n)})),t}function la(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(i){return la(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 xs(){this.__u=0,this.o=null,this.__b=null}function ca(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function bi(){this.i=null,this.l=null}G.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),oa&&oa(t)},(xs.prototype=new et).__c=function(t,e){var n=e.__c,i=this;i.o==null&&(i.o=[]),i.o.push(n);var s=ca(i.__v),o=!1,r=function(){o||(o=!0,n.__R=null,s?s(a):a())};n.__R=r;var a=function(){if(!--i.__u){if(i.state.__a){var l=i.state.__a;i.__v.__k[0]=la(l,l.__c.__P,l.__c.__O)}var c;for(i.setState({__a:i.__b=null});c=i.o.pop();)c.forceUpdate()}};i.__u++||32&e.__u||i.setState({__a:i.__b=i.__v.__k[0]}),t.then(r,r)},xs.prototype.componentWillUnmount=function(){this.o=[]},xs.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]=aa(this.__b,n,i.__O=i.__P)}this.__b=null}var s=e.__a&&We(rt,null,t.fallback);return s&&(s.__u&=-33),[We(rt,null,e.__a?null:t.children),s]};var da=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]}};(bi.prototype=new et).__a=function(t){var e=this,n=ca(e.__v),i=e.l.get(t);return i[0]++,function(s){var o=function(){e.props.revealOrder?(i.push(s),da(e,t,i)):s()};n?n(o):o()}},bi.prototype.render=function(t){this.i=null,this.l=new Map;var e=ot(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},bi.prototype.componentDidUpdate=bi.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){da(t,n,e)})};var ua=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Th=/^(?: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]/,Ah=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Eh=/[A-Z0-9]/g,Ih=typeof document<"u",Rh=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};et.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(et.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var ha=G.event;function Lh(){}function Ph(){return this.cancelBubble}function Mh(){return this.defaultPrevented}G.event=function(t){return ha&&(t=ha(t)),t.persist=Lh,t.isPropagationStopped=Ph,t.isDefaultPrevented=Mh,t.nativeEvent=t};var Dh={enumerable:!1,configurable:!0,get:function(){return this.class}},fa=G.vnode;G.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||Ih&&r==="children"&&i==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in n&&n.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||i!=="input"&&i!=="textarea"||Rh(n.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Ah.test(r)&&(r=l):l=r="oninput":o&&Th.test(r)?r=r.replace(Eh,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}i=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),i=="select"&&s.defaultValue!=null&&(s.value=ot(n.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),n.class&&!n.className?(s.class=n.class,Object.defineProperty(s,"className",Dh)):(n.className&&!n.class||n.class&&n.className)&&(s.class=s.className=n.className),e.props=s}(t),t.$$typeof=ua,fa&&fa(t)};var pa=G.__r;G.__r=function(t){pa&&pa(t),t.__c};var ga=G.diffed;G.diffed=function(t){ga&&ga(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 ma(t){return!!t&&t.$$typeof===ua}function Oh(t){return ma(t)?ps.apply(null,arguments):t}var va={};const Nh={},Fh=vt(void 0);function ya(t){return Te(Fh)||wh()}const ks=t=>typeof(t==null?void 0:t.then)=="function",Ts=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Vh=va.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ts(t),t)}),As=new WeakMap,_a=(t,e)=>{let n=As.get(t);return n||(n=new Promise((i,s)=>{let o=t;const r=c=>d=>{o===c&&i(d)},a=c=>d=>{o===c&&s(d)},l=()=>{try{const c=e();ks(c)?(As.set(c,n),o=c,c.then(r(c),a(c)),Qo(c,l)):i(c)}catch(c){s(c)}};t.then(r(t),a(t)),Qo(t,l)}),As.set(t,n)),n};function Es(t,e){const{delay:n,unstable_promiseStatus:i=!va.use}={},s=ya(),[[o,r,a],l]=Uo(d=>{const u=s.get(t);return Object.is(d[0],u)&&d[1]===s&&d[2]===t?d:[u,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),ke(()=>{const d=s.sub(t,()=>{if(i)try{const u=s.get(t);ks(u)&&Ts(_a(u,()=>s.get(t)))}catch{}if(typeof n=="number"){setTimeout(l,n);return}l()});return l(),d},[s,t,n,i]),lh(c),ks(c)){const d=_a(c,()=>s.get(t));return i&&Ts(d),Vh(d)}return c}function wi(t,e){const n=ya();return yt((...s)=>{if((Nh?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...s)},[n,t])}function ba(t,e){return[Es(t),wi(t)]}const Is=vt({});function Si(t){const e=me(null);return e.current===null&&(e.current=t()),e.current}const Rs=typeof window<"u",wa=Rs?$o:ke,Ci=vt(null);function Ls(t,e){t.indexOf(e)===-1&&t.push(e)}function Ps(t,e){const n=t.indexOf(e);n>-1&&t.splice(n,1)}const _t=(t,e,n)=>n>e?e:n<t?t:n;let Ms=()=>{};const bt={},Sa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Ca(t){return typeof t=="object"&&t!==null}const xa=t=>/^0[^.\s]+$/u.test(t);function Ds(t){let e;return()=>(e===void 0&&(e=t()),e)}const qe=t=>t,Bh=(t,e)=>n=>e(t(n)),Pn=(...t)=>t.reduce(Bh),Mn=(t,e,n)=>{const i=e-t;return i===0?1:(n-t)/i};class Os{constructor(){this.subscriptions=[]}add(e){return Ls(this.subscriptions,e),()=>Ps(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 at=t=>t*1e3,lt=t=>t/1e3;function ka(t,e){return e?t*(1e3/e):0}const Ta=(t,e,n)=>(((1-3*n+3*e)*t+(3*n-6*e))*t+3*e)*t,jh=1e-7,Uh=12;function $h(t,e,n,i,s){let o,r,a=0;do r=e+(n-e)/2,o=Ta(r,i,s)-t,o>0?n=r:e=r;while(Math.abs(o)>jh&&++a<Uh);return r}function Dn(t,e,n,i){if(t===e&&n===i)return qe;const s=o=>$h(o,0,1,t,n);return o=>o===0||o===1?o:Ta(s(o),e,i)}const Aa=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Ea=t=>e=>1-t(1-e),Ia=Dn(.33,1.53,.69,.99),Ns=Ea(Ia),Ra=Aa(Ns),La=t=>(t*=2)<1?.5*Ns(t):.5*(2-Math.pow(2,-10*(t-1))),Fs=t=>1-Math.sin(Math.acos(t)),Pa=Ea(Fs),Ma=Aa(Fs),Hh=Dn(.42,0,1,1),Gh=Dn(0,0,.58,1),Da=Dn(.42,0,.58,1),Wh=t=>Array.isArray(t)&&typeof t[0]!="number",Oa=t=>Array.isArray(t)&&typeof t[0]=="number",zh={linear:qe,easeIn:Hh,easeInOut:Da,easeOut:Gh,circIn:Fs,circInOut:Ma,circOut:Pa,backIn:Ns,backInOut:Ra,backOut:Ia,anticipate:La},qh=t=>typeof t=="string",Na=t=>{if(Oa(t)){Ms(t.length===4);const[e,n,i,s]=t;return Dn(e,n,i,s)}else if(qh(t))return zh[t];return t},xi=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Fa={value:null};function Kh(t,e){let n=new Set,i=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(u){r.has(u)&&(d.schedule(u),t()),l++,u(a)}const d={schedule:(u,f=!1,m=!1)=>{const v=m&&s?n:i;return f&&r.add(u),v.has(u)||v.add(u),u},cancel:u=>{i.delete(u),r.delete(u)},process:u=>{if(a=u,s){o=!0;return}s=!0,[n,i]=[i,n],n.forEach(c),e&&Fa.value&&Fa.value.frameloop[e].push(l),l=0,n.clear(),s=!1,o&&(o=!1,d.process(u))}};return d}const Xh=40;function Va(t,e){let n=!1,i=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>n=!0,r=xi.reduce((k,T)=>(k[T]=Kh(o,e?T:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:d,update:u,preRender:f,render:m,postRender:_}=r,v=()=>{const k=bt.useManualTiming?s.timestamp:performance.now();n=!1,bt.useManualTiming||(s.delta=i?1e3/60:Math.max(Math.min(k-s.timestamp,Xh),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),d.process(s),u.process(s),f.process(s),m.process(s),_.process(s),s.isProcessing=!1,n&&e&&(i=!1,t(v))},w=()=>{n=!0,i=!0,s.isProcessing||t(v)};return{schedule:xi.reduce((k,T)=>{const E=r[T];return k[T]=(D,S=!1,x=!1)=>(n||w(),E.schedule(D,S,x)),k},{}),cancel:k=>{for(let T=0;T<xi.length;T++)r[xi[T]].cancel(k)},state:s,steps:r}}const{schedule:ue,cancel:At,state:Ee,steps:Vs}=Va(typeof requestAnimationFrame<"u"?requestAnimationFrame:qe,!0);let ki;function Yh(){ki=void 0}const Be={now:()=>(ki===void 0&&Be.set(Ee.isProcessing||bt.useManualTiming?Ee.timestamp:performance.now()),ki),set:t=>{ki=t,queueMicrotask(Yh)}},Ba=t=>e=>typeof e=="string"&&e.startsWith(t),Bs=Ba("--"),Jh=Ba("var(--"),js=t=>Jh(t)?Zh.test(t.split("/*")[0].trim()):!1,Zh=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,rn={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},On={...rn,transform:t=>_t(0,1,t)},Ti={...rn,default:1},Nn=t=>Math.round(t*1e5)/1e5,Us=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Qh(t){return t==null}const ef=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,$s=(t,e)=>n=>!!(typeof n=="string"&&ef.test(n)&&n.startsWith(t)||e&&!Qh(n)&&Object.prototype.hasOwnProperty.call(n,e)),ja=(t,e,n)=>i=>{if(typeof i!="string")return i;const[s,o,r,a]=i.match(Us);return{[t]:parseFloat(s),[e]:parseFloat(o),[n]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},tf=t=>_t(0,255,t),Hs={...rn,transform:t=>Math.round(tf(t))},Ut={test:$s("rgb","red"),parse:ja("red","green","blue"),transform:({red:t,green:e,blue:n,alpha:i=1})=>"rgba("+Hs.transform(t)+", "+Hs.transform(e)+", "+Hs.transform(n)+", "+Nn(On.transform(i))+")"};function nf(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 Gs={test:$s("#"),parse:nf,transform:Ut.transform},Fn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Et=Fn("deg"),ct=Fn("%"),z=Fn("px"),sf=Fn("vh"),rf=Fn("vw"),Ua={...ct,parse:t=>ct.parse(t)/100,transform:t=>ct.transform(t*100)},on={test:$s("hsl","hue"),parse:ja("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:n,alpha:i=1})=>"hsla("+Math.round(t)+", "+ct.transform(Nn(e))+", "+ct.transform(Nn(n))+", "+Nn(On.transform(i))+")"},we={test:t=>Ut.test(t)||Gs.test(t)||on.test(t),parse:t=>Ut.test(t)?Ut.parse(t):on.test(t)?on.parse(t):Gs.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Ut.transform(t):on.transform(t),getAnimatableNone:t=>{const e=we.parse(t);return e.alpha=0,we.transform(e)}},of=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function af(t){var e,n;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Us))==null?void 0:e.length)||0)+(((n=t.match(of))==null?void 0:n.length)||0)>0}const $a="number",Ha="color",lf="var",cf="var(",Ga="${}",df=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Vn(t){const e=t.toString(),n=[],i={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(df,l=>(we.test(l)?(i.color.push(o),s.push(Ha),n.push(we.parse(l))):l.startsWith(cf)?(i.var.push(o),s.push(lf),n.push(l)):(i.number.push(o),s.push($a),n.push(parseFloat(l))),++o,Ga)).split(Ga);return{values:n,split:a,indexes:i,types:s}}function Wa(t){return Vn(t).values}function za(t){const{split:e,types:n}=Vn(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===$a?o+=Nn(s[r]):a===Ha?o+=we.transform(s[r]):o+=s[r]}return o}}const uf=t=>typeof t=="number"?0:we.test(t)?we.getAnimatableNone(t):t;function hf(t){const e=Wa(t);return za(t)(e.map(uf))}const It={test:af,parse:Wa,createTransformer:za,getAnimatableNone:hf};function Ws(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 ff({hue:t,saturation:e,lightness:n,alpha:i}){t/=360,e/=100,n/=100;let s=0,o=0,r=0;if(!e)s=o=r=n;else{const a=n<.5?n*(1+e):n+e-n*e,l=2*n-a;s=Ws(l,a,t+1/3),o=Ws(l,a,t),r=Ws(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:i}}function Ai(t,e){return n=>n>0?e:t}const ve=(t,e,n)=>t+(e-t)*n,zs=(t,e,n)=>{const i=t*t,s=n*(e*e-i)+i;return s<0?0:Math.sqrt(s)},pf=[Gs,Ut,on],gf=t=>pf.find(e=>e.test(t));function qa(t){const e=gf(t);if(!e)return!1;let n=e.parse(t);return e===on&&(n=ff(n)),n}const Ka=(t,e)=>{const n=qa(t),i=qa(e);if(!n||!i)return Ai(t,e);const s={...n};return o=>(s.red=zs(n.red,i.red,o),s.green=zs(n.green,i.green,o),s.blue=zs(n.blue,i.blue,o),s.alpha=ve(n.alpha,i.alpha,o),Ut.transform(s))},qs=new Set(["none","hidden"]);function mf(t,e){return qs.has(t)?n=>n<=0?t:e:n=>n>=1?e:t}function vf(t,e){return n=>ve(t,e,n)}function Ks(t){return typeof t=="number"?vf:typeof t=="string"?js(t)?Ai:we.test(t)?Ka:bf:Array.isArray(t)?Xa:typeof t=="object"?we.test(t)?Ka:yf:Ai}function Xa(t,e){const n=[...t],i=n.length,s=t.map((o,r)=>Ks(o)(o,e[r]));return o=>{for(let r=0;r<i;r++)n[r]=s[r](o);return n}}function yf(t,e){const n={...t,...e},i={};for(const s in n)t[s]!==void 0&&e[s]!==void 0&&(i[s]=Ks(t[s])(t[s],e[s]));return s=>{for(const o in i)n[o]=i[o](s);return n}}function _f(t,e){const n=[],i={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][i[o]],a=t.values[r]??0;n[s]=a,i[o]++}return n}const bf=(t,e)=>{const n=It.createTransformer(e),i=Vn(t),s=Vn(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?qs.has(t)&&!s.values.length||qs.has(e)&&!i.values.length?mf(t,e):Pn(Xa(_f(i,s),s.values),n):Ai(t,e)};function Ya(t,e,n){return typeof t=="number"&&typeof e=="number"&&typeof n=="number"?ve(t,e,n):Ks(t)(t,e)}const wf=t=>{const e=({timestamp:n})=>t(n);return{start:(n=!0)=>ue.update(e,n),stop:()=>At(e),now:()=>Ee.isProcessing?Ee.timestamp:Be.now()}},Ja=(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)})`},Ei=2e4;function Xs(t){let e=0;const n=50;let i=t.next(e);for(;!i.done&&e<Ei;)e+=n,i=t.next(e);return e>=Ei?1/0:e}function Sf(t,e=100,n){const i=n({...t,keyframes:[0,e]}),s=Math.min(Xs(i),Ei);return{type:"keyframes",ease:o=>i.next(s*o).value/e,duration:lt(s)}}const Cf=5;function Za(t,e,n){const i=Math.max(e-Cf,0);return ka(n-t(i),e-i)}const ye={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},Ys=.001;function xf({duration:t=ye.duration,bounce:e=ye.bounce,velocity:n=ye.velocity,mass:i=ye.mass}){let s,o,r=1-e;r=_t(ye.minDamping,ye.maxDamping,r),t=_t(ye.minDuration,ye.maxDuration,lt(t)),r<1?(s=c=>{const d=c*r,u=d*t,f=d-n,m=Js(c,r),_=Math.exp(-u);return Ys-f/m*_},o=c=>{const u=c*r*t,f=u*n+n,m=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-u),v=Js(Math.pow(c,2),r);return(-s(c)+Ys>0?-1:1)*((f-m)*_)/v}):(s=c=>{const d=Math.exp(-c*t),u=(c-n)*t+1;return-Ys+d*u},o=c=>{const d=Math.exp(-c*t),u=(n-c)*(t*t);return d*u});const a=5/t,l=Tf(s,o,a);if(t=at(t),isNaN(l))return{stiffness:ye.stiffness,damping:ye.damping,duration:t};{const c=Math.pow(l,2)*i;return{stiffness:c,damping:r*2*Math.sqrt(i*c),duration:t}}}const kf=12;function Tf(t,e,n){let i=n;for(let s=1;s<kf;s++)i=i-t(i)/e(i);return i}function Js(t,e){return t*Math.sqrt(1-e*e)}const Af=["duration","bounce"],Ef=["stiffness","damping","mass"];function Qa(t,e){return e.some(n=>t[n]!==void 0)}function If(t){let e={velocity:ye.velocity,stiffness:ye.stiffness,damping:ye.damping,mass:ye.mass,isResolvedFromDuration:!1,...t};if(!Qa(t,Ef)&&Qa(t,Af))if(t.visualDuration){const n=t.visualDuration,i=2*Math.PI/(n*1.2),s=i*i,o=2*_t(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:ye.mass,stiffness:s,damping:o}}else{const n=xf(t);e={...e,...n,mass:ye.mass},e.isResolvedFromDuration=!0}return e}function Ii(t=ye.visualDuration,e=ye.bounce){const n=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:i,restDelta:s}=n;const o=n.keyframes[0],r=n.keyframes[n.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:d,duration:u,velocity:f,isResolvedFromDuration:m}=If({...n,velocity:-lt(n.velocity||0)}),_=f||0,v=c/(2*Math.sqrt(l*d)),w=r-o,y=lt(Math.sqrt(l/d)),C=Math.abs(w)<5;i||(i=C?ye.restSpeed.granular:ye.restSpeed.default),s||(s=C?ye.restDelta.granular:ye.restDelta.default);let k;if(v<1){const E=Js(y,v);k=D=>{const S=Math.exp(-v*y*D);return r-S*((_+v*y*w)/E*Math.sin(E*D)+w*Math.cos(E*D))}}else if(v===1)k=E=>r-Math.exp(-y*E)*(w+(_+y*w)*E);else{const E=y*Math.sqrt(v*v-1);k=D=>{const S=Math.exp(-v*y*D),x=Math.min(E*D,300);return r-S*((_+v*y*w)*Math.sinh(x)+E*w*Math.cosh(x))/E}}const T={calculatedDuration:m&&u||null,next:E=>{const D=k(E);if(m)a.done=E>=u;else{let S=E===0?_:0;v<1&&(S=E===0?at(_):Za(k,E,D));const x=Math.abs(S)<=i,p=Math.abs(r-D)<=s;a.done=x&&p}return a.value=a.done?r:D,a},toString:()=>{const E=Math.min(Xs(T),Ei),D=Ja(S=>T.next(E*S).value,E,30);return E+"ms "+D},toTransition:()=>{}};return T}Ii.applyToOptions=t=>{const e=Sf(t,100,Ii);return t.ease=e.ease,t.duration=at(e.duration),t.type="keyframes",t};function Zs({keyframes:t,velocity:e=0,power:n=.8,timeConstant:i=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:d}){const u=t[0],f={done:!1,value:u},m=x=>a!==void 0&&x<a||l!==void 0&&x>l,_=x=>a===void 0?l:l===void 0||Math.abs(a-x)<Math.abs(l-x)?a:l;let v=n*e;const w=u+v,y=r===void 0?w:r(w);y!==w&&(v=y-u);const C=x=>-v*Math.exp(-x/i),k=x=>y+C(x),T=x=>{const p=C(x),g=k(x);f.done=Math.abs(p)<=c,f.value=f.done?y:g};let E,D;const S=x=>{m(f.value)&&(E=x,D=Ii({keyframes:[f.value,_(f.value)],velocity:Za(k,x,f.value),damping:s,stiffness:o,restDelta:c,restSpeed:d}))};return S(0),{calculatedDuration:null,next:x=>{let p=!1;return!D&&E===void 0&&(p=!0,T(x),S(x)),E!==void 0&&x>=E?D.next(x-E):(!p&&T(x),f)}}}function Rf(t,e,n){const i=[],s=n||bt.mix||Ya,o=t.length-1;for(let r=0;r<o;r++){let a=s(t[r],t[r+1]);if(e){const l=Array.isArray(e)?e[r]||qe:e;a=Pn(l,a)}i.push(a)}return i}function Lf(t,e,{clamp:n=!0,ease:i,mixer:s}={}){const o=t.length;if(Ms(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=Rf(e,i,s),l=a.length,c=d=>{if(r&&d<t[0])return e[0];let u=0;if(l>1)for(;u<t.length-2&&!(d<t[u+1]);u++);const f=Mn(t[u],t[u+1],d);return a[u](f)};return n?d=>c(_t(t[0],t[o-1],d)):c}function Pf(t,e){const n=t[t.length-1];for(let i=1;i<=e;i++){const s=Mn(0,e,i);t.push(ve(n,1,s))}}function Mf(t){const e=[0];return Pf(e,t.length-1),e}function Df(t,e){return t.map(n=>n*e)}function Of(t,e){return t.map(()=>e||Da).splice(0,t.length-1)}function Bn({duration:t=300,keyframes:e,times:n,ease:i="easeInOut"}){const s=Wh(i)?i.map(Na):Na(i),o={done:!1,value:e[0]},r=Df(n&&n.length===e.length?n:Mf(e),t),a=Lf(r,e,{ease:Array.isArray(s)?s:Of(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Nf=t=>t!==null;function Qs(t,{repeat:e,repeatType:n="loop"},i,s=1){const o=t.filter(Nf),a=s<0||e&&n!=="loop"&&e%2===1?0:o.length-1;return!a||i===void 0?o[a]:i}const Ff={decay:Zs,inertia:Zs,tween:Bn,keyframes:Bn,spring:Ii};function el(t){typeof t.type=="string"&&(t.type=Ff[t.type])}class er{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 Vf=t=>t/100;class tr extends er{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!==Be.now()&&this.tick(Be.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;el(e);const{type:n=Bn,repeat:i=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=n||Bn;l!==Bn&&typeof a[0]!="number"&&(this.mixKeyframes=Pn(Vf,Ya(a[0],a[1])),a=[0,100]);const c=l({...e,keyframes:a});o==="mirror"&&(this.mirroredGenerator=l({...e,keyframes:[...a].reverse(),velocity:-r})),c.calculatedDuration===null&&(c.calculatedDuration=Xs(c));const{calculatedDuration:d}=c;this.calculatedDuration=d,this.resolvedDuration=d+s,this.totalDuration=this.resolvedDuration*(i+1)-s,this.generator=c}updateTime(e){const n=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(e,n=!1){const{generator:i,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return i.next(0);const{delay:c=0,keyframes:d,repeat:u,repeatType:f,repeatDelay:m,type:_,onUpdate:v,finalKeyframe:w}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),n?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,T=i;if(u){const x=Math.min(this.currentTime,s)/a;let p=Math.floor(x),g=x%1;!g&&x>=1&&(g=1),g===1&&p--,p=Math.min(p,u+1),!!(p%2)&&(f==="reverse"?(g=1-g,m&&(g-=m/a)):f==="mirror"&&(T=r)),k=_t(0,1,g)*a}const E=C?{done:!1,value:d[0]}:T.next(k);o&&(E.value=o(E.value));let{done:D}=E;!C&&l!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const S=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return S&&_!==Zs&&(E.value=Qs(d,this.options,w,this.speed)),v&&v(E.value),S&&this.finish(),E}then(e,n){return this.finished.then(e,n)}get duration(){return lt(this.calculatedDuration)}get time(){return lt(this.currentTime)}set time(e){var n;e=at(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(Be.now());const n=this.playbackSpeed!==e;this.playbackSpeed=e,n&&(this.time=lt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=wf,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(Be.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 Bf(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const $t=t=>t*180/Math.PI,nr=t=>{const e=$t(Math.atan2(t[1],t[0]));return ir(e)},jf={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:nr,rotateZ:nr,skewX:t=>$t(Math.atan(t[1])),skewY:t=>$t(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},ir=t=>(t=t%360,t<0&&(t+=360),t),tl=nr,nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),il=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:nl,scaleY:il,scale:t=>(nl(t)+il(t))/2,rotateX:t=>ir($t(Math.atan2(t[6],t[5]))),rotateY:t=>ir($t(Math.atan2(-t[2],t[0]))),rotateZ:tl,rotate:tl,skewX:t=>$t(Math.atan(t[4])),skewY:t=>$t(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function sr(t){return t.includes("scale")?1:0}function rr(t,e){if(!t||t==="none")return sr(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=jf,s=a}if(!s)return sr(e);const o=i[e],r=s[1].split(",").map(Hf);return typeof o=="function"?o(r):r[o]}const $f=(t,e)=>{const{transform:n="none"}=getComputedStyle(t);return rr(n,e)};function Hf(t){return parseFloat(t.trim())}const an=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],ln=new Set(an),sl=t=>t===rn||t===z,Gf=new Set(["x","y","z"]),Wf=an.filter(t=>!Gf.has(t));function zf(t){const e=[];return Wf.forEach(n=>{const i=t.getValue(n);i!==void 0&&(e.push([n,i.get()]),i.set(n.startsWith("scale")?1:0))}),e}const Ht={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})=>rr(e,"x"),y:(t,{transform:e})=>rr(e,"y")};Ht.translateX=Ht.x,Ht.translateY=Ht.y;const Gt=new Set;let or=!1,ar=!1,lr=!1;function rl(){if(ar){const t=Array.from(Gt).filter(i=>i.needsMeasurement),e=new Set(t.map(i=>i.element)),n=new Map;e.forEach(i=>{const s=zf(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)})}ar=!1,or=!1,Gt.forEach(t=>t.complete(lr)),Gt.clear()}function ol(){Gt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ar=!0)})}function qf(){lr=!0,ol(),rl(),lr=!1}class cr{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?(Gt.add(this),or||(or=!0,ue.read(ol),ue.resolveKeyframes(rl))):(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])}Bf(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Gt.delete(this)}cancel(){this.state==="scheduled"&&(Gt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Kf=t=>t.startsWith("--");function Xf(t,e,n){Kf(e)?t.style.setProperty(e,n):t.style[e]=n}const Yf=Ds(()=>window.ScrollTimeline!==void 0),Jf={};function Zf(t,e){const n=Ds(t);return()=>Jf[e]??n()}const al=Zf(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),jn=([t,e,n,i])=>`cubic-bezier(${t}, ${e}, ${n}, ${i})`,ll={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:jn([0,.65,.55,1]),circOut:jn([.55,0,1,.45]),backIn:jn([.31,.01,.66,-.59]),backOut:jn([.33,1.53,.69,.99])};function cl(t,e){if(t)return typeof t=="function"?al()?Ja(t,e):"ease-out":Oa(t)?jn(t):Array.isArray(t)?t.map(n=>cl(n,e)||ll.easeOut):ll[t]}function Qf(t,e,n,{delay:i=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const d={[e]:n};l&&(d.offset=l);const u=cl(a,s);Array.isArray(u)&&(d.easing=u);const f={delay:i,duration:s,easing:Array.isArray(u)?"linear":u,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(f.pseudoElement=c),t.animate(d,f)}function dl(t){return typeof t=="function"&&"applyToOptions"in t}function ep({type:t,...e}){return dl(t)&&al()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class tp extends er{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:n,name:i,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Ms(typeof e.type!="string");const c=ep(e);this.animation=Qf(n,i,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const d=Qs(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(d):Xf(n,i,d),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,n;(n=(e=this.animation).finish)==null||n.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,n;this.isPseudoElement||(n=(e=this.animation).commitStyles)==null||n.call(e)}get duration(){var n,i;const e=((i=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:i.call(n).duration)||0;return lt(Number(e))}get time(){return lt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=at(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&&Yf()?(this.animation.timeline=e,qe):n(this)}}const ul={anticipate:La,backInOut:Ra,circInOut:Ma};function np(t){return t in ul}function ip(t){typeof t.ease=="string"&&np(t.ease)&&(t.ease=ul[t.ease])}const hl=10;class sp extends tp{constructor(e){ip(e),el(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 tr({...r,autoplay:!1}),l=at(this.finishedTime??this.time);n.setWithVelocity(a.sample(l-hl).value,a.sample(l).value,hl),a.stop()}}const fl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(It.test(t)||t==="0")&&!t.startsWith("url("));function rp(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 op(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=fl(s,e),a=fl(o,e);return!r||!a?!1:rp(t)||(n==="spring"||dl(n))&&i}function dr(t){return Ca(t)&&"offsetHeight"in t}const ap=new Set(["opacity","clipPath","filter","transform"]),lp=Ds(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function cp(t){var c;const{motionValue:e,name:n,repeatDelay:i,repeatType:s,damping:o,type:r}=t;if(!dr((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return lp()&&n&&ap.has(n)&&(n!=="transform"||!l)&&!a&&!i&&s!=="mirror"&&o!==0&&r!=="inertia"}const dp=40;class up extends er{constructor({autoplay:e=!0,delay:n=0,type:i="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:d,...u}){var _;super(),this.stop=()=>{var v,w;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(w=this.keyframeResolver)==null||w.cancel()},this.createdAt=Be.now();const f={autoplay:e,delay:n,type:i,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:d,...u},m=(d==null?void 0:d.KeyframeResolver)||cr;this.keyframeResolver=new m(a,(v,w,y)=>this.onKeyframesResolved(v,w,f,!y),l,c,d),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,n,i,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:d}=i;this.resolvedAt=Be.now(),op(e,o,r,a)||((bt.instantAnimations||!l)&&(d==null||d(Qs(e,i,n))),e[0]=e[e.length-1],i.duration=0,i.repeat=0);const f={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>dp?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...i,keyframes:e},m=!c&&cp(f)?new sp({...f,element:f.motionValue.owner.current}):new tr(f);m.finished.then(()=>this.notifyFinished()).catch(qe),this.pendingTimeline&&(this.stopTimeline=m.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=m}get finished(){return this._animation?this.animation.finished:this._finished}then(e,n){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),qf()),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 hp=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function fp(t){const e=hp.exec(t);if(!e)return[,];const[,n,i,s]=e;return[`--${n??i}`,s]}function pl(t,e,n=1){const[i,s]=fp(t);if(!i)return;const o=window.getComputedStyle(e).getPropertyValue(i);if(o){const r=o.trim();return Sa(r)?parseFloat(r):r}return js(s)?pl(s,e,n+1):s}function ur(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const gl=new Set(["width","height","top","left","right","bottom",...an]),pp={test:t=>t==="auto",parse:t=>t},ml=t=>e=>e.test(t),vl=[rn,z,ct,Et,rf,sf,pp],yl=t=>vl.find(ml(t));function gp(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||xa(t):!0}const mp=new Set(["brightness","contrast","saturate","opacity"]);function vp(t){const[e,n]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[i]=n.match(Us)||[];if(!i)return t;const s=n.replace(i,"");let o=mp.has(e)?1:0;return i!==n&&(o*=100),e+"("+o+s+")"}const yp=/\b([a-z-]*)\(.*?\)/gu,hr={...It,getAnimatableNone:t=>{const e=t.match(yp);return e?e.map(vp).join(" "):t}},_l={...rn,transform:Math.round},fr={borderWidth:z,borderTopWidth:z,borderRightWidth:z,borderBottomWidth:z,borderLeftWidth:z,borderRadius:z,radius:z,borderTopLeftRadius:z,borderTopRightRadius:z,borderBottomRightRadius:z,borderBottomLeftRadius:z,width:z,maxWidth:z,height:z,maxHeight:z,top:z,right:z,bottom:z,left:z,padding:z,paddingTop:z,paddingRight:z,paddingBottom:z,paddingLeft:z,margin:z,marginTop:z,marginRight:z,marginBottom:z,marginLeft:z,backgroundPositionX:z,backgroundPositionY:z,...{rotate:Et,rotateX:Et,rotateY:Et,rotateZ:Et,scale:Ti,scaleX:Ti,scaleY:Ti,scaleZ:Ti,skew:Et,skewX:Et,skewY:Et,distance:z,translateX:z,translateY:z,translateZ:z,x:z,y:z,z,perspective:z,transformPerspective:z,opacity:On,originX:Ua,originY:Ua,originZ:z},zIndex:_l,fillOpacity:On,strokeOpacity:On,numOctaves:_l},_p={...fr,color:we,backgroundColor:we,outlineColor:we,fill:we,stroke:we,borderColor:we,borderTopColor:we,borderRightColor:we,borderBottomColor:we,borderLeftColor:we,filter:hr,WebkitFilter:hr},bl=t=>_p[t];function wl(t,e){let n=bl(t);return n!==hr&&(n=It),n.getAnimatableNone?n.getAnimatableNone(e):void 0}const bp=new Set(["auto","none","0"]);function wp(t,e,n){let i=0,s;for(;i<t.length&&!s;){const o=t[i];typeof o=="string"&&!bp.has(o)&&Vn(o).values.length&&(s=t[i]),i++}if(s&&n)for(const o of e)t[o]=wl(n,s)}class Sp extends cr{constructor(e,n,i,s,o){super(e,n,i,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:n,name:i}=this;if(!n||!n.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),js(c))){const d=pl(c,n.current);d!==void 0&&(e[l]=d),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!gl.has(i)||e.length!==2)return;const[s,o]=e,r=yl(s),a=yl(o);if(r!==a)if(sl(r)&&sl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Ht[i]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:n}=this,i=[];for(let s=0;s<e.length;s++)(e[s]===null||gp(e[s]))&&i.push(s);i.length&&wp(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=Ht[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]=Ht[n](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function Cp(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 Sl=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Cl=30,xp=t=>!isNaN(parseFloat(t));class kp{constructor(e,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(i,s=!0)=>{var r,a;const o=Be.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(i),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=n.owner}setCurrent(e){this.current=e,this.updatedAt=Be.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=xp(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 Os);const i=this.events[e].add(n);return e==="change"?()=>{i(),ue.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=Be.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Cl)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,Cl);return ka(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 cn(t,e){return new kp(t,e)}const{schedule:pr}=Va(queueMicrotask,!1),tt={x:!1,y:!1};function xl(){return tt.x||tt.y}function Tp(t){return t==="x"||t==="y"?tt[t]?null:(tt[t]=!0,()=>{tt[t]=!1}):tt.x||tt.y?null:(tt.x=tt.y=!0,()=>{tt.x=tt.y=!1})}function kl(t,e){const n=Cp(t),i=new AbortController,s={passive:!0,...e,signal:i.signal};return[n,s,()=>i.abort()]}function Tl(t){return!(t.pointerType==="touch"||xl())}function Ap(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{if(!Tl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const d=u=>{Tl(u)&&(c(u),l.removeEventListener("pointerleave",d))};l.addEventListener("pointerleave",d,s)};return i.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Al=(t,e)=>e?t===e?!0:Al(t,e.parentElement):!1,gr=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ep=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ip(t){return Ep.has(t.tagName)||t.tabIndex!==-1}const Ri=new WeakSet;function El(t){return e=>{e.key==="Enter"&&t(e)}}function mr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Rp=(t,e)=>{const n=t.currentTarget;if(!n)return;const i=El(()=>{if(Ri.has(n))return;mr(n,"down");const s=El(()=>{mr(n,"up")}),o=()=>mr(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 Il(t){return gr(t)&&!xl()}function Lp(t,e,n={}){const[i,s,o]=kl(t,n),r=a=>{const l=a.currentTarget;if(!Il(a))return;Ri.add(l);const c=e(l,a),d=(m,_)=>{window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",f),Ri.has(l)&&Ri.delete(l),Il(m)&&typeof c=="function"&&c(m,{success:_})},u=m=>{d(m,l===window||l===document||n.useGlobalTarget||Al(l,m.target))},f=m=>{d(m,!1)};window.addEventListener("pointerup",u,s),window.addEventListener("pointercancel",f,s)};return i.forEach(a=>{(n.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),dr(a)&&(a.addEventListener("focus",c=>Rp(c,s)),!Ip(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Rl(t){return Ca(t)&&"ownerSVGElement"in t}function Pp(t){return Rl(t)&&t.tagName==="svg"}const Pe=t=>!!(t&&t.getVelocity),Mp=[...vl,we,It],Dp=t=>Mp.find(ml(t)),Un=vt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Op extends et{getSnapshotBeforeUpdate(e){const n=this.props.childRef.current;if(n&&e.isPresent&&!this.props.isPresent){const i=n.offsetParent,s=dr(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 Np({children:t,isPresent:e,anchorX:n,root:i}){const s=vs(),o=me(null),r=me({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Te(Un);return na(()=>{const{width:l,height:c,top:d,left:u,right:f}=r.current;if(e||!o.current||!l||!c)return;const m=n==="left"?`left: ${u}`:`right: ${f}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=i??document.head;return v.appendChild(_),_.sheet&&_.sheet.insertRule(`
2
2
  [data-motion-pop-id="${s}"] {
3
3
  position: absolute !important;
4
4
  width: ${l}px !important;
@@ -6,34 +6,34 @@ var s0=Object.defineProperty;var r0=(Qe,G,Ft)=>G in Qe?s0(Qe,G,{enumerable:!0,co
6
6
  ${m}px !important;
7
7
  top: ${d}px !important;
8
8
  }
9
- `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),I(Dp,{isPresent:e,childRef:o,sizeRef:r,children:Dh(t,{ref:o})})}const Np=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=bi(Fp),d=gs();let u=!0,f=ze(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:m=>{c.set(m,!0);for(const _ of c.values())if(!_)return;i&&i()},register:m=>(c.set(m,!1),()=>c.delete(m))}),[n,c,i]);return o&&u&&(f={...f}),ze(()=>{c.forEach((m,_)=>c.set(_,!1))},[n]),xe(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=I(Op,{isPresent:n,anchorX:a,root:l,children:t})),I(wi.Provider,{value:f,children:t})};function Fp(){return new Map}function Ll(t=!0){const e=ke(wi);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=gs();xe(()=>{if(t)return s(o)},[t]);const r=yt(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Ii=t=>t.key||"";function Pl(t){const e=[];return Ch.forEach(t,n=>{ga(n)&&e.push(n)}),e}const Vp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,d]=Ll(r),u=ze(()=>Pl(t),[t]),f=r&&!c?[]:u.map(Ii),m=me(!0),_=me(u),v=bi(()=>new Map),[w,y]=Ce(u),[C,k]=Ce(u);wa(()=>{m.current=!1,_.current=u;for(let O=0;O<C.length;O++){const S=Ii(C[O]);f.includes(S)?v.delete(S):v.get(S)!==!0&&v.set(S,!1)}},[C,f.length,f.join("-")]);const E=[];if(u!==w){let O=[...u];for(let S=0;S<C.length;S++){const x=C[S],p=Ii(x);f.includes(p)||(O.splice(S,0,x),E.push(x))}return o==="wait"&&E.length&&(O=E),k(Pl(O)),y(u),null}const{forceRender:R}=ke(As);return I(rt,{children:C.map(O=>{const S=Ii(O),x=r&&!c?!1:u===C||f.includes(S),p=()=>{if(v.has(S))v.set(S,!0);else return;let g=!0;v.forEach(h=>{h||(g=!1)}),g&&(R==null||R(),k(_.current),r&&(d==null||d()),i&&i())};return I(Np,{isPresent:x,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:x?void 0:p,anchorX:a,children:O},S)})})},Ml=vt({strict:!1}),Dl={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"]},dn={};for(const t in Dl)dn[t]={isEnabled:e=>Dl[t].some(n=>!!e[n])};function Bp(t){for(const e in t)dn[e]={...dn[e],...t[e]}}const jp=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 Ri(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||jp.has(t)}let Ol=t=>!Ri(t);function Nl(t){typeof t=="function"&&(Ol=e=>e.startsWith("on")?!Ri(e):t(e))}try{Nl(require("@emotion/is-prop-valid").default)}catch{}function Up(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Ol(s)||n===!0&&Ri(s)||!e&&!Ri(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function $p({children:t,isValidProp:e,...n}){e&&Nl(e),n={...ke(Un),...n},n.isStatic=bi(()=>n.isStatic);const i=ze(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return I(Un.Provider,{value:i,children:t})}function Hp(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 Li=vt({});function Pi(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function $n(t){return typeof t=="string"||Array.isArray(t)}const mr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],vr=["initial",...mr];function Mi(t){return Pi(t.animate)||vr.some(e=>$n(t[e]))}function Fl(t){return!!(Mi(t)||t.variants)}function Gp(t,e){if(Mi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||$n(n)?n:void 0,animate:$n(i)?i:void 0}}return t.inherit!==!1?e:{}}function Wp(t){const{initial:e,animate:n}=Gp(t,ke(Li));return ze(()=>({initial:e,animate:n}),[Vl(e),Vl(n)])}function Vl(t){return Array.isArray(t)?t.join(" "):t}const zp=Symbol.for("motionComponentSymbol");function un(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function qp(t,e,n){return yt(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):un(n)&&(n.current=i))},[e])}const yr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bl="data-"+yr("framerAppearId"),jl=vt({});function Kp(t,e,n,i,s){var v,w;const{visualElement:o}=ke(Li),r=ke(Ml),a=ke(wi),l=ke(Un).reducedMotion,c=me(null);i=i||r.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,u=ke(jl);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&Xp(c.current,n,s,u);const f=me(!1);ta(()=>{d&&f.current&&d.update(n,a)});const m=n[Bl],_=me(!!m&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,m))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,m)));return wa(()=>{d&&(f.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),fr.render(d.render),_.current&&d.animationState&&d.animationState.animateChanges())}),xe(()=>{d&&(!_.current&&d.animationState&&d.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,m)}),_.current=!1))}),d}function Xp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Ul(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&un(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:d,layoutScroll:l,layoutRoot:c})}function Ul(t){if(t)return t.options.allowProjection!==!1?t.projection:Ul(t.parent)}function Yp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&Bp(t);function o(a,l){let c;const d={...ke(Un),...a,layoutId:Jp(a)},{isStatic:u}=d,f=Wp(a),m=i(a,u);if(!u&&Is){Zp();const _=Qp(d);c=_.MeasureLayout,f.visualElement=Kp(s,m,d,e,_.ProjectionNode)}return I(Li.Provider,{value:f,children:[c&&f.visualElement?I(c,{visualElement:f.visualElement,...d}):null,n(s,a,qp(m,f.visualElement,l),m,u,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Sh(o);return r[zp]=s,r}function Jp({layoutId:t}){const e=ke(As).id;return e&&t!==void 0?e+"-"+t:t}function Zp(t,e){ke(Ml).strict}function Qp(t){const{drag:e,layout:n}=dn;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 Hn={};function eg(t){for(const e in t)Hn[e]=t[e],Vs(e)&&(Hn[e].isCSSVariable=!0)}function $l(t,{layout:e,layoutId:n}){return ln.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Hn[t]||t==="opacity")}const tg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ng=an.length;function ig(t,e,n){let i="",s=!0;for(let o=0;o<ng;o++){const r=an[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Sl(a,hr[r]);if(!l){s=!1;const d=tg[r]||r;i+=`${d}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function _r(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(ln.has(l)){r=!0;continue}else if(Vs(l)){s[l]=c;continue}else{const d=Sl(c,hr[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(e.transform||(r||n?i.transform=ig(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;i.transformOrigin=`${l} ${c} ${d}`}}const br=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Hl(t,e,n){for(const i in e)!Pe(e[i])&&!$l(i,n)&&(t[i]=e[i])}function sg({transformTemplate:t},e){return ze(()=>{const n=br();return _r(n,e,t),Object.assign({},n.vars,n.style)},[e])}function rg(t,e){const n=t.style||{},i={};return Hl(i,n,t),Object.assign(i,sg(t,e)),i}function og(t,e){const n={},i=rg(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 ag={offset:"stroke-dashoffset",array:"stroke-dasharray"},lg={offset:"strokeDashoffset",array:"strokeDasharray"};function cg(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?ag:lg;t[o.offset]=z.transform(-i);const r=z.transform(e),a=z.transform(n);t[o.array]=`${r} ${a}`}function Gl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(_r(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:f}=t;u.transform&&(f.transform=u.transform,delete u.transform),(f.transform||u.transformOrigin)&&(f.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),f.transform&&(f.transformBox=(d==null?void 0:d.transformBox)??"fill-box",delete u.transformBox),e!==void 0&&(u.x=e),n!==void 0&&(u.y=n),i!==void 0&&(u.scale=i),s!==void 0&&cg(u,s,o,r,!1)}const Wl=()=>({...br(),attrs:{}}),zl=t=>typeof t=="string"&&t.toLowerCase()==="svg";function dg(t,e,n,i){const s=ze(()=>{const o=Wl();return Gl(o,e,zl(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Hl(o,t.style,t),s.style={...o,...s.style}}return s}const ug=["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 wr(t){return typeof t!="string"||t.includes("-")?!1:!!(ug.indexOf(t)>-1||/[A-Z]/u.test(t))}function hg(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(wr(n)?dg:og)(i,o,r,n),c=Up(i,typeof n=="string",t),d=n!==rt?{...c,...l,ref:s}:{},{children:u}=i,f=ze(()=>Pe(u)?u.get():u,[u]);return We(n,{...d,children:f})}}function ql(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Sr(t,e,n,i){if(typeof e=="function"){const[s,o]=ql(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]=ql(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function Di(t){return Pe(t)?t.get():t}function fg({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:pg(n,i,s,t),renderState:e()}}const Kl=t=>(e,n)=>{const i=ke(Li),s=ke(wi),o=()=>fg(t,e,i,s);return n?o():bi(o)};function pg(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=Di(o[f]);let{initial:r,animate:a}=t;const l=Mi(t),c=Fl(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let d=n?n.initial===!1:!1;d=d||r===!1;const u=d?a:r;if(u&&typeof u!="boolean"&&!Pi(u)){const f=Array.isArray(u)?u:[u];for(let m=0;m<f.length;m++){const _=Sr(t,f[m]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const C in y){let k=y[C];if(Array.isArray(k)){const E=d?k.length-1:0;k=k[E]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function Cr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Pe(i[r])||e.style&&Pe(e.style[r])||$l(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const gg={useVisualState:Kl({scrapeMotionValuesFromProps:Cr,createRenderState:br})};function Xl(t,e,n){const i=Cr(t,e,n);for(const s in t)if(Pe(t[s])||Pe(e[s])){const o=an.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const mg={useVisualState:Kl({scrapeMotionValuesFromProps:Xl,createRenderState:Wl})};function vg(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...wr(i)?mg:gg,preloadedFeatures:t,useRender:hg(s),createVisualElement:e,Component:i};return Yp(r)}}function Gn(t,e,n){const i=t.getProps();return Sr(i,e,n!==void 0?n:i.custom,t)}const xr=t=>Array.isArray(t);function yg(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,cn(n))}function _g(t){return xr(t)?t[t.length-1]||0:t}function bg(t,e){const n=Gn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=_g(o[r]);yg(t,r,a)}}function wg(t){return!!(Pe(t)&&t.add)}function kr(t,e){const n=t.getValue("willChange");if(wg(n))return n.add(e);if(!n&&bt.WillChange){const i=new bt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Yl(t){return t.props[Bl]}const Sg=t=>t!==null;function Cg(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Sg),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const xg={type:"spring",stiffness:500,damping:25,restSpeed:10},kg=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Tg={type:"keyframes",duration:.8},Eg={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ag=(t,{keyframes:e})=>e.length>2?Tg:ln.has(t)?t.startsWith("scale")?kg(e[1]):xg:Eg;function Ig({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Tr=(t,e,n,i={},s,o)=>r=>{const a=dr(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-at(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Ig(a)||Object.assign(d,Ag(t,d)),d.duration&&(d.duration=at(d.duration)),d.repeatDelay&&(d.repeatDelay=at(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let u=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(d.duration=0,d.delay===0&&(u=!0)),(bt.instantAnimations||bt.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const f=Cg(d.keyframes,a);if(f!==void 0){ue.update(()=>{d.onUpdate(f),d.onComplete()});return}}return a.isSync?new er(d):new dp(d)};function Rg({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function Jl(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const d in a){const u=t.getValue(d,t.latestValues[d]??null),f=a[d];if(f===void 0||c&&Rg(c,d))continue;const m={delay:n,...dr(o||{},d)},_=u.get();if(_!==void 0&&!u.isAnimating&&!Array.isArray(f)&&f===_&&!m.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Yl(t);if(y){const C=window.MotionHandoffAnimation(y,d,ue);C!==null&&(m.startTime=C,v=!0)}}kr(t,d),u.start(Tr(d,u,f,t.shouldReduceMotion&&gl.has(d)?{type:!1}:m,t,v));const w=u.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{ue.update(()=>{r&&bg(t,r)})}),l}function Er(t,e,n={}){var l;const i=Gn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(Jl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:f}=s;return Lg(t,e,c,d,u,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,d]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>d())}else return Promise.all([o(),r(n.delay)])}function Lg(t,e,n=0,i=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,d=typeof i=="function",u=d?f=>i(f,l):o===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(Pg).forEach((f,m)=>{f.notify("AnimationStart",e),a.push(Er(f,e,{...r,delay:n+(d?0:i)+u(m)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function Pg(t,e){return t.sortNodePosition(e)}function Mg(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>Er(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=Er(t,e,n);else{const s=typeof e=="function"?Gn(t,e,n.custom):e;i=Promise.all(Jl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Zl(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 Dg=vr.length;function Ql(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Ql(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Dg;n++){const i=vr[n],s=t.props[i];($n(s)||s===!1)&&(e[i]=s)}return e}const Og=[...mr].reverse(),Ng=mr.length;function Fg(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Mg(t,n,i)))}function Vg(t){let e=Fg(t),n=ec(),i=!0;const s=l=>(c,d)=>{var f;const u=Gn(t,d,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(u){const{transition:m,transitionEnd:_,...v}=u;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,d=Ql(t.parent)||{},u=[],f=new Set;let m={},_=1/0;for(let w=0;w<Ng;w++){const y=Og[w],C=n[y],k=c[y]!==void 0?c[y]:d[y],E=$n(k),R=y===l?C.isActive:null;R===!1&&(_=w);let O=k===d[y]&&k!==c[y]&&E;if(O&&i&&t.manuallyAnimateOnMount&&(O=!1),C.protectedKeys={...m},!C.isActive&&R===null||!k&&!C.prevProp||Pi(k)||typeof k=="boolean")continue;const S=Bg(C.prevProp,k);let x=S||y===l&&C.isActive&&!O&&E||w>_&&E,p=!1;const g=Array.isArray(k)?k:[k];let h=g.reduce(s(y),{});R===!1&&(h={});const{prevResolvedValues:b={}}=C,A={...b,...h},P=M=>{x=!0,f.has(M)&&(p=!0,f.delete(M)),C.needsAnimating[M]=!0;const N=t.getValue(M);N&&(N.liveStyle=!1)};for(const M in A){const N=h[M],W=b[M];if(m.hasOwnProperty(M))continue;let j=!1;xr(N)&&xr(W)?j=!Zl(N,W):j=N!==W,j?N!=null?P(M):f.add(M):N!==void 0&&f.has(M)?P(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=h,C.isActive&&(m={...m,...h}),i&&t.blockInitialAnimation&&(x=!1),x&&(!(O&&S)||p)&&u.push(...g.map(M=>({animation:M,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=Gn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const C=t.getBaseTarget(y),k=t.getValue(y);k&&(k.liveStyle=!0),w[y]=C??null}),u.push({animation:w})}let v=!!u.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),i=!1,v?e(u):Promise.resolve()}function a(l,c){var u;if(n[l].isActive===c)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(f=>{var m;return(m=f.animationState)==null?void 0:m.setActive(l,c)}),n[l].isActive=c;const d=r(l);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=ec(),i=!0}}}function Bg(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Zl(e,t):!1}function Ht(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ec(){return{animate:Ht(!0),whileInView:Ht(),whileHover:Ht(),whileTap:Ht(),whileDrag:Ht(),whileFocus:Ht(),exit:Ht()}}class Rt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class jg extends Rt{constructor(e){super(e),e.animationState||(e.animationState=Vg(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Pi(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 Ug=0;class $g extends Rt{constructor(){super(...arguments),this.id=Ug++}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 Hg={animation:{Feature:jg},exit:{Feature:$g}};function Wn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function zn(t){return{point:{x:t.pageX,y:t.pageY}}}const Gg=t=>e=>pr(e)&&t(e,zn(e));function qn(t,e,n,i){return Wn(t,e,Gg(n),i)}function tc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function Wg({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function zg(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 nc=1e-4,qg=1-nc,Kg=1+nc,ic=.01,Xg=0-ic,Yg=0+ic;function Oe(t){return t.max-t.min}function Jg(t,e,n){return Math.abs(t-e)<=n}function sc(t,e,n,i=.5){t.origin=i,t.originPoint=ve(e.min,e.max,t.origin),t.scale=Oe(n)/Oe(e),t.translate=ve(n.min,n.max,t.origin)-t.originPoint,(t.scale>=qg&&t.scale<=Kg||isNaN(t.scale))&&(t.scale=1),(t.translate>=Xg&&t.translate<=Yg||isNaN(t.translate))&&(t.translate=0)}function Kn(t,e,n,i){sc(t.x,e.x,n.x,i?i.originX:void 0),sc(t.y,e.y,n.y,i?i.originY:void 0)}function rc(t,e,n){t.min=n.min+e.min,t.max=t.min+Oe(e)}function Zg(t,e,n){rc(t.x,e.x,n.x),rc(t.y,e.y,n.y)}function oc(t,e,n){t.min=e.min-n.min,t.max=t.min+Oe(e)}function Xn(t,e,n){oc(t.x,e.x,n.x),oc(t.y,e.y,n.y)}const ac=()=>({translate:0,scale:1,origin:0,originPoint:0}),hn=()=>({x:ac(),y:ac()}),lc=()=>({min:0,max:0}),be=()=>({x:lc(),y:lc()});function Ke(t){return[t("x"),t("y")]}function Ar(t){return t===void 0||t===1}function Ir({scale:t,scaleX:e,scaleY:n}){return!Ar(t)||!Ar(e)||!Ar(n)}function Gt(t){return Ir(t)||cc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function cc(t){return dc(t.x)||dc(t.y)}function dc(t){return t&&t!=="0%"}function Oi(t,e,n){const i=t-n,s=e*i;return n+s}function uc(t,e,n,i,s){return s!==void 0&&(t=Oi(t,s,i)),Oi(t,n,i)+e}function Rr(t,e=0,n=1,i,s){t.min=uc(t.min,e,n,i,s),t.max=uc(t.max,e,n,i,s)}function hc(t,{x:e,y:n}){Rr(t.x,e.translate,e.scale,e.originPoint),Rr(t.y,n.translate,n.scale,n.originPoint)}const fc=.999999999999,pc=1.0000000000001;function Qg(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&pn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,hc(t,r)),i&&Gt(o.latestValues)&&pn(t,o.latestValues))}e.x<pc&&e.x>fc&&(e.x=1),e.y<pc&&e.y>fc&&(e.y=1)}function fn(t,e){t.min=t.min+e,t.max=t.max+e}function gc(t,e,n,i,s=.5){const o=ve(t.min,t.max,s);Rr(t,e,n,o,i)}function pn(t,e){gc(t.x,e.x,e.scaleX,e.scale,e.originX),gc(t.y,e.y,e.scaleY,e.scale,e.originY)}function mc(t,e){return tc(zg(t.getBoundingClientRect(),e))}function em(t,e,n){const i=mc(t,n),{scroll:s}=e;return s&&(fn(i.x,s.offset.x),fn(i.y,s.offset.y)),i}const vc=({current:t})=>t?t.ownerDocument.defaultView:null,yc=(t,e)=>Math.abs(t-e);function tm(t,e){const n=yc(t.x,e.x),i=yc(t.y,e.y);return Math.sqrt(n**2+i**2)}class _c{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=Pr(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,_=tm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!_)return;const{point:v}=f,{timestamp:w}=Ae;this.history.push({...v,timestamp:w});const{onStart:y,onMove:C}=this.handlers;m||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Lr(m,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Pr(f.type==="pointercancel"?this.lastMoveEventInfo:Lr(m,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,y),v&&v(f,y)},!pr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=zn(e),l=Lr(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Ae;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Pr(l,this.history)),this.removeListeners=Pn(qn(this.contextWindow,"pointermove",this.handlePointerMove),qn(this.contextWindow,"pointerup",this.handlePointerUp),qn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Et(this.updatePoint)}}function Lr(t,e){return e?{point:e(t.point)}:t}function bc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Pr({point:t},e){return{point:t,delta:bc(t,wc(e)),offset:bc(t,nm(e)),velocity:im(e,.1)}}function nm(t){return t[0]}function wc(t){return t[t.length-1]}function im(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=wc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>at(e)));)n--;if(!i)return{x:0,y:0};const o=lt(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 sm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ve(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ve(n,t,i.max):Math.min(t,n)),t}function Sc(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 rm(t,{top:e,left:n,bottom:i,right:s}){return{x:Sc(t.x,n,s),y:Sc(t.y,e,i)}}function Cc(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 om(t,e){return{x:Cc(t.x,e.x),y:Cc(t.y,e.y)}}function am(t,e){let n=.5;const i=Oe(t),s=Oe(e);return s>i?n=Mn(e.min,e.max-i,t.min):i>s&&(n=Mn(t.min,t.max-s,e.min)),_t(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 Mr=.35;function cm(t=Mr){return t===!1?t=0:t===!0&&(t=Mr),{x:xc(t,"left","right"),y:xc(t,"top","bottom")}}function xc(t,e,n){return{min:kc(t,e),max:kc(t,n)}}function kc(t,e){return typeof t=="number"?t:t[e]||0}const dm=new WeakMap;class um{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=be(),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=u=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(zn(u).point)},r=(u,f)=>{const{drag:m,dragPropagation:_,onDragStart:v}=this.getProps();if(m&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=kp(m),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ke(y=>{let C=this.getAxisMotionValue(y).get()||0;if(ct.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const E=k.layout.layoutBox[y];E&&(C=Oe(E)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&ue.postRender(()=>v(u,f)),kr(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f;const{dragPropagation:m,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:y}=f;if(_&&this.currentDirection===null){this.currentDirection=hm(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(u,f)},l=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f,this.stop(u,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ke(u=>{var f;return this.getAnimationState(u)==="paused"&&((f=this.getAxisMotionValue(u).animation)==null?void 0:f.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _c(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:i,contextWindow:vc(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&&ue.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||!Ni(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=sm(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&&un(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=rm(i.layoutBox,e):this.constraints=!1,this.elastic=cm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Ke(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||!un(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=em(i,s.root,this.visualElement.getTransformPagePoint());let r=om(s.layout.layoutBox,o);if(n){const a=n(Wg(r));this.hasMutatedConstraints=!!a,a&&(r=tc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ke(d=>{if(!Ni(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const f=s?200:1e6,m=s?40:1e7,_={type:"inertia",velocity:i?e[d]:0,bounceStiffness:f,bounceDamping:m,timeConstant:750,restDelta:1,restSpeed:10,...o,...u};return this.startAxisValueAnimation(d,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return kr(this.visualElement,e),i.start(Tr(e,i,0,n,this.visualElement,!1))}stopAnimation(){Ke(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Ke(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){Ke(n=>{const{drag:i}=this.getProps();if(!Ni(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]-ve(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!un(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Ke(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=am({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Ke(r=>{if(!Ni(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ve(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;dm.set(this.visualElement,this);const e=this.visualElement.current,n=qn(e,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();un(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ue.read(i);const r=Wn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ke(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=l[d].translate,u.set(u.get()+l[d].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=Mr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Ni(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function hm(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 Rt{constructor(e){super(e),this.removeGroupControls=qe,this.removeListeners=qe,this.controls=new um(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Tc=t=>(e,n)=>{t&&ue.postRender(()=>t(e,n))};class pm extends Rt{constructor(){super(...arguments),this.removePointerDownListener=qe}onPointerDown(e){this.session=new _c(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:vc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Tc(e),onStart:Tc(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&ue.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=qn(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 Fi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ec(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Yn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ec(t,e.target.x),i=Ec(t,e.target.y);return`${n}% ${i}%`}},gm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=It.parse(t);if(s.length>5)return i;const o=It.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=ve(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Ac=!1;class mm extends et{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;eg(vm),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Ac&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Fi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Ac=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||ue.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),fr.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 Ic(t){const[e,n]=Ll(),i=ke(As);return I(mm,{...t,layoutGroup:i,switchLayoutGroup:ke(jl),isPresent:e,safeToRemove:n})}const vm={borderRadius:{...Yn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Yn,borderTopRightRadius:Yn,borderBottomLeftRadius:Yn,borderBottomRightRadius:Yn,boxShadow:gm};function ym(t,e,n){const i=Pe(t)?t:cn(t);return i.start(Tr("",i,e,n)),i.animation}const _m=(t,e)=>t.depth-e.depth;class bm{constructor(){this.children=[],this.isDirty=!1}add(e){Rs(this.children,e),this.isDirty=!0}remove(e){Ls(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(_m),this.isDirty=!1,this.children.forEach(e)}}function wm(t,e){const n=Be.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(Et(i),t(o-e))};return ue.setup(i,!0),()=>Et(i)}const Rc=["TopLeft","TopRight","BottomLeft","BottomRight"],Sm=Rc.length,Lc=t=>typeof t=="string"?parseFloat(t):t,Pc=t=>typeof t=="number"||z.test(t);function Cm(t,e,n,i,s,o){s?(t.opacity=ve(0,n.opacity??1,xm(i)),t.opacityExit=ve(e.opacity??1,0,km(i))):o&&(t.opacity=ve(e.opacity??1,n.opacity??1,i));for(let r=0;r<Sm;r++){const a=`border${Rc[r]}Radius`;let l=Mc(e,a),c=Mc(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Pc(l)===Pc(c)?(t[a]=Math.max(ve(Lc(l),Lc(c),i),0),(ct.test(c)||ct.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ve(e.rotate||0,n.rotate||0,i))}function Mc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const xm=Dc(0,.5,Pa),km=Dc(.5,.95,qe);function Dc(t,e,n){return i=>i<t?0:i>e?1:n(Mn(t,e,i))}function Oc(t,e){t.min=e.min,t.max=e.max}function Xe(t,e){Oc(t.x,e.x),Oc(t.y,e.y)}function Nc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Fc(t,e,n,i,s){return t-=e,t=Oi(t,1/n,i),s!==void 0&&(t=Oi(t,1/s,i)),t}function Tm(t,e=0,n=1,i=.5,s,o=t,r=t){if(ct.test(e)&&(e=parseFloat(e),e=ve(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ve(o.min,o.max,i);t===o&&(a-=e),t.min=Fc(t.min,e,n,a,s),t.max=Fc(t.max,e,n,a,s)}function Vc(t,e,[n,i,s],o,r){Tm(t,e[n],e[i],e[s],e.scale,o,r)}const Em=["x","scaleX","originX"],Am=["y","scaleY","originY"];function Bc(t,e,n,i){Vc(t.x,e,Em,n?n.x:void 0,i?i.x:void 0),Vc(t.y,e,Am,n?n.y:void 0,i?i.y:void 0)}function jc(t){return t.translate===0&&t.scale===1}function Uc(t){return jc(t.x)&&jc(t.y)}function $c(t,e){return t.min===e.min&&t.max===e.max}function Im(t,e){return $c(t.x,e.x)&&$c(t.y,e.y)}function Hc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Gc(t,e){return Hc(t.x,e.x)&&Hc(t.y,e.y)}function Wc(t){return Oe(t.x)/Oe(t.y)}function zc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Rm{constructor(){this.members=[]}add(e){Rs(this.members,e),e.scheduleRender()}remove(e){if(Ls(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 Lm(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:u,rotateY:f,skewX:m,skewY:_}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),f&&(i+=`rotateY(${f}deg) `),m&&(i+=`skewX(${m}deg) `),_&&(i+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Dr=["","X","Y","Z"],Pm=1e3;let Mm=0;function Or(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function qc(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Yl(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&qc(i)}function Kc({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Mm++,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(Nm),this.nodes.forEach(jm),this.nodes.forEach(Um),this.nodes.forEach(Fm)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new bm)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Ds),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=Rl(r)&&!Lp(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let d,u=0;const f=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{u=window.innerWidth}),t(r,()=>{const m=window.innerWidth;m!==u&&(u=m,this.root.updateBlockedByResize=!0,d&&d(),d=wm(f,250),Fi.hasAnimatedSinceResize&&(Fi.hasAnimatedSinceResize=!1,this.nodes.forEach(Jc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:f,layout:m})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||zm,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Gc(this.targetLayout,m),C=!u&&f;if(this.options.layoutRoot||this.resumeFrom||C||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...dr(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,C)}else u||Jc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=m})}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(),Et(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($m),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&&qc(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const u=this.path[d];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Xc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Yc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Bm),this.nodes.forEach(Dm),this.nodes.forEach(Om)):this.nodes.forEach(Yc),this.clearAllSnapshots();const a=Be.now();Ae.delta=_t(0,1e3/60,a-Ae.timestamp),Ae.timestamp=a,Ae.isProcessing=!0,Fs.update.process(Ae),Fs.preRender.process(Ae),Fs.render.process(Ae),Ae.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,fr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Vm),this.sharedNodes.forEach(Hm)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Oe(this.snapshot.measuredBox.x)&&!Oe(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=be(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Uc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Gt(this.latestValues)||d)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),qm(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return be();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Km))){const{scroll:d}=this.root;d&&(fn(a.x,d.offset.x),fn(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=be();if(Xe(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const d=this.path[c],{scroll:u,options:f}=d;d!==this.root&&u&&f.layoutScroll&&(u.wasRoot&&Xe(a,r),fn(a.x,u.offset.x),fn(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=be();Xe(l,r);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&pn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),Gt(d.latestValues)&&pn(l,d.latestValues)}return Gt(this.latestValues)&&pn(l,this.latestValues),l}removeTransform(r){const a=be();Xe(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Gt(c.latestValues))continue;Ir(c.latestValues)&&c.updateSnapshot();const d=be(),u=c.measurePageBox();Xe(d,u),Bc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return Gt(this.latestValues)&&Bc(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!==Ae.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:u}=this.options;if(!(!this.layout||!(d||u))){if(this.resolvedRelativeTargetAt=Ae.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=be(),this.targetWithTransforms=be()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Zg(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Xe(this.target,this.layout.layoutBox),hc(this.target,this.targetDelta)):Xe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.target,m.target),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Ir(this.parent.latestValues)||cc(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 _;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(_=this.parent)!=null&&_.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Ae.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;Xe(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,f=this.treeScale.y;Qg(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=be());const{target:m}=r;if(!m){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Nc(this.prevProjectionDelta.x,this.projectionDelta.x),Nc(this.prevProjectionDelta.y,this.projectionDelta.y)),Kn(this.projectionDelta,this.layoutCorrected,m,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==f||!zc(this.projectionDelta.x,this.prevProjectionDelta.x)||!zc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",m))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=hn(),this.projectionDelta=hn(),this.projectionDeltaWithTransform=hn()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=hn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=be(),m=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=m!==_,w=this.getStack(),y=!w||w.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Wm));this.animationProgress=0;let k;this.mixTargetDelta=E=>{const R=E/1e3;Zc(u.x,r.x,R),Zc(u.y,r.y,R),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Gm(this.relativeTarget,this.relativeTargetOrigin,f,R),k&&Im(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=be()),Xe(k,this.relativeTarget)),v&&(this.animationValues=d,Cm(d,c,this.latestValues,R,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Et(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{Fi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=cn(0)),this.currentAnimation=ym(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:d=>{this.mixTargetDelta(d),r.onUpdate&&r.onUpdate(d)},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(Pm),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&id(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||be();const u=Oe(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const f=Oe(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Xe(a,l),pn(a,d),Kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Rm),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Or("z",r,c,this.animationValues);for(let d=0;d<Dr.length;d++)Or(`rotate${Dr[d]}`,r,c,this.animationValues),Or(`skew${Dr[d]}`,r,c,this.animationValues);r.render();for(const d in c)r.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Di(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Di(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Gt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=Lm(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:f,y:m}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${m.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const _ in Hn){if(d[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=Hn[_],C=u==="none"?d[_]:v(d[_],c);if(w){const k=w.length;for(let E=0;E<k;E++)r[w[E]]=C}else y?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Di(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(Xc),this.root.sharedNodes.clear()}}}function Dm(t){t.updateLayout()}function Om(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"?Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(f);f.min=i[u].min,f.max=f.min+m}):id(o,e.layoutBox,i)&&Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(i[u]);f.max=f.min+m,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+m)});const a=hn();Kn(a,i,e.layoutBox);const l=hn();r?Kn(l,t.applyTransform(s,!0),e.measuredBox):Kn(l,i,e.layoutBox);const c=!Uc(a);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:f,layout:m}=u;if(f&&m){const _=be();Xn(_,e.layoutBox,f.layoutBox);const v=be();Xn(v,i,m.layoutBox),Gc(_,v)||(d=!0),u.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:d})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function Nm(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 Fm(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Vm(t){t.clearSnapshot()}function Xc(t){t.clearMeasurements()}function Yc(t){t.isLayoutDirty=!1}function Bm(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Jc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function jm(t){t.resolveTargetDelta()}function Um(t){t.calcProjection()}function $m(t){t.resetSkewAndRotation()}function Hm(t){t.removeLeadSnapshot()}function Zc(t,e,n){t.translate=ve(e.translate,0,n),t.scale=ve(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Qc(t,e,n,i){t.min=ve(e.min,n.min,i),t.max=ve(e.max,n.max,i)}function Gm(t,e,n,i){Qc(t.x,e.x,n.x,i),Qc(t.y,e.y,n.y,i)}function Wm(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const zm={duration:.45,ease:[.4,0,.1,1]},ed=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),td=ed("applewebkit/")&&!ed("chrome/")?Math.round:qe;function nd(t){t.min=td(t.min),t.max=td(t.max)}function qm(t){nd(t.x),nd(t.y)}function id(t,e,n){return t==="position"||t==="preserve-aspect"&&!Jg(Wc(e),Wc(n),.2)}function Km(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Xm=Kc({attachResizeListener:(t,e)=>Wn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Nr={current:void 0},sd=Kc({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Nr.current){const t=new Xm({});t.mount(window),t.setOptions({layoutScroll:!0}),Nr.current=t}return Nr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Ym={pan:{Feature:pm},drag:{Feature:fm,ProjectionNode:sd,MeasureLayout:Ic}};function rd(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&&ue.postRender(()=>o(e,zn(e)))}class Jm extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Tp(e,(n,i)=>(rd(this.node,i,"Start"),s=>rd(this.node,s,"End"))))}unmount(){}}class Zm extends Rt{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=Pn(Wn(this.node.current,"focus",()=>this.onFocus()),Wn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function od(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&&ue.postRender(()=>o(e,zn(e)))}class Qm extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Rp(e,(n,i)=>(od(this.node,i,"Start"),(s,{success:o})=>od(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Fr=new WeakMap,Vr=new WeakMap,ev=t=>{const e=Fr.get(t.target);e&&e(t)},tv=t=>{t.forEach(ev)};function nv({root:t,...e}){const n=t||document;Vr.has(n)||Vr.set(n,{});const i=Vr.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(tv,{root:t,...e})),i[s]}function iv(t,e,n){const i=nv(e);return Fr.set(t,n),i.observe(t),()=>{Fr.delete(t),i.unobserve(t)}}const sv={some:0,all:1};class rv extends Rt{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:sv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),f=c?d:u;f&&f(l)};return iv(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(ov(e,n))&&this.startObserver()}unmount(){}}function ov({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const av={inView:{Feature:rv},tap:{Feature:Qm},focus:{Feature:Zm},hover:{Feature:Jm}},lv={layout:{ProjectionNode:sd,MeasureLayout:Ic}},Br={current:null},ad={current:!1};function cv(){if(ad.current=!0,!!Is)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Br.current=t.matches;t.addEventListener("change",e),e()}else Br.current=!1}const dv=new WeakMap;function uv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Pe(s))t.addValue(i,s);else if(Pe(o))t.addValue(i,cn(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,cn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const ld=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class hv{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=lr,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Be.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ue.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Mi(n),this.isVariantNode=Fl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in u){const m=u[f];l[f]!==void 0&&Pe(m)&&m.set(l[f],!1)}}mount(e){this.current=e,dv.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,i)=>this.bindToMotionValue(i,n)),ad.current||cv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Br.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Et(this.notifyUpdate),Et(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=ln.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ue.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 dn){const n=dn[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):be()}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<ld.length;i++){const s=ld[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=uv(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=cn(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"&&(Sa(i)||xa(i))?i=parseFloat(i):!Mp(i)&&It.test(n)&&(i=wl(e,n)),this.setBaseTarget(e,Pe(i)?i.get():i)),Pe(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=Sr(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&&!Pe(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 Ds),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class cd extends hv{constructor(){super(...arguments),this.KeyframeResolver=wp}sortInstanceNodePosition(e,n){return e.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(e,n){return e.style?e.style[n]:void 0}removeValueFromRenderState(e,{vars:n,style:i}){delete n[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Pe(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function dd(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 fv(t){return window.getComputedStyle(t)}class pv extends cd{constructor(){super(...arguments),this.type="html",this.renderInstance=dd}readValueFromInstance(e,n){var i;if(ln.has(n))return(i=this.projection)!=null&&i.isProjecting?ir(n):Uf(e,n);{const s=fv(e),o=(Vs(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return mc(e,n)}build(e,n,i){_r(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return Cr(e,n,i)}}const ud=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 gv(t,e,n,i){dd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(ud.has(s)?s:yr(s),e.attrs[s])}class mv extends cd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=be}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(ln.has(n)){const i=bl(n);return i&&i.default||0}return n=ud.has(n)?n:yr(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Xl(e,n,i)}build(e,n,i){Gl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){gv(e,n,i,s)}mount(e){this.isSVGTag=zl(e.tagName),super.mount(e)}}const vv=(t,e)=>wr(t)?new mv(e):new pv(e,{allowProjection:t!==rt}),yv=vg({...Hg,...av,...Ym,...lv},vv),gn=Hp(yv),_v=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region"],Jn="widget-layout-id";function hd(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=hd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function wt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=hd(t))&&(i&&(i+=" "),i+=e);return i}const bv=Ss("listening"),jr=()=>ba(bv);function wv(t){var n;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((n=e.params)==null?void 0:n.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Vi={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},fd=Ss(Vi),Sv=()=>{const t=Es(fd);return yt(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=Vi.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=Vi.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=Vi.speak_to_interrupt_text),n}),[t])},Wt=()=>_a(fd),pd=({size:t="large",className:e})=>{const n=Wt(),[i]=jr();return I("h1",{className:wt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},gd=({stream:t,chatMode:e})=>{const n=me(null);return xe(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:I("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),R(Op,{isPresent:e,childRef:o,sizeRef:r,children:Oh(t,{ref:o})})}const Fp=({children:t,initial:e,isPresent:n,onExitComplete:i,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Si(Vp),d=vs();let u=!0,f=ze(()=>(u=!1,{id:d,initial:e,isPresent:n,custom:s,onExitComplete:m=>{c.set(m,!0);for(const _ of c.values())if(!_)return;i&&i()},register:m=>(c.set(m,!1),()=>c.delete(m))}),[n,c,i]);return o&&u&&(f={...f}),ze(()=>{c.forEach((m,_)=>c.set(_,!1))},[n]),ke(()=>{!n&&!c.size&&i&&i()},[n]),r==="popLayout"&&(t=R(Np,{isPresent:n,anchorX:a,root:l,children:t})),R(Ci.Provider,{value:f,children:t})};function Vp(){return new Map}function Ll(t=!0){const e=Te(Ci);if(e===null)return[!0,null];const{isPresent:n,onExitComplete:i,register:s}=e,o=vs();ke(()=>{if(t)return s(o)},[t]);const r=yt(()=>t&&i&&i(o),[o,i,t]);return!n&&i?[!1,r]:[!0]}const Li=t=>t.key||"";function Pl(t){const e=[];return xh.forEach(t,n=>{ma(n)&&e.push(n)}),e}const Bp=({children:t,custom:e,initial:n=!0,onExitComplete:i,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,d]=Ll(r),u=ze(()=>Pl(t),[t]),f=r&&!c?[]:u.map(Li),m=me(!0),_=me(u),v=Si(()=>new Map),[w,y]=xe(u),[C,k]=xe(u);wa(()=>{m.current=!1,_.current=u;for(let D=0;D<C.length;D++){const S=Li(C[D]);f.includes(S)?v.delete(S):v.get(S)!==!0&&v.set(S,!1)}},[C,f.length,f.join("-")]);const T=[];if(u!==w){let D=[...u];for(let S=0;S<C.length;S++){const x=C[S],p=Li(x);f.includes(p)||(D.splice(S,0,x),T.push(x))}return o==="wait"&&T.length&&(D=T),k(Pl(D)),y(u),null}const{forceRender:E}=Te(Is);return R(rt,{children:C.map(D=>{const S=Li(D),x=r&&!c?!1:u===C||f.includes(S),p=()=>{if(v.has(S))v.set(S,!0);else return;let g=!0;v.forEach(h=>{h||(g=!1)}),g&&(E==null||E(),k(_.current),r&&(d==null||d()),i&&i())};return R(Fp,{isPresent:x,initial:!m.current||n?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:x?void 0:p,anchorX:a,children:D},S)})})},Ml=vt({strict:!1}),Dl={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"]},dn={};for(const t in Dl)dn[t]={isEnabled:e=>Dl[t].some(n=>!!e[n])};function jp(t){for(const e in t)dn[e]={...dn[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 Pi(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 Ol=t=>!Pi(t);function Nl(t){typeof t=="function"&&(Ol=e=>e.startsWith("on")?!Pi(e):t(e))}try{Nl(require("@emotion/is-prop-valid").default)}catch{}function $p(t,e,n){const i={};for(const s in t)s==="values"&&typeof t.values=="object"||(Ol(s)||n===!0&&Pi(s)||!e&&!Pi(s)||t.draggable&&s.startsWith("onDrag"))&&(i[s]=t[s]);return i}function Hp({children:t,isValidProp:e,...n}){e&&Nl(e),n={...Te(Un),...n},n.isStatic=Si(()=>n.isStatic);const i=ze(()=>n,[JSON.stringify(n.transition),n.transformPagePoint,n.reducedMotion]);return R(Un.Provider,{value:i,children:t})}function Gp(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 Mi=vt({});function Di(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function $n(t){return typeof t=="string"||Array.isArray(t)}const vr=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],yr=["initial",...vr];function Oi(t){return Di(t.animate)||yr.some(e=>$n(t[e]))}function Fl(t){return!!(Oi(t)||t.variants)}function Wp(t,e){if(Oi(t)){const{initial:n,animate:i}=t;return{initial:n===!1||$n(n)?n:void 0,animate:$n(i)?i:void 0}}return t.inherit!==!1?e:{}}function zp(t){const{initial:e,animate:n}=Wp(t,Te(Mi));return ze(()=>({initial:e,animate:n}),[Vl(e),Vl(n)])}function Vl(t){return Array.isArray(t)?t.join(" "):t}const qp=Symbol.for("motionComponentSymbol");function un(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Kp(t,e,n){return yt(i=>{i&&t.onMount&&t.onMount(i),e&&(i?e.mount(i):e.unmount()),n&&(typeof n=="function"?n(i):un(n)&&(n.current=i))},[e])}const _r=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Bl="data-"+_r("framerAppearId"),jl=vt({});function Xp(t,e,n,i,s){var v,w;const{visualElement:o}=Te(Mi),r=Te(Ml),a=Te(Ci),l=Te(Un).reducedMotion,c=me(null);i=i||r.renderer,!c.current&&i&&(c.current=i(t,{visualState:e,parent:o,props:n,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const d=c.current,u=Te(jl);d&&!d.projection&&s&&(d.type==="html"||d.type==="svg")&&Yp(c.current,n,s,u);const f=me(!1);na(()=>{d&&f.current&&d.update(n,a)});const m=n[Bl],_=me(!!m&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,m))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,m)));return wa(()=>{d&&(f.current=!0,window.MotionIsMounted=!0,d.updateFeatures(),pr.render(d.render),_.current&&d.animationState&&d.animationState.animateChanges())}),ke(()=>{d&&(!_.current&&d.animationState&&d.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,m)}),_.current=!1))}),d}function Yp(t,e,n,i){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:d}=e;t.projection=new n(t.latestValues,e["data-framer-portal-id"]?void 0:Ul(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&un(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:i,crossfade:d,layoutScroll:l,layoutRoot:c})}function Ul(t){if(t)return t.options.allowProjection!==!1?t.projection:Ul(t.parent)}function Jp({preloadedFeatures:t,createVisualElement:e,useRender:n,useVisualState:i,Component:s}){t&&jp(t);function o(a,l){let c;const d={...Te(Un),...a,layoutId:Zp(a)},{isStatic:u}=d,f=zp(a),m=i(a,u);if(!u&&Rs){Qp();const _=eg(d);c=_.MeasureLayout,f.visualElement=Xp(s,m,d,e,_.ProjectionNode)}return R(Mi.Provider,{value:f,children:[c&&f.visualElement?R(c,{visualElement:f.visualElement,...d}):null,n(s,a,Kp(m,f.visualElement,l),m,u,f.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Ch(o);return r[qp]=s,r}function Zp({layoutId:t}){const e=Te(Is).id;return e&&t!==void 0?e+"-"+t:t}function Qp(t,e){Te(Ml).strict}function eg(t){const{drag:e,layout:n}=dn;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 Hn={};function tg(t){for(const e in t)Hn[e]=t[e],Bs(e)&&(Hn[e].isCSSVariable=!0)}function $l(t,{layout:e,layoutId:n}){return ln.has(t)||t.startsWith("origin")||(e||n!==void 0)&&(!!Hn[t]||t==="opacity")}const ng={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},ig=an.length;function sg(t,e,n){let i="",s=!0;for(let o=0;o<ig;o++){const r=an[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||n){const c=Sl(a,fr[r]);if(!l){s=!1;const d=ng[r]||r;i+=`${d}(${c}) `}n&&(e[r]=c)}}return i=i.trim(),n?i=n(e,s?"":i):s&&(i="none"),i}function br(t,e,n){const{style:i,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(ln.has(l)){r=!0;continue}else if(Bs(l)){s[l]=c;continue}else{const d=Sl(c,fr[l]);l.startsWith("origin")?(a=!0,o[l]=d):i[l]=d}}if(e.transform||(r||n?i.transform=sg(e,t.transform,n):i.transform&&(i.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:d=0}=o;i.transformOrigin=`${l} ${c} ${d}`}}const wr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Hl(t,e,n){for(const i in e)!Pe(e[i])&&!$l(i,n)&&(t[i]=e[i])}function rg({transformTemplate:t},e){return ze(()=>{const n=wr();return br(n,e,t),Object.assign({},n.vars,n.style)},[e])}function og(t,e){const n=t.style||{},i={};return Hl(i,n,t),Object.assign(i,rg(t,e)),i}function ag(t,e){const n={},i=og(t,e);return t.drag&&t.dragListener!==!1&&(n.draggable=!1,i.userSelect=i.WebkitUserSelect=i.WebkitTouchCallout="none",i.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(n.tabIndex=0),n.style=i,n}const lg={offset:"stroke-dashoffset",array:"stroke-dasharray"},cg={offset:"strokeDashoffset",array:"strokeDasharray"};function dg(t,e,n=1,i=0,s=!0){t.pathLength=1;const o=s?lg:cg;t[o.offset]=z.transform(-i);const r=z.transform(e),a=z.transform(n);t[o.array]=`${r} ${a}`}function Gl(t,{attrX:e,attrY:n,attrScale:i,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,d){if(br(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:u,style:f}=t;u.transform&&(f.transform=u.transform,delete u.transform),(f.transform||u.transformOrigin)&&(f.transformOrigin=u.transformOrigin??"50% 50%",delete u.transformOrigin),f.transform&&(f.transformBox=(d==null?void 0:d.transformBox)??"fill-box",delete u.transformBox),e!==void 0&&(u.x=e),n!==void 0&&(u.y=n),i!==void 0&&(u.scale=i),s!==void 0&&dg(u,s,o,r,!1)}const Wl=()=>({...wr(),attrs:{}}),zl=t=>typeof t=="string"&&t.toLowerCase()==="svg";function ug(t,e,n,i){const s=ze(()=>{const o=Wl();return Gl(o,e,zl(i),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Hl(o,t.style,t),s.style={...o,...s.style}}return s}const hg=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function Sr(t){return typeof t!="string"||t.includes("-")?!1:!!(hg.indexOf(t)>-1||/[A-Z]/u.test(t))}function fg(t=!1){return(n,i,s,{latestValues:o},r)=>{const l=(Sr(n)?ug:ag)(i,o,r,n),c=$p(i,typeof n=="string",t),d=n!==rt?{...c,...l,ref:s}:{},{children:u}=i,f=ze(()=>Pe(u)?u.get():u,[u]);return We(n,{...d,children:f})}}function ql(t){const e=[{},{}];return t==null||t.values.forEach((n,i)=>{e[0][i]=n.get(),e[1][i]=n.getVelocity()}),e}function Cr(t,e,n,i){if(typeof e=="function"){const[s,o]=ql(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]=ql(i);e=e(n!==void 0?n:t.custom,s,o)}return e}function Ni(t){return Pe(t)?t.get():t}function pg({scrapeMotionValuesFromProps:t,createRenderState:e},n,i,s){return{latestValues:gg(n,i,s,t),renderState:e()}}const Kl=t=>(e,n)=>{const i=Te(Mi),s=Te(Ci),o=()=>pg(t,e,i,s);return n?o():Si(o)};function gg(t,e,n,i){const s={},o=i(t,{});for(const f in o)s[f]=Ni(o[f]);let{initial:r,animate:a}=t;const l=Oi(t),c=Fl(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let d=n?n.initial===!1:!1;d=d||r===!1;const u=d?a:r;if(u&&typeof u!="boolean"&&!Di(u)){const f=Array.isArray(u)?u:[u];for(let m=0;m<f.length;m++){const _=Cr(t,f[m]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const C in y){let k=y[C];if(Array.isArray(k)){const T=d?k.length-1:0;k=k[T]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function xr(t,e,n){var o;const{style:i}=t,s={};for(const r in i)(Pe(i[r])||e.style&&Pe(e.style[r])||$l(r,t)||((o=n==null?void 0:n.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=i[r]);return s}const mg={useVisualState:Kl({scrapeMotionValuesFromProps:xr,createRenderState:wr})};function Xl(t,e,n){const i=xr(t,e,n);for(const s in t)if(Pe(t[s])||Pe(e[s])){const o=an.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;i[o]=t[s]}return i}const vg={useVisualState:Kl({scrapeMotionValuesFromProps:Xl,createRenderState:Wl})};function yg(t,e){return function(i,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Sr(i)?vg:mg,preloadedFeatures:t,useRender:fg(s),createVisualElement:e,Component:i};return Jp(r)}}function Gn(t,e,n){const i=t.getProps();return Cr(i,e,n!==void 0?n:i.custom,t)}const kr=t=>Array.isArray(t);function _g(t,e,n){t.hasValue(e)?t.getValue(e).set(n):t.addValue(e,cn(n))}function bg(t){return kr(t)?t[t.length-1]||0:t}function wg(t,e){const n=Gn(t,e);let{transitionEnd:i={},transition:s={},...o}=n||{};o={...o,...i};for(const r in o){const a=bg(o[r]);_g(t,r,a)}}function Sg(t){return!!(Pe(t)&&t.add)}function Tr(t,e){const n=t.getValue("willChange");if(Sg(n))return n.add(e);if(!n&&bt.WillChange){const i=new bt.WillChange("auto");t.addValue("willChange",i),i.add(e)}}function Yl(t){return t.props[Bl]}const Cg=t=>t!==null;function xg(t,{repeat:e,repeatType:n="loop"},i){const s=t.filter(Cg),o=e&&n!=="loop"&&e%2===1?0:s.length-1;return s[o]}const kg={type:"spring",stiffness:500,damping:25,restSpeed:10},Tg=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Ag={type:"keyframes",duration:.8},Eg={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Ig=(t,{keyframes:e})=>e.length>2?Ag:ln.has(t)?t.startsWith("scale")?Tg(e[1]):kg:Eg;function Rg({when:t,delay:e,delayChildren:n,staggerChildren:i,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}const Ar=(t,e,n,i={},s,o)=>r=>{const a=ur(i,t)||{},l=a.delay||i.delay||0;let{elapsed:c=0}=i;c=c-at(l);const d={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:f=>{e.set(f),a.onUpdate&&a.onUpdate(f)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Rg(a)||Object.assign(d,Ig(t,d)),d.duration&&(d.duration=at(d.duration)),d.repeatDelay&&(d.repeatDelay=at(d.repeatDelay)),d.from!==void 0&&(d.keyframes[0]=d.from);let u=!1;if((d.type===!1||d.duration===0&&!d.repeatDelay)&&(d.duration=0,d.delay===0&&(u=!0)),(bt.instantAnimations||bt.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),d.allowFlatten=!a.type&&!a.ease,u&&!o&&e.get()!==void 0){const f=xg(d.keyframes,a);if(f!==void 0){ue.update(()=>{d.onUpdate(f),d.onComplete()});return}}return a.isSync?new tr(d):new up(d)};function Lg({protectedKeys:t,needsAnimating:e},n){const i=t.hasOwnProperty(n)&&e[n]!==!0;return e[n]=!1,i}function Jl(t,e,{delay:n=0,transitionOverride:i,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;i&&(o=i);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const d in a){const u=t.getValue(d,t.latestValues[d]??null),f=a[d];if(f===void 0||c&&Lg(c,d))continue;const m={delay:n,...ur(o||{},d)},_=u.get();if(_!==void 0&&!u.isAnimating&&!Array.isArray(f)&&f===_&&!m.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Yl(t);if(y){const C=window.MotionHandoffAnimation(y,d,ue);C!==null&&(m.startTime=C,v=!0)}}Tr(t,d),u.start(Ar(d,u,f,t.shouldReduceMotion&&gl.has(d)?{type:!1}:m,t,v));const w=u.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{ue.update(()=>{r&&wg(t,r)})}),l}function Er(t,e,n={}){var l;const i=Gn(t,e,n.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=i||{};n.transitionOverride&&(s=n.transitionOverride);const o=i?()=>Promise.all(Jl(t,i,n)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:d=0,staggerChildren:u,staggerDirection:f}=s;return Pg(t,e,c,d,u,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,d]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>d())}else return Promise.all([o(),r(n.delay)])}function Pg(t,e,n=0,i=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,d=typeof i=="function",u=d?f=>i(f,l):o===1?(f=0)=>f*s:(f=0)=>c-f*s;return Array.from(t.variantChildren).sort(Mg).forEach((f,m)=>{f.notify("AnimationStart",e),a.push(Er(f,e,{...r,delay:n+(d?0:i)+u(m)}).then(()=>f.notify("AnimationComplete",e)))}),Promise.all(a)}function Mg(t,e){return t.sortNodePosition(e)}function Dg(t,e,n={}){t.notify("AnimationStart",e);let i;if(Array.isArray(e)){const s=e.map(o=>Er(t,o,n));i=Promise.all(s)}else if(typeof e=="string")i=Er(t,e,n);else{const s=typeof e=="function"?Gn(t,e,n.custom):e;i=Promise.all(Jl(t,s,n))}return i.then(()=>{t.notify("AnimationComplete",e)})}function Zl(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 Og=yr.length;function Ql(t){if(!t)return;if(!t.isControllingVariants){const n=t.parent?Ql(t.parent)||{}:{};return t.props.initial!==void 0&&(n.initial=t.props.initial),n}const e={};for(let n=0;n<Og;n++){const i=yr[n],s=t.props[i];($n(s)||s===!1)&&(e[i]=s)}return e}const Ng=[...vr].reverse(),Fg=vr.length;function Vg(t){return e=>Promise.all(e.map(({animation:n,options:i})=>Dg(t,n,i)))}function Bg(t){let e=Vg(t),n=ec(),i=!0;const s=l=>(c,d)=>{var f;const u=Gn(t,d,l==="exit"?(f=t.presenceContext)==null?void 0:f.custom:void 0);if(u){const{transition:m,transitionEnd:_,...v}=u;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,d=Ql(t.parent)||{},u=[],f=new Set;let m={},_=1/0;for(let w=0;w<Fg;w++){const y=Ng[w],C=n[y],k=c[y]!==void 0?c[y]:d[y],T=$n(k),E=y===l?C.isActive:null;E===!1&&(_=w);let D=k===d[y]&&k!==c[y]&&T;if(D&&i&&t.manuallyAnimateOnMount&&(D=!1),C.protectedKeys={...m},!C.isActive&&E===null||!k&&!C.prevProp||Di(k)||typeof k=="boolean")continue;const S=jg(C.prevProp,k);let x=S||y===l&&C.isActive&&!D&&T||w>_&&T,p=!1;const g=Array.isArray(k)?k:[k];let h=g.reduce(s(y),{});E===!1&&(h={});const{prevResolvedValues:b={}}=C,I={...b,...h},P=M=>{x=!0,f.has(M)&&(p=!0,f.delete(M)),C.needsAnimating[M]=!0;const N=t.getValue(M);N&&(N.liveStyle=!1)};for(const M in I){const N=h[M],W=b[M];if(m.hasOwnProperty(M))continue;let j=!1;kr(N)&&kr(W)?j=!Zl(N,W):j=N!==W,j?N!=null?P(M):f.add(M):N!==void 0&&f.has(M)?P(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=h,C.isActive&&(m={...m,...h}),i&&t.blockInitialAnimation&&(x=!1),x&&(!(D&&S)||p)&&u.push(...g.map(M=>({animation:M,options:{type:y}})))}if(f.size){const w={};if(typeof c.initial!="boolean"){const y=Gn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}f.forEach(y=>{const C=t.getBaseTarget(y),k=t.getValue(y);k&&(k.liveStyle=!0),w[y]=C??null}),u.push({animation:w})}let v=!!u.length;return i&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),i=!1,v?e(u):Promise.resolve()}function a(l,c){var u;if(n[l].isActive===c)return Promise.resolve();(u=t.variantChildren)==null||u.forEach(f=>{var m;return(m=f.animationState)==null?void 0:m.setActive(l,c)}),n[l].isActive=c;const d=r(l);for(const f in n)n[f].protectedKeys={};return d}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>n,reset:()=>{n=ec(),i=!0}}}function jg(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Zl(e,t):!1}function Wt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ec(){return{animate:Wt(!0),whileInView:Wt(),whileHover:Wt(),whileTap:Wt(),whileDrag:Wt(),whileFocus:Wt(),exit:Wt()}}class Rt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Ug extends Rt{constructor(e){super(e),e.animationState||(e.animationState=Bg(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Di(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 $g=0;class Hg extends Rt{constructor(){super(...arguments),this.id=$g++}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 Gg={animation:{Feature:Ug},exit:{Feature:Hg}};function Wn(t,e,n,i={passive:!0}){return t.addEventListener(e,n,i),()=>t.removeEventListener(e,n)}function zn(t){return{point:{x:t.pageX,y:t.pageY}}}const Wg=t=>e=>gr(e)&&t(e,zn(e));function qn(t,e,n,i){return Wn(t,e,Wg(n),i)}function tc({top:t,left:e,right:n,bottom:i}){return{x:{min:e,max:n},y:{min:t,max:i}}}function zg({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function qg(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 nc=1e-4,Kg=1-nc,Xg=1+nc,ic=.01,Yg=0-ic,Jg=0+ic;function Oe(t){return t.max-t.min}function Zg(t,e,n){return Math.abs(t-e)<=n}function sc(t,e,n,i=.5){t.origin=i,t.originPoint=ve(e.min,e.max,t.origin),t.scale=Oe(n)/Oe(e),t.translate=ve(n.min,n.max,t.origin)-t.originPoint,(t.scale>=Kg&&t.scale<=Xg||isNaN(t.scale))&&(t.scale=1),(t.translate>=Yg&&t.translate<=Jg||isNaN(t.translate))&&(t.translate=0)}function Kn(t,e,n,i){sc(t.x,e.x,n.x,i?i.originX:void 0),sc(t.y,e.y,n.y,i?i.originY:void 0)}function rc(t,e,n){t.min=n.min+e.min,t.max=t.min+Oe(e)}function Qg(t,e,n){rc(t.x,e.x,n.x),rc(t.y,e.y,n.y)}function oc(t,e,n){t.min=e.min-n.min,t.max=t.min+Oe(e)}function Xn(t,e,n){oc(t.x,e.x,n.x),oc(t.y,e.y,n.y)}const ac=()=>({translate:0,scale:1,origin:0,originPoint:0}),hn=()=>({x:ac(),y:ac()}),lc=()=>({min:0,max:0}),be=()=>({x:lc(),y:lc()});function Ke(t){return[t("x"),t("y")]}function Ir(t){return t===void 0||t===1}function Rr({scale:t,scaleX:e,scaleY:n}){return!Ir(t)||!Ir(e)||!Ir(n)}function zt(t){return Rr(t)||cc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function cc(t){return dc(t.x)||dc(t.y)}function dc(t){return t&&t!=="0%"}function Fi(t,e,n){const i=t-n,s=e*i;return n+s}function uc(t,e,n,i,s){return s!==void 0&&(t=Fi(t,s,i)),Fi(t,n,i)+e}function Lr(t,e=0,n=1,i,s){t.min=uc(t.min,e,n,i,s),t.max=uc(t.max,e,n,i,s)}function hc(t,{x:e,y:n}){Lr(t.x,e.translate,e.scale,e.originPoint),Lr(t.y,n.translate,n.scale,n.originPoint)}const fc=.999999999999,pc=1.0000000000001;function em(t,e,n,i=!1){const s=n.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=n[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(i&&o.options.layoutScroll&&o.scroll&&o!==o.root&&pn(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,hc(t,r)),i&&zt(o.latestValues)&&pn(t,o.latestValues))}e.x<pc&&e.x>fc&&(e.x=1),e.y<pc&&e.y>fc&&(e.y=1)}function fn(t,e){t.min=t.min+e,t.max=t.max+e}function gc(t,e,n,i,s=.5){const o=ve(t.min,t.max,s);Lr(t,e,n,o,i)}function pn(t,e){gc(t.x,e.x,e.scaleX,e.scale,e.originX),gc(t.y,e.y,e.scaleY,e.scale,e.originY)}function mc(t,e){return tc(qg(t.getBoundingClientRect(),e))}function tm(t,e,n){const i=mc(t,n),{scroll:s}=e;return s&&(fn(i.x,s.offset.x),fn(i.y,s.offset.y)),i}const vc=({current:t})=>t?t.ownerDocument.defaultView:null,yc=(t,e)=>Math.abs(t-e);function nm(t,e){const n=yc(t.x,e.x),i=yc(t.y,e.y);return Math.sqrt(n**2+i**2)}class _c{constructor(e,n,{transformPagePoint:i,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=Mr(this.lastMoveEventInfo,this.history),m=this.startEvent!==null,_=nm(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!m&&!_)return;const{point:v}=f,{timestamp:w}=Ee;this.history.push({...v,timestamp:w});const{onStart:y,onMove:C}=this.handlers;m||(y&&y(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,f)},this.handlePointerMove=(f,m)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Pr(m,this.transformPagePoint),ue.update(this.updatePoint,!0)},this.handlePointerUp=(f,m)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Mr(f.type==="pointercancel"?this.lastMoveEventInfo:Pr(m,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,y),v&&v(f,y)},!gr(e))return;this.dragSnapToOrigin=o,this.handlers=n,this.transformPagePoint=i,this.distanceThreshold=r,this.contextWindow=s||window;const a=zn(e),l=Pr(a,this.transformPagePoint),{point:c}=l,{timestamp:d}=Ee;this.history=[{...c,timestamp:d}];const{onSessionStart:u}=n;u&&u(e,Mr(l,this.history)),this.removeListeners=Pn(qn(this.contextWindow,"pointermove",this.handlePointerMove),qn(this.contextWindow,"pointerup",this.handlePointerUp),qn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),At(this.updatePoint)}}function Pr(t,e){return e?{point:e(t.point)}:t}function bc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Mr({point:t},e){return{point:t,delta:bc(t,wc(e)),offset:bc(t,im(e)),velocity:sm(e,.1)}}function im(t){return t[0]}function wc(t){return t[t.length-1]}function sm(t,e){if(t.length<2)return{x:0,y:0};let n=t.length-1,i=null;const s=wc(t);for(;n>=0&&(i=t[n],!(s.timestamp-i.timestamp>at(e)));)n--;if(!i)return{x:0,y:0};const o=lt(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 rm(t,{min:e,max:n},i){return e!==void 0&&t<e?t=i?ve(e,t,i.min):Math.max(t,e):n!==void 0&&t>n&&(t=i?ve(n,t,i.max):Math.min(t,n)),t}function Sc(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 om(t,{top:e,left:n,bottom:i,right:s}){return{x:Sc(t.x,n,s),y:Sc(t.y,e,i)}}function Cc(t,e){let n=e.min-t.min,i=e.max-t.max;return e.max-e.min<t.max-t.min&&([n,i]=[i,n]),{min:n,max:i}}function am(t,e){return{x:Cc(t.x,e.x),y:Cc(t.y,e.y)}}function lm(t,e){let n=.5;const i=Oe(t),s=Oe(e);return s>i?n=Mn(e.min,e.max-i,t.min):i>s&&(n=Mn(t.min,t.max-s,e.min)),_t(0,1,n)}function cm(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 Dr=.35;function dm(t=Dr){return t===!1?t=0:t===!0&&(t=Dr),{x:xc(t,"left","right"),y:xc(t,"top","bottom")}}function xc(t,e,n){return{min:kc(t,e),max:kc(t,n)}}function kc(t,e){return typeof t=="number"?t:t[e]||0}const um=new WeakMap;class hm{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=be(),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=u=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(zn(u).point)},r=(u,f)=>{const{drag:m,dragPropagation:_,onDragStart:v}=this.getProps();if(m&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Tp(m),!this.openDragLock))return;this.latestPointerEvent=u,this.latestPanInfo=f,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ke(y=>{let C=this.getAxisMotionValue(y).get()||0;if(ct.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const T=k.layout.layoutBox[y];T&&(C=Oe(T)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&ue.postRender(()=>v(u,f)),Tr(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f;const{dragPropagation:m,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!m&&!this.openDragLock)return;const{offset:y}=f;if(_&&this.currentDirection===null){this.currentDirection=fm(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",f.point,y),this.updateAxis("y",f.point,y),this.visualElement.render(),w&&w(u,f)},l=(u,f)=>{this.latestPointerEvent=u,this.latestPanInfo=f,this.stop(u,f),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ke(u=>{var f;return this.getAnimationState(u)==="paused"&&((f=this.getAxisMotionValue(u).animation)==null?void 0:f.play())}),{dragSnapToOrigin:d}=this.getProps();this.panSession=new _c(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:d,distanceThreshold:i,contextWindow:vc(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&&ue.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||!Vi(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(r=rm(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&&un(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&i?this.constraints=om(i.layoutBox,e):this.constraints=!1,this.elastic=dm(n),s!==this.constraints&&i&&this.constraints&&!this.hasMutatedConstraints&&Ke(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=cm(i.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:n}=this.getProps();if(!e||!un(e))return!1;const i=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=tm(i,s.root,this.visualElement.getTransformPagePoint());let r=am(s.layout.layoutBox,o);if(n){const a=n(zg(r));this.hasMutatedConstraints=!!a,a&&(r=tc(a))}return r}startAnimation(e){const{drag:n,dragMomentum:i,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ke(d=>{if(!Vi(d,n,this.currentDirection))return;let u=l&&l[d]||{};r&&(u={min:0,max:0});const f=s?200:1e6,m=s?40:1e7,_={type:"inertia",velocity:i?e[d]:0,bounceStiffness:f,bounceDamping:m,timeConstant:750,restDelta:1,restSpeed:10,...o,...u};return this.startAxisValueAnimation(d,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,n){const i=this.getAxisMotionValue(e);return Tr(this.visualElement,e),i.start(Ar(e,i,0,n,this.visualElement,!1))}stopAnimation(){Ke(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Ke(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){Ke(n=>{const{drag:i}=this.getProps();if(!Vi(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]-ve(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:n}=this.getProps(),{projection:i}=this.visualElement;if(!un(n)||!i||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Ke(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=lm({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),Ke(r=>{if(!Vi(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ve(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;um.set(this.visualElement,this);const e=this.visualElement.current,n=qn(e,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),i=()=>{const{dragConstraints:l}=this.getProps();un(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",i);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),ue.read(i);const r=Wn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ke(d=>{const u=this.getAxisMotionValue(d);u&&(this.originPoint[d]+=l[d].translate,u.set(u.get()+l[d].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=Dr,dragMomentum:a=!0}=e;return{...e,drag:n,dragDirectionLock:i,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Vi(t,e,n){return(e===!0||e===t)&&(n===null||n===t)}function fm(t,e=10){let n=null;return Math.abs(t.y)>e?n="y":Math.abs(t.x)>e&&(n="x"),n}class pm extends Rt{constructor(e){super(e),this.removeGroupControls=qe,this.removeListeners=qe,this.controls=new hm(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||qe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Tc=t=>(e,n)=>{t&&ue.postRender(()=>t(e,n))};class gm extends Rt{constructor(){super(...arguments),this.removePointerDownListener=qe}onPointerDown(e){this.session=new _c(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:vc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:n,onPan:i,onPanEnd:s}=this.node.getProps();return{onSessionStart:Tc(e),onStart:Tc(n),onMove:i,onEnd:(o,r)=>{delete this.session,s&&ue.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=qn(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 Bi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Ac(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const Yn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(z.test(t))t=parseFloat(t);else return t;const n=Ac(t,e.target.x),i=Ac(t,e.target.y);return`${n}% ${i}%`}},mm={correct:(t,{treeScale:e,projectionDelta:n})=>{const i=t,s=It.parse(t);if(s.length>5)return i;const o=It.createTransformer(t),r=typeof s[0]!="number"?1:0,a=n.x.scale*e.x,l=n.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=ve(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Ec=!1;class vm extends et{componentDidMount(){const{visualElement:e,layoutGroup:n,switchLayoutGroup:i,layoutId:s}=this.props,{projection:o}=e;tg(ym),o&&(n.group&&n.group.add(o),i&&i.register&&s&&i.register(o),Ec&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Bi.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:n,visualElement:i,drag:s,isPresent:o}=this.props,{projection:r}=i;return r&&(r.isPresent=o,Ec=!0,s||e.layoutDependency!==n||n===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||ue.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),pr.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 Ic(t){const[e,n]=Ll(),i=Te(Is);return R(vm,{...t,layoutGroup:i,switchLayoutGroup:Te(jl),isPresent:e,safeToRemove:n})}const ym={borderRadius:{...Yn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Yn,borderTopRightRadius:Yn,borderBottomLeftRadius:Yn,borderBottomRightRadius:Yn,boxShadow:mm};function _m(t,e,n){const i=Pe(t)?t:cn(t);return i.start(Ar("",i,e,n)),i.animation}const bm=(t,e)=>t.depth-e.depth;class wm{constructor(){this.children=[],this.isDirty=!1}add(e){Ls(this.children,e),this.isDirty=!0}remove(e){Ps(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(bm),this.isDirty=!1,this.children.forEach(e)}}function Sm(t,e){const n=Be.now(),i=({timestamp:s})=>{const o=s-n;o>=e&&(At(i),t(o-e))};return ue.setup(i,!0),()=>At(i)}const Rc=["TopLeft","TopRight","BottomLeft","BottomRight"],Cm=Rc.length,Lc=t=>typeof t=="string"?parseFloat(t):t,Pc=t=>typeof t=="number"||z.test(t);function xm(t,e,n,i,s,o){s?(t.opacity=ve(0,n.opacity??1,km(i)),t.opacityExit=ve(e.opacity??1,0,Tm(i))):o&&(t.opacity=ve(e.opacity??1,n.opacity??1,i));for(let r=0;r<Cm;r++){const a=`border${Rc[r]}Radius`;let l=Mc(e,a),c=Mc(n,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Pc(l)===Pc(c)?(t[a]=Math.max(ve(Lc(l),Lc(c),i),0),(ct.test(c)||ct.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||n.rotate)&&(t.rotate=ve(e.rotate||0,n.rotate||0,i))}function Mc(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const km=Dc(0,.5,Pa),Tm=Dc(.5,.95,qe);function Dc(t,e,n){return i=>i<t?0:i>e?1:n(Mn(t,e,i))}function Oc(t,e){t.min=e.min,t.max=e.max}function Xe(t,e){Oc(t.x,e.x),Oc(t.y,e.y)}function Nc(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Fc(t,e,n,i,s){return t-=e,t=Fi(t,1/n,i),s!==void 0&&(t=Fi(t,1/s,i)),t}function Am(t,e=0,n=1,i=.5,s,o=t,r=t){if(ct.test(e)&&(e=parseFloat(e),e=ve(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ve(o.min,o.max,i);t===o&&(a-=e),t.min=Fc(t.min,e,n,a,s),t.max=Fc(t.max,e,n,a,s)}function Vc(t,e,[n,i,s],o,r){Am(t,e[n],e[i],e[s],e.scale,o,r)}const Em=["x","scaleX","originX"],Im=["y","scaleY","originY"];function Bc(t,e,n,i){Vc(t.x,e,Em,n?n.x:void 0,i?i.x:void 0),Vc(t.y,e,Im,n?n.y:void 0,i?i.y:void 0)}function jc(t){return t.translate===0&&t.scale===1}function Uc(t){return jc(t.x)&&jc(t.y)}function $c(t,e){return t.min===e.min&&t.max===e.max}function Rm(t,e){return $c(t.x,e.x)&&$c(t.y,e.y)}function Hc(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Gc(t,e){return Hc(t.x,e.x)&&Hc(t.y,e.y)}function Wc(t){return Oe(t.x)/Oe(t.y)}function zc(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Lm{constructor(){this.members=[]}add(e){Ls(this.members,e),e.scheduleRender()}remove(e){if(Ps(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 Pm(t,e,n){let i="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(n==null?void 0:n.z)||0;if((s||o||r)&&(i=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(i+=`scale(${1/e.x}, ${1/e.y}) `),n){const{transformPerspective:c,rotate:d,rotateX:u,rotateY:f,skewX:m,skewY:_}=n;c&&(i=`perspective(${c}px) ${i}`),d&&(i+=`rotate(${d}deg) `),u&&(i+=`rotateX(${u}deg) `),f&&(i+=`rotateY(${f}deg) `),m&&(i+=`skewX(${m}deg) `),_&&(i+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(i+=`scale(${a}, ${l})`),i||"none"}const Or=["","X","Y","Z"],Mm=1e3;let Dm=0;function Nr(t,e,n,i){const{latestValues:s}=e;s[t]&&(n[t]=s[t],e.setStaticValue(t,0),i&&(i[t]=0))}function qc(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const n=Yl(e);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",ue,!(s||o))}const{parent:i}=t;i&&!i.hasCheckedOptimisedAppear&&qc(i)}function Kc({attachResizeListener:t,defaultParent:e,measureScroll:n,checkIsScrollRoot:i,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Dm++,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(Fm),this.nodes.forEach(Um),this.nodes.forEach($m),this.nodes.forEach(Vm)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=r,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;l<this.path.length;l++)this.path[l].shouldResetTransform=!0;this.root===this&&(this.nodes=new wm)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Os),this.eventHandlers.get(r).add(a)}notifyListeners(r,...a){const l=this.eventHandlers.get(r);l&&l.notify(...a)}hasListeners(r){return this.eventHandlers.has(r)}mount(r){if(this.instance)return;this.isSVG=Rl(r)&&!Pp(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let d,u=0;const f=()=>this.root.updateBlockedByResize=!1;ue.read(()=>{u=window.innerWidth}),t(r,()=>{const m=window.innerWidth;m!==u&&(u=m,this.root.updateBlockedByResize=!0,d&&d(),d=Sm(f,250),Bi.hasAnimatedSinceResize&&(Bi.hasAnimatedSinceResize=!1,this.nodes.forEach(Jc)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u,hasRelativeLayoutChanged:f,layout:m})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||qm,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!Gc(this.targetLayout,m),C=!u&&f;if(this.options.layoutRoot||this.resumeFrom||C||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...ur(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(d,C)}else u||Jc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=m})}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(),At(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Hm),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&&qc(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;d<this.path.length;d++){const u=this.path[d];u.shouldResetTransform=!0,u.updateScroll("snapshot"),u.options.layoutRoot&&u.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Xc);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Yc);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(jm),this.nodes.forEach(Om),this.nodes.forEach(Nm)):this.nodes.forEach(Yc),this.clearAllSnapshots();const a=Be.now();Ee.delta=_t(0,1e3/60,a-Ee.timestamp),Ee.timestamp=a,Ee.isProcessing=!0,Vs.update.process(Ee),Vs.preRender.process(Ee),Vs.render.process(Ee),Ee.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,pr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Bm),this.sharedNodes.forEach(Gm)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,ue.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){ue.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Oe(this.snapshot.measuredBox.x)&&!Oe(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=be(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=i(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!Uc(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,d=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||zt(this.latestValues)||d)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),Km(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return be();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Xm))){const{scroll:d}=this.root;d&&(fn(a.x,d.offset.x),fn(a.y,d.offset.y))}return a}removeElementScroll(r){var l;const a=be();if(Xe(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const d=this.path[c],{scroll:u,options:f}=d;d!==this.root&&u&&f.layoutScroll&&(u.wasRoot&&Xe(a,r),fn(a.x,u.offset.x),fn(a.y,u.offset.y))}return a}applyTransform(r,a=!1){const l=be();Xe(l,r);for(let c=0;c<this.path.length;c++){const d=this.path[c];!a&&d.options.layoutScroll&&d.scroll&&d!==d.root&&pn(l,{x:-d.scroll.offset.x,y:-d.scroll.offset.y}),zt(d.latestValues)&&pn(l,d.latestValues)}return zt(this.latestValues)&&pn(l,this.latestValues),l}removeTransform(r){const a=be();Xe(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!zt(c.latestValues))continue;Rr(c.latestValues)&&c.updateSnapshot();const d=be(),u=c.measurePageBox();Xe(d,u),Bc(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,d)}return zt(this.latestValues)&&Bc(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!==Ee.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var f;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(f=this.parent)!=null&&f.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:d,layoutId:u}=this.options;if(!(!this.layout||!(d||u))){if(this.resolvedRelativeTargetAt=Ee.timestamp,!this.targetDelta&&!this.relativeTarget){const m=this.getClosestProjectingParent();m&&m.layout&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.layout.layoutBox,m.layout.layoutBox),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=be(),this.targetWithTransforms=be()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Qg(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):Xe(this.target,this.layout.layoutBox),hc(this.target,this.targetDelta)):Xe(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const m=this.getClosestProjectingParent();m&&!!m.resumingFrom==!!this.resumingFrom&&!m.options.layoutScroll&&m.target&&this.animationProgress!==1?(this.relativeParent=m,this.forceRelativeParentToResolveTarget(),this.relativeTarget=be(),this.relativeTargetOrigin=be(),Xn(this.relativeTargetOrigin,this.target,m.target),Xe(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Rr(this.parent.latestValues)||cc(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 _;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(_=this.parent)!=null&&_.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Ee.timestamp&&(l=!1),l)return;const{layout:c,layoutId:d}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||d))return;Xe(this.layoutCorrected,this.layout.layoutBox);const u=this.treeScale.x,f=this.treeScale.y;em(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=be());const{target:m}=r;if(!m){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Nc(this.prevProjectionDelta.x,this.projectionDelta.x),Nc(this.prevProjectionDelta.y,this.projectionDelta.y)),Kn(this.projectionDelta,this.layoutCorrected,m,this.latestValues),(this.treeScale.x!==u||this.treeScale.y!==f||!zc(this.projectionDelta.x,this.prevProjectionDelta.x)||!zc(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",m))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=hn(),this.projectionDelta=hn(),this.projectionDeltaWithTransform=hn()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},d={...this.latestValues},u=hn();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const f=be(),m=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=m!==_,w=this.getStack(),y=!w||w.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(zm));this.animationProgress=0;let k;this.mixTargetDelta=T=>{const E=T/1e3;Zc(u.x,r.x,E),Zc(u.y,r.y,E),this.setTargetDelta(u),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Xn(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Wm(this.relativeTarget,this.relativeTargetOrigin,f,E),k&&Rm(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=be()),Xe(k,this.relativeTarget)),v&&(this.animationValues=d,xm(d,c,this.latestValues,E,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(At(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ue.update(()=>{Bi.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=cn(0)),this.currentAnimation=_m(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:d=>{this.mixTargetDelta(d),r.onUpdate&&r.onUpdate(d)},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(Mm),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&id(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||be();const u=Oe(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+u;const f=Oe(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+f}Xe(a,l),pn(a,d),Kn(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Lm),this.sharedNodes.get(r).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const r=this.getStack();return r?r.lead===this:!0}getLead(){var a;const{layoutId:r}=this.options;return r?((a=this.getStack())==null?void 0:a.lead)||this:this}getPrevLead(){var a;const{layoutId:r}=this.options;return r?(a=this.getStack())==null?void 0:a.prevLead:void 0}getStack(){const{layoutId:r}=this.options;if(r)return this.root.sharedNodes.get(r)}promote({needsReset:r,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),r&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const r=this.getStack();return r?r.relegate(this):!1}resetSkewAndRotation(){const{visualElement:r}=this.options;if(!r)return;let a=!1;const{latestValues:l}=r;if((l.z||l.rotate||l.rotateX||l.rotateY||l.rotateZ||l.skewX||l.skewY)&&(a=!0),!a)return;const c={};l.z&&Nr("z",r,c,this.animationValues);for(let d=0;d<Or.length;d++)Nr(`rotate${Or[d]}`,r,c,this.animationValues),Nr(`skew${Or[d]}`,r,c,this.animationValues);r.render();for(const d in c)r.setStaticValue(d,c[d]),this.animationValues&&(this.animationValues[d]=c[d]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Ni(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Ni(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const d=c.animationValues||c.latestValues;this.applyTransformsToTarget();let u=Pm(this.projectionDeltaWithTransform,this.treeScale,d);l&&(u=l(d,u)),r.transform=u;const{x:f,y:m}=this.projectionDelta;r.transformOrigin=`${f.origin*100}% ${m.origin*100}% 0`,c.animationValues?r.opacity=c===this?d.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:d.opacityExit:r.opacity=c===this?d.opacity!==void 0?d.opacity:"":d.opacityExit!==void 0?d.opacityExit:0;for(const _ in Hn){if(d[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=Hn[_],C=u==="none"?d[_]:v(d[_],c);if(w){const k=w.length;for(let T=0;T<k;T++)r[w[T]]=C}else y?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Ni(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(Xc),this.root.sharedNodes.clear()}}}function Om(t){t.updateLayout()}function Nm(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"?Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(f);f.min=i[u].min,f.max=f.min+m}):id(o,e.layoutBox,i)&&Ke(u=>{const f=r?e.measuredBox[u]:e.layoutBox[u],m=Oe(i[u]);f.max=f.min+m,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[u].max=t.relativeTarget[u].min+m)});const a=hn();Kn(a,i,e.layoutBox);const l=hn();r?Kn(l,t.applyTransform(s,!0),e.measuredBox):Kn(l,i,e.layoutBox);const c=!Uc(a);let d=!1;if(!t.resumeFrom){const u=t.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:f,layout:m}=u;if(f&&m){const _=be();Xn(_,e.layoutBox,f.layoutBox);const v=be();Xn(v,i,m.layoutBox),Gc(_,v)||(d=!0),u.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=u)}}}t.notifyListeners("didUpdate",{layout:i,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:d})}else if(t.isLead()){const{onExitComplete:i}=t.options;i&&i()}t.options.transition=void 0}function Fm(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 Vm(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Bm(t){t.clearSnapshot()}function Xc(t){t.clearMeasurements()}function Yc(t){t.isLayoutDirty=!1}function jm(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Jc(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Um(t){t.resolveTargetDelta()}function $m(t){t.calcProjection()}function Hm(t){t.resetSkewAndRotation()}function Gm(t){t.removeLeadSnapshot()}function Zc(t,e,n){t.translate=ve(e.translate,0,n),t.scale=ve(e.scale,1,n),t.origin=e.origin,t.originPoint=e.originPoint}function Qc(t,e,n,i){t.min=ve(e.min,n.min,i),t.max=ve(e.max,n.max,i)}function Wm(t,e,n,i){Qc(t.x,e.x,n.x,i),Qc(t.y,e.y,n.y,i)}function zm(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const qm={duration:.45,ease:[.4,0,.1,1]},ed=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),td=ed("applewebkit/")&&!ed("chrome/")?Math.round:qe;function nd(t){t.min=td(t.min),t.max=td(t.max)}function Km(t){nd(t.x),nd(t.y)}function id(t,e,n){return t==="position"||t==="preserve-aspect"&&!Zg(Wc(e),Wc(n),.2)}function Xm(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Ym=Kc({attachResizeListener:(t,e)=>Wn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Fr={current:void 0},sd=Kc({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Fr.current){const t=new Ym({});t.mount(window),t.setOptions({layoutScroll:!0}),Fr.current=t}return Fr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Jm={pan:{Feature:gm},drag:{Feature:pm,ProjectionNode:sd,MeasureLayout:Ic}};function rd(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&&ue.postRender(()=>o(e,zn(e)))}class Zm extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Ap(e,(n,i)=>(rd(this.node,i,"Start"),s=>rd(this.node,s,"End"))))}unmount(){}}class Qm extends Rt{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=Pn(Wn(this.node.current,"focus",()=>this.onFocus()),Wn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function od(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&&ue.postRender(()=>o(e,zn(e)))}class ev extends Rt{mount(){const{current:e}=this.node;e&&(this.unmount=Lp(e,(n,i)=>(od(this.node,i,"Start"),(s,{success:o})=>od(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Vr=new WeakMap,Br=new WeakMap,tv=t=>{const e=Vr.get(t.target);e&&e(t)},nv=t=>{t.forEach(tv)};function iv({root:t,...e}){const n=t||document;Br.has(n)||Br.set(n,{});const i=Br.get(n),s=JSON.stringify(e);return i[s]||(i[s]=new IntersectionObserver(nv,{root:t,...e})),i[s]}function sv(t,e,n){const i=iv(e);return Vr.set(t,n),i.observe(t),()=>{Vr.delete(t),i.unobserve(t)}}const rv={some:0,all:1};class ov extends Rt{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:rv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:u}=this.node.getProps(),f=c?d:u;f&&f(l)};return sv(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(av(e,n))&&this.startObserver()}unmount(){}}function av({viewport:t={}},{viewport:e={}}={}){return n=>t[n]!==e[n]}const lv={inView:{Feature:ov},tap:{Feature:ev},focus:{Feature:Qm},hover:{Feature:Zm}},cv={layout:{ProjectionNode:sd,MeasureLayout:Ic}},jr={current:null},ad={current:!1};function dv(){if(ad.current=!0,!!Rs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>jr.current=t.matches;t.addEventListener("change",e),e()}else jr.current=!1}const uv=new WeakMap;function hv(t,e,n){for(const i in e){const s=e[i],o=n[i];if(Pe(s))t.addValue(i,s);else if(Pe(o))t.addValue(i,cn(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,cn(r!==void 0?r:s,{owner:t}))}}for(const i in n)e[i]===void 0&&t.removeValue(i);return e}const ld=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class fv{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=cr,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Be.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,ue.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=n.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=n,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=Oi(n),this.isVariantNode=Fl(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:d,...u}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in u){const m=u[f];l[f]!==void 0&&Pe(m)&&m.set(l[f],!1)}}mount(e){this.current=e,uv.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)),ad.current||dv(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:jr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),At(this.notifyUpdate),At(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const n=this.features[e];n&&(n.unmount(),n.isMounted=!1)}this.current=null}bindToMotionValue(e,n){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const i=ln.has(e);i&&this.onBindTransform&&this.onBindTransform();const s=n.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&ue.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 dn){const n=dn[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):be()}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<ld.length;i++){const s=ld[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=hv(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=cn(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"&&(Sa(i)||xa(i))?i=parseFloat(i):!Dp(i)&&It.test(n)&&(i=wl(e,n)),this.setBaseTarget(e,Pe(i)?i.get():i)),Pe(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=Cr(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&&!Pe(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 Os),this.events[e].add(n)}notify(e,...n){this.events[e]&&this.events[e].notify(...n)}}class cd extends fv{constructor(){super(...arguments),this.KeyframeResolver=Sp}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;Pe(e)&&(this.childSubscription=e.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}function dd(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 pv(t){return window.getComputedStyle(t)}class gv extends cd{constructor(){super(...arguments),this.type="html",this.renderInstance=dd}readValueFromInstance(e,n){var i;if(ln.has(n))return(i=this.projection)!=null&&i.isProjecting?sr(n):$f(e,n);{const s=pv(e),o=(Bs(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:n}){return mc(e,n)}build(e,n,i){br(e,n,i.transformTemplate)}scrapeMotionValuesFromProps(e,n,i){return xr(e,n,i)}}const ud=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 mv(t,e,n,i){dd(t,e,void 0,i);for(const s in e.attrs)t.setAttribute(ud.has(s)?s:_r(s),e.attrs[s])}class vv extends cd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=be}getBaseTargetFromProps(e,n){return e[n]}readValueFromInstance(e,n){if(ln.has(n)){const i=bl(n);return i&&i.default||0}return n=ud.has(n)?n:_r(n),e.getAttribute(n)}scrapeMotionValuesFromProps(e,n,i){return Xl(e,n,i)}build(e,n,i){Gl(e,n,this.isSVGTag,i.transformTemplate,i.style)}renderInstance(e,n,i,s){mv(e,n,i,s)}mount(e){this.isSVGTag=zl(e.tagName),super.mount(e)}}const yv=(t,e)=>Sr(t)?new vv(e):new gv(e,{allowProjection:t!==rt}),_v=yg({...Gg,...lv,...Jm,...cv},yv),gn=Gp(_v),bv=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region"],Jn="widget-layout-id";function hd(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=hd(t[e]))&&(i&&(i+=" "),i+=n)}else for(n in t)t[n]&&(i&&(i+=" "),i+=n);return i}function wt(){for(var t,e,n=0,i="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=hd(t))&&(i&&(i+=" "),i+=e);return i}const wv=_i("listening"),Ur=()=>ba(wv);function Sv(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 ji={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},fd=_i(ji),Cv=()=>{const t=wi(fd);return yt(e=>t(()=>{const n={...e};return n.start_call_text||(n.start_call_text=ji.start_call_text),n.agent_thinking_text||(n.agent_thinking_text=ji.agent_thinking_text),n.speak_to_interrupt_text||(n.speak_to_interrupt_text=ji.speak_to_interrupt_text),n}),[t])},qt=()=>Es(fd),pd=({size:t="large",className:e})=>{const n=qt(),[i]=Ur();return R("h1",{className:wt({"text-xs":t==="small"},e),children:i==="speaking"?n.speak_to_interrupt_text:i==="listening"?"":i==="processing_image"?"Processing image...":n.agent_thinking_text})},gd=({stream:t,chatMode:e})=>{const n=me(null);return ke(()=>{!n.current||!t||(n.current.srcObject=t)},[t]),e?null:R("audio",{muted:!0,ref:n,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const Cv="4.5.1",Ur=Math.PI,mn=2*Ur,$r=Ur/2,md=8.17579892,vd="dual-combined",Bi="dual-horizontal",St="single",dt="dual-vertical",yd="bar-index",_d="bar-level",ji="gradient",bd=60,wd="click",xv="fullscreenchange",Sd="resize",kv="#111",Cd="",xd="A",kd="B",Td="C",Ed="D",Ad="468",Ui="sans-serif",Tv="#0f0",Ev="#7f7f7f22",vn=10,Id="create",Rd="fschange",Av="lores",Iv=Sd,Hr="user",Rv="#000c",Ld="#fff",Lv="#4f4",Pd="#888",Pv="#555",Gr="bark",Zn="linear",yn="log",Wr="mel",Md=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Dd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Md}],["rainbow",{dir:"h",colorStops:["#817",...Md,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Qn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:St,colorMode:ji,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:yn,gradient:Dd[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:Cd,width:void 0},Mv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],Dv=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Ov=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],zr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Nv=["ERR_INVALID_MODE","Invalid mode"],Fv=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Vv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Bv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],jv=["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 Ye extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Od=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Nd=t=>{for(const e in t)return!1;return!0},$i=(t,e,n="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[n]()))],$v=(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 Hv{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||(Nd(n)&&!Nd(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[u,f]of Dd)this.registerGradient(u,f);this._container=e||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Ye(Mv)}}if(!s.createGain)throw new Ye(Dv);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 u of[0,1])r.connect(o[u],u);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const u of["_scaleX","_scaleR"])this[u]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Iv),this._fsTimeout=0)},bd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Sd,l,{signal:c}),i.addEventListener(xv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Rd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},bd)},{signal:c});const d=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(wd,d))};window.addEventListener(wd,d),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Id)}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=$i(e,[St,Bi,dt,vd]),this._input.disconnect(),this._input.connect(this._chLayout!=St?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=St?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=$i(e,[ji,yd,_d])}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=$i(e,[yn,Gr,Wr,Zn]),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||Qn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Hr)}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(Av)}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 Ye(zr);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 Ye(zr);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 Ye(Nv,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||Qn.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 Ye(Fv);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=-$r),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Od("stereo","channelLayout"),this._chLayout!=St}set stereo(e){Od("stereo","channelLayout"),this.channelLayout=e?dt:St}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=$i(e,[Cd,xd,kd,Td,Ed,Ad],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Hr)}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 Cv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ye(Vv);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==St&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const o of i.mediaStream.getAudioTracks())o.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==St?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Qn))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 Ye(Bv);if(typeof n!="object")throw new Ye(jv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ye(Uv);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||kv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Hr)}setFreqRange(e,n){if(e<1||n<1)throw new Ye(zr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:d,_radialInvert:u,_reflexRatio:f}=this,m=s.width>>1,_=s.height>>1,v=o==dt&&!d,w=o==Bi,y=c%10!=0,C=y&&this._frequencyScale==yn,k=this._showLeds&&y&&!d,E=this._lumiBars&&y&&!d,R=this._alphaBars&&!E&&c!=vn,O=this._outlineBars&&y&&!E&&!k,S=this._roundBars&&y&&!E&&!k,x=o!=dt||f>0&&!E,p=s.height-(v&&!k?.5:0)>>v,g=p*(E||d?1:1-f)|0,h=s.width-m*(w||l!=0),b=v?s.height-p*2:0,A=m*(l==-1&&!w&&!d);let P=Math.min(s.width,s.height)*.375*(o==dt?1:this._radius)|0,L=Math.min(m,_);u&&o!=dt&&([P,L]=[L,P]);const D=U=>e.push({...U,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=U=>{const q=this._freqToBin(U,"floor"),J=this._binToFreq(q),ne=this._binToFreq(q+1),he=Math.log2(U/J)/Math.log2(ne/J);return[q,he]};let N,W,j;if(C){const U=(oe,pe,se)=>+oe.toPrecision(se?Math.max(pe,1+Math.log10(oe)|0):pe),q=oe=>{const pe=[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],se=Math.log10(oe)|0,ft=oe/10**se;let nt=1;for(;nt<pe.length&&ft>pe[nt];)nt++;return ft-pe[nt-1]<pe[nt]-ft&&nt--,(pe[nt]*10**(se+5)|0)/1e5},J=[0,24,12,8,6,4,3,2,1][c],ne=n?10**(3/(J*10)):2**(1/J),he=ne**.5;let Fe=n?7.94328235/(J%2?1:he):md;do{let oe=Fe;const pe=U(oe/he,4,!0),se=U(oe*he,4,!0),[ft,nt]=M(pe),[li,pt]=M(se);n?oe=J<4?q(oe):U(oe,oe.toString()[0]<5?3:2):oe=U(oe,4,!0),oe>=a&&D({posX:0,freq:oe,freqLo:pe,freqHi:se,binLo:ft,binHi:li,ratioLo:nt,ratioHi:pt}),Fe*=ne}while(Fe<=r);N=h/e.length,e.forEach((oe,pe)=>oe.posX=A+pe*N);const fe=e[0],De=e[e.length-1];W=this._freqScaling(fe.freqLo),j=h/(this._freqScaling(De.freqHi)-W),fe.freqLo<a&&(fe.freqLo=a,[fe.binLo,fe.ratioLo]=M(a)),De.freqHi>r&&(De.freqHi=r,[De.binHi,De.ratioHi]=M(r))}else if(y){const U=[0,24,12,8,6,4,3,2,1][c]*10,q=J=>{switch(this._frequencyScale){case Gr:return 1960/(26.81/(J+.53)-1);case Wr:return 700*(2**J-1);case Zn:return J}};N=h/U,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);for(let J=0,ne=0;J<U;J++,ne+=N){const he=q(W+ne/j),Fe=q(W+(ne+N/2)/j),fe=q(W+(ne+N)/j),[De,oe]=M(he),[pe,se]=M(fe);D({posX:A+ne,freq:Fe,freqLo:he,freqHi:fe,binLo:De,binHi:pe,ratioLo:oe,ratioHi:se})}}else{N=1,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);const U=this._freqToBin(a,"floor"),q=this._freqToBin(r);let J=-999;for(let ne=U;ne<=q;ne++){const he=this._binToFreq(ne),Fe=A+Math.round(j*(this._freqScaling(he)-W));if(Fe>J)D({posX:Fe,freq:he,freqLo:he,freqHi:he,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),J=Fe;else if(e.length){const fe=e[e.length-1];fe.binHi=ne,fe.freqHi=he,fe.freq=(fe.freqLo*he)**.5}}}let re=0,te=0;if(k){const U=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),q=[[],[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,[ne,he,Fe]=J||q[c];let fe,De=g;if(J){const oe=2*U;let pe;fe=ne+1;do fe--,pe=De/fe/(1+he),te=pe*he;while((pe<oe||te<oe)&&fe>1)}else{const oe=540/he;te=Math.min(he*U,Math.max(2,De/oe+.1|0))}x&&(De+=te),J||(fe=Math.min(ne,De/(te*2)|0)),re=Fe>=1?Fe:N*Fe,this._leds=[fe,re,te,De/fe-te]}const $=Math.min(N-1,i*(i>0&&i<1?N:1));y&&(N-=Math.max(k?re:0,$)),e.forEach((U,q)=>{let J=U.posX,ne=N;y&&(i==0&&!k?(J|=0,ne|=0,q>0&&J>e[q-1].posX+e[q-1].width&&(J--,ne++)):J+=Math.max(k?re:0,$)/2,U.posX=J),U.barCenter=J+(N==1?0:ne/2),U.width=ne});const ae=[];for(const U of[0,1]){const q=o==dt?(p+b)*U:0,J=q+p,ne=q+g-(!k||x?0:te);ae.push({channelTop:q,channelBottom:J,analyzerBottom:ne})}this._aux={analyzerHeight:g,analyzerWidth:h,centerX:m,centerY:_,channelCoords:ae,channelHeight:p,channelGap:b,initialX:A,innerRadius:P,outerRadius:L,scaleMin:W,unitWidth:j},this._flg={isAlpha:R,isBands:y,isLeds:k,isLumi:E,isOctaves:C,isOutline:O,isRound:S,noLedGap:x},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:f}=this,m=u.canvas,_=f.canvas,v=[],w=this._chLayout==Bi,y=this._chLayout==dt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],E=C/34|0,R=m.height>>1,O=E>>1,S=R*(c?.7:1.5),x=O*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=yn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Zn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let L=md;for(let D=-1;D<11;D++)for(let M=0;M<12;M++){if(L>=this._minFreq&&L<=this._maxFreq){const N=k[M],W=N=="C";(N&&c&&!l&&!w||W)&&v.push(c?[L,N+(W?D:"")]:L)}L*=p}}_.width=_.height=Math.max(C*.15,(i<<1)+y*E);const g=_.width>>1,h=g-E*.7,b=(L,D)=>{const M=mn*(L/r.width),N=M-$r,W=h*Math.cos(N),j=h*Math.sin(N);f.save(),f.translate(g+W,g+j),f.rotate(M),f.fillText(D,0,0),f.restore()};m.width|=0,u.fillStyle=f.strokeStyle=Rv,u.fillRect(0,0,m.width,m.height),f.arc(g,g,g-E/2,0,mn),f.lineWidth=E,f.stroke(),u.fillStyle=f.fillStyle=Ld,u.font=`${R}px ${Ui}`,f.font=`${O}px ${Ui}`,u.textAlign=f.textAlign="center";let A=-S/4,P=-x;for(const L of v){const[D,M]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],N=o*(this._freqScaling(D)-s),W=m.height*.75,j=M[0]=="C",re=R*(c&&!l&&!w?j?1.2:.6:3);if(u.fillStyle=f.fillStyle=j&&!l&&!w?Lv:Ld,c){const te=a==yn,$=a==Zn;let ae=["C"];if((te||D>2e3||!$&&D>250||(!d||y)&&(!$&&D>125||D>1e3))&&ae.push("G"),(te||D>4e3||!$&&D>500||(!d||y)&&(!$&&D>250||D>2e3))&&ae.push("E"),($&&D>4e3||(!d||y)&&(te||D>2e3||!$&&D>500))&&ae.push("D","F","A","B"),!ae.includes(M[0]))continue}N>=A+S/2&&N<=e&&(u.fillText(M,w&&l==-1?e-N:n+N,W,re),(w||l&&(N>S||l==1))&&u.fillText(M,w&&l!=1?e+N:(n||r.width)-N,W,re),A=N+Math.min(re,u.measureText(M).width)/2),N>=P+x&&N<e-x&&(b(w&&l==1?e-N:N,M),(w||l&&(N>x||l==1))&&b(w&&l!=-1?e+N:-N,M),P=N)}}_draw(e){this._runId=requestAnimationFrame(F=>this._draw(F));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:d,isRound:u,noLedGap:f}=this._flg,{analyzerHeight:m,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:C,initialX:k,innerRadius:E,outerRadius:R}=this._aux,{_bars:O,canvas:S,_canvasGradients:x,_chLayout:p,_colorMode:g,_ctx:h,_energy:b,_fadePeaks:A,fillAlpha:P,_fps:L,_linearAmplitude:D,_lineWidth:M,maxDecibels:N,minDecibels:W,_mirror:j,_mode:re,overlay:te,_radial:$,showBgColor:ae,showPeaks:U,useCanvas:q,_weightingFilter:J}=this,ne=this._scaleX.canvas,he=this._scaleR.canvas,Fe=L*this._peakFadeTime/1e3,fe=L**2,De=this._gravity*1e3,oe=L*this._peakHoldTime/1e3,pe=p==vd,se=p==Bi,ft=p==dt,nt=p==St,li=a&&this._trueLeds&&g==ji,pt=$?S.width:this._aux.analyzerWidth,oo=k+pt,ci=U&&this._peakLine&&re==vn,Mt=$?R-E:m,Z_=Mt/this._pixelRatio,[Q_,c0,di,ao]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*mn/60/L);const e0=F=>{if(this._reflexRatio>0&&!l&&!$){let ie,gt;this.reflexFit||ft?(ie=ft&&F==0?y+C:0,gt=y-m):(ie=S.height-m*2,gt=m),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[F].channelTop,S.width,m,0,ie,S.width,gt),h.restore()}},t0=()=>{this.showScaleX&&($?(h.save(),h.translate(_,v),this._spinSpeed&&h.rotate(this._spinAngle+$r),h.drawImage(he,-he.width>>1,-he.width>>1),h.restore()):h.drawImage(ne,0,S.height-ne.height))},n0=F=>{const ie=F**2,gt=424.36,Le=11599.29,ns=25122.25,Dt=544496.41,kt=148693636,Jt=Zt=>20*Math.log10(Zt);switch(J){case xd:const Zt=kt*ie**2/((ie+gt)*Math.sqrt((ie+Le)*(ie+Dt))*(ie+kt));return 2+Jt(Zt);case kd:const Qt=kt*ie*F/((ie+gt)*Math.sqrt(ie+ns)*(ie+kt));return .17+Jt(Qt);case Td:const uo=kt*ie/((ie+gt)*(ie+kt));return .06+Jt(uo);case Ed:const is=((103791848e-2-ie)**2+108076816e-2*ie)/((9837328-ie)**2+11723776*ie),ho=F/68966888496476e-18*Math.sqrt(is/((ie+79919.29)*(ie+1345600)));return Jt(ho);case Ad:const ss=-4737338981378384e-39*F**6+2043828333606125e-30*F**4-1363894795463638e-22*ie+1,en=1306612257412824e-34*F**5-2118150887518656e-26*F**3+.0005559488023498642*F,Ge=.0001246332637532143*F/Math.hypot(ss,en);return 18.2+Jt(Ge)}return 0},lo=(F,ie,gt)=>{h.beginPath(),h.moveTo(F,ie),h.lineTo(F,gt),h.stroke()},co=F=>{if(F&&M){const ie=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ie}},Yt=F=>Math.max(0,(F*Q_|0)*(ao+di)-di),i0=F=>{b.val=F,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*De/fe/S.height*this._pixelRatio)),F>=b.peak&&(b.peak=F,b.hold=oe)};te&&h.clearRect(0,0,S.width,S.height);let Gu=0;const Wu=O.length,zu=nt?1:2;for(let F=0;F<zu;F++){const{channelTop:ie,channelBottom:gt,analyzerBottom:Le}=w[F],ns=this._gradients[this._selectedGrads[F]],Dt=ns.colorStops,kt=Dt.length,Jt=!ae||a&&!te?"#000":ns.bgColor,Zt=ft&&$&&F?-1:1,Qt=!F&&j==-1||F&&j==1,uo=!se||F&&j!=1?0:pt>>(F||!Qt),is=se&&Qt?-1:1,ho=()=>{const H=ne.height,K=H>>1,Z=D?100:N,de=D?0:W,Se=D?20:5,$e=m/(Z-de),mt=j!=-1&&(!se||F==0||j==1),Ot=j!=1&&(!se||F!=j);h.save(),h.fillStyle=Pd,h.font=`${K}px ${Ui}`,h.textAlign="right",h.lineWidth=1;for(let Nt=Z;Nt>de;Nt-=Se){const xn=ie+(Z-Nt)*$e,Ee=Nt%2==0|0;if(Ee){const Ve=xn+K*(xn==ie?.8:.35);mt&&h.fillText(Nt,H*.85,Ve),Ot&&h.fillText(Nt,(se?pt:S.width)-H*.1,Ve),h.strokeStyle=Pd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=Pv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(k+H*Ee*mt,~~xn+.5),h.lineTo(oo-H*Ee*Ot,~~xn+.5),h.stroke()}h.restore()},ss=(H,K)=>{const Z=it[H]+(H<it.length-1?(it[H+1]-it[H])*K:0);return isNaN(Z)?-1/0:Z},en=(H,K=is)=>K*mn*((H+uo)/S.width)+this._spinAngle,Ge=(H,K,Z)=>{const de=E+K*Zt,Se=en(H,Z);return[_+de*Math.cos(Se),v+de*Math.sin(Se)]},fo=(H,K,Z,de,Se)=>{h.beginPath();for(const $e of j&&!se?[1,-1]:[is]){const[mt,Ot]=u?[en(H,$e),en(H+Z,$e)]:[];h.moveTo(...Ge(H,K,$e)),h.lineTo(...Ge(H,K+de,$e)),u?h.arc(_,v,E+(K+de)*Zt,mt,Ot,$e!=1):h.lineTo(...Ge(H+Z,K+de,$e)),h.lineTo(...Ge(H+Z,K,$e)),u&&!Se&&h.arc(_,v,E+K*Zt,Ot,mt,$e==1)}co(Se),h.fill()},po=(H=0,K=0)=>{let Z;if(g==ji&&!li||re==vn)Z=x[F];else{const de=g==yd?K%kt:Dt.findLastIndex(Se=>a?Yt(H)<=Yt(Se.level):H<=Se.level);Z=Dt[de].color}h.fillStyle=h.strokeStyle=Z};if(q){if(se&&!$){const H=pt*(F+Qt),K=Qt?-1:1;h.setTransform(K,0,0,1,H,0)}if((!te||ae)&&(te&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Jt,(F==0||!$&&!pe)&&h.fillRect(k,ie-C,pt,(te&&this.reflexAlpha==1?m:y)+C),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(F==0||!pe)&&ho(),a?(h.setLineDash([ao,di]),h.lineWidth=O[0].width):h.lineWidth=d?Math.min(M,O[0].width/2):M,h.save(),!$){const H=new Path2D;H.rect(0,ie,S.width,m),h.clip(H)}}let it=this._fftData[F];this._analyzer[F].getFloatFrequencyData(it),J&&(it=it.map((H,K)=>H+n0(this._binToFreq(K)))),h.beginPath();let ui=[];for(let H=0;H<Wu;H++){const K=O[H],{posX:Z,barCenter:de,width:Se,freq:$e,binLo:mt,binHi:Ot,ratioLo:Nt,ratioHi:xn}=K;let Ee=Math.max(ss(mt,Nt),ss(Ot,xn));for(let le=mt+1;le<Ot;le++)it[le]>Ee&&(Ee=it[le]);if(Ee=this._normalizedB(Ee),K.value[F]=Ee,Gu+=Ee,K.peak[F]>0&&K.alpha[F]>0&&(K.hold[F]--,K.hold[F]<0)){if(A&&!ci){const le=!o||d&&M>0?1:o?K.peak[F]:P;K.alpha[F]=le*(1+K.hold[F]/Fe)}else K.peak[F]+=K.hold[F]*De/fe/Z_;K.alpha[F]<=0&&(K.peak[F]=0)}if(Ee>=K.peak[F]&&(K.peak[F]=Ee,K.hold[F]=oe,K.alpha[F]=!o||d&&M>0?1:o?Ee:P),!q)continue;h.globalAlpha=l||o?Ee:d?P:1,po(Ee,H);const Ve=l?Mt:a?Yt(Ee):Ee*Mt|0;if(re==vn){const le=H?0:(this._normalizedB(it[O[1].binLo])*Mt+Ve)/2;if($){if(H==0&&(se&&h.moveTo(...Ge(0,0)),h.lineTo(...Ge(0,Z<0?le:Ve))),Z>=0){const Ze=[Z,Ve];h.lineTo(...Ge(...Ze)),ui.push(Ze)}}else{if(H==0)if(j==-1&&!se)h.moveTo(k,Le-(Z<k?le:Ve));else{const Ze=mt?this._normalizedB(it[mt-1])*Mt:Ve;h.moveTo(k-M,Le-Ze)}(se||j!=-1||Z>=k)&&h.lineTo(Z,Le-Ve)}}else if(a){if(ae&&!te&&(F==0||!pe)){const le=h.globalAlpha;h.strokeStyle=Ev,h.globalAlpha=1,lo(de,ie,Le),h.strokeStyle=h.fillStyle,h.globalAlpha=le}if(li){const le=l?0:Dt.findLastIndex(tn=>Yt(Ee)<=Yt(tn.level));let Ze=Le;for(let tn=kt-1;tn>=le;tn--){h.strokeStyle=Dt[tn].color;let Ku=Le-(tn==le?Ve:Yt(Dt[tn].level));lo(de,Ze,Ku),Ze=Ku-di}}else lo(de,Le,Le-Ve)}else if(Z>=k)if($)fo(Z,0,Se,Ve,d);else if(u){const le=Se/2,Ze=Le+le;h.beginPath(),h.moveTo(Z,Ze),h.lineTo(Z,Ze-Ve),h.arc(de,Ze-Ve,le,Ur,mn),h.lineTo(Z+Se,Ze),co(d),h.fill()}else{const le=d?h.lineWidth:0;h.beginPath(),h.rect(Z,Le+le,Se,-Ve-le),co(d),h.fill()}const kn=K.peak[F],qu=K.alpha[F];if(kn>0&&qu>0&&U&&!ci&&!l&&Z>=k&&Z<oo){if(A?h.globalAlpha=qu:d&&M>0?h.globalAlpha=1:o&&(h.globalAlpha=kn),(g==_d||li)&&po(kn),a){const le=Yt(kn);le>=di&&h.fillRect(Z,Le-le,Se,ao)}else if(!$)h.fillRect(Z,Le-kn*Mt,Se,2);else if(re!=vn){const le=kn*Mt;fo(Z,le,Se,!this._radialInvert||ft||le+E>=2?-2:2)}}}if(q){if(h.globalAlpha=1,re==vn){if(po(),$&&!se){if(j){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1))}h.closePath()}if(M>0&&h.stroke(),P>0){if($){const H=se?en(pt>>1):0,K=se?en(pt):mn;h.moveTo(...Ge(se?pt>>1:0,0)),h.arc(_,v,E,H,K,se?!Qt:!0)}else h.lineTo(oo,Le),h.lineTo(k,Le);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((ci||$&&U)&&(ui=[],h.beginPath(),O.forEach((H,K)=>{let Z=H.posX,de=H.peak[F],Se=K?"lineTo":"moveTo";if($&&Z<0){const $e=O[K+1];de=$v(Z,de,$e.posX,$e.peak[F],0),Z=0}de*=Mt,ci?(h[Se](...$?Ge(Z,de):[Z,Le-de]),$&&j&&!se&&ui.push([Z,de])):de>0&&fo(Z,de,1,-2)}),ci)){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1));h.lineWidth=1,h.stroke()}}h.restore(),se&&!$&&h.setTransform(1,0,0,1,0,0),(!se&&!pe||F)&&e0(F)}}if(i0(Gu/(Wu<<zu-1)),q&&(j&&!$&&!se&&(h.setTransform(-1,0,0,1,S.width-k,0),h.drawImage(S,k,0,_,S.height,0,0,_,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),t0()),this.showFPS){const F=ne.height;h.font=`bold ${F}px ${Ui}`,h.fillStyle=Tv,h.textAlign="right",h.fillText(Math.round(L),S.width-F,F*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=x[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:x}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case yn:return Math.log2(e);case Gr:return 26.81*e/(1960+e)-.53;case Wr:return Math.log2(1+e/700);case Zn:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:d}=this._aux,{isLumi:u}=this._flg,f=this._chLayout==dt,m=1-s,_=u?e.height:e.height*(1-s*!f)|0;for(const v of[0,1]){const w=this._gradients[this._selectedGrads[v]],y=w.colorStops,C=w.dir=="h";let k;if(i?k=n.createRadialGradient(r,a,d,r,a,c-(d-c)*f):k=n.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),y){const E=f&&!this._splitGradient&&(!C||i);for(let R=0;R<1+E;R++){const O=y.length-1;y.forEach((S,x)=>{let p=S.pos;if(E&&(p/=2),f&&!u&&!i&&!C&&(p*=m,!E&&p>.5*m&&(p+=.5*s)),R==1)if(i||u){const g=O-x;S=y[g],p=1-S.pos/2}else x==0&&p>0&&k.addColorStop(.5,S.color),p+=.5;k.addColorStop(p,S.color),f&&x==O&&p<.5&&k.addColorStop(.5,S.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,d)=>l<=c?c:l>=d?d:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==n,d=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,u=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Id&&n.width==d&&n.height==u)&&(n.width=d,n.height=u,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,d,u)),i.lineJoin="bevel",s.width=d,s.height=Math.max(20*o,Math.min(d,u)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Rd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Ye(Ov,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(Qn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Qn,...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 Gv={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}]}},Fd=({stream:t,className:e,onClick:n})=>{var o;const i=me(null),s=Wt();return xe(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Hv(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",Gv[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),I("div",{onClick:n,className:wt("w-full",e),ref:i})};/**
16
+ */const xv="4.5.1",$r=Math.PI,mn=2*$r,Hr=$r/2,md=8.17579892,vd="dual-combined",Ui="dual-horizontal",St="single",dt="dual-vertical",yd="bar-index",_d="bar-level",$i="gradient",bd=60,wd="click",kv="fullscreenchange",Sd="resize",Tv="#111",Cd="",xd="A",kd="B",Td="C",Ad="D",Ed="468",Hi="sans-serif",Av="#0f0",Ev="#7f7f7f22",vn=10,Id="create",Rd="fschange",Iv="lores",Rv=Sd,Gr="user",Lv="#000c",Ld="#fff",Pv="#4f4",Pd="#888",Mv="#555",Wr="bark",Zn="linear",yn="log",zr="mel",Md=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Dd=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Md}],["rainbow",{dir:"h",colorStops:["#817",...Md,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],Qn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:St,colorMode:$i,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:yn,gradient:Dd[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:Cd,width:void 0},Dv=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],Ov=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Nv=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],qr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Fv=["ERR_INVALID_MODE","Invalid mode"],Vv=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Bv=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],jv=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Uv=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],$v=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class Ye extends Error{constructor(e,n){const[i,s]=e;super(s+(n!==void 0?`: ${n}`:"")),this.name="AudioMotionError",this.code=i}}const Od=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Nd=t=>{for(const e in t)return!1;return!0},Gi=(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 Gv{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||(Nd(n)&&!Nd(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[u,f]of Dd)this.registerGradient(u,f);this._container=e||!this._ownCanvas&&i.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(n.source&&(s=n.source.context))){if(!(s=n.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new Ye(Dv)}}if(!s.createGain)throw new Ye(Ov);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 u of[0,1])r.connect(o[u],u);a.connect(this._output),n.connectSpeakers!==!1&&this.connectOutput();for(const u of["_scaleX","_scaleR"])this[u]=document.createElement("canvas").getContext("2d");this._fsEl=n.fsElement||i;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(Rv),this._fsTimeout=0)},bd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Sd,l,{signal:c}),i.addEventListener(kv,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Rd),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},bd)},{signal:c});const d=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(wd,d))};window.addEventListener(wd,d),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(n,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(i),this._ready=!0,this._setCanvas(Id)}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=Gi(e,[St,Ui,dt,vd]),this._input.disconnect(),this._input.connect(this._chLayout!=St?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=St?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=Gi(e,[$i,yd,_d])}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=Gi(e,[yn,Wr,zr,Zn]),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||Qn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Gr)}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(Iv)}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 Ye(qr);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 Ye(qr);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 Ye(Fv,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||Qn.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 Ye(Vv);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=-Hr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Od("stereo","channelLayout"),this._chLayout!=St}set stereo(e){Od("stereo","channelLayout"),this.channelLayout=e?dt:St}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=Gi(e,[Cd,xd,kd,Td,Ad,Ed],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Gr)}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 xv}connectInput(e){const n=e instanceof HTMLMediaElement;if(!(n||e.connect))throw new Ye(Bv);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==St&&!n?this._output:this._merger,0,n)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:n,_controller:i,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),i.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&n.remove(),this._calcBars()}disconnectInput(e,n){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const i of e){const s=this._sources.indexOf(i);if(n&&i.mediaStream)for(const o of i.mediaStream.getAudioTracks())o.stop();s>=0&&(i.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(n=>n!==e):[],this._outNodes.length==0))for(const n of[0,1])this._analyzer[n].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:n,freqLo:i,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,n){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,n]=a[e]}const i=this._freqToBin(e),s=n?this._freqToBin(n):i,o=this._chLayout==St?1:2;let r=0;for(let a=0;a<o;a++)for(let l=i;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-i+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let n={};for(const i of Object.keys(Qn))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 Ye(jv);if(typeof n!="object")throw new Ye(Uv);const{colorStops:i}=n;if(!Array.isArray(i)||!i.length)throw new Ye($v);const s=i.length,o=r=>+r!=r||r<0||r>1;i.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?i[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(i[a].level=1-a/s)}),i.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),i[0].level=1,this._gradients[e]={bgColor:n.bgColor||Tv,dir:n.dir,colorStops:i},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,n){this._width=e,this._height=n,this._setCanvas(Gr)}setFreqRange(e,n){if(e<1||n<1)throw new Ye(qr);this._minFreq=Math.min(e,n),this.maxFreq=Math.max(e,n)}setLedParams(e){let n,i,s;e&&(n=e.maxLeds|0,i=+e.spaceV,s=+e.spaceH),this._ledParams=n>0&&i>0&&s>=0?[n,i,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,n){for(const i of[0,1])this._analyzer[i].minDecibels=Math.min(e,n),this._analyzer[i].maxDecibels=Math.max(e,n)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const n=this.isOn;return e===void 0&&(e=!n),n&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!n&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(i=>this._draw(i))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:n,_barSpace:i,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:d,_radialInvert:u,_reflexRatio:f}=this,m=s.width>>1,_=s.height>>1,v=o==dt&&!d,w=o==Ui,y=c%10!=0,C=y&&this._frequencyScale==yn,k=this._showLeds&&y&&!d,T=this._lumiBars&&y&&!d,E=this._alphaBars&&!T&&c!=vn,D=this._outlineBars&&y&&!T&&!k,S=this._roundBars&&y&&!T&&!k,x=o!=dt||f>0&&!T,p=s.height-(v&&!k?.5:0)>>v,g=p*(T||d?1:1-f)|0,h=s.width-m*(w||l!=0),b=v?s.height-p*2:0,I=m*(l==-1&&!w&&!d);let P=Math.min(s.width,s.height)*.375*(o==dt?1:this._radius)|0,L=Math.min(m,_);u&&o!=dt&&([P,L]=[L,P]);const O=U=>e.push({...U,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=U=>{const q=this._freqToBin(U,"floor"),Z=this._binToFreq(q),ne=this._binToFreq(q+1),he=Math.log2(U/Z)/Math.log2(ne/Z);return[q,he]};let N,W,j;if(C){const U=(oe,pe,se)=>+oe.toPrecision(se?Math.max(pe,1+Math.log10(oe)|0):pe),q=oe=>{const pe=[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],se=Math.log10(oe)|0,ft=oe/10**se;let nt=1;for(;nt<pe.length&&ft>pe[nt];)nt++;return ft-pe[nt-1]<pe[nt]-ft&&nt--,(pe[nt]*10**(se+5)|0)/1e5},Z=[0,24,12,8,6,4,3,2,1][c],ne=n?10**(3/(Z*10)):2**(1/Z),he=ne**.5;let Fe=n?7.94328235/(Z%2?1:he):md;do{let oe=Fe;const pe=U(oe/he,4,!0),se=U(oe*he,4,!0),[ft,nt]=M(pe),[li,pt]=M(se);n?oe=Z<4?q(oe):U(oe,oe.toString()[0]<5?3:2):oe=U(oe,4,!0),oe>=a&&O({posX:0,freq:oe,freqLo:pe,freqHi:se,binLo:ft,binHi:li,ratioLo:nt,ratioHi:pt}),Fe*=ne}while(Fe<=r);N=h/e.length,e.forEach((oe,pe)=>oe.posX=I+pe*N);const fe=e[0],De=e[e.length-1];W=this._freqScaling(fe.freqLo),j=h/(this._freqScaling(De.freqHi)-W),fe.freqLo<a&&(fe.freqLo=a,[fe.binLo,fe.ratioLo]=M(a)),De.freqHi>r&&(De.freqHi=r,[De.binHi,De.ratioHi]=M(r))}else if(y){const U=[0,24,12,8,6,4,3,2,1][c]*10,q=Z=>{switch(this._frequencyScale){case Wr:return 1960/(26.81/(Z+.53)-1);case zr:return 700*(2**Z-1);case Zn:return Z}};N=h/U,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);for(let Z=0,ne=0;Z<U;Z++,ne+=N){const he=q(W+ne/j),Fe=q(W+(ne+N/2)/j),fe=q(W+(ne+N)/j),[De,oe]=M(he),[pe,se]=M(fe);O({posX:I+ne,freq:Fe,freqLo:he,freqHi:fe,binLo:De,binHi:pe,ratioLo:oe,ratioHi:se})}}else{N=1,W=this._freqScaling(a),j=h/(this._freqScaling(r)-W);const U=this._freqToBin(a,"floor"),q=this._freqToBin(r);let Z=-999;for(let ne=U;ne<=q;ne++){const he=this._binToFreq(ne),Fe=I+Math.round(j*(this._freqScaling(he)-W));if(Fe>Z)O({posX:Fe,freq:he,freqLo:he,freqHi:he,binLo:ne,binHi:ne,ratioLo:0,ratioHi:0}),Z=Fe;else if(e.length){const fe=e[e.length-1];fe.binHi=ne,fe.freqHi=he,fe.freq=(fe.freqLo*he)**.5}}}let re=0,te=0;if(k){const U=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),q=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Z=this._ledParams,[ne,he,Fe]=Z||q[c];let fe,De=g;if(Z){const oe=2*U;let pe;fe=ne+1;do fe--,pe=De/fe/(1+he),te=pe*he;while((pe<oe||te<oe)&&fe>1)}else{const oe=540/he;te=Math.min(he*U,Math.max(2,De/oe+.1|0))}x&&(De+=te),Z||(fe=Math.min(ne,De/(te*2)|0)),re=Fe>=1?Fe:N*Fe,this._leds=[fe,re,te,De/fe-te]}const $=Math.min(N-1,i*(i>0&&i<1?N:1));y&&(N-=Math.max(k?re:0,$)),e.forEach((U,q)=>{let Z=U.posX,ne=N;y&&(i==0&&!k?(Z|=0,ne|=0,q>0&&Z>e[q-1].posX+e[q-1].width&&(Z--,ne++)):Z+=Math.max(k?re:0,$)/2,U.posX=Z),U.barCenter=Z+(N==1?0:ne/2),U.width=ne});const ae=[];for(const U of[0,1]){const q=o==dt?(p+b)*U:0,Z=q+p,ne=q+g-(!k||x?0:te);ae.push({channelTop:q,channelBottom:Z,analyzerBottom:ne})}this._aux={analyzerHeight:g,analyzerWidth:h,centerX:m,centerY:_,channelCoords:ae,channelHeight:p,channelGap:b,initialX:I,innerRadius:P,outerRadius:L,scaleMin:W,unitWidth:j},this._flg={isAlpha:E,isBands:y,isLeds:k,isLumi:T,isOctaves:C,isOutline:D,isRound:S,noLedGap:x},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:n,innerRadius:i,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:d,_scaleX:u,_scaleR:f}=this,m=u.canvas,_=f.canvas,v=[],w=this._chLayout==Ui,y=this._chLayout==dt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],T=C/34|0,E=m.height>>1,D=T>>1,S=E*(c?.7:1.5),x=D*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=yn))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==Zn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let L=md;for(let O=-1;O<11;O++)for(let M=0;M<12;M++){if(L>=this._minFreq&&L<=this._maxFreq){const N=k[M],W=N=="C";(N&&c&&!l&&!w||W)&&v.push(c?[L,N+(W?O:"")]:L)}L*=p}}_.width=_.height=Math.max(C*.15,(i<<1)+y*T);const g=_.width>>1,h=g-T*.7,b=(L,O)=>{const M=mn*(L/r.width),N=M-Hr,W=h*Math.cos(N),j=h*Math.sin(N);f.save(),f.translate(g+W,g+j),f.rotate(M),f.fillText(O,0,0),f.restore()};m.width|=0,u.fillStyle=f.strokeStyle=Lv,u.fillRect(0,0,m.width,m.height),f.arc(g,g,g-T/2,0,mn),f.lineWidth=T,f.stroke(),u.fillStyle=f.fillStyle=Ld,u.font=`${E}px ${Hi}`,f.font=`${D}px ${Hi}`,u.textAlign=f.textAlign="center";let I=-S/4,P=-x;for(const L of v){const[O,M]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],N=o*(this._freqScaling(O)-s),W=m.height*.75,j=M[0]=="C",re=E*(c&&!l&&!w?j?1.2:.6:3);if(u.fillStyle=f.fillStyle=j&&!l&&!w?Pv:Ld,c){const te=a==yn,$=a==Zn;let ae=["C"];if((te||O>2e3||!$&&O>250||(!d||y)&&(!$&&O>125||O>1e3))&&ae.push("G"),(te||O>4e3||!$&&O>500||(!d||y)&&(!$&&O>250||O>2e3))&&ae.push("E"),($&&O>4e3||(!d||y)&&(te||O>2e3||!$&&O>500))&&ae.push("D","F","A","B"),!ae.includes(M[0]))continue}N>=I+S/2&&N<=e&&(u.fillText(M,w&&l==-1?e-N:n+N,W,re),(w||l&&(N>S||l==1))&&u.fillText(M,w&&l!=1?e+N:(n||r.width)-N,W,re),I=N+Math.min(re,u.measureText(M).width)/2),N>=P+x&&N<e-x&&(b(w&&l==1?e-N:N,M),(w||l&&(N>x||l==1))&&b(w&&l!=-1?e+N:-N,M),P=N)}}_draw(e){this._runId=requestAnimationFrame(F=>this._draw(F));const n=e-this._time,i=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(i<s)return;this._last=e-(s?i%s:0),this._frames++,n>=1e3&&(this._fps=this._frames/n*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:d,isRound:u,noLedGap:f}=this._flg,{analyzerHeight:m,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:C,initialX:k,innerRadius:T,outerRadius:E}=this._aux,{_bars:D,canvas:S,_canvasGradients:x,_chLayout:p,_colorMode:g,_ctx:h,_energy:b,_fadePeaks:I,fillAlpha:P,_fps:L,_linearAmplitude:O,_lineWidth:M,maxDecibels:N,minDecibels:W,_mirror:j,_mode:re,overlay:te,_radial:$,showBgColor:ae,showPeaks:U,useCanvas:q,_weightingFilter:Z}=this,ne=this._scaleX.canvas,he=this._scaleR.canvas,Fe=L*this._peakFadeTime/1e3,fe=L**2,De=this._gravity*1e3,oe=L*this._peakHoldTime/1e3,pe=p==vd,se=p==Ui,ft=p==dt,nt=p==St,li=a&&this._trueLeds&&g==$i,pt=$?S.width:this._aux.analyzerWidth,ao=k+pt,ci=U&&this._peakLine&&re==vn,Ot=$?E-T:m,e0=Ot/this._pixelRatio,[t0,u0,di,lo]=this._leds||[];b.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*mn/60/L);const n0=F=>{if(this._reflexRatio>0&&!l&&!$){let ie,gt;this.reflexFit||ft?(ie=ft&&F==0?y+C:0,gt=y-m):(ie=S.height-m*2,gt=m),h.save(),h.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(h.filter=`brightness(${this.reflexBright})`),h.setTransform(1,0,0,-1,0,S.height),h.drawImage(S,0,w[F].channelTop,S.width,m,0,ie,S.width,gt),h.restore()}},i0=()=>{this.showScaleX&&($?(h.save(),h.translate(_,v),this._spinSpeed&&h.rotate(this._spinAngle+Hr),h.drawImage(he,-he.width>>1,-he.width>>1),h.restore()):h.drawImage(ne,0,S.height-ne.height))},s0=F=>{const ie=F**2,gt=424.36,Le=11599.29,ss=25122.25,Nt=544496.41,kt=148693636,Jt=Zt=>20*Math.log10(Zt);switch(Z){case xd:const Zt=kt*ie**2/((ie+gt)*Math.sqrt((ie+Le)*(ie+Nt))*(ie+kt));return 2+Jt(Zt);case kd:const Qt=kt*ie*F/((ie+gt)*Math.sqrt(ie+ss)*(ie+kt));return .17+Jt(Qt);case Td:const ho=kt*ie/((ie+gt)*(ie+kt));return .06+Jt(ho);case Ad:const rs=((103791848e-2-ie)**2+108076816e-2*ie)/((9837328-ie)**2+11723776*ie),fo=F/68966888496476e-18*Math.sqrt(rs/((ie+79919.29)*(ie+1345600)));return Jt(fo);case Ed:const os=-4737338981378384e-39*F**6+2043828333606125e-30*F**4-1363894795463638e-22*ie+1,en=1306612257412824e-34*F**5-2118150887518656e-26*F**3+.0005559488023498642*F,Ge=.0001246332637532143*F/Math.hypot(os,en);return 18.2+Jt(Ge)}return 0},co=(F,ie,gt)=>{h.beginPath(),h.moveTo(F,ie),h.lineTo(F,gt),h.stroke()},uo=F=>{if(F&&M){const ie=h.globalAlpha;h.globalAlpha=1,h.stroke(),h.globalAlpha=ie}},Yt=F=>Math.max(0,(F*t0|0)*(lo+di)-di),r0=F=>{b.val=F,b.peak>0&&(b.hold--,b.hold<0&&(b.peak+=b.hold*De/fe/S.height*this._pixelRatio)),F>=b.peak&&(b.peak=F,b.hold=oe)};te&&h.clearRect(0,0,S.width,S.height);let Wu=0;const zu=D.length,qu=nt?1:2;for(let F=0;F<qu;F++){const{channelTop:ie,channelBottom:gt,analyzerBottom:Le}=w[F],ss=this._gradients[this._selectedGrads[F]],Nt=ss.colorStops,kt=Nt.length,Jt=!ae||a&&!te?"#000":ss.bgColor,Zt=ft&&$&&F?-1:1,Qt=!F&&j==-1||F&&j==1,ho=!se||F&&j!=1?0:pt>>(F||!Qt),rs=se&&Qt?-1:1,fo=()=>{const H=ne.height,K=H>>1,Q=O?100:N,de=O?0:W,Se=O?20:5,$e=m/(Q-de),mt=j!=-1&&(!se||F==0||j==1),Ft=j!=1&&(!se||F!=j);h.save(),h.fillStyle=Pd,h.font=`${K}px ${Hi}`,h.textAlign="right",h.lineWidth=1;for(let Vt=Q;Vt>de;Vt-=Se){const xn=ie+(Q-Vt)*$e,Ae=Vt%2==0|0;if(Ae){const Ve=xn+K*(xn==ie?.8:.35);mt&&h.fillText(Vt,H*.85,Ve),Ft&&h.fillText(Vt,(se?pt:S.width)-H*.1,Ve),h.strokeStyle=Pd,h.setLineDash([2,4]),h.lineDashOffset=0}else h.strokeStyle=Mv,h.setLineDash([2,8]),h.lineDashOffset=1;h.beginPath(),h.moveTo(k+H*Ae*mt,~~xn+.5),h.lineTo(ao-H*Ae*Ft,~~xn+.5),h.stroke()}h.restore()},os=(H,K)=>{const Q=it[H]+(H<it.length-1?(it[H+1]-it[H])*K:0);return isNaN(Q)?-1/0:Q},en=(H,K=rs)=>K*mn*((H+ho)/S.width)+this._spinAngle,Ge=(H,K,Q)=>{const de=T+K*Zt,Se=en(H,Q);return[_+de*Math.cos(Se),v+de*Math.sin(Se)]},po=(H,K,Q,de,Se)=>{h.beginPath();for(const $e of j&&!se?[1,-1]:[rs]){const[mt,Ft]=u?[en(H,$e),en(H+Q,$e)]:[];h.moveTo(...Ge(H,K,$e)),h.lineTo(...Ge(H,K+de,$e)),u?h.arc(_,v,T+(K+de)*Zt,mt,Ft,$e!=1):h.lineTo(...Ge(H+Q,K+de,$e)),h.lineTo(...Ge(H+Q,K,$e)),u&&!Se&&h.arc(_,v,T+K*Zt,Ft,mt,$e==1)}uo(Se),h.fill()},go=(H=0,K=0)=>{let Q;if(g==$i&&!li||re==vn)Q=x[F];else{const de=g==yd?K%kt:Nt.findLastIndex(Se=>a?Yt(H)<=Yt(Se.level):H<=Se.level);Q=Nt[de].color}h.fillStyle=h.strokeStyle=Q};if(q){if(se&&!$){const H=pt*(F+Qt),K=Qt?-1:1;h.setTransform(K,0,0,1,H,0)}if((!te||ae)&&(te&&(h.globalAlpha=this.bgAlpha),h.fillStyle=Jt,(F==0||!$&&!pe)&&h.fillRect(k,ie-C,pt,(te&&this.reflexAlpha==1?m:y)+C),h.globalAlpha=1),this.showScaleY&&!l&&!$&&(F==0||!pe)&&fo(),a?(h.setLineDash([lo,di]),h.lineWidth=D[0].width):h.lineWidth=d?Math.min(M,D[0].width/2):M,h.save(),!$){const H=new Path2D;H.rect(0,ie,S.width,m),h.clip(H)}}let it=this._fftData[F];this._analyzer[F].getFloatFrequencyData(it),Z&&(it=it.map((H,K)=>H+s0(this._binToFreq(K)))),h.beginPath();let ui=[];for(let H=0;H<zu;H++){const K=D[H],{posX:Q,barCenter:de,width:Se,freq:$e,binLo:mt,binHi:Ft,ratioLo:Vt,ratioHi:xn}=K;let Ae=Math.max(os(mt,Vt),os(Ft,xn));for(let le=mt+1;le<Ft;le++)it[le]>Ae&&(Ae=it[le]);if(Ae=this._normalizedB(Ae),K.value[F]=Ae,Wu+=Ae,K.peak[F]>0&&K.alpha[F]>0&&(K.hold[F]--,K.hold[F]<0)){if(I&&!ci){const le=!o||d&&M>0?1:o?K.peak[F]:P;K.alpha[F]=le*(1+K.hold[F]/Fe)}else K.peak[F]+=K.hold[F]*De/fe/e0;K.alpha[F]<=0&&(K.peak[F]=0)}if(Ae>=K.peak[F]&&(K.peak[F]=Ae,K.hold[F]=oe,K.alpha[F]=!o||d&&M>0?1:o?Ae:P),!q)continue;h.globalAlpha=l||o?Ae:d?P:1,go(Ae,H);const Ve=l?Ot:a?Yt(Ae):Ae*Ot|0;if(re==vn){const le=H?0:(this._normalizedB(it[D[1].binLo])*Ot+Ve)/2;if($){if(H==0&&(se&&h.moveTo(...Ge(0,0)),h.lineTo(...Ge(0,Q<0?le:Ve))),Q>=0){const Ze=[Q,Ve];h.lineTo(...Ge(...Ze)),ui.push(Ze)}}else{if(H==0)if(j==-1&&!se)h.moveTo(k,Le-(Q<k?le:Ve));else{const Ze=mt?this._normalizedB(it[mt-1])*Ot:Ve;h.moveTo(k-M,Le-Ze)}(se||j!=-1||Q>=k)&&h.lineTo(Q,Le-Ve)}}else if(a){if(ae&&!te&&(F==0||!pe)){const le=h.globalAlpha;h.strokeStyle=Ev,h.globalAlpha=1,co(de,ie,Le),h.strokeStyle=h.fillStyle,h.globalAlpha=le}if(li){const le=l?0:Nt.findLastIndex(tn=>Yt(Ae)<=Yt(tn.level));let Ze=Le;for(let tn=kt-1;tn>=le;tn--){h.strokeStyle=Nt[tn].color;let Xu=Le-(tn==le?Ve:Yt(Nt[tn].level));co(de,Ze,Xu),Ze=Xu-di}}else co(de,Le,Le-Ve)}else if(Q>=k)if($)po(Q,0,Se,Ve,d);else if(u){const le=Se/2,Ze=Le+le;h.beginPath(),h.moveTo(Q,Ze),h.lineTo(Q,Ze-Ve),h.arc(de,Ze-Ve,le,$r,mn),h.lineTo(Q+Se,Ze),uo(d),h.fill()}else{const le=d?h.lineWidth:0;h.beginPath(),h.rect(Q,Le+le,Se,-Ve-le),uo(d),h.fill()}const kn=K.peak[F],Ku=K.alpha[F];if(kn>0&&Ku>0&&U&&!ci&&!l&&Q>=k&&Q<ao){if(I?h.globalAlpha=Ku:d&&M>0?h.globalAlpha=1:o&&(h.globalAlpha=kn),(g==_d||li)&&go(kn),a){const le=Yt(kn);le>=di&&h.fillRect(Q,Le-le,Se,lo)}else if(!$)h.fillRect(Q,Le-kn*Ot,Se,2);else if(re!=vn){const le=kn*Ot;po(Q,le,Se,!this._radialInvert||ft||le+T>=2?-2:2)}}}if(q){if(h.globalAlpha=1,re==vn){if(go(),$&&!se){if(j){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1))}h.closePath()}if(M>0&&h.stroke(),P>0){if($){const H=se?en(pt>>1):0,K=se?en(pt):mn;h.moveTo(...Ge(se?pt>>1:0,0)),h.arc(_,v,T,H,K,se?!Qt:!0)}else h.lineTo(ao,Le),h.lineTo(k,Le);h.globalAlpha=P,h.fill(),h.globalAlpha=1}if((ci||$&&U)&&(ui=[],h.beginPath(),D.forEach((H,K)=>{let Q=H.posX,de=H.peak[F],Se=K?"lineTo":"moveTo";if($&&Q<0){const $e=D[K+1];de=Hv(Q,de,$e.posX,$e.peak[F],0),Q=0}de*=Ot,ci?(h[Se](...$?Ge(Q,de):[Q,Le-de]),$&&j&&!se&&ui.push([Q,de])):de>0&&po(Q,de,1,-2)}),ci)){let H;for(;H=ui.pop();)h.lineTo(...Ge(...H,-1));h.lineWidth=1,h.stroke()}}h.restore(),se&&!$&&h.setTransform(1,0,0,1,0,0),(!se&&!pe||F)&&n0(F)}}if(r0(Wu/(zu<<qu-1)),q&&(j&&!$&&!se&&(h.setTransform(-1,0,0,1,S.width-k,0),h.drawImage(S,k,0,_,S.height,0,0,_,S.height),h.setTransform(1,0,0,1,0,0)),h.setLineDash([]),i0()),this.showFPS){const F=ne.height;h.font=`bold ${F}px ${Hi}`,h.fillStyle=Av,h.textAlign="right",h.fillText(Math.round(L),S.width-F,F*2)}this.onCanvasDraw&&(h.save(),h.fillStyle=h.strokeStyle=x[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:x}),h.restore())}_freqScaling(e){switch(this._frequencyScale){case yn:return Math.log2(e);case Wr:return 26.81*e/(1960+e)-.53;case zr:return Math.log2(1+e/700);case Zn:return e}}_freqToBin(e,n="round"){const i=this._analyzer[0].frequencyBinCount-1,s=Math[n](e*this.fftSize/this.audioCtx.sampleRate);return s<i?s:i}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:n,_radial:i,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:d}=this._aux,{isLumi:u}=this._flg,f=this._chLayout==dt,m=1-s,_=u?e.height:e.height*(1-s*!f)|0;for(const v of[0,1]){const w=this._gradients[this._selectedGrads[v]],y=w.colorStops,C=w.dir=="h";let k;if(i?k=n.createRadialGradient(r,a,d,r,a,c-(d-c)*f):k=n.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),y){const T=f&&!this._splitGradient&&(!C||i);for(let E=0;E<1+T;E++){const D=y.length-1;y.forEach((S,x)=>{let p=S.pos;if(T&&(p/=2),f&&!u&&!i&&!C&&(p*=m,!T&&p>.5*m&&(p+=.5*s)),E==1)if(i||u){const g=D-x;S=y[g],p=1-S.pos/2}else x==0&&p>0&&k.addColorStop(.5,S.color),p+=.5;k.addColorStop(p,S.color),f&&x==D&&p<.5&&k.addColorStop(.5,S.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const n=this._linearAmplitude,i=n?1/this._linearBoost:1,s=(l,c,d)=>l<=c?c:l>=d?d:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return n&&(r=o(r),a=o(a),e=o(e)**i),s((e-a)/(r-a)**i,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:n,_ctx:i}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==n,d=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,u=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Id&&n.width==d&&n.height==u)&&(n.width=d,n.height=u,this.overlay||(i.fillStyle="#000",i.fillRect(0,0,d,u)),i.lineJoin="bevel",s.width=d,s.height=Math.max(20*o,Math.min(d,u)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=Rd),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,n){if(!this._gradients.hasOwnProperty(e))throw new Ye(Nv,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(Qn).filter(r=>r!="start").concat(i,s);(n||e===void 0)&&(e={...Qn,...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 Wv={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}]}},Fd=({stream:t,className:e,onClick:n})=>{var o;const i=me(null),s=qt();return ke(()=>{var c;if(!i.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Gv(i.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",Wv[((c=s.audio_visualizer_config)==null?void 0:c.color)||"verdant"]),l.gradient="gradient",()=>{l.destroy()}},[(o=s.audio_visualizer_config)==null?void 0:o.color,t]),R("div",{onClick:n,className:wt("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.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const Vd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Wv=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Bd=t=>{const e=Wv(t);return e.charAt(0).toUpperCase()+e.slice(1)},zv=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
21
+ */const Vd=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zv=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,i)=>i?i.toUpperCase():n.toLowerCase()),Bd=t=>{const e=zv(t);return e.charAt(0).toUpperCase()+e.slice(1)},qv=(...t)=>t.filter((e,n,i)=>!!e&&e.trim()!==""&&i.indexOf(e)===n).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var qv={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
26
+ */var Kv={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
27
27
  * @license lucide-preact v0.515.0 - ISC
28
28
  *
29
29
  * This source code is licensed under the ISC license.
30
30
  * See the LICENSE file in the root directory of this source tree.
31
- */const Kv=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>We("svg",{...qv,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>We(l,c)),...ot(s)]);/**
31
+ */const Xv=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:i,children:s,iconNode:o,class:r="",...a})=>We("svg",{...Kv,width:String(e),height:e,stroke:t,"stroke-width":i?Number(n)*24/Number(e):n,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>We(l,c)),...ot(s)]);/**
32
32
  * @license lucide-preact v0.515.0 - ISC
33
33
  *
34
34
  * This source code is licensed under the ISC license.
35
35
  * See the LICENSE file in the root directory of this source tree.
36
- */const je=(t,e)=>{const n=({class:i="",children:s,...o})=>We(Kv,{...o,iconNode:e,class:zv(`lucide-${Vd(Bd(t))}`,`lucide-${Vd(t)}`,i)},s);return n.displayName=Bd(t),n};/**
36
+ */const je=(t,e)=>{const n=({class:i="",children:s,...o})=>We(Xv,{...o,iconNode:e,class:qv(`lucide-${Vd(Bd(t))}`,`lucide-${Vd(t)}`,i)},s);return n.displayName=Bd(t),n};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
@@ -43,7 +43,7 @@ var s0=Object.defineProperty;var r0=(Qe,G,Ft)=>G in Qe?s0(Qe,G,{enumerable:!0,co
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Xv=je("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
46
+ */const Yv=je("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
@@ -53,62 +53,62 @@ var s0=Object.defineProperty;var r0=(Qe,G,Ft)=>G in Qe?s0(Qe,G,{enumerable:!0,co
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const Yv=je("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
56
+ */const Jv=je("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/**
57
57
  * @license lucide-preact v0.515.0 - ISC
58
58
  *
59
59
  * This source code is licensed under the ISC license.
60
60
  * See the LICENSE file in the root directory of this source tree.
61
- */const Jv=je("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const Zv=je("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
62
62
  * @license lucide-preact v0.515.0 - ISC
63
63
  *
64
64
  * This source code is licensed under the ISC license.
65
65
  * See the LICENSE file in the root directory of this source tree.
66
- */const Zv=je("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
66
+ */const Qv=je("mic-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
67
67
  * @license lucide-preact v0.515.0 - ISC
68
68
  *
69
69
  * This source code is licensed under the ISC license.
70
70
  * See the LICENSE file in the root directory of this source tree.
71
- */const Qv=je("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
71
+ */const ey=je("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
72
72
  * @license lucide-preact v0.515.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const ey=je("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
76
+ */const ty=je("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
77
77
  * @license lucide-preact v0.515.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const ty=je("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
81
+ */const ny=je("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
82
82
  * @license lucide-preact v0.515.0 - ISC
83
83
  *
84
84
  * This source code is licensed under the ISC license.
85
85
  * See the LICENSE file in the root directory of this source tree.
86
- */const ny=je("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
86
+ */const iy=je("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
87
87
  * @license lucide-preact v0.515.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const iy=je("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
91
+ */const sy=je("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
92
92
  * @license lucide-preact v0.515.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const sy=je("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
96
+ */const ry=je("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const ry=je("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
101
+ */const oy=je("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const qr=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$d=Ss(!1),oy=()=>ba($d),Ct=({children:t,className:e,onClick:n,tooltip:i})=>I("button",{title:i,onClick:n,className:wt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Hd=({call:t,chatMode:e})=>{const[n,i]=oy(),s=()=>{i(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return I("div",{className:"flex items-center justify-center gap-2",children:[!e&&I(Ct,{tooltip:n?"Unmute":"Mute",onClick:s,className:wt(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?I(Zv,{className:"w-5 h-5 text-black dark:text-white"}):I(Qv,{className:"w-5 h-5 text-black dark:text-white"})}),I(Ct,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:I(ty,{className:"w-4 h-4 text-black dark:text-white"})})]})},Gd=({call:t,onExpand:e,chatMode:n})=>I(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!n&&I(Fd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),I(gd,{stream:t.remoteStream,chatMode:n}),I(pd,{size:"small"}),I(Hd,{call:t,chatMode:n})]});function ay(){const[t,e]=Ce(!1),n=Wt();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 I("div",{children:[I(Ct,{tooltip:"More",onClick:()=>e(!t),children:I(Ud,{className:"text-black dark:text-white"})}),t&&I("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:[I(Ct,{tooltip:"More",onClick:()=>e(!t),children:I(Ud,{className:"text-black dark:text-white"})}),I("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&I("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",I(sy,{className:"w-4 h-4"})]}),n.report_issue_url&&I("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",I(ry,{className:"w-4 h-4"})]}),n.view_history_url&&I("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",I(Yv,{className:"w-4 h-4"})]})]})]})]})}function ly(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Hi={exports:{}},cy=Hi.exports,Wd;function dy(){return Wd||(Wd=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(cy,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,E,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!R)){try{window.localStorage[R]=b;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!R)){try{h=window.localStorage[R]}catch{}if(typeof h===n)try{var b=window.document.cookie,A=encodeURIComponent(R),P=b.indexOf(A+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+A.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return E??k??C},y.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(E=p(g)),d.call(y)}r=new m,r.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[w];return y||(y=o[w]=new m(w,r.methodFactory)),y};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Hi)),Hi.exports}var uy=dy();const hy=ly(uy),fy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),py="[ai-agent-widget]",Te=hy.getLogger("telnyx-ai-agent-widget"),gy=Te.methodFactory;Te.methodFactory=(t,e,n)=>{const i=gy(t,e,n);return function(...s){i(fy(),py,...s)}},Te.setLevel("info");function my({onCapture:t,onClose:e}){const n=me(null),i=me(null),s=me(null),[o,r]=Ce(null),[a,l]=Ce(!0);xe(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){Te.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?r("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const u=n.current,f=i.current,m=f.getContext("2d");if(!m)return;f.width=u.videoWidth,f.height=u.videoHeight,m.drawImage(u,0,0,f.width,f.height);const _=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},d=()=>{s.current&&s.current.getTracks().forEach(u=>u.stop()),e()};return I("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:[I("div",{className:"absolute top-2 right-2 z-10",children:I(Ct,{tooltip:"Close",onClick:d,children:I(qr,{className:"text-white w-5 h-5"})})}),I("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&I("div",{className:"absolute text-white text-center",children:I("p",{className:"text-sm",children:"Loading camera..."})}),o&&I("div",{className:"text-white text-center max-w-xs",children:[I("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),I("p",{className:"text-xs",children:o}),I("button",{onClick:d,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&&I(rt,{children:[I("video",{ref:n,autoPlay:!0,playsInline:!0,className:wt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),I("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&I("div",{className:"p-3 flex justify-center",children:I("button",{onClick:c,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[I(jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function vy({item:t,containerRef:e}){const n=me(null);return xe(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),I("li",{className:wt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[I("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&I("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&I("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),I("div",{className:wt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&I("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&I("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&&I("p",{className:wt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const yy=({transcript:t,call:e})=>{const n=me(null),i=me(null),s=me(null),[o,r]=Ce([]),[a,l]=Ce(!1),[c,d]=Ce([]),[,u]=jr();xe(()=>()=>{o.forEach(S=>URL.revokeObjectURL(S.preview))},[o]),xe(()=>{if(c.length===0)return;const S=t.filter(x=>x.role==="user"&&!x.id.startsWith("optimistic-"));if(S.length>0){const x=S[S.length-1];d(p=>p.filter(g=>g.timestamp>x.timestamp))}},[t,c]);const f=S=>new Promise((x,p)=>{const g=new FileReader;g.onload=()=>x(g.result),g.onerror=p,g.readAsDataURL(S)}),m=async S=>{if(S.type.startsWith("image/"))try{const x=await f(S),p=URL.createObjectURL(S),g={id:Date.now().toString(),file:S,base64:x,preview:p};r(h=>[...h,g])}catch(x){Te.error("Error processing image:",x)}},_=S=>{r(x=>{const p=x.find(g=>g.id===S);return p&&URL.revokeObjectURL(p.preview),x.filter(g=>g.id!==S)})},v=S=>{const x=S.target,p=x.files;p&&p.length>0&&(Array.from(p).forEach(m),x.value="")},w=S=>{var p;const x=(p=S.clipboardData)==null?void 0:p.items;x&&Array.from(x).forEach(g=>{if(g.type.startsWith("image/")){const h=g.getAsFile();h&&m(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},C=()=>{l(!0)},k=S=>{fetch(S).then(x=>x.blob()).then(x=>{const p=new File([x],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});m(p)}).catch(x=>{Te.error("Error processing camera capture:",x)})},E=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",x=o.length>0;if(S||x){const g=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:g,timestamp:h,attachments:o.map(A=>({type:"image",url:A.base64}))};d(A=>[...A,b]),x&&u("processing_image"),e.sendConversationMessage(g,o.map(A=>A.base64)),n.current&&(n.current.value=""),o.forEach(A=>URL.revokeObjectURL(A.preview)),r([])}},R=S=>{S.key==="Enter"&&(S.preventDefault(),E())},O=[...t,...c];return I("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:[I("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:O.map((S,x)=>I(vy,{item:S,containerRef:s},S.id+x))}),o.length>0&&I("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(S=>I("div",{className:"relative",children:[I("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),I("button",{onClick:()=>_(S.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:I(qr,{className:"w-3 h-3"})})]},S.id))}),I("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:[I("input",{ref:n,type:"text",onKeyDown:R,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),I("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),I(Ct,{tooltip:"Attach image",onClick:y,children:I(ey,{className:"text-[#969696] w-4 h-4"})}),I(Ct,{tooltip:"Take photo",onClick:C,children:I(jd,{className:"text-[#969696] w-4 h-4"})}),I(Ct,{tooltip:"Send",children:I(ny,{onClick:E,className:"text-[#969696] w-4 h-4"})})]}),a&&I(my,{onCapture:k,onClose:()=>l(!1)})]})};function _y({onCollapse:t}){return I("div",{className:"flex items-center justify-between w-full",children:[I(ay,{}),I(Ct,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:I(qr,{className:"text-black dark:text-white"})})]})}const by=({call:t,onCollapse:e,transcript:n,chatMode:i})=>I(Vp,{children:I(gn.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:[I("div",{className:"p-4 text-center",children:[I(_y,{onCollapse:e}),!i&&I(Fd,{className:"h-[144px]",stream:t.remoteStream}),I(pd,{size:"large",className:"mb-4"}),I(Hd,{call:t,chatMode:i})]}),I(gd,{stream:t.remoteStream,chatMode:i}),I(yy,{call:t,transcript:n})]})});function Gi(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 B(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(d){o(d)}}function a(c){try{l(i.throw(c))}catch(d){o(d)}}function l(c){var d;c.done?s(c.value):(d=c.value,d instanceof n?d:new n(function(u){u(d)})).then(r,a)}l((i=i.apply(t,[])).next())})}var zd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),wy=new Uint8Array(16);function Sy(){if(!zd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return zd(wy)}for(var qd=[],Wi=0;Wi<256;++Wi)qd[Wi]=(Wi+256).toString(16).substr(1);function _n(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||Sy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=qd;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const Kd="wss://rtc.telnyx.com",Cy=1006,Xd={urls:"stun:stun.l.google.com:19302"},xy=[{urls:"stun:stun.telnyx.com:3478"},Xd,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],ky=[{urls:"stun:stundev.telnyx.com:3478"},Xd,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var V;(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",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"})(V||(V={}));var Ty=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Yd(t,e){return t(e={exports:{}},e.exports),e.exports}var Ey=Yd(function(t){var e,n;e=Ty,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(w,y){var C=w[y];if(typeof C.bind=="function")return C.bind(w);try{return Function.prototype.bind.call(C,w)}catch{return function(){return Function.prototype.apply.apply(C,[w,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(w,y){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<w?i:this.methodFactory(k,w,y)}this.log=this.debug}function d(w,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[w].apply(this,arguments))}}function u(w,y,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):i)}(w)||d.apply(this,arguments)}function f(w,y,C){var k,E=this;y=y??"WARN";var R="loglevel";function O(){var x;if(typeof window!==s&&R){try{x=window.localStorage[R]}catch{}if(typeof x===s)try{var p=window.document.cookie,g=p.indexOf(encodeURIComponent(R)+"=");g!==-1&&(x=/^([^;]+)/.exec(p.slice(g))[1])}catch{}return E.levels[x]===void 0&&(x=void 0),x}}typeof w=="string"?R+=":"+w:typeof w=="symbol"&&(R=void 0),E.name=w,E.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},E.methodFactory=C||u,E.getLevel=function(){return k},E.setLevel=function(x,p){if(typeof x=="string"&&E.levels[x.toUpperCase()]!==void 0&&(x=E.levels[x.toUpperCase()]),!(typeof x=="number"&&x>=0&&x<=E.levels.SILENT))throw"log.setLevel() called with invalid level: "+x;if(k=x,p!==!1&&function(g){var h=(r[g]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=h)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+h+";"}catch{}}}(x),c.call(E,x,w),typeof console===s&&x<E.levels.SILENT)return"No console available for logging"},E.setDefaultLevel=function(x){y=x,O()||E.setLevel(x,!1)},E.resetLevel=function(){E.setLevel(y,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},E.enableAll=function(x){E.setLevel(E.levels.TRACE,x)},E.disableAll=function(x){E.setLevel(E.levels.SILENT,x)};var S=O();S==null&&(S=y),E.setLevel(S,!1)}var m=new f,_={};m.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=_[w];return y||(y=_[w]=new f(w,m.getLevel(),m.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return m.noConflict=function(){return typeof window!==s&&window.log===m&&(window.log=v),m},m.getLoggers=function(){return _},m.default=m,m},t.exports?t.exports=n():e.log=n()});const Jd={debug:0,info:1,warn:2,error:3};class Ay{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||Jd[e]<Jd[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Zd=null;function Qd(){return Zd}function eu(t){Zd=t}const T=Ey.getLogger("telnyx"),zi={trace:0,debug:1,info:2,warn:3,error:4};let tu=zi.info;function nu(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const Iy=T.methodFactory;T.methodFactory=(t,e,n)=>{const i=Iy(t,e,n);return function(...s){if(zi[t]>=tu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);i(...r)}const o=Qd();if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?nu(a[0]):{args:a.map(nu)}),o.addEntry(t,l,c)}}},T.setLevel("debug",!1);const qi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{T.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},iu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},bn=t=>t instanceof Function||typeof t=="function",Ki=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Ry=/^(ws|wss):\/\//,su=(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?su(a,r):{result:s}},ru=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Xi=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),ei=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Kr=t=>{var e,n,i,s,o,r;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function ou({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?Ly(i,t):i,n=s}),resolve:e,reject:n}}const Ly=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Xr="telnyx-voice-sdk-id";function zt(){return sessionStorage.getItem(Xr)}var Ie,ut,ee;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Xr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ie||(Ie={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(ut||(ut={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ee||(ee={}));const Je={generic:"event",[ee.Display]:"participantData",[ee.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Py={invalidCredentialsOptions:"InvalidCredentialsOptions"},My={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!0};var X,Yr,He,ht,Ne;(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"})(X||(X={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Yr||(Yr={})),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"}(He||(He={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(ht||(ht={})),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"}(Ne||(Ne={}));const wn="GLOBAL",Ue={},ti=(t,e)=>`${t}|${e}`,au=(t,e=wn)=>ti(t,e)in Ue,Lt=(t,e,n=wn)=>{const i=ti(t,n);i in Ue||(Ue[i]=[]),Ue[i].push(e)},lu=(t,e,n=wn)=>{const i=function(s){Pt(t,i,n),e(s)};return i.prototype.targetRef=e,Lt(t,i,n)},Pt=(t,e,n=wn)=>{if(!au(t,n))return!1;const i=ti(t,n);if(bn(e))for(let s=Ue[i].length-1;s>=0;s--){const o=Ue[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Ue[i].splice(s,1)}else Ue[i]=[];return Ue[i].length===0&&delete Ue[i],!0},Y=(t,e,n=wn,i=!0)=>{const s=i&&n!==wn;if(!au(t,n))return s&&Y(t,e),!1;const o=ti(t,n),r=Ue[o].length;if(!r)return s&&Y(t,e),!1;for(let a=r-1;a>=0;a--)Ue[o][a](e);return s&&Y(t,e),!0},Jr=t=>{const e=ti(t,"");Object.keys(Ue).filter(n=>n.indexOf(e)===0).forEach(n=>delete Ue[n])};let Dy=typeof WebSocket<"u"?WebSocket:null;const Oy=0,Ny=1,Fy=2,cu=3;class du{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Kd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Kd),n&&(this._host=(r=>`${Ry.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===Ny}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Oy}get closing(){return!!this._wsClient&&this._wsClient.readyState===Fy}get closed(){return!!this._wsClient&&this._wsClient.readyState===cu}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=zt();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),T.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new Dy(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){const s=i instanceof Error?i:new Error(`Failed to create WebSocket: ${String(i)}`);Y(V.Error,{error:s},this.session.uuid),T.error("WebSocket connection failed:",s)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((o,r)=>{if(i.hasOwnProperty("result"))return o();lu(i.id,a=>{const{result:l,error:c}=su(a);return c?r(c):o(l)})});return T.debug(`SEND:
106
+ */const Kr=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),$d=_i(!1),ay=()=>ba($d),Ct=({children:t,className:e,onClick:n,tooltip:i})=>R("button",{title:i,onClick:n,className:wt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Hd=({call:t,chatMode:e})=>{const[n,i]=ay(),s=()=>{i(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return R("div",{className:"flex items-center justify-center gap-2",children:[!e&&R(Ct,{tooltip:n?"Unmute":"Mute",onClick:s,className:wt(n?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:n?R(Qv,{className:"w-5 h-5 text-black dark:text-white"}):R(ey,{className:"w-5 h-5 text-black dark:text-white"})}),R(Ct,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:R(ny,{className:"w-4 h-4 text-black dark:text-white"})})]})},Gd=({call:t,onExpand:e,chatMode:n})=>R(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!n&&R(Fd,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),R(gd,{stream:t.remoteStream,chatMode:n}),R(pd,{size:"small"}),R(Hd,{call:t,chatMode:n})]}),Wd=_i(null),ly=({className:t})=>{const e=Es(Wd);return!e||!(e.region||e.dc)?null:R("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[e.region&&R("span",{"data-testid":"connection-info-region",children:["region: ",e.region]}),e.region&&e.dc&&R("span",{children:" · "}),e.dc&&R("span",{"data-testid":"connection-info-dc",children:["dc: ",e.dc]})]})};function cy(){const[t,e]=xe(!1),n=qt();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 R("div",{children:[R(Ct,{tooltip:"More",onClick:()=>e(!t),children:R(Ud,{className:"text-black dark:text-white"})}),t&&R("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[R(Ct,{tooltip:"More",onClick:()=>e(!t),children:R(Ud,{className:"text-black dark:text-white"})}),R("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[n.give_feedback_url&&R("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",R(ry,{className:"w-4 h-4"})]}),n.report_issue_url&&R("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",R(oy,{className:"w-4 h-4"})]}),n.view_history_url&&R("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",R(Jv,{className:"w-4 h-4"})]})]})]})]})}function dy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Wi={exports:{}},uy=Wi.exports,zd;function hy(){return zd||(zd=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(uy,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,T,E="loglevel";typeof v=="string"?E+=":"+v:typeof v=="symbol"&&(E=void 0);function D(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!E)){try{window.localStorage[E]=b;return}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!E)){try{h=window.localStorage[E]}catch{}if(typeof h===n)try{var b=window.document.cookie,I=encodeURIComponent(E),P=b.indexOf(I+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+I.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!E)){try{window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return T??k??C},y.setLevel=function(h,b){return T=p(h),b!==!1&&D(T),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){T=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(T=p(g)),d.call(y)}r=new m,r.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[w];return y||(y=o[w]=new m(w,r.methodFactory)),y};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Wi)),Wi.exports}var fy=hy();const py=dy(fy),gy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),my="[ai-agent-widget]",Ce=py.getLogger("telnyx-ai-agent-widget"),vy=Ce.methodFactory;Ce.methodFactory=(t,e,n)=>{const i=vy(t,e,n);return function(...s){i(gy(),my,...s)}},Ce.setLevel("info");function yy({onCapture:t,onClose:e}){const n=me(null),i=me(null),s=me(null),[o,r]=xe(null),[a,l]=xe(!0);ke(()=>((async()=>{try{const f=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=f,n.current&&(n.current.srcObject=f,l(!1))}catch(f){Ce.error("Error accessing camera:",f),f instanceof Error?f.name==="NotAllowedError"||f.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):f.name==="NotFoundError"||f.name==="DevicesNotFoundError"?r("No camera found on this device."):f.name==="NotReadableError"||f.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(f=>f.stop())}),[]);const c=()=>{if(!n.current||!i.current)return;const u=n.current,f=i.current,m=f.getContext("2d");if(!m)return;f.width=u.videoWidth,f.height=u.videoHeight,m.drawImage(u,0,0,f.width,f.height);const _=f.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},d=()=>{s.current&&s.current.getTracks().forEach(u=>u.stop()),e()};return R("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[R("div",{className:"absolute top-2 right-2 z-10",children:R(Ct,{tooltip:"Close",onClick:d,children:R(Kr,{className:"text-white w-5 h-5"})})}),R("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&R("div",{className:"absolute text-white text-center",children:R("p",{className:"text-sm",children:"Loading camera..."})}),o&&R("div",{className:"text-white text-center max-w-xs",children:[R("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),R("p",{className:"text-xs",children:o}),R("button",{onClick:d,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&&R(rt,{children:[R("video",{ref:n,autoPlay:!0,playsInline:!0,className:wt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),R("canvas",{ref:i,className:"hidden"})]})]}),!o&&!a&&R("div",{className:"p-3 flex justify-center",children:R("button",{onClick:c,className:"flex items-center gap-2 px-4 py-2 bg-white text-black rounded-full hover:bg-gray-200 transition-colors font-semibold text-sm",children:[R(jd,{className:"w-4 h-4"}),"Capture Photo"]})})]})}function _y({item:t,containerRef:e}){const n=me(null);return ke(()=>{var i;n.current&&((i=e==null?void 0:e.current)==null||i.scrollTo({top:n.current.offsetTop,behavior:"smooth"}))},[e]),R("li",{className:wt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:n,children:[R("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&R("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),R("div",{className:wt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&R("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((i,s)=>i.type==="image"&&R("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&&R("p",{className:wt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:t.content})]})]})}const by=({transcript:t,call:e})=>{const n=me(null),i=me(null),s=me(null),[o,r]=xe([]),[a,l]=xe(!1),[c,d]=xe([]),[,u]=Ur();ke(()=>()=>{o.forEach(S=>URL.revokeObjectURL(S.preview))},[o]),ke(()=>{if(c.length===0)return;const S=t.filter(x=>x.role==="user"&&!x.id.startsWith("optimistic-"));if(S.length>0){const x=S[S.length-1];d(p=>p.filter(g=>g.timestamp>x.timestamp))}},[t,c]);const f=S=>new Promise((x,p)=>{const g=new FileReader;g.onload=()=>x(g.result),g.onerror=p,g.readAsDataURL(S)}),m=async S=>{if(S.type.startsWith("image/"))try{const x=await f(S),p=URL.createObjectURL(S),g={id:Date.now().toString(),file:S,base64:x,preview:p};r(h=>[...h,g])}catch(x){Ce.error("Error processing image:",x)}},_=S=>{r(x=>{const p=x.find(g=>g.id===S);return p&&URL.revokeObjectURL(p.preview),x.filter(g=>g.id!==S)})},v=S=>{const x=S.target,p=x.files;p&&p.length>0&&(Array.from(p).forEach(m),x.value="")},w=S=>{var p;const x=(p=S.clipboardData)==null?void 0:p.items;x&&Array.from(x).forEach(g=>{if(g.type.startsWith("image/")){const h=g.getAsFile();h&&m(h)}})},y=()=>{var S;(S=i.current)==null||S.click()},C=()=>{l(!0)},k=S=>{fetch(S).then(x=>x.blob()).then(x=>{const p=new File([x],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});m(p)}).catch(x=>{Ce.error("Error processing camera capture:",x)})},T=async()=>{var p;const S=n.current&&n.current.value.trim()!=="",x=o.length>0;if(S||x){const g=((p=n.current)==null?void 0:p.value)||"",h=new Date,b={id:`optimistic-${h.getTime()}`,role:"user",content:g,timestamp:h,attachments:o.map(I=>({type:"image",url:I.base64}))};d(I=>[...I,b]),x&&u("processing_image"),e.sendConversationMessage(g,o.map(I=>I.base64)),n.current&&(n.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},E=S=>{S.key==="Enter"&&(S.preventDefault(),T())},D=[...t,...c];return R("div",{className:"relative h-[300px] sm:h-[386px] bg-[#E6E3D3] dark:bg-[#38383C] rounded-t-3xl sm:rounded-3xl p-4 flex flex-col w-full",children:[R("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((S,x)=>R(_y,{item:S,containerRef:s},S.id+x))}),o.length>0&&R("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(S=>R("div",{className:"relative",children:[R("img",{src:S.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),R("button",{onClick:()=>_(S.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:R(Kr,{className:"w-3 h-3"})})]},S.id))}),R("div",{className:"flex items-center h-8 bg-[#FEFDF5] border border-[#969696] dark:border-[#3D3D46] dark:bg-[#222227] rounded-full p-2 gap-2",children:[R("input",{ref:n,type:"text",onKeyDown:E,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),R("input",{ref:i,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),R(Ct,{tooltip:"Attach image",onClick:y,children:R(ty,{className:"text-[#969696] w-4 h-4"})}),R(Ct,{tooltip:"Take photo",onClick:C,children:R(jd,{className:"text-[#969696] w-4 h-4"})}),R(Ct,{tooltip:"Send",children:R(iy,{onClick:T,className:"text-[#969696] w-4 h-4"})})]}),a&&R(yy,{onCapture:k,onClose:()=>l(!1)})]})};function wy({onCollapse:t}){return R("div",{className:"flex items-center justify-between w-full",children:[R(cy,{}),R(Ct,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:R(Kr,{className:"text-black dark:text-white"})})]})}const Sy=({call:t,onCollapse:e,transcript:n,chatMode:i})=>R(Bp,{children:R(gn.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},layoutId:"transcript-widget",className:"relative bg-[#FEFDF5] text-black dark:bg-black gap-3 w-full sm:w-[400px] dark:text-white rounded-t-3xl sm:rounded-3xl shadow-lg shadow-[#38383878]",children:[R("div",{className:"p-4 text-center",children:[R(wy,{onCollapse:e}),!i&&R(Fd,{className:"h-[144px]",stream:t.remoteStream}),R(pd,{size:"large",className:"mb-4"}),R(Hd,{call:t,chatMode:i}),R(ly,{className:"mt-2"})]}),R(gd,{stream:t.remoteStream,chatMode:i}),R(by,{call:t,transcript:n})]})});function zi(t,e){var n={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(n[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(n[i[s]]=t[i[s]])}return n}function B(t,e,n,i){return new(n||(n=Promise))(function(s,o){function r(c){try{l(i.next(c))}catch(d){o(d)}}function a(c){try{l(i.throw(c))}catch(d){o(d)}}function l(c){var d;c.done?s(c.value):(d=c.value,d instanceof n?d:new n(function(u){u(d)})).then(r,a)}l((i=i.apply(t,[])).next())})}var qd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Cy=new Uint8Array(16);function xy(){if(!qd)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qd(Cy)}for(var Kd=[],qi=0;qi<256;++qi)Kd[qi]=(qi+256).toString(16).substr(1);function _n(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||xy)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[i+o]=s[o];return e||function(r,a){var l=0,c=Kd;return[c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],"-",c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]],c[r[l++]]].join("")}(s)}const Xd="wss://rtc.telnyx.com",ky=1006,Yd={urls:"stun:stun.l.google.com:19302"},Ty=[{urls:"stun:stun.telnyx.com:3478"},Yd,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],Ay=[{urls:"stun:stundev.telnyx.com:3478"},Yd,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var V;(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",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed"})(V||(V={}));var Ey=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jd(t,e){return t(e={exports:{}},e.exports),e.exports}var Iy=Jd(function(t){var e,n;e=Ey,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(w,y){var C=w[y];if(typeof C.bind=="function")return C.bind(w);try{return Function.prototype.bind.call(C,w)}catch{return function(){return Function.prototype.apply.apply(C,[w,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(w,y){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<w?i:this.methodFactory(k,w,y)}this.log=this.debug}function d(w,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[w].apply(this,arguments))}}function u(w,y,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):i)}(w)||d.apply(this,arguments)}function f(w,y,C){var k,T=this;y=y??"WARN";var E="loglevel";function D(){var x;if(typeof window!==s&&E){try{x=window.localStorage[E]}catch{}if(typeof x===s)try{var p=window.document.cookie,g=p.indexOf(encodeURIComponent(E)+"=");g!==-1&&(x=/^([^;]+)/.exec(p.slice(g))[1])}catch{}return T.levels[x]===void 0&&(x=void 0),x}}typeof w=="string"?E+=":"+w:typeof w=="symbol"&&(E=void 0),T.name=w,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=C||u,T.getLevel=function(){return k},T.setLevel=function(x,p){if(typeof x=="string"&&T.levels[x.toUpperCase()]!==void 0&&(x=T.levels[x.toUpperCase()]),!(typeof x=="number"&&x>=0&&x<=T.levels.SILENT))throw"log.setLevel() called with invalid level: "+x;if(k=x,p!==!1&&function(g){var h=(r[g]||"silent").toUpperCase();if(typeof window!==s&&E){try{return void(window.localStorage[E]=h)}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+h+";"}catch{}}}(x),c.call(T,x,w),typeof console===s&&x<T.levels.SILENT)return"No console available for logging"},T.setDefaultLevel=function(x){y=x,D()||T.setLevel(x,!1)},T.resetLevel=function(){T.setLevel(y,!1),function(){if(typeof window!==s&&E){try{return void window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},T.enableAll=function(x){T.setLevel(T.levels.TRACE,x)},T.disableAll=function(x){T.setLevel(T.levels.SILENT,x)};var S=D();S==null&&(S=y),T.setLevel(S,!1)}var m=new f,_={};m.getLogger=function(w){if(typeof w!="symbol"&&typeof w!="string"||w==="")throw new TypeError("You must supply a name when creating a logger.");var y=_[w];return y||(y=_[w]=new f(w,m.getLevel(),m.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return m.noConflict=function(){return typeof window!==s&&window.log===m&&(window.log=v),m},m.getLoggers=function(){return _},m.default=m,m},t.exports?t.exports=n():e.log=n()});const Zd={debug:0,info:1,warn:2,error:3};class Ry{constructor(e={}){var n,i,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(n=e.enabled)!==null&&n!==void 0&&n,level:(i=e.level)!==null&&i!==void 0?i:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,n,i){if(!this.isCapturing||!this.options.enabled||Zd[e]<Zd[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:n},i&&Object.keys(i).length>0?{context:i}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Qd=null;function eu(){return Qd}function tu(t){Qd=t}const A=Iy.getLogger("telnyx"),Ki={trace:0,debug:1,info:2,warn:3,error:4};let nu=Ki.info;function iu(t){if(t==null||typeof t!="object")return t;try{const n=JSON.stringify(t),i=JSON.parse(n);if(typeof i=="object"&&i!==null&&Object.keys(i).length>1)return i}catch{}const e={};for(const n in t)try{const i=t[n];if(typeof i=="function")continue;if(typeof i=="object"&&i!==null)try{e[n]=JSON.parse(JSON.stringify(i))}catch{e[n]=String(i)}else e[n]=i}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const Ly=A.methodFactory;A.methodFactory=(t,e,n)=>{const i=Ly(t,e,n);return function(...s){if(Ki[t]>=nu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);i(...r)}const o=eu();if(o!=null&&o.isActive()){const[r,...a]=s,l=typeof r=="string"?r:JSON.stringify(r);let c;a.length>0&&(c=a.length===1&&typeof a[0]=="object"&&a[0]!==null?iu(a[0]):{args:a.map(iu)}),o.addEntry(t,l,c)}}},A.setLevel("debug",!1);const Xi=t=>{const[e,n,i,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{A.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:n,participantName:i,codec:s,media:a,participantData:r}},su=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},bn=t=>t instanceof Function||typeof t=="function",Yi=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Py=/^(ws|wss):\/\//,ru=(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?ru(a,r):{result:s}},ou=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),Ji=({login:t,passwd:e,password:n,login_token:i})=>!!(t&&(e||n)||i),ei=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Xr=t=>{var e,n,i,s,o,r;let a="",l="";return!((n=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||n===void 0)&&n.state&&(a=(s=(i=t==null?void 0:t.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function au({debounceTime:t}){let e,n;return{promise:new Promise((i,s)=>{e=t?My(i,t):i,n=s}),resolve:e,reject:n}}const My=(t,e)=>{let n;return(...i)=>{clearTimeout(n),n=window.setTimeout(()=>{t(...i)},e)}},Yr="telnyx-voice-sdk-id";function Kt(){return sessionStorage.getItem(Yr)}var Ie,ut,ee;typeof window<"u"&&window.addEventListener("beforeunload",()=>{sessionStorage.removeItem(Yr)}),function(t){t.Offer="offer",t.Answer="answer"}(Ie||(Ie={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(ut||(ut={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ee||(ee={}));const Je={generic:"event",[ee.Display]:"participantData",[ee.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Dy={invalidCredentialsOptions:"InvalidCredentialsOptions"},Oy={destinationNumber:"",remoteCallerName:"Outbound Call",remoteCallerNumber:"",callerName:"",callerNumber:"",audio:!0,useStereo:!1,debug:!1,debugOutput:"socket",attach:!1,screenShare:!1,userVariables:{},mediaSettings:{useSdpASBandwidthKbps:!1,sdpASBandwidthKbps:0},mutedMicOnStart:!1,prefetchIceCandidates:!0};var X,Jr,He,ht,Ne;(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"})(X||(X={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Jr||(Jr={})),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"}(He||(He={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(ht||(ht={})),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"}(Ne||(Ne={}));const wn="GLOBAL",Ue={},ti=(t,e)=>`${t}|${e}`,lu=(t,e=wn)=>ti(t,e)in Ue,Lt=(t,e,n=wn)=>{const i=ti(t,n);i in Ue||(Ue[i]=[]),Ue[i].push(e)},cu=(t,e,n=wn)=>{const i=function(s){Pt(t,i,n),e(s)};return i.prototype.targetRef=e,Lt(t,i,n)},Pt=(t,e,n=wn)=>{if(!lu(t,n))return!1;const i=ti(t,n);if(bn(e))for(let s=Ue[i].length-1;s>=0;s--){const o=Ue[i][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Ue[i].splice(s,1)}else Ue[i]=[];return Ue[i].length===0&&delete Ue[i],!0},J=(t,e,n=wn,i=!0)=>{const s=i&&n!==wn;if(!lu(t,n))return s&&J(t,e),!1;const o=ti(t,n),r=Ue[o].length;if(!r)return s&&J(t,e),!1;for(let a=r-1;a>=0;a--)Ue[o][a](e);return s&&J(t,e),!0},Zr=t=>{const e=ti(t,"");Object.keys(Ue).filter(n=>n.indexOf(e)===0).forEach(n=>delete Ue[n])};let Ny=typeof WebSocket<"u"?WebSocket:null;const Fy=0,Vy=1,By=2,du=3;class uu{constructor(e){this.session=e,this.previousGatewayState="",this._wsClient=null,this._host=Xd,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this.upDur=null,this.downDur=null;const{host:n,env:i,region:s,useCanaryRtcServer:o}=e.options;i&&(this._host=i==="development"?"wss://rtcdev.telnyx.com":Xd),n&&(this._host=(r=>`${Py.test(r)?"":"wss://"}${r}`)(n)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===Vy}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Fy}get closing(){return!!this._wsClient&&this._wsClient.readyState===By}get closed(){return!!this._wsClient&&this._wsClient.readyState===du}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){const e=new URL(this._host);let n=Kt();this.session.options.rtcIp&&this.session.options.rtcPort&&(n=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),n&&e.searchParams.set("voice_sdk_id",n),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),n&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),A.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0);try{this._wsClient=new Ny(e.toString()),this._registerSocketEvents(this._wsClient)}catch(i){const s=i instanceof Error?i:new Error(`Failed to create WebSocket: ${String(i)}`);J(V.Error,{error:s},this.session.uuid),A.error("WebSocket connection failed:",s)}}sendRawText(e){var n;(n=this._wsClient)===null||n===void 0||n.send(e)}send(e){var n;const{request:i}=e,s=new Promise((o,r)=>{if(i.hasOwnProperty("result"))return o();cu(i.id,a=>{const{result:l,error:c}=ru(a);return c?r(c):o(l)})});return A.debug(`SEND:
107
107
  `,JSON.stringify(i,null,2),`
108
- `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;bn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>Y(V.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),Y(V.SocketClose,n,this.session.uuid)),e.onerror=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),Y(V.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)),e.onmessage=n=>{var i,s;const o=iu(n.data);var r;if(typeof o!="string"){if(o.voice_sdk_id&&(r=o.voice_sdk_id,sessionStorage.setItem(Xr,r)),this._unsetTimer(o.id),T.debug(`RECV:
108
+ `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(i)),s}close(){if(!this._wsClient||this.closing)return;const e=this._wsClient;bn(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=n=>J(V.SocketOpen,n,this.session.uuid),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),J(V.SocketClose,n,this.session.uuid)),e.onerror=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),J(V.SocketError,{error:n,sessionId:this.session.sessionid},this.session.uuid)),e.onmessage=n=>{var i,s;const o=su(n.data);var r;if(typeof o!="string"){if(o.voice_sdk_id&&(r=o.voice_sdk_id,sessionStorage.setItem(Yr,r)),this._unsetTimer(o.id),A.debug(`RECV:
109
109
  `,JSON.stringify(o,null,2),`
110
- `),Ne[`${(s=(i=o==null?void 0:o.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!Y(o.id,o)){const a=Kr(o);Y(V.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==cu?(T.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||Y(V.SocketClose,{code:Cy,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):T.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(T.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(T.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):T.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),Y(V.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else T.warn("Unknown message from socket",e)}}class ni{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:_n()},e)}}const uu={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 Me extends ni{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=Gi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in uu)i&&n.hasOwnProperty(i)&&(n[uu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class hu extends Me{constructor(e){super(),this.method=ee.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Vy{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>B(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Kr(n))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const n=new hu(zt());this.pendingRequestId=n.request.id,this.gatewayStateTask=ou({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ne.REGISTER,Ne.REGED].includes(i)}),this.session=e,this.gatewayStateTask=ou({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class fu extends Me{constructor(e){super(),this.method=ee.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var pu="2.25.25",Zr=pu;class By extends Me{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:Zr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class jy extends Me{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class gu extends Me{toString(){return ee.Invite}}class mu extends Me{toString(){return ee.Answer}}class vu extends Me{toString(){return ee.Attach}}class Uy extends Me{toString(){return ee.Bye}}class $y extends Me{toString(){return ee.Candidate}}class Hy extends Me{toString(){return ee.EndOfCandidates}}class Qr extends Me{toString(){return ee.Modify}}class yu extends Me{toString(){return ee.Info}}class Gy extends Me{toString(){return ee.Broadcast}}class Wy extends Me{toString(){return ee.Subscribe}}class zy extends Me{toString(){return ee.Unsubscribe}}class qy extends Me{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Zr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class Ky{constructor(e){if(this.options=e,this.uuid=_n(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",tu=(i=zi[n])!==null&&i!==void 0?i:zi.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new du(this),this.registerAgent=new Vy(this)}get __logger(){return T}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*ru(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}),T.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Xi(this.options)||ei(this.options)}broadcast(e){}disconnect(){return B(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(),T.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Lt(e,n,this.uuid),this}off(e,n){return Pt(e,n,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(T.debug("No existing connection found, creating a new one."),this.connection=new du(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(T.debug("Initiating connection to the server..."),this.connection.connect()),T.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){Y(V.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return B(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),Xi(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(ei(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";return T.error(s),void Y(V.Error,{error:new Error(s),type:Py.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return B(this,void 0,void 0,function*(){let s;s=e==="login"?new By(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!zt()):new qy({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!zt()});const o=yield this.execute(s).catch(r=>{this._handleLoginError(r),i&&i(r)});o&&(this.sessionid=o.sessid,n&&n())})}_onSocketOpen(){return B(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Jr(this.relayProtocol);for(const e in this.subscriptions)Jr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{T.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Pt(e,null,n)):(delete this.subscriptions[e],Jr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},bn(n)&&Lt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(V.SocketOpen,this._onSocketOpen),this.on(V.SocketClose,this.onNetworkClose),this.on(V.SocketError,this.onNetworkClose),this.on(V.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(V.SocketOpen,this._onSocketOpen),this.off(V.SocketClose,this.onNetworkClose),this.off(V.SocketError,this.onNetworkClose),this.off(V.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&&(T.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new fu(zt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){T.debug("Ping received"),this._pong=!0}static on(e,n){Lt(e,n)}static off(e){Pt(e)}static uuid(){return _n()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Yi=t=>navigator.mediaDevices.getUserMedia(t),Sn=t=>t&&t instanceof MediaStream,ii=(t,e)=>{const n=Ki(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},_u=(t,e)=>B(void 0,void 0,void 0,function*(){const n=Ki(t);if(n===null)return T.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return T.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Xy=t=>{t&&t.readyState==="live"&&t.stop()},si=t=>{Sn(t)&&t.getTracks().forEach(Xy),t=null},Ji=t=>B(void 0,void 0,void 0,function*(){T.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Yi(t)}catch(i){if(T.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,d=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const u=Gi(r,["deviceId"]);c=Object.keys(u).length===0||u}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const u=Gi(a,["deviceId"]);d=Object.keys(u).length===0||u}return l?{audio:c,video:d}:null})(t);if(s){T.warn("Device not found or not readable, falling back to default device");try{return yield Yi(s)}catch(o){throw T.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),ri=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===ht.AudioIn||s===ht.AudioOut,video:!s||s===ht.Video}))(t)).catch(s=>(T.error(s),null));if(i){if(si(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}),bu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Zi=(t,e,n)=>B(void 0,void 0,void 0,function*(){const i=yield ri(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}),Yy=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},eo=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=to(t);return n.includes(e)||i.includes(e)},to=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},Cn=(t,e=null,n=null)=>{if(!Sn(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}})},wu=t=>{Cn(t,"audio",!0)},no=t=>{Cn(t,"audio",!1)},Su=t=>{Cn(t,"audio",null)},Jy=t=>((e,n=null)=>{if(!Sn(e))return null;let i=[];switch(n){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some(s=>s.enabled)})(t,"audio");function Zy(){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 d=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/safari/gim)[0],u=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const d=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Ji}}catch(t){return t.message}}var _e;function Cu(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 xu(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{T.error("playAudio",e),t._playFulfilled=!0}))}function ku(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"})(_e||(_e={}));const Tu=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class Qy extends ni{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:_n(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class xt{constructor(e,n){this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(i){return new Ay(i)}(this.logCollectorOptions),this.logCollector.start(),eu(this.logCollector))}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,T.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return B(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),T.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,o=this.statsBuffer;this.statsBuffer=[];const r=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:o},r.length>0?{logs:r}:{}),{segment:s});return T.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:o.length,logEntries:r.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void T.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void T.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,d=this._segmentIndex,u=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:d}:{});yield this._sendPayload(u,n,i,s)})}sendPayload(e,n,i,s){return B(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";T.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(r=(o=e.logs)===null||o===void 0?void 0:o.length)!==null&&r!==void 0?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:d,body:u}),m=yield f();if(m.ok)T.info(`CallReportCollector: Successfully posted ${c}`);else{const _=yield m.text();T.error(`CallReportCollector: Failed to post ${c}`,{status:m.status,error:_})}}catch(a){T.warn(`CallReportCollector: Network error posting call report, retrying in ${xt.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,xt.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=yield fetch(c,{method:"POST",headers:d,body:JSON.stringify(e)});if(u.ok)T.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield u.text();T.error("CallReportCollector: Failed to post call report on retry",{status:u.status,error:f})}}catch(l){T.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),Qd()===this.logCollector&&eu(null),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return B(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const o=yield this.peerConnection.getStats(),r=new Date;let a,l,c=null,d=null,u=null,f=null;if(o.forEach(_=>{switch(_.type){case"outbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(c=_);break;case"inbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(d=_);break;case"candidate-pair":(_.nominated||_.state==="succeeded")&&(u=_);break;case"transport":f=_}}),c){const _=this._getOutboundAudioLevel(o,c);if(_!==null&&this.intervalAudioLevels.outbound.push(_),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.outbound.push(y)}}this.previousStats.outboundBytes=c.bytesSent}if(d){const _=this._getInboundAudioLevel(o,d);if(_!==null&&this.intervalAudioLevels.inbound.push(_),d.jitter!==void 0&&this.intervalJitters.push(1e3*d.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(d.bytesReceived||0)-this.previousStats.inboundBytes,w=(d.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.inbound.push(y)}}this.previousStats.inboundBytes=d.bytesReceived}u&&(u.currentRoundTripTime!==void 0&&this.intervalRTTs.push(u.currentRoundTripTime),this.previousCandidatePairId!==null&&u.id!==this.previousCandidatePairId&&T.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:u.id}),this.previousCandidatePairId=(n=u.id)!==null&&n!==void 0?n:null),u&&(a=this._resolveCandidate(o,u.localCandidateId),l=this._resolveCandidate(o,u.remoteCandidateId)),this.previousStats.timestamp=r.getTime();const m=r.getTime()-this.intervalStartTime.getTime();if(e||m>=this.options.interval){const _=this._createStatsEntry(this.intervalStartTime,r,c,d,u,a,l,f);if(this.statsBuffer.push(_),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),T.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const v=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(v>=xt.STATS_FLUSH_THRESHOLD||w>=xt.LOGS_FLUSH_THRESHOLD){T.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:v,logEntries:w});try{this.onFlushNeeded()}catch(y){T.error("CallReportCollector: onFlushNeeded callback error",{error:y})}}}this.intervalStartTime=r,this._resetIntervalAccumulators()}}catch(o){T.error("CallReportCollector: Error collecting stats",{error:o})}})}_createStatsEntry(e,n,i,s,o,r,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),o&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived},c.ice=Object.assign(Object.assign({id:o.id,state:o.state,nominated:o.nominated,writable:o.writable,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(c.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{})),c}_resolveCandidate(e,n){if(!n)return void T.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void T.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;T.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=n,r===void 0||a===void 0)return null;const l=e-r,c=n-a;if(c<=0)return null;const d=Math.sqrt(l/c);return Math.min(1,Math.max(0,d))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}xt.STATS_FLUSH_THRESHOLD=300,xt.LOGS_FLUSH_THRESHOLD=800,xt.RETRY_DELAY_MS=500;var Qi,Eu=Yd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,g,h,b){var A,P,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=p._events)?(P.newListener&&(p.emit("newListener",g,h.listener?h.listener:h),P=p._events),L=P[g]):(P=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=P[g]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(A=o(p))&&0<A&&L.length>A){L.warned=!0;var D=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+g+" listeners added. Use emitter.setMaxListeners() to increase limit");D.name="MaxListenersExceededWarning",D.emitter=p,D.type=g,D.count=L.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(D)}}else L=P[g]=h,++p._eventsCount;return p}function a(p,g,h){function b(){p.removeListener(g,b),A||(A=!0,h.apply(p,arguments))}var A=!1;return b.listener=h,b}function l(p){var g=this._events;if(g){var h=g[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,g){for(var h=Array(g);g--;)h[g]=p[g];return h}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var g,h,b,A,P,L,D,M=p==="error";if(L=this._events)M=M&&L.error==null;else if(!M)return!1;if(D=this.domain,M){if(g=arguments[1],!D){if(g instanceof Error)throw g;var N=new Error('Uncaught, unspecified "error" event. ('+g+")");throw N.context=g,N}return g||(g=new Error('Uncaught, unspecified "error" event')),g.domainEmitter=this,g.domain=D,g.domainThrown=!1,D.emit("error",g),!1}if(!(h=L[p]))return!1;var W=typeof h=="function";switch(b=arguments.length){case 1:(function(j,re,te){if(re)j.call(te);else for(var $=j.length,ae=c(j,$),U=0;U<$;++U)ae[U].call(te)})(h,W,this);break;case 2:(function(j,re,te,$){if(re)j.call(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].call(te,$)})(h,W,this,arguments[1]);break;case 3:(function(j,re,te,$,ae){if(re)j.call(te,$,ae);else for(var U=j.length,q=c(j,U),J=0;J<U;++J)q[J].call(te,$,ae)})(h,W,this,arguments[1],arguments[2]);break;case 4:(function(j,re,te,$,ae,U){if(re)j.call(te,$,ae,U);else for(var q=j.length,J=c(j,q),ne=0;ne<q;++ne)J[ne].call(te,$,ae,U)})(h,W,this,arguments[1],arguments[2],arguments[3]);break;default:for(A=Array(b-1),P=1;P<b;P++)A[P-1]=arguments[P];(function(j,re,te,$){if(re)j.apply(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].apply(te,$)})(h,W,this,A)}return!0},s.prototype.addListener=function(p,g){return r(this,p,g,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,g){return r(this,p,g,!0)},s.prototype.once=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,g)),this},s.prototype.prependOnceListener=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,g)),this},s.prototype.removeListener=function(p,g){var h,b,A,P,L;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===g||h.listener&&h.listener===g)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||g));else if(typeof h!="function"){for(A=-1,P=h.length;0<P--;)if(h[P]===g||h[P].listener&&h[P].listener===g){L=h[P].listener,A=P;break}if(0>A)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(D,M){for(var N=M,W=N+1,j=D.length;W<j;N+=1,W+=1)D[N]=D[W];D.pop()})(h,A);b.removeListener&&this.emit("removeListener",p,L||g)}return this},s.prototype.removeAllListeners=function(p){var g,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,A=Object.keys(h),P=0;P<A.length;++P)(b=A[P])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(g=h[p])=="function")this.removeListener(p,g);else if(g)do this.removeListener(p,g[g.length-1]);while(g[0]);return this},s.prototype.listeners=function(p){var g,h,b=this._events;return b?h=(g=b[p])?typeof g=="function"?[g.listener||g]:function(A){for(var P=Array(A.length),L=0;L<P.length;++L)P[L]=A[L].listener||A[L];return P}(g):[]:h=[],h},s.listenerCount=function(p,g){return typeof p.listenerCount=="function"?p.listenerCount(g):l.call(p,g)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function f(){if(!d&&!(d=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 d(u)}for(var m=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],v=0;256>v;++v)_.push((v+256).toString(16).substr(1));function w(p){var g=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[p[g+0]]+_[p[g+1]]+_[p[g+2]]+_[p[g+3]]+"-"+_[p[g+4]]+_[p[g+5]]+"-"+_[p[g+6]]+_[p[g+7]]+"-"+_[p[g+8]]+_[p[g+9]]+"-"+_[p[g+10]]+_[p[g+11]]+_[p[g+12]]+_[p[g+13]]+_[p[g+14]]+_[p[g+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&m.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(p,g,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function C(p,g){if(!p||!g)return{};const h={...p};if(h.localCandidateId){const b=g.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=g.get(h.remoteCandidateId);h.remote={...b}}return h}function k(p,g,h){return 8*function(b,A,P){const L=b[P],D=A?A[P]:null;return L===null||D===null?null:(L-D)/(b.timestamp-A.timestamp)*1e3}(p,g,h)}function E(p){if(!p.entries)return p;const g={};return p.forEach(function(h,b){g[b]=h}),g}function R(p,g,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const A of p.values())switch(A.type){case"outbound-rtp":{const P=A.mediaType||A.kind,L={};let D={};if(!["audio","video"].includes(P))continue;if(A.codecId){const M=p.get(A.codecId);M&&(L.clockRate=M.clockRate,L.mimeType=M.mimeType,L.payloadType=M.payloadType)}D=p.get(A.mediaSourceId)||p.get(A.trackId)||{},b[P].outbound.push({...A,...L,track:{...D}});break}case"inbound-rtp":{let P=A.mediaType||A.kind,L={};const D={};if(!["audio","video"].includes(P))if(A.id.includes("Video"))P="video";else{if(!A.id.includes("Audio"))continue;P="audio"}if(A.codecId){const M=p.get(A.codecId);M&&(D.clockRate=M.clockRate,D.mimeType=M.mimeType,D.payloadType=M.payloadType)}if(!b.connection.id&&A.transportId){const M=p.get(A.transportId);if(M&&M.selectedCandidatePairId){const N=p.get(M.selectedCandidatePairId);b.connection=C(N,p)}}L=p.get(A.mediaSourceId)||p.get(A.trackId)||{},b[P].inbound.push({...A,...D,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=A.dataChannelsClosed,b.connection.dataChannelsOpened=A.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=A.mediaType||A.kind;const L={};if(!["audio","video"].includes(P))if(A.id.includes("Video"))P="video";else{if(!A.id.includes("Audio"))continue;P="audio"}if(A.codecId){const D=p.get(A.codecId);D&&(L.clockRate=D.clockRate,L.mimeType=D.mimeType,L.payloadType=D.payloadType)}if(!b.connection.id&&A.transportId){const D=p.get(A.transportId);if(D&&D.selectedCandidatePairId){const M=p.get(D.selectedCandidatePairId);b.connection=C(M,p)}}b.remote[P].inbound.push({...A,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=A.mediaType||A.kind,L={};if(!["audio","video"].includes(P))continue;if(A.codecId){const D=p.get(A.codecId);D&&(L.clockRate=D.clockRate,L.mimeType=D.mimeType,L.payloadType=D.payloadType)}b.remote[P].outbound.push({...A,...L});break}}if(!b.connection.id)for(const A of p.values())A.type==="candidate-pair"&&A.nominated&&A.state==="succeeded"&&(b.connection=C(A,p));return b=function(A,P){return P&&(A.audio.inbound.map(L=>{let D=P.audio.inbound.find(M=>M.id===L.id);L.bitrate=k(L,D,"bytesReceived"),L.packetRate=k(L,D,"packetsReceived")}),A.audio.outbound.map(L=>{let D=P.audio.outbound.find(M=>M.id===L.id);L.bitrate=k(L,D,"bytesSent"),L.packetRate=k(L,D,"packetsSent")}),A.video.inbound.map(L=>{let D=P.video.inbound.find(M=>M.id===L.id);L.bitrate=k(L,D,"bytesReceived"),L.packetRate=k(L,D,"packetsReceived")}),A.video.outbound.map(L=>{let D=P.video.outbound.find(M=>M.id===L.id);L.bitrate=k(L,D,"bytesSent"),L.packetRate=k(L,D,"packetsSent")})),A}(b,g),b}let O,S={},x=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const g={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=g.getStatsInterval||1e3,this.rawStats=!!g.rawStats,this.statsObject=!!g.statsObject,this.filteredStats=!!g.filteredStats,this.shouldWrapGetUserMedia=!!g.wrapGetUserMedia,typeof g.remote=="boolean"&&(this.remote=g.remote),this.debug=!!g.debug,this.logLevel=g.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,g){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:g})}async addConnection(p){const{pc:g,peerId:h}=p;let{connectionId:b,remote:A}=p;if(A=typeof A=="boolean"?A:this.remote,!(g&&g instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const D=this.peersToMonitor[h][L];if(D.pc===g)throw new Error(`We are already monitoring peer with id ${h}.`);D.pc.connectionState==="closed"&&this.removeConnection({pc:D.pc})}}const P=g.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(L){delete L.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:b,pc:g,remote:A}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((g,h)=>g.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(g=>g.tag===p):this.timeline}get logger(){const p=g=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(g)>-1};return{error(...g){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...g)},warn(...g){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...g)},info(...g){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...g)},debug(...g){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...g)}}}removeConnection(p){let g,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let A in this.peersToMonitor)h in this.peersToMonitor[A]&&(b=this.peersToMonitor[A][h].pc,g=A)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let A in this.peersToMonitor)for(let P in this.peersToMonitor[A])this.peersToMonitor[A][P].pc===b&&(h=P,g=A)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[g][h],Object.values(this.peersToMonitor[g]).length===0&&delete this.peersToMonitor[g],{connectionId:h}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let g in this.peersToMonitor[p]){let h=this.peersToMonitor[p][g].pc;this.removePeerConnectionEventListeners(g,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),x.forEach(p=>{this.removeTrackEventListeners(p)}),x=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(p){let{peerId:g,connectionId:h,pc:b,remote:A}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:A}};if(this.peersToMonitor[g]){if(h in this.peersToMonitor[g])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[g][h]=P}else this.peersToMonitor[g]={[h]:P};this.addPeerConnectionEventListeners(g,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(g=>{this.emitEvent(g)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let g={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);g[p]=this.peersToMonitor[p]}else g=this.peersToMonitor;let h=[];for(const b in g)for(const A in g[b]){const P=g[b][A],L=P.pc;if(L&&!this.checkIfConnectionIsClosed(b,A,L))try{const D=this.getTimestamp(),M=L.getStats(null);if(M){const N=await M,W=this.getTimestamp(),j=E(N),re={remote:P.options.remote},te=R(N,P.stats.parsed,re),$={event:"stats",tag:"stats",peerId:b,connectionId:A,timeTaken:W-D,data:te};this.rawStats===!0&&($.rawStats=N),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),P.stats.parsed=te}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(D){this.logger.error(D)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const g in this.peersToMonitor[p]){const h=this.peersToMonitor[p][g].pc;this.checkIfConnectionIsClosed(p,g,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,g,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let A=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:A,peerId:p,connectionId:g,tag:"connection",data:"closed"})}return b}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),O.apply(navigator.mediaDevices,arguments).then(g=>(p({stream:g}),g),g=>(p({error:g}),Promise.reject(g)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const g={...p};for(const b in g){var h=g[b];this.statsToMonitor.includes(h.type)||delete g[b]}return g}get peerConnectionListeners(){return{icecandidate:(p,g,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:g,data:b.candidate})},track:(p,g,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const A=b.track,P=b.streams[0];p in this.peersToMonitor&&g in this.peersToMonitor[p]&&(this.peersToMonitor[p][g].stream=P),this.addTrackEventListeners(A,g),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:g,data:{stream:P?this.getStreamDetails(P):null,track:A?this.getMediaTrackDetails(A):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:g,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceConnectionState})},icegatheringstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceGatheringState})},icecandidateerror:(p,g,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:g,error:{errorCode:b.errorCode}})},connectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.connectionState})},negotiationneeded:(p,g,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:g})},datachannel:(p,g,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:g,data:b.channel})}}}addPeerConnectionEventListeners(p,g,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${g}.`),S[g]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[g][b]=this.peerConnectionListeners[b].bind(this,p,g,h),h.addEventListener(b,S[g][b],!1)})}parseGetUserMedia(p){try{const g={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(g.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),x.push(h)})),this.emitEvent(g)}catch{}}parseStream(p){const g={audio:[],video:[]};return p.getTracks().forEach(h=>{g[h.kind].push(this.getMediaTrackDetails(h))}),g}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:g=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:g}})},unmute:g=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:g}})},overconstrained:g=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:g}})},ended:g=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:g}}),this.removeTrackEventListeners(g.target)}}}addTrackEventListeners(p,g){S[p.id]={};const h=this.getTrackEventObject(g);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const g=this.getTrackEventObject();Object.keys(g).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const g={...p,timestamp:new Date};this.addToTimeline(g),g.tag&&this.emit(g.tag,g)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,g){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{g.removeEventListener(h,S[p][h],!1)}),delete S[p]),g.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),g.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const g=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),g.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(Qi=Eu)&&Qi.__esModule&&Object.prototype.hasOwnProperty.call(Qi,"default")&&Qi.default;var e_=Eu.WebRTCStats;function t_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(c){const{jitter:d,rtt:u}=c,f=d+u/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,f=d/(u+d)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function n_(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 i_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class s_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class r_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function Au(t,e){var n,i;return{errorCode:t.errorCode,errorText:t.errorText,url:t.url,address:t.address,port:t.port,connectionState:e.connectionState,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState,localDescriptionType:(n=e.localDescription)===null||n===void 0?void 0:n.type,remoteDescriptionType:(i=e.remoteDescription)===null||i===void 0?void 0:i.type}}function o_(t,e){const n=_n();let i=!1;const s=new e_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&Y(V.StatsFrame,function({data:a}){var l,c,d,u,f,m,_,v;const{audio:w,remote:y}=a,{audio:C}=y,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,E=(u=(d=C.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&u!==void 0?u:1/0,R=(m=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&m!==void 0?m:-1,O=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,S=t_({jitter:1e3*k,rtt:1e3*E,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:E,mos:S,quality:n_(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new r_(n,r))});return{get isRunning(){return i},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(i)T.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new i_(n,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0}catch(c){T.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();Y(V.StatsReport,a,t.uuid),r==="file"&&function(l,c){const d=new Blob([JSON.stringify(l)],{type:"application/json"}),u=URL.createObjectURL(d),f=document.createElement("a");f.href=u,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(u)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new s_(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const Iu=(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:a_(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:He.LayerInfo},a);Y(V.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:He.LayoutInfo},a);Y(V.Notification,l,t.uuid);break}}},a_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return iu(e)};class Ru{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._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>B(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(T.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${r}`),r==="failed"||r==="disconnected"){const a=()=>B(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,d){return B(this,void 0,void 0,function*(){const u={connectionState:c.connectionState,previousConnectionState:d,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const m=f[0].sender,_=m==null?void 0:m.transport;_&&(u.dtlsState=_.state)}c.sctp&&(u.sctpState=c.sctp.state);try{const m=yield c.getStats();m.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(u.candidatePairState=_.state,m.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(u.localCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(u.remoteCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(u.dtlsCipher=_.dtlsCipher,u.srtpCipher=_.srtpCipher,u.tlsVersion=_.tlsVersion,_.dtlsState&&(u.dtlsState=_.dtlsState))})}catch(m){T.error("Error gathering connection state details:",m)}return u})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}r==="failed"&&Y(V.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${r}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=r,this._isTrickleIce()&&(r==="connecting"&&performance.mark("peer-connection-connecting"),r==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=()=>{T.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{T.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},T.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Ie.Offer}get isAnswer(){return this.type===Ie.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return B(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(){this.instance?(T.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{T.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),T.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):T.warn("Cannot log transceivers: peer connection is null")}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=l=>`${l.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(){switch(T.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":Y(V.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(T.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){T.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?T.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;this.options.remoteStream=n,s===!1&&ii(i,this.options.remoteStream)}createPeerConnection(){return B(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:Ie.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(Y(V.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&Sn(this.options.localStream)&&(T.info("Muting local audio tracks on start"),no(this.options.localStream)),this.options.localStream||(T.warn("No local media stream available"),!this.options.audio)?performance.mark("peer-creation-end"):T.warn("Audio is required but no local stream — skipping negotiation")})}init(){var e;return B(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=o_(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Sn(i)){const o=i.getAudioTracks();let r=[...o];if(T.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{T.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],T.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(d=>{T.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Tu(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(d=>{d.kind==="audio"&&(this.options.userVariables.microphoneLabel=d.label),d.kind==="video"&&(this.options.userVariables.cameraLabel=d.label);const u=this.instance.addTransceiver(d,c);d.kind==="audio"&&a.length>0&&this._setCodecs(u,a),d.kind==="video"&&l.length>0&&this._setCodecs(u,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&ii(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});T.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Tu(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);T.info("Add transceiver",e,n)}}_createOffer(){return B(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,T.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){T.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){T.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return T.debug("Skipping negotiation, state:",this.instance.signalingState),T.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ie.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){T.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){bn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(Sn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,B(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield Zi(s,a,ht.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield Zi(r,l,ht.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Ji(e)})}_isOffer(){return this.type===Ie.Offer}_isAnswer(){return this.type===Ie.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return T.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?T.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(T.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):T.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}const es=Zr;class Lu{constructor(e,n,i=!1){this.session=e,this._isRecovering=i,this._callReportCollector=null,this.id="",this.state=X[X.New],this.prevState="",this.channels=[],this.role=Yr.Participant,this.extension=null,this._state=X.New,this._prevState=X.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(const E in k.constraints)if(k.constraints.hasOwnProperty(E)&&k.constraints[E]!==C[E])return}k.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:d,remoteElement:u,options:f,mediaConstraints:{audio:m,video:_},ringtoneFile:v,ringbackFile:w}=e;this.options=Object.assign({},My,{audio:m,video:_,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:s,localElement:d,remoteElement:u,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:w,debug:f.debug,debugOutput:f.debugOutput,trickleIce:f.trickleIce,prefetchIceCandidates:f.prefetchIceCandidates,forceRelayCandidate:f.forceRelayCandidate,keepConnectionAliveOnSocketClose:f.keepConnectionAliveOnSocketClose,mutedMicOnStart:f.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=Cu(this.options.ringtoneFile,"_ringtone"),this._ringback=Cu(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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 isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return!Jy(this.options.localStream)}invite(){return B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=ut.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new Ru(Ie.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1})}answer(e={}){var n;return B(this,void 0,void 0,function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=ut.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 Ru(Ie.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1})}playRingtone(){xu(this._ringtone)}stopRingtone(){ku(this._ringtone)}playRingback(){xu(this._ringback)}stopRingback(){ku(this._ringback)}hangup(e,n){var i,s,o;const r=e||{},a=n!==!1,l=this._state<X.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=r.cause||l.cause,this.causeCode=r.causeCode||l.causeCode,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:[]],r.isRecovering)return this._isRecovering=!0,this.setState(X.Recovering),void this._finalize();this.setState(X.Hangup);const c=()=>{var d;T.debug(`[${this.id}] Closing peer from hangup`),(d=this.peer)===null||d===void 0||d.close(),this.setState(X.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const d=new Uy({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(d).catch(u=>{T.error("telnyx_rtc.bye failed!",u),Y(V.Error,{error:u,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new Qr({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 Qr({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 Qr({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 yu({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 yu({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){no(this.options.localStream)}unmuteAudio(){wu(this.options.localStream)}toggleAudioMute(){Su(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return B(this,void 0,void 0,function*(){const{instance:i}=this.peer,s=i.getSenders().find(({track:{kind:o}})=>o==="audio");if(s){const o=yield Yi({audio:{deviceId:{exact:e}}}),r=o.getAudioTracks()[0];r.enabled=!n,s.replaceTrack(r),this.options.micId=e;const{localStream:a}=this.options;a.getAudioTracks().forEach(l=>l.stop()),a.getVideoTracks().forEach(l=>o.addTrack(l)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,Cn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Cn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Cn(e,"video",null)}setVideoDevice(e){return B(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 Yi({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ii(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){no(this.options.remoteStream)}undeaf(){wu(this.options.remoteStream)}toggleDeaf(){Su(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void T.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 T.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"}]),T.info("Parameters: ",r),T.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{T.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>T.error(a))}else T.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n;switch(this._prevState=this._state,this._state=e,this.state=X[this._state].toLowerCase(),this.prevState=X[this._prevState].toLowerCase(),T.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case X.Purge:T.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case X.Active:this._isRecovering&&(this._isRecovering=!1,T.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:i,speakerId:s}=this.options;i&&s&&_u(i,s)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case X.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case ee.Answer:if(this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=X.Active)return;this._state>=X.Early&&this.setState(X.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case ee.Media:if(this._state>=X.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case ee.Display:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===ut.Inbound?ut.Outbound:ut.Inbound,c={type:Je[n],call:this,displayName:o,displayNumber:r,displayDirection:l};Y(V.Notification,c,this.id)||Y(V.Notification,c,this.session.uuid);break}case ee.Candidate:this._addIceCandidate(i);break;case ee.Info:case ee.Event:{const o=Object.assign(Object.assign({},i),{type:Je.generic,call:this});Y(V.Notification,o,this.id)||Y(V.Notification,o,this.session.uuid);break}case ee.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 ee.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 B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return T.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:d,conferenceMemberID:u,role:f}=n;this._dispatchConferenceUpdate({action:He.Join,conferenceName:d,participantId:Number(u),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const m=[];for(const _ in s)m.push(Object.assign({callId:s[_][0],index:Number(_)},qi(s[_][1])));this._dispatchConferenceUpdate({action:He.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:He.Add,callId:o,index:r},qi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:He.Modify,callId:o,index:r},qi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:He.Delete,callId:o,index:r},qi(s)));break;case"clear":this._dispatchConferenceUpdate({action:He.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 B(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:He.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{T.error("ConfChat subscription error:",s)});eo(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 B(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,Iu(this.session,o)):T.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{T.error("ConfInfo subscription error:",s)});eo(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(X.Active):this.setState(X.Held),!0}_handleChangeHoldStateError(e){return T.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return B(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ie.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(X.Early),this.gotAnswer&&this.setState(X.Active)}).catch(i=>{T.error("Call setRemoteDescription Error: ",i),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})})}_requestAnotherLocalDescription(){bn(this.peer.onSdpReadyTwice)?Y(V.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 T.info(`No candidate - retry
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-${es}`};switch(o){case Ie.Offer:this.setState(X.Requesting),r=new gu(a);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),r=this.options.attach===!0?new vu(a):new mu(a);break;default:return T.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(l=>{T.error(`${this.id} - Sending ${o} error:`,l),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return T.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-${es}`};switch(i){case Ie.Offer:this.setState(X.Requesting),s=new gu(o);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),s=this.options.attach===!0?new vu(o):new mu(o);break;default:return T.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===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(r=>{T.error(`${this.id} - Sending ${i} error:`,r),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;if(this._iceTimeout===null){const i=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),i)}e.candidate?T.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(T.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new $y({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 T.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(()=>{T.debug("Successfully added ICE candidate:",e)}).catch(i=>{T.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Hy({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.onicecandidateerror=n=>{var i;if(T.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Au(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ii(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{T.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&T.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(T.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Au(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ii(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error";this._dispatchNotification({type:Je.userMediaError,error:e,call:this,errorName:n,errorMessage:i}),T.error(`Media error (${n}): ${i}`,e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),T.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),T.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Je.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(Y(V.Notification,e,this.id,!1)||Y(V.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():_n(),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,Lt(V.MediaError,this._onMediaError,this.id),Lt(V.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Lt(V.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),bn(s)&&Lt(V.Notification,s.bind(this),this.id);const r=this.session.options.enableCallReports!==!1,a=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",c=this.session.options.debugLogMaxEntries||1e3;r&&(this._callReportCollector=new xt({enabled:!0,interval:a},{enabled:!0,level:l,maxEntries:c}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(X.Recovering):this.setState(X.New),T.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),T.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;si(n),si(i),Pt(V.MediaError,null,this.id),Pt(V.PeerConnectionFailureError,null,this.id),Pt(V.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{T.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void T.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void T.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:es},o=this._callReportCollector.flush(s);if(!o)return;const r=zt()||void 0;this._callReportCollector.sendPayload(o,n,i,r).catch(a=>{T.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void T.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return T.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:es},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void T.error("Cannot post call report: connection host not available");const o=zt()||void 0;this._callReportCollector.postReport(i,n,s,o).catch(r=>{T.error("Failed to post call report",{error:r})}).finally(()=>{var r;(r=this._callReportCollector)===null||r===void 0||r.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),T.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),T.debug("Stats stopped")}}Lu.setStateTelnyx=t=>{if(t){switch(t._state){case X.Recovering:t.state="recovering";break;case X.Requesting:case X.Trying:case X.Early:t.state="connecting";break;case X.Active:t.state="active";break;case X.Held:t.state="held";break;case X.Hangup:case X.Destroy:t.state="done";break;case X.Answering:t.state="ringing";break;case X.New:t.state="new"}return t}};class qt extends Lu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new Qy(e,n))}hangup(e={},n=!0){this.screenShare instanceof qt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return B(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new qt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof qt&&this.screenShare.hangup()}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&_u(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(this,void 0,void 0,function*(){const 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+=`
110
+ `),Ne[`${(s=(i=o==null?void 0:o.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.state}`]||!J(o.id,o)){const a=Xr(o);J(V.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==du?(A.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||J(V.SocketClose,{code:ky,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):A.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(A.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,n){this._wsClient===e?(A.debug(`Nulling socket reference (reason: ${n})`),this._wsClient=null):A.debug(`Skipping socket cleanup - old socket already replaced (reason: ${n})`)}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),J(V.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else A.warn("Unknown message from socket",e)}}class ni{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:_n()},e)}}const hu={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 Me extends ni{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const n=zi(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const i in hu)i&&n.hasOwnProperty(i)&&(n[hu[i]]=n[i],delete n[i]);e.dialogParams=n}this.buildRequest({method:this.toString(),params:e})}}class fu extends Me{constructor(e){super(),this.method=ee.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class jy{constructor(e){this.pendingRequestId=null,this.onSocketMessage=n=>B(this,void 0,void 0,function*(){n.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Xr(n))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const n=new fu(Kt());this.pendingRequestId=n.request.id,this.gatewayStateTask=au({}),this.session.execute(n);const i=yield this.gatewayStateTask.promise;return!!i&&[Ne.REGISTER,Ne.REGED].includes(i)}),this.session=e,this.gatewayStateTask=au({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class pu extends Me{constructor(e){super(),this.method=ee.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}var gu="2.25.25",Qr=gu;class Uy extends Me{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:Qr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class $y extends Me{constructor(e,n){super(),this.buildRequest({id:e,result:{method:n}})}}class mu extends Me{toString(){return ee.Invite}}class vu extends Me{toString(){return ee.Answer}}class yu extends Me{toString(){return ee.Attach}}class Hy extends Me{toString(){return ee.Bye}}class Gy extends Me{toString(){return ee.Candidate}}class Wy extends Me{toString(){return ee.EndOfCandidates}}class eo extends Me{toString(){return ee.Modify}}class _u extends Me{toString(){return ee.Info}}class zy extends Me{toString(){return ee.Broadcast}}class qy extends Me{toString(){return ee.Subscribe}}class Ky extends Me{toString(){return ee.Unsubscribe}}class Xy extends Me{constructor(e){super(),this.method="anonymous_login";const{target_type:n,target_id:i,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:n,target_id:i,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Qr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class Yy{constructor(e){if(this.options=e,this.uuid=_n(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var n,i;n=e.debug?"debug":"info",nu=(i=Ki[n])!==null&&i!==void 0?i:Ki.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._attachListeners(),this.connection=new uu(this),this.registerAgent=new jy(this)}get __logger(){return A}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*ou(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}),A.debug("Calling connect from execute since not currently connected."),this.connect()})}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}validateOptions(){return Ji(this.options)||ei(this.options)}broadcast(e){}disconnect(){return B(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(),A.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,n){return Lt(e,n,this.uuid),this}off(e,n){return Pt(e,n,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(A.debug("No existing connection found, creating a new one."),this.connection=new uu(this)),this._attachListeners(),this._autoReconnect=!0,this.connection.isAlive||(A.debug("Initiating connection to the server..."),this.connection.connect()),A.debug("Connect method called. Connection initiated.")})}_handleLoginError(e){J(V.Error,{error:e,sessionId:this.sessionid},this.uuid)}login({creds:e,onSuccess:n,onError:i}={}){return B(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),Ji(this.options))return this._login({type:"login",onSuccess:n,onError:i});if(ei(this.options))return this._login({type:"anonymous_login",onSuccess:n,onError:i});{const s="Invalid login options provided for authentication.";return A.error(s),void J(V.Error,{error:new Error(s),type:Dy.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:n,onError:i}){return B(this,void 0,void 0,function*(){let s;s=e==="login"?new Uy(this.options.login,this.options.password||this.options.passwd,this.options.login_token,this.sessionid,this.options.userVariables,!!Kt()):new Xy({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:this.sessionid,userVariables:this.options.userVariables,reconnection:!!Kt()});const o=yield this.execute(s).catch(r=>{this._handleLoginError(r),i&&i(r)});o&&(this.sessionid=o.sessid,n&&n())})}_onSocketOpen(){return B(this,void 0,void 0,function*(){})}onNetworkClose(){this.relayProtocol&&Zr(this.relayProtocol);for(const e in this.subscriptions)Zr(e);this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect&&(this._reconnectTimeout=setTimeout(()=>{A.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay))}_onSocketMessage(e){}_removeSubscription(e,n){this._existsSubscription(e,n)&&(n?(delete this.subscriptions[e][n],Pt(e,null,n)):(delete this.subscriptions[e],Zr(e)))}_addSubscription(e,n=null,i){this._existsSubscription(e,i)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][i]={},bn(n)&&Lt(e,n,i))}_existsSubscription(e,n){return!(!this.subscriptions.hasOwnProperty(e)||!(!n||n&&this.subscriptions[e].hasOwnProperty(n)))}_attachListeners(){this._detachListeners(),this.on(V.SocketOpen,this._onSocketOpen),this.on(V.SocketClose,this.onNetworkClose),this.on(V.SocketError,this.onNetworkClose),this.on(V.SocketMessage,this._onSocketMessage)}_detachListeners(){this.off(V.SocketOpen,this._onSocketOpen),this.off(V.SocketClose,this.onNetworkClose),this.off(V.SocketError,this.onNetworkClose),this.off(V.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&&(A.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new pu(Kt()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){A.debug("Ping received"),this._pong=!0}static on(e,n){Lt(e,n)}static off(e){Pt(e)}static uuid(){return _n()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}const Zi=t=>navigator.mediaDevices.getUserMedia(t),Sn=t=>t&&t instanceof MediaStream,ii=(t,e)=>{const n=Yi(t);n!==null&&(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject=e)},bu=(t,e)=>B(void 0,void 0,void 0,function*(){const n=Yi(t);if(n===null)return A.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return A.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield n.setSinkId(e),!0}catch{return!1}}),Jy=t=>{t&&t.readyState==="live"&&t.stop()},si=t=>{Sn(t)&&t.getTracks().forEach(Jy),t=null},Qi=t=>B(void 0,void 0,void 0,function*(){A.info("RTCService.getUserMedia",t);const{audio:e,video:n}=t;if(!e&&!n)return null;try{return yield Zi(t)}catch(i){if(A.error("getUserMedia error: ",i),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(i)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,d=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const u=zi(r,["deviceId"]);c=Object.keys(u).length===0||u}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const u=zi(a,["deviceId"]);d=Object.keys(u).length===0||u}return l?{audio:c,video:d}:null})(t);if(s){A.warn("Device not found or not readable, falling back to default device");try{return yield Zi(s)}catch(o){throw A.error("Fallback getUserMedia also failed: ",o),i}}}throw i}}),ri=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let n=[];const i=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===ht.AudioIn||s===ht.AudioOut,video:!s||s===ht.Video}))(t)).catch(s=>(A.error(s),null));if(i){if(si(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}),wu=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],es=(t,e,n)=>B(void 0,void 0,void 0,function*(){const i=yield ri(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}),Zy=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(n=>{e.hasOwnProperty(n)&&t[n]!==null&&t[n]!==void 0||delete t[n]})},to=(t,e)=>{if(!t)return!1;const{subscribed:n,alreadySubscribed:i}=no(t);return n.includes(e)||i.includes(e)},no=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(n=>{e[n]=t[`${n}Channels`]||[]}),e},Cn=(t,e=null,n=null)=>{if(!Sn(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}})},Su=t=>{Cn(t,"audio",!0)},io=t=>{Cn(t,"audio",!1)},Cu=t=>{Cn(t,"audio",null)},Qy=t=>((e,n=null)=>{if(!Sn(e))return null;let i=[];switch(n){case"audio":i=e.getAudioTracks();break;case"video":i=e.getVideoTracks();break;default:i=e.getTracks()}return i.some(s=>s.enabled)})(t,"audio");function e_(){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 d=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const d=navigator.userAgent.match(/safari/gim)[0],u=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),f=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:f,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const d=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),u=d[0],f=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:f,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:n,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:i,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!Qi}}catch(t){return t.message}}var _e;function xu(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 ku(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{A.error("playAudio",e),t._playFulfilled=!0}))}function Tu(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"})(_e||(_e={}));const Au=t=>{const e=[],n=[];return t&&t.length!==0?(t.forEach(i=>{const s=i.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(i):s.startsWith("video/")&&n.push(i)}),{audioCodecs:e,videoCodecs:n}):{audioCodecs:e,videoCodecs:n}};class t_ extends ni{constructor(e,n){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:_n(),type:"message",role:"user",content:[{type:"input_text",text:e},...n==null?void 0:n.map(i=>({type:"image_url",image_url:{url:i}}))]}}})}}class xt{constructor(e,n){this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairId=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this._segmentIndex=0,this._flushing=!1,this.options=e,this.logCollectorOptions=n||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this.logCollectorOptions.enabled&&(this.logCollector=function(i){return new Ry(i)}(this.logCollectorOptions),this.logCollector.start(),tu(this.logCollector))}start(e){var n,i;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,A.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,logCollectorActive:(i=(n=this.logCollector)===null||n===void 0?void 0:n.isActive())!==null&&i!==void 0&&i}),this.intervalId=setInterval(()=>{this._collectStats()},this.options.interval))}stop(){var e,n;return B(this,void 0,void 0,function*(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const i=(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&n!==void 0?n:0;this.logCollector&&this.logCollector.stop(),A.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:i,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e){var n,i;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const s=this._segmentIndex++,o=this.statsBuffer;this.statsBuffer=[];const r=(i=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&i!==void 0?i:[],a=new Date,l=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(a.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:a.toISOString()}),stats:o},r.length>0?{logs:r}:{}),{segment:s});return A.info("CallReportCollector: Flushed intermediate segment",{segment:s,intervals:o.length,logEntries:r.length,callId:e.callId}),l}finally{this._flushing=!1}}postReport(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void A.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void A.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,d=this._segmentIndex,u=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:d}:{});yield this._sendPayload(u,n,i,s)})}sendPayload(e,n,i,s){return B(this,void 0,void 0,function*(){yield this._sendPayload(e,n,i,s)})}_sendPayload(e,n,i,s){var o,r;return B(this,void 0,void 0,function*(){try{const a=new URL(i),l=`${a.protocol.replace(/^ws/,"http")}//${a.host}/call_report`,c=e.segment!==void 0&&!e.summary.endTimestamp?`intermediate segment ${e.segment}`:"final report";A.info(`CallReportCollector: Posting ${c}`,{endpoint:l,intervals:e.stats.length,logEntries:(r=(o=e.logs)===null||o===void 0?void 0:o.length)!==null&&r!==void 0?r:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=JSON.stringify(e),f=()=>fetch(l,{method:"POST",headers:d,body:u}),m=yield f();if(m.ok)A.info(`CallReportCollector: Successfully posted ${c}`);else{const _=yield m.text();A.error(`CallReportCollector: Failed to post ${c}`,{status:m.status,error:_})}}catch(a){A.warn(`CallReportCollector: Network error posting call report, retrying in ${xt.RETRY_DELAY_MS}ms`,{error:a}),yield new Promise(l=>setTimeout(l,xt.RETRY_DELAY_MS));try{const l=new URL(i),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,d={"Content-Type":"application/json","x-call-report-id":n,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const u=yield fetch(c,{method:"POST",headers:d,body:JSON.stringify(e)});if(u.ok)A.info("CallReportCollector: Successfully posted call report on retry");else{const f=yield u.text();A.error("CallReportCollector: Failed to post call report on retry",{status:u.status,error:f})}}catch(l){A.error("CallReportCollector: Retry also failed, giving up",{error:l})}}})}getStatsBuffer(){return this.statsBuffer}getLogs(){var e,n;return(n=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&n!==void 0?n:[]}cleanup(){this.logCollector&&(this.logCollector.clear(),eu()===this.logCollector&&tu(null),this.logCollector=null)}_collectStats(e=!1){var n,i,s;return B(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const o=yield this.peerConnection.getStats(),r=new Date;let a,l,c=null,d=null,u=null,f=null;if(o.forEach(_=>{switch(_.type){case"outbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(c=_);break;case"inbound-rtp":_.kind==="audio"&&_.mediaType==="audio"&&(d=_);break;case"candidate-pair":(_.nominated||_.state==="succeeded")&&(u=_);break;case"transport":f=_}}),c){const _=this._getOutboundAudioLevel(o,c);if(_!==null&&this.intervalAudioLevels.outbound.push(_),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(c.bytesSent||0)-this.previousStats.outboundBytes,w=(c.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.outbound.push(y)}}this.previousStats.outboundBytes=c.bytesSent}if(d){const _=this._getInboundAudioLevel(o,d);if(_!==null&&this.intervalAudioLevels.inbound.push(_),d.jitter!==void 0&&this.intervalJitters.push(1e3*d.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const v=(d.bytesReceived||0)-this.previousStats.inboundBytes,w=(d.timestamp||r.getTime())-this.previousStats.timestamp;if(w>0){const y=8*v*1e3/w;this.intervalBitrates.inbound.push(y)}}this.previousStats.inboundBytes=d.bytesReceived}u&&(u.currentRoundTripTime!==void 0&&this.intervalRTTs.push(u.currentRoundTripTime),this.previousCandidatePairId!==null&&u.id!==this.previousCandidatePairId&&A.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairId,current:u.id}),this.previousCandidatePairId=(n=u.id)!==null&&n!==void 0?n:null),u&&(a=this._resolveCandidate(o,u.localCandidateId),l=this._resolveCandidate(o,u.remoteCandidateId)),this.previousStats.timestamp=r.getTime();const m=r.getTime()-this.intervalStartTime.getTime();if(e||m>=this.options.interval){const _=this._createStatsEntry(this.intervalStartTime,r,c,d,u,a,l,f);if(this.statsBuffer.push(_),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),A.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this.onFlushNeeded&&!this._flushing){const v=this.statsBuffer.length,w=(s=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&s!==void 0?s:0;if(v>=xt.STATS_FLUSH_THRESHOLD||w>=xt.LOGS_FLUSH_THRESHOLD){A.info("CallReportCollector: Approaching buffer limits, requesting flush",{statsIntervals:v,logEntries:w});try{this.onFlushNeeded()}catch(y){A.error("CallReportCollector: onFlushNeeded callback error",{error:y})}}}this.intervalStartTime=r,this._resetIntervalAccumulators()}}catch(o){A.error("CallReportCollector: Error collecting stats",{error:o})}})}_createStatsEntry(e,n,i,s,o,r,a,l){const c={intervalStartUtc:e.toISOString(),intervalEndUtc:n.toISOString(),audio:{}};return i&&(c.audio.outbound={packetsSent:i.packetsSent,bytesSent:i.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)}),s&&(c.audio.inbound={packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),o&&(c.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived},c.ice=Object.assign(Object.assign({id:o.id,state:o.state,nominated:o.nominated,writable:o.writable,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(c.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{})),c}_resolveCandidate(e,n){if(!n)return void A.debug("CallReportCollector: candidateId is empty, skipping resolve");const i=e.get(n);if(!i)return void A.debug("CallReportCollector: candidate not found in stats report",{candidateId:n});const s={};if(i.address!==void 0&&(s.address=i.address),i.port!==void 0&&(s.port=i.port),i.candidateType!==void 0&&(s.candidateType=i.candidateType),i.protocol!==void 0&&(s.protocol=i.protocol),i.networkType!==void 0&&(s.networkType=i.networkType),Object.keys(s).length!==0)return s;A.debug("CallReportCollector: candidate report has no usable fields",{candidateId:n})}_getOutboundAudioLevel(e,n){let i;if(n.mediaSourceId&&(i=e.get(n.mediaSourceId)),i||e.forEach(s=>{i||s.type!=="media-source"||s.kind!=="audio"||(i=s)}),(i==null?void 0:i.audioLevel)!==void 0)return i.audioLevel;if(i){const s=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,n.trackId)}_getInboundAudioLevel(e,n){if(n.audioLevel!==void 0)return n.audioLevel;const i=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"inbound");return i!==null?i:this._getTrackAudioLevel(e,n.trackId)}_computeAudioLevelFromEnergy(e,n,i){if(e===void 0||n===void 0)return null;const s=i==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=i==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=n,r===void 0||a===void 0)return null;const l=e-r,c=n-a;if(c<=0)return null;const d=Math.sqrt(l/c);return Math.min(1,Math.max(0,d))}_getTrackAudioLevel(e,n){var i;if(!n)return null;const s=e.get(n);return s&&(i=s.audioLevel)!==null&&i!==void 0?i:null}_average(e){if(e.length===0)return;const n=e.reduce((i,s)=>i+s,0);return parseFloat((n/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}xt.STATS_FLUSH_THRESHOLD=300,xt.LOGS_FLUSH_THRESHOLD=800,xt.RETRY_DELAY_MS=500;var ts,Eu=Jd(function(t,e){var n;function i(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,g,h,b){var I,P,L;if(typeof h!="function")throw new TypeError('"listener" argument must be a function');if((P=p._events)?(P.newListener&&(p.emit("newListener",g,h.listener?h.listener:h),P=p._events),L=P[g]):(P=p._events=new i,p._eventsCount=0),L){if(typeof L=="function"?L=P[g]=b?[h,L]:[L,h]:b?L.unshift(h):L.push(h),!L.warned&&(I=o(p))&&0<I&&L.length>I){L.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+g+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=p,O.type=g,O.count=L.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(O)}}else L=P[g]=h,++p._eventsCount;return p}function a(p,g,h){function b(){p.removeListener(g,b),I||(I=!0,h.apply(p,arguments))}var I=!1;return b.listener=h,b}function l(p){var g=this._events;if(g){var h=g[p];if(typeof h=="function")return 1;if(h)return h.length}return 0}function c(p,g){for(var h=Array(g);g--;)h[g]=p[g];return h}Object.defineProperty(e,"__esModule",{value:!0}),i.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&n.active&&!(this instanceof n.Domain)&&(this.domain=n.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new i,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var g,h,b,I,P,L,O,M=p==="error";if(L=this._events)M=M&&L.error==null;else if(!M)return!1;if(O=this.domain,M){if(g=arguments[1],!O){if(g instanceof Error)throw g;var N=new Error('Uncaught, unspecified "error" event. ('+g+")");throw N.context=g,N}return g||(g=new Error('Uncaught, unspecified "error" event')),g.domainEmitter=this,g.domain=O,g.domainThrown=!1,O.emit("error",g),!1}if(!(h=L[p]))return!1;var W=typeof h=="function";switch(b=arguments.length){case 1:(function(j,re,te){if(re)j.call(te);else for(var $=j.length,ae=c(j,$),U=0;U<$;++U)ae[U].call(te)})(h,W,this);break;case 2:(function(j,re,te,$){if(re)j.call(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].call(te,$)})(h,W,this,arguments[1]);break;case 3:(function(j,re,te,$,ae){if(re)j.call(te,$,ae);else for(var U=j.length,q=c(j,U),Z=0;Z<U;++Z)q[Z].call(te,$,ae)})(h,W,this,arguments[1],arguments[2]);break;case 4:(function(j,re,te,$,ae,U){if(re)j.call(te,$,ae,U);else for(var q=j.length,Z=c(j,q),ne=0;ne<q;++ne)Z[ne].call(te,$,ae,U)})(h,W,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(b-1),P=1;P<b;P++)I[P-1]=arguments[P];(function(j,re,te,$){if(re)j.apply(te,$);else for(var ae=j.length,U=c(j,ae),q=0;q<ae;++q)U[q].apply(te,$)})(h,W,this,I)}return!0},s.prototype.addListener=function(p,g){return r(this,p,g,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,g){return r(this,p,g,!0)},s.prototype.once=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,g)),this},s.prototype.prependOnceListener=function(p,g){if(typeof g!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,g)),this},s.prototype.removeListener=function(p,g){var h,b,I,P,L;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if(!(b=this._events))return this;if(!(h=b[p]))return this;if(h===g||h.listener&&h.listener===g)--this._eventsCount==0?this._events=new i:(delete b[p],b.removeListener&&this.emit("removeListener",p,h.listener||g));else if(typeof h!="function"){for(I=-1,P=h.length;0<P--;)if(h[P]===g||h[P].listener&&h[P].listener===g){L=h[P].listener,I=P;break}if(0>I)return this;if(h.length===1){if(h[0]=void 0,--this._eventsCount==0)return this._events=new i,this;delete b[p]}else(function(O,M){for(var N=M,W=N+1,j=O.length;W<j;N+=1,W+=1)O[N]=O[W];O.pop()})(h,I);b.removeListener&&this.emit("removeListener",p,L||g)}return this},s.prototype.removeAllListeners=function(p){var g,h;if(!(h=this._events))return this;if(!h.removeListener)return arguments.length===0?(this._events=new i,this._eventsCount=0):h[p]&&(--this._eventsCount==0?this._events=new i:delete h[p]),this;if(arguments.length===0){for(var b,I=Object.keys(h),P=0;P<I.length;++P)(b=I[P])!=="removeListener"&&this.removeAllListeners(b);return this.removeAllListeners("removeListener"),this._events=new i,this._eventsCount=0,this}if(typeof(g=h[p])=="function")this.removeListener(p,g);else if(g)do this.removeListener(p,g[g.length-1]);while(g[0]);return this},s.prototype.listeners=function(p){var g,h,b=this._events;return b?h=(g=b[p])?typeof g=="function"?[g.listener||g]:function(I){for(var P=Array(I.length),L=0;L<P.length;++L)P[L]=I[L].listener||I[L];return P}(g):[]:h=[],h},s.listenerCount=function(p,g){return typeof p.listenerCount=="function"?p.listenerCount(g):l.call(p,g)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var d,u=new Uint8Array(16);function f(){if(!d&&!(d=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 d(u)}for(var m=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,_=[],v=0;256>v;++v)_.push((v+256).toString(16).substr(1));function w(p){var g=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,h=(_[p[g+0]]+_[p[g+1]]+_[p[g+2]]+_[p[g+3]]+"-"+_[p[g+4]]+_[p[g+5]]+"-"+_[p[g+6]]+_[p[g+7]]+"-"+_[p[g+8]]+_[p[g+9]]+"-"+_[p[g+10]]+_[p[g+11]]+_[p[g+12]]+_[p[g+13]]+_[p[g+14]]+_[p[g+15]]).toLowerCase();if(!function(b){return typeof b=="string"&&m.test(b)}(h))throw TypeError("Stringified UUID is invalid");return h}function y(p,g,h){var b=(p=p||{}).random||(p.rng||f)();return b[6]=64|15&b[6],b[8]=128|63&b[8],w(b)}function C(p,g){if(!p||!g)return{};const h={...p};if(h.localCandidateId){const b=g.get(h.localCandidateId);h.local={...b}}if(h.remoteCandidateId){const b=g.get(h.remoteCandidateId);h.remote={...b}}return h}function k(p,g,h){return 8*function(b,I,P){const L=b[P],O=I?I[P]:null;return L===null||O===null?null:(L-O)/(b.timestamp-I.timestamp)*1e3}(p,g,h)}function T(p){if(!p.entries)return p;const g={};return p.forEach(function(h,b){g[b]=h}),g}function E(p,g,h={}){if(!p)return null;let b={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};h.remote&&(b.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of p.values())switch(I.type){case"outbound-rtp":{const P=I.mediaType||I.kind,L={};let O={};if(!["audio","video"].includes(P))continue;if(I.codecId){const M=p.get(I.codecId);M&&(L.clockRate=M.clockRate,L.mimeType=M.mimeType,L.payloadType=M.payloadType)}O=p.get(I.mediaSourceId)||p.get(I.trackId)||{},b[P].outbound.push({...I,...L,track:{...O}});break}case"inbound-rtp":{let P=I.mediaType||I.kind,L={};const O={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const M=p.get(I.codecId);M&&(O.clockRate=M.clockRate,O.mimeType=M.mimeType,O.payloadType=M.payloadType)}if(!b.connection.id&&I.transportId){const M=p.get(I.transportId);if(M&&M.selectedCandidatePairId){const N=p.get(M.selectedCandidatePairId);b.connection=C(N,p)}}L=p.get(I.mediaSourceId)||p.get(I.trackId)||{},b[P].inbound.push({...I,...O,track:{...L}});break}case"peer-connection":b.connection.dataChannelsClosed=I.dataChannelsClosed,b.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!h.remote)break;let P=I.mediaType||I.kind;const L={};if(!["audio","video"].includes(P))if(I.id.includes("Video"))P="video";else{if(!I.id.includes("Audio"))continue;P="audio"}if(I.codecId){const O=p.get(I.codecId);O&&(L.clockRate=O.clockRate,L.mimeType=O.mimeType,L.payloadType=O.payloadType)}if(!b.connection.id&&I.transportId){const O=p.get(I.transportId);if(O&&O.selectedCandidatePairId){const M=p.get(O.selectedCandidatePairId);b.connection=C(M,p)}}b.remote[P].inbound.push({...I,...L});break}case"remote-outbound-rtp":{if(!h.remote)break;const P=I.mediaType||I.kind,L={};if(!["audio","video"].includes(P))continue;if(I.codecId){const O=p.get(I.codecId);O&&(L.clockRate=O.clockRate,L.mimeType=O.mimeType,L.payloadType=O.payloadType)}b.remote[P].outbound.push({...I,...L});break}}if(!b.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(b.connection=C(I,p));return b=function(I,P){return P&&(I.audio.inbound.map(L=>{let O=P.audio.inbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesReceived"),L.packetRate=k(L,O,"packetsReceived")}),I.audio.outbound.map(L=>{let O=P.audio.outbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesSent"),L.packetRate=k(L,O,"packetsSent")}),I.video.inbound.map(L=>{let O=P.video.inbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesReceived"),L.packetRate=k(L,O,"packetsReceived")}),I.video.outbound.map(L=>{let O=P.video.outbound.find(M=>M.id===L.id);L.bitrate=k(L,O,"bytesSent"),L.packetRate=k(L,O,"packetsSent")})),I}(b,g),b}let D,S={},x=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const g={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=g.getStatsInterval||1e3,this.rawStats=!!g.rawStats,this.statsObject=!!g.statsObject,this.filteredStats=!!g.filteredStats,this.shouldWrapGetUserMedia=!!g.wrapGetUserMedia,typeof g.remote=="boolean"&&(this.remote=g.remote),this.debug=!!g.debug,this.logLevel=g.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,g){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:g})}async addConnection(p){const{pc:g,peerId:h}=p;let{connectionId:b,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(g&&g instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!h)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[h]){if(b&&b in this.peersToMonitor[h])throw new Error(`We are already monitoring connection with id ${b}.`);for(let L in this.peersToMonitor[h]){const O=this.peersToMonitor[h][L];if(O.pc===g)throw new Error(`We are already monitoring peer with id ${h}.`);O.pc.connectionState==="closed"&&this.removeConnection({pc:O.pc})}}const P=g.getConfiguration();return P.iceServers&&P.iceServers.forEach(function(L){delete L.credential}),b||(b=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:h,connectionId:b,data:{options:p,peerConfiguration:P}}),this.monitorPeer({peerId:h,connectionId:b,pc:g,remote:I}),{connectionId:b}}getTimeline(p){return this.timeline=this.timeline.sort((g,h)=>g.timestamp.getTime()-h.timestamp.getTime()),p?this.timeline.filter(g=>g.tag===p):this.timeline}get logger(){const p=g=>{const h=["none","error","warn","info","debug"];return h.slice(0,h.indexOf(this.logLevel)+1).indexOf(g)>-1};return{error(...g){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...g)},warn(...g){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...g)},info(...g){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...g)},debug(...g){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...g)}}}removeConnection(p){let g,{connectionId:h,pc:b}=p;if(!b&&!h)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(h){if(typeof h!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)h in this.peersToMonitor[I]&&(b=this.peersToMonitor[I][h].pc,g=I)}else if(b){if(!(b instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let P in this.peersToMonitor[I])this.peersToMonitor[I][P].pc===b&&(h=P,g=I)}if(!b||!h)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(h,b),delete this.peersToMonitor[g][h],Object.values(this.peersToMonitor[g]).length===0&&delete this.peersToMonitor[g],{connectionId:h}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let g in this.peersToMonitor[p]){let h=this.peersToMonitor[p][g].pc;this.removePeerConnectionEventListeners(g,h)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),x.forEach(p=>{this.removeTrackEventListeners(p)}),x=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(p){let{peerId:g,connectionId:h,pc:b,remote:I}=p;if(!b)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const P={pc:b,connectionId:h,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[g]){if(h in this.peersToMonitor[g])return void this.logger.warn(`Already watching connection with ID ${h}`);this.peersToMonitor[g][h]=P}else this.peersToMonitor[g]={[h]:P};this.addPeerConnectionEventListeners(g,h,b),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(g=>{this.emitEvent(g)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let g={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);g[p]=this.peersToMonitor[p]}else g=this.peersToMonitor;let h=[];for(const b in g)for(const I in g[b]){const P=g[b][I],L=P.pc;if(L&&!this.checkIfConnectionIsClosed(b,I,L))try{const O=this.getTimestamp(),M=L.getStats(null);if(M){const N=await M,W=this.getTimestamp(),j=T(N),re={remote:P.options.remote},te=E(N,P.stats.parsed,re),$={event:"stats",tag:"stats",peerId:b,connectionId:I,timeTaken:W-O,data:te};this.rawStats===!0&&($.rawStats=N),this.statsObject===!0&&($.statsObject=j),this.filteredStats===!0&&($.filteredStats=this.filteroutStats(j)),h.push($),P.stats.parsed=te}else this.logger.error(`PeerConnection from peer ${b} did not return any stats data`)}catch(O){this.logger.error(O)}}return h}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const g in this.peersToMonitor[p]){const h=this.peersToMonitor[p][g].pc;this.checkIfConnectionIsClosed(p,g,h)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,g,h){const b=this.isConnectionClosed(h);if(b){this.removeConnection({pc:h});let I=h.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:g,tag:"connection",data:"closed"})}return b}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(g=>(p({stream:g}),g),g=>(p({error:g}),Promise.reject(g)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const g={...p};for(const b in g){var h=g[b];this.statsToMonitor.includes(h.type)||delete g[b]}return g}get peerConnectionListeners(){return{icecandidate:(p,g,h,b)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",b),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:g,data:b.candidate})},track:(p,g,h,b)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,b);const I=b.track,P=b.streams[0];p in this.peersToMonitor&&g in this.peersToMonitor[p]&&(this.peersToMonitor[p][g].stream=P),this.addTrackEventListeners(I,g),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:g,data:{stream:P?this.getStreamDetails(P):null,track:I?this.getMediaTrackDetails(I):null,title:b.track.kind+":"+b.track.id+" "+b.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:g,data:{signalingState:h.signalingState,localDescription:h.localDescription,remoteDescription:h.remoteDescription}})},iceconnectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceConnectionState})},icegatheringstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:g,data:h.iceGatheringState})},icecandidateerror:(p,g,h,b)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:g,error:{errorCode:b.errorCode}})},connectionstatechange:(p,g,h)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:g,data:h.connectionState})},negotiationneeded:(p,g,h)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:g})},datachannel:(p,g,h,b)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,b),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:g,data:b.channel})}}}addPeerConnectionEventListeners(p,g,h){this.logger.debug(`Adding event listeners for peer ${p} and connection ${g}.`),S[g]={},Object.keys(this.peerConnectionListeners).forEach(b=>{S[g][b]=this.peerConnectionListeners[b].bind(this,p,g,h),h.addEventListener(b,S[g][b],!1)})}parseGetUserMedia(p){try{const g={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(g.data.details=this.parseStream(p.stream),p.stream.getTracks().map(h=>{this.addTrackEventListeners(h),x.push(h)})),this.emitEvent(g)}catch{}}parseStream(p){const g={audio:[],video:[]};return p.getTracks().forEach(h=>{g[h.kind].push(this.getMediaTrackDetails(h))}),g}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:g=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:g}})},unmute:g=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:g}})},overconstrained:g=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:g}})},ended:g=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:g}}),this.removeTrackEventListeners(g.target)}}}addTrackEventListeners(p,g){S[p.id]={};const h=this.getTrackEventObject(g);Object.keys(h).forEach(b=>{S[p.id][b]=h[b].bind(this),p.addEventListener(b,S[p.id][b])}),S[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let b=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(b)}},1e3)}removeTrackEventListeners(p){if(p.id in S){const g=this.getTrackEventObject();Object.keys(g).forEach(h=>{p.removeEventListener(h,S[p.id][h])}),clearInterval(S[p.id].readyState),delete S[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const g={...p,timestamp:new Date};this.addToTimeline(g),g.tag&&this.emit(g.tag,g)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,g){p in S&&(Object.keys(this.peerConnectionListeners).forEach(h=>{g.removeEventListener(h,S[p][h],!1)}),delete S[p]),g.getSenders().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)}),g.getReceivers().forEach(h=>{h.track&&this.removeTrackEventListeners(h.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const g=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),h=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),g.apply(navigator.mediaDevices,arguments).then(function(b){return b},function(b){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,b.name),Promise.reject(b)})};navigator.mediaDevices.getDisplayMedia=h.bind(navigator.mediaDevices)}}}});(ts=Eu)&&ts.__esModule&&Object.prototype.hasOwnProperty.call(ts,"default")&&ts.default;var n_=Eu.WebRTCStats;function i_(t){const{packetsLost:e,packetsReceived:n,jitter:i,rtt:s}=t,o=function(c){const{jitter:d,rtt:u}=c,f=d+u/2;return .024*f+.11*(f-177.3)*(f>177.3?1:0)}({rtt:s,jitter:i}),r=function(c){const{packetsLost:d,packetsReceived:u}=c,f=d/(u+d)*100;return 20*Math.log(1+f)}({packetsLost:e,packetsReceived:n}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function s_(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 r_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:n})}}class o_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:n})}}class a_ extends ni{constructor(e,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:n})}}function Iu(t,e){var n,i;return{errorCode:t.errorCode,errorText:t.errorText,url:t.url,address:t.address,port:t.port,connectionState:e.connectionState,iceConnectionState:e.iceConnectionState,iceGatheringState:e.iceGatheringState,signalingState:e.signalingState,localDescriptionType:(n=e.localDescription)===null||n===void 0?void 0:n.type,remoteDescriptionType:(i=e.remoteDescription)===null||i===void 0?void 0:i.type}}function l_(t,e){const n=_n();let i=!1;const s=new n_({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&J(V.StatsFrame,function({data:a}){var l,c,d,u,f,m,_,v;const{audio:w,remote:y}=a,{audio:C}=y,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,T=(u=(d=C.inbound[0])===null||d===void 0?void 0:d.roundTripTime)!==null&&u!==void 0?u:1/0,E=(m=(f=w.inbound[0])===null||f===void 0?void 0:f.packetsReceived)!==null&&m!==void 0?m:-1,D=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,S=i_({jitter:1e3*k,rtt:1e3*T,packetsLost:D,packetsReceived:E});return{jitter:k,rtt:T,mos:S,quality:s_(S),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new a_(n,r))});return{get isRunning(){return i},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(i)A.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new r_(n,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),i=!0}catch(c){A.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();J(V.StatsReport,a,t.uuid),r==="file"&&function(l,c){const d=new Blob([JSON.stringify(l)],{type:"application/json"}),u=URL.createObjectURL(d),f=document.createElement("a");f.href=u,f.download=`${c}.json`,f.click(),URL.revokeObjectURL(u)}(a,`webrtc-stats-${n}-${Date.now()}`),yield t.execute(new o_(n,e)),s.removeAllPeers(),s.destroy(),i=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const Ru=(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:c_(o),currentLayerIdx:r};switch(n){case"layer-info":{const l=Object.assign({action:He.LayerInfo},a);J(V.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:He.LayoutInfo},a);J(V.Notification,l,t.uuid);break}}},c_=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return su(e)};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._sleepWakeupIntervalId=null,this.handleConnectionStateChange=()=>B(this,void 0,void 0,function*(){const{connectionState:r}=this.instance;if(A.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${r}`),r==="failed"||r==="disconnected"){const a=()=>B(this,void 0,void 0,function*(){if(this.isDebugEnabled&&this.statsReporter){const l=yield function(c,d){return B(this,void 0,void 0,function*(){const u={connectionState:c.connectionState,previousConnectionState:d,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},f=c.getTransceivers();if(f.length>0){const m=f[0].sender,_=m==null?void 0:m.transport;_&&(u.dtlsState=_.state)}c.sctp&&(u.sctpState=c.sctp.state);try{const m=yield c.getStats();m.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(u.candidatePairState=_.state,m.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(u.localCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(u.remoteCandidateType=v.candidateType,u.selectedCandidatePair=u.selectedCandidatePair||{local:{},remote:{}},u.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(u.dtlsCipher=_.dtlsCipher,u.srtpCipher=_.srtpCipher,u.tlsVersion=_.tlsVersion,_.dtlsState&&(u.dtlsState=_.dtlsState))})}catch(m){A.error("Error gathering connection state details:",m)}return u})}(this.instance,this._prevConnectionState);this.statsReporter.reportConnectionStateChange(l)}window.removeEventListener("online",a)});navigator.onLine?a():window.addEventListener("online",a)}r==="failed"&&J(V.PeerConnectionFailureError,{error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${r}`),sessionId:this._session.sessionid},this.options.id),this._prevConnectionState=r,this._isTrickleIce()&&(r==="connecting"&&performance.mark("peer-connection-connecting"),r==="connected"&&(performance.mark("peer-connection-connected"),console.group("Performance Metrics"),console.table(this.trickleIcePerformanceMetrics),console.groupEnd(),performance.clearMarks()))}),this._handleIceConnectionStateChange=()=>{A.debug(`[${new Date().toISOString()}] ICE Connection State`,this.instance.iceConnectionState)},this._handleIceGatheringStateChange=()=>{A.debug(`[${new Date().toISOString()}] ICE Gathering State`,this.instance.iceGatheringState)},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},A.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!n.video},this._sdpReady=this._sdpReady.bind(this),this.handleSignalingStateChangeEvent=this.handleSignalingStateChangeEvent.bind(this),this.handleNegotiationNeededEvent=this.handleNegotiationNeededEvent.bind(this),this.handleTrackEvent=this.handleTrackEvent.bind(this),this.createPeerConnection=this.createPeerConnection.bind(this),this._session=i,this._trickleIceSdpFn=s,this._registerPeerEvents=o}get isOffer(){return this.type===Ie.Offer}get isAnswer(){return this.type===Ie.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark("ice-gathering-start"),this._negotiating=!0,this._isOffer()?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return B(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(){this.instance?(A.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,n)=>{A.info(`>> Transceiver [${n}]:`,e.mid,e.direction,e.stopped),A.info(`>> Sender Params [${n}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):A.warn("Cannot log transceivers: peer connection is null")}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=l=>`${l.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(){switch(A.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":J(V.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(A.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){A.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?A.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;this.options.remoteStream=n,s===!1&&ii(i,this.options.remoteStream)}createPeerConnection(){return B(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:Ie.Offer})),this.options.localStream=yield this._retrieveLocalStream().catch(n=>(J(V.MediaError,n,this.options.id),null)),this.options.mutedMicOnStart&&Sn(this.options.localStream)&&(A.info("Muting local audio tracks on start"),io(this.options.localStream)),this.options.localStream||(A.warn("No local media stream available"),!this.options.audio)?performance.mark("peer-creation-end"):A.warn("Audio is required but no local stream — skipping negotiation")})}init(){var e;return B(this,void 0,void 0,function*(){yield this.createPeerConnection(),this.isDebugEnabled&&(this.statsReporter=l_(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:n,localStream:i=null,screenShare:s=!1}=this.options;if(Sn(i)){const o=i.getAudioTracks();let r=[...o];if(A.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{A.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=i.getVideoTracks();r=[...o,...c],A.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(d=>{A.info("Local video tracks constraints: ",d.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Au(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[i]};r.forEach(d=>{d.kind==="audio"&&(this.options.userVariables.microphoneLabel=d.label),d.kind==="video"&&(this.options.userVariables.cameraLabel=d.label);const u=this.instance.addTransceiver(d,c);d.kind==="audio"&&a.length>0&&this._setCodecs(u,a),d.kind==="video"&&l.length>0&&this._setCodecs(u,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,i)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(i);s===!1&&ii(n,i)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});A.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Au(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation(),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:n})=>n&&n.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const n=this.instance.addTransceiver(e);A.info("Add transceiver",e,n)}}_createOffer(){return B(this,void 0,void 0,function*(){if(this._isOffer()){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,A.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){A.error("Peer _createOffer error:",e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){A.debug("Setting remote description",e),yield this.instance.setRemoteDescription(e)})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return A.debug("Skipping negotiation, state:",this.instance.signalingState),A.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ie.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return yield this._setLocalDescription(e),e}catch(e){A.error("Peer _createAnswer error:",e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){yield this.instance.setLocalDescription(e)})}_sdpReady(){bn(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(Sn(this.options.localStream))return this.options.localStream;const e=yield(n=this.options,B(void 0,void 0,void 0,function*(){let{audio:i=!0,micId:s,video:o=!1,camId:r}=n;const{micLabel:a="",camLabel:l=""}=n;return s&&(s=yield es(s,a,ht.AudioIn).catch(c=>null),s&&(typeof i=="boolean"&&(i={}),i.deviceId={exact:s})),r&&(r=yield es(r,l,ht.Video).catch(c=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:i,video:o}}));var n;return Qi(e)})}_isOffer(){return this.type===Ie.Offer}_isAnswer(){return this.type===Ie.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:n,iceServers:i}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:i,iceTransportPolicy:n?"relay":"all"};return A.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?A.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(A.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):A.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}const ns=Qr;class Pu{constructor(e,n,i=!1){this.session=e,this._isRecovering=i,this._callReportCollector=null,this.id="",this.state=X[X.New],this.prevState="",this.channels=[],this.role=Jr.Participant,this.extension=null,this._state=X.New,this._prevState=X.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._iceDone=!1,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._checkConferenceSerno=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(const T in k.constraints)if(k.constraints.hasOwnProperty(T)&&k.constraints[T]!==C[T])return}k.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:d,remoteElement:u,options:f,mediaConstraints:{audio:m,video:_},ringtoneFile:v,ringbackFile:w}=e;this.options=Object.assign({},Oy,{audio:m,video:_,iceServers:n!=null&&n.iceServers&&Array.isArray(n.iceServers)?n.iceServers:s,localElement:d,remoteElement:u,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:w,debug:f.debug,debugOutput:f.debugOutput,trickleIce:f.trickleIce,prefetchIceCandidates:f.prefetchIceCandidates,forceRelayCandidate:f.forceRelayCandidate,keepConnectionAliveOnSocketClose:f.keepConnectionAliveOnSocketClose,mutedMicOnStart:f.mutedMicOnStart},n),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._registerTrickleIcePeerEvents=this._registerTrickleIcePeerEvents.bind(this),this._init(),this.options&&(this._ringtone=xu(this.options.ringtoneFile,"_ringtone"),this._ringback=xu(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}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 isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return!Qy(this.options.localStream)}invite(){return B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=ut.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark("peer-creation-start"),this.peer=new Lu(Ie.Offer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),this._creatingPeer=!1})}answer(e={}){var n;return B(this,void 0,void 0,function*(){this._creatingPeer=!0,performance.mark("new-call-start"),this.stopRingtone(),this.direction=ut.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(Ie.Answer,this.options,this.session,this._onTrickleIceSdp,this.options.trickleIce?this._registerTrickleIcePeerEvents:this._registerPeerEvents),yield this.peer.init(),performance.mark("new-call-end"),this._creatingPeer=!1})}playRingtone(){ku(this._ringtone)}stopRingtone(){Tu(this._ringtone)}playRingback(){ku(this._ringback)}stopRingback(){Tu(this._ringback)}hangup(e,n){var i,s,o;const r=e||{},a=n!==!1,l=this._state<X.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=r.cause||l.cause,this.causeCode=r.causeCode||l.causeCode,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:[]],r.isRecovering)return this._isRecovering=!0,this.setState(X.Recovering),void this._finalize();this.setState(X.Hangup);const c=()=>{var d;A.debug(`[${this.id}] Closing peer from hangup`),(d=this.peer)===null||d===void 0||d.close(),this.setState(X.Destroy)};if(this.stopRingtone(),this.stopRingback(),a){const d=new Hy({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});this._execute(d).catch(u=>{A.error("telnyx_rtc.bye failed!",u),J(V.Error,{error:u,sessionId:this.session.sessionid},this.session.uuid)}).then(c.bind(this))}else c()}hold(){const e=new eo({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 eo({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 eo({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 _u({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 _u({sessid:this.session.sessionid,msg:i,dialogParams:this.options});this._execute(s)}muteAudio(){io(this.options.localStream)}unmuteAudio(){Su(this.options.localStream)}toggleAudioMute(){Cu(this.options.localStream)}setAudioInDevice(e,n=this.options.mutedMicOnStart){return B(this,void 0,void 0,function*(){const{instance:i}=this.peer,s=i.getSenders().find(({track:{kind:o}})=>o==="audio");if(s){const o=yield Zi({audio:{deviceId:{exact:e}}}),r=o.getAudioTracks()[0];r.enabled=!n,s.replaceTrack(r),this.options.micId=e;const{localStream:a}=this.options;a.getAudioTracks().forEach(l=>l.stop()),a.getVideoTracks().forEach(l=>o.addTrack(l)),this.options.localStream=o}})}muteVideo(){var e;e=this.options.localStream,Cn(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Cn(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Cn(e,"video",null)}setVideoDevice(e){return B(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 Zi({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];i.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ii(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s}})}deaf(){io(this.options.remoteStream)}undeaf(){Su(this.options.remoteStream)}toggleDeaf(){Cu(this.options.remoteStream)}setBandwidthEncodingsMaxBps(e,n){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void A.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 A.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"}]),A.info("Parameters: ",r),A.info("Setting max ",n==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{A.info(n==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>A.error(a))}else A.error("Could not set bandwidth (reason: no "+n+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}getStats(e,n){if(!e)return;const i={callback:e,constraints:n};this._statsBindings.push(i),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var n;switch(this._prevState=this._state,this._state=e,this.state=X[this._state].toLowerCase(),this.prevState=X[this._prevState].toLowerCase(),A.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:Je.callUpdate,call:this}),e){case X.Purge:A.debug(`Call ${this.id} hangup call due to purge state`),this.hangup({cause:"PURGE",causeCode:1},!1);break;case X.Active:this._isRecovering&&(this._isRecovering=!1,A.debug(`[${this.id}] Recovery complete, call is active`)),setTimeout(()=>{const{remoteElement:i,speakerId:s}=this.options;i&&s&&bu(i,s)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance);break;case X.Destroy:this._finalize()}}handleMessage(e){const{method:n,params:i}=e;switch(n){case ee.Answer:if(this.gotAnswer=!0,i.telnyx_call_control_id&&(this.options.telnyxCallControlId=i.telnyx_call_control_id),i.telnyx_session_id&&(this.options.telnyxSessionId=i.telnyx_session_id),i.telnyx_leg_id&&(this.options.telnyxLegId=i.telnyx_leg_id),this._state>=X.Active)return;this._state>=X.Early&&this.setState(X.Active),this.gotEarly||this._onRemoteSdp(i.sdp),this.stopRingback(),this.stopRingtone();break;case ee.Media:if(this._state>=X.Early)return;this.gotEarly=!0,this._onRemoteSdp(i.sdp);break;case ee.Display:{const{display_name:o,display_number:r,display_direction:a}=i;this.extension=r;const l=a===ut.Inbound?ut.Outbound:ut.Inbound,c={type:Je[n],call:this,displayName:o,displayNumber:r,displayDirection:l};J(V.Notification,c,this.id)||J(V.Notification,c,this.session.uuid);break}case ee.Candidate:this._addIceCandidate(i);break;case ee.Info:case ee.Event:{const o=Object.assign(Object.assign({},i),{type:Je.generic,call:this});J(V.Notification,o,this.id)||J(V.Notification,o,this.session.uuid);break}case ee.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 ee.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 B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==n.laName)return A.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:i,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(i){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:d,conferenceMemberID:u,role:f}=n;this._dispatchConferenceUpdate({action:He.Join,conferenceName:d,participantId:Number(u),role:f}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const m=[];for(const _ in s)m.push(Object.assign({callId:s[_][0],index:Number(_)},Xi(s[_][1])));this._dispatchConferenceUpdate({action:He.Bootstrap,participants:m});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:He.Add,callId:o,index:r},Xi(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:He.Modify,callId:o,index:r},Xi(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:He.Delete,callId:o,index:r},Xi(s)));break;case"clear":this._dispatchConferenceUpdate({action:He.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 B(this,void 0,void 0,function*(){const n={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:He.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},i=yield this.session.vertoSubscribe(n).catch(s=>{A.error("ConfChat subscription error:",s)});to(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 B(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,Ru(this.session,o)):A.error("Conference-Info unknown contentType",s)}},i=yield this.session.vertoSubscribe(n).catch(s=>{A.error("ConfInfo subscription error:",s)});to(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(X.Active):this.setState(X.Held),!0}_handleChangeHoldStateError(e){return A.error(`Failed to ${e.action} on call ${this.id}`),!1}_onRemoteSdp(e){return B(this,void 0,void 0,function*(){const n=new RTCSessionDescription({sdp:e,type:Ie.Answer});yield this.peer.instance.setRemoteDescription(n).then(()=>{this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(X.Early),this.gotAnswer&&this.setState(X.Active)}).catch(i=>{A.error("Call setRemoteDescription Error: ",i),this.hangup({cause:"USER_BUSY",causeCode:17},!0)})})}_requestAnotherLocalDescription(){bn(this.peer.onSdpReadyTwice)?J(V.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 A.info(`No candidate - retry
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-${ns}`};switch(o){case Ie.Offer:this.setState(X.Requesting),r=new mu(a);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),r=this.options.attach===!0?new yu(a):new vu(a);break;default:return A.error(`${this.id} - Unknown local SDP type:`,e),this.hangup({},!1)}performance.mark("sdp-send-start"),this._execute(r).then(l=>{const{node_id:c=null}=l;this._targetNodeId=c,o===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(l=>{A.error(`${this.id} - Sending ${o} error:`,l),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end"),console.group("Performance Metrics"),console.table(this.performanceMetrics),console.groupEnd(),performance.clearMarks()})}_onTrickleIceSdp(e){if(!e)return A.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-${ns}`};switch(i){case Ie.Offer:this.setState(X.Requesting),s=new mu(o);break;case Ie.Answer:this._isRecovering||this.setState(X.Answering),s=this.options.attach===!0?new yu(o):new vu(o);break;default:return A.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===Ie.Offer?this.setState(X.Trying):this.setState(X.Active)}).catch(r=>{A.error(`${this.id} - Sending ${i} error:`,r),this.hangup({cause:"USER_BUSY",causeCode:17},!0)}).finally(()=>{performance.mark("sdp-send-end")})}_onIce(e){const{instance:n}=this.peer;if(this._iceTimeout===null){const i=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),i)}e.candidate?A.debug("RTCPeer Candidate:",e.candidate):this._onIceSdp(n.localDescription)}_onTrickleIce(e){e.candidate&&e.candidate.candidate?(A.debug("RTCPeer Candidate:",e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const n=new Gy({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 A.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(()=>{A.debug("Successfully added ICE candidate:",e)}).catch(i=>{A.error("Failed to add ICE candidate:",i,e)})}_sendEndOfCandidates(){const e=new Wy({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.onicecandidateerror=n=>{var i;if(A.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Iu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ii(i,s)})}_registerTrickleIcePeerEvents(e){e.onicecandidate=n=>{this._onTrickleIce(n)},e.onicegatheringstatechange=n=>{A.debug("ICE gathering state changed:",e.iceGatheringState),e.iceGatheringState==="complete"&&A.debug("Finished gathering candidates")},e.onicecandidateerror=n=>{var i;if(A.debug("ICE candidate error:",n),(i=this.peer)===null||i===void 0?void 0:i.statsReporter){const s=Iu(n,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",n=>{this.options.remoteStream=n.stream}),e.addEventListener("track",n=>{this.options.remoteStream=n.streams[0];const{remoteElement:i,remoteStream:s,screenShare:o}=this.options;o===!1&&ii(i,s)})}_onMediaError(e){const n=(e==null?void 0:e.name)||"UnknownError",i=(e==null?void 0:e.message)||"Unknown media error";this._dispatchNotification({type:Je.userMediaError,error:e,call:this,errorName:n,errorMessage:i}),A.error(`Media error (${n}): ${i}`,e),this.hangup({},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:Je.peerConnectionFailureError,error:e}),A.error("Peer connection failure error")}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:Je.signalingStateClosed},e)),A.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:Je.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(J(V.Notification,e,this.id,!1)||J(V.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():_n(),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,Lt(V.MediaError,this._onMediaError,this.id),Lt(V.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Lt(V.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),bn(s)&&Lt(V.Notification,s.bind(this),this.id);const r=this.session.options.enableCallReports!==!1,a=this.session.options.callReportInterval||5e3,l=this.session.options.debugLogLevel||"debug",c=this.session.options.debugLogMaxEntries||1e3;r&&(this._callReportCollector=new xt({enabled:!0,interval:a},{enabled:!0,level:l,maxEntries:c}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()}),this._isRecovering?this.setState(X.Recovering):this.setState(X.New),A.info("New Call with Options:",this.options)}_finalize(){var e;this._stopStats(),A.debug(`[${this.id}] Closing peer from _finalize`),(e=this.peer)===null||e===void 0||e.close();const{remoteStream:n,localStream:i}=this.options;si(n),si(i),Pt(V.MediaError,null,this.id),Pt(V.PeerConnectionFailureError,null,this.id),Pt(V.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id],this._postCallReport().catch(s=>{A.error("Unexpected error in _postCallReport",{error:s})})}_flushIntermediateReport(){var e;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void A.debug("Cannot flush intermediate report: call_report_id not available");const i=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!i)return void A.debug("Cannot flush intermediate report: connection host not available");const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ns},o=this._callReportCollector.flush(s);if(!o)return;const r=Kt()||void 0;this._callReportCollector.sendPayload(o,n,i,r).catch(a=>{A.error("Failed to post intermediate call report segment",{error:a})})}_postCallReport(){var e;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void A.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return A.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const i={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===ut.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ns},s=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!s)return void A.error("Cannot post call report: connection host not available");const o=Kt()||void 0;this._callReportCollector.postReport(i,n,s,o).catch(r=>{A.error("Failed to post call report",{error:r})}).finally(()=>{var r;(r=this._callReportCollector)===null||r===void 0||r.cleanup()})})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),A.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),A.debug("Stats stopped")}}Pu.setStateTelnyx=t=>{if(t){switch(t._state){case X.Recovering:t.state="recovering";break;case X.Requesting:case X.Trying:case X.Early:t.state="connecting";break;case X.Active:t.state="active";break;case X.Held:t.state="held";break;case X.Hangup:case X.Destroy:t.state="done";break;case X.Answering:t.state="ringing";break;case X.New:t.state="new"}return t}};class Xt extends Pu{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,n)=>this.session.execute(new t_(e,n))}hangup(e={},n=!0){this.screenShare instanceof Xt&&this.screenShare.hangup(e,n),super.hangup(e,n)}startScreenShare(e){return B(this,void 0,void 0,function*(){const n=yield(i={video:!0},navigator.mediaDevices.getDisplayMedia(i));var i;n.getTracks().forEach(c=>{c.addEventListener("ended",()=>{this.screenShare&&this.screenShare.hangup()})});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:n,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new Xt(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){this.screenShare instanceof Xt&&this.screenShare.hangup()}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:n,speakerId:i}=this.options;return!(!n||!i)&&bu(n,i)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(this,void 0,void 0,function*(){const 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
- `)}))}),T.info(i)}),2e3)}}class l_ extends Ky{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return B(this,void 0,void 0,function*(){try{const i=yield Ji({audio:e,video:n});return si(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(X.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(lu(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return ri().catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return ri(ht.Video).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ri(ht.AudioIn).catch(e=>(Y(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ri(ht.AudioOut).catch(e=>(T.error("getAudioOutDevices",e),Y(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return Zi(e,n,i)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(n=>B(void 0,void 0,void 0,function*(){const i=[],s=yield Ji({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<bu.length;r++){const[a,l]=bu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return si(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=Gi(e,["micId","micLabel"]);return Yy(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield Zi(o,r,a).catch(u=>null);d&&(l.deviceId={exact:d})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?ky:xy}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Ki(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Ki(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 Gy({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 B(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Wy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=to(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return B(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new zy({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=to(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&&(T.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,T.debug(`Network connectivity lost for session ${this.sessionid}`)},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 qt.setStateTelnyx(e)}}class Pu{constructor(e,n){this.code=n,this.message=e}}class c_{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,n){const i=new jy(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ru(2,6)}handleMessage(e){var n,i,s;const{session:o}=this,{id:r,method:a,params:l={},voice_sdk_id:c}=e,d=l==null?void 0:l.callID,u=l==null?void 0:l.eventChannel,f=l==null?void 0:l.eventType,m=o.calls[d],_=(n=m==null?void 0:m.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(f==="channelPvtData")return this._handlePvtEvent(l.pvtData);const v=(C=!1)=>{var k,E,R,O,S,x;const p={audio:!0,video:o.options.video,remoteSdp:l.sdp,destinationNumber:l.callee_id_number,remoteCallerName:l.caller_id_name,remoteCallerNumber:l.caller_id_number,callerName:l.callee_id_name,callerNumber:l.callee_id_number,attach:a===ee.Attach,mediaSettings:l.mediaSettings,debug:(k=o.options.debug)!==null&&k!==void 0&&k,debugOutput:(E=o.options.debugOutput)!==null&&E!==void 0?E:"socket",trickleIce:a!==ee.Attach&&(R=o.options.trickleIce)!==null&&R!==void 0&&R,prefetchIceCandidates:(O=o.options.prefetchIceCandidates)===null||O===void 0||O,forceRelayCandidate:(S=o.options.forceRelayCandidate)!==null&&S!==void 0&&S,keepConnectionAliveOnSocketClose:(x=o.options.keepConnectionAliveOnSocketClose)!==null&&x!==void 0&&x};d&&(p.id=d),l.telnyx_call_control_id&&(p.telnyxCallControlId=l.telnyx_call_control_id),l.telnyx_session_id&&(p.telnyxSessionId=l.telnyx_session_id),l.telnyx_leg_id&&(p.telnyxLegId=l.telnyx_leg_id),l.client_state&&(p.clientState=l.client_state),l.dialogParams&&l.dialogParams.custom_headers&&l.dialogParams.custom_headers.length&&(p.customHeaders=l.dialogParams.custom_headers);const g=new qt(o,p,C);return g.nodeId=this.nodeId,g},w=new hu(c),y=new fu(c);switch(a){case ee.Answer:case ee.Display:case ee.Candidate:case ee.Ringing:case ee.Bye:case ee.Media:if(!d||!m)return void T.error(`Received ${a} for non existing call:`,l);m.handleMessage(e),this._ack(r,a);break;case ee.Ping:this.session.setPingReceived(),this.session.execute(y).then(()=>{this.receivedAuthenticationRequired=0}).catch(E=>B(this,void 0,void 0,function*(){E.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(T.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}));break;case ee.Punt:o.options.keepConnectionAliveOnSocketClose&&_?(T.info(`[${new Date().toISOString()}][${d}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case ee.Invite:{const E=v();E.direction=ut.Inbound,E.playRingtone(),E.setState(X.Ringing),this._ack(r,a);break}case ee.Attach:{if(!m)return v().answer(),void this._ack(r,a);const E=!!m;T.info(`[${new Date().toISOString()}][${d}] closing existing call on ATTACH.`),m.hangup({isRecovering:E},!1),T.info(`[${new Date().toISOString()}][${d}] Attach: Creating new call for recovery`),v(E).answer(),this._ack(r,a);break}case ee.Event:case"webrtc.event":if(!u)return void T.error("Verto received an unknown event:",l);const C=o.relayProtocol,k=u.split(".")[0];o._existsSubscription(C,u)?Y(C,l,u):u===o.sessionid?this._handleSessionEvent(l.eventData):o._existsSubscription(C,k)?Y(C,l,k):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):Y(V.Notification,l,o.uuid);break;case ee.Info:l.type=Je.generic,Y(V.Notification,l,o.uuid);break;case ee.ClientReady:this.session.execute(w);break;default:{const E=Kr(e);if(E){switch(E){case Ne.REGISTER:case Ne.REGED:if(o.connection.previousGatewayState!==Ne.REGED&&o.connection.previousGatewayState!==Ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const R=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;R&&(o.callReportId=R,T.debug("Captured call_report_id from REGED:",R)),l.type=Je.vertoClientReady,Y(V.Ready,l,o.uuid)}break;case Ne.UNREGED:case Ne.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0,Y(V.Error,{error:new Pu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{this.session.execute(w)},this.reconnectDelay());break;case Ne.FAILED:case Ne.FAIL_WAIT:if(o.connection.previousGatewayState!==Ne.FAILED&&o.connection.previousGatewayState!==Ne.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,Y(V.Error,{error:new Pu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,Y(V.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{if(T.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(o.calls).some(R=>{var O;return((O=R.peer)===null||O===void 0?void 0:O.instance)&&!R.signalingStateClosed}))return T.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();T.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:T.warn("GatewayState message unknown method:",e)}break}T.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 B(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const y=f||this._retrieveCallId(w,o);if(y&&n.calls.hasOwnProperty(y)){const C=n.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&m()})}}},v=yield n.vertoSubscribe(_).catch(w=>{T.error("liveArray subscription error:",w)});eo(v,o)&&m();break}case"conference-liveArray-part":{let m=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(m=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};Y(V.Notification,w,v,!1)||Y(V.Notification,w,n.uuid),m===null&&Pt(V.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{m&&(m.channels=m.channels.filter(w=>!v.includes(w)))}).catch(v=>{T.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Iu(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};Y(V.Notification,n,this.session.uuid);break}}}}class d_ extends l_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new c_(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(T.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Xi(this.options)||ei(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 qt(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!!ei(this.options)||!!e.destinationNumber}_onSocketOpen(){return B(this,void 0,void 0,function*(){return Xi(this.options)?this.handleLoginOnSocketOpen():ei(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class u_ extends d_{constructor(e){super(e),T.info(`SDK version: ${pu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Zy()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:_e.not_supported},{browserName:"Firefox",supported:_e.not_supported},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",features:["audio"],supported:_e.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",features:["audio"],supported:_e.partial}]}]}}function Mu(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Du={exports:{}},Ou;function h_(){return Ou||(Ou=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function o(l,c,d,u,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],m]:l._events[_].push(m):(l._events[_]=m,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,m=new Array(f);u<f;u++)m[u]=d[u].fn;return m},a.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,f,m){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],w=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),w){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,u),!0;case 5:return v.fn.call(v.context,c,d,u,f),!0;case 6:return v.fn.call(v.context,c,d,u,f,m),!0}for(C=1,y=new Array(w-1);C<w;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var k=v.length,E;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),w){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,d);break;case 4:v[C].fn.call(v[C].context,c,d,u);break;default:if(!y)for(E=1,y=new Array(w-1);E<w;E++)y[E-1]=arguments[E];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,d){return o(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return o(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!d||m.context===d)&&r(this,f);else{for(var _=0,v=[],w=m.length;_<w;_++)(m[_].fn!==c||u&&!m[_].once||d&&m[_].context!==d)&&v.push(m[_]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Du)),Du.exports}var f_=h_();const io=Mu(f_),ts=new io;var so={exports:{}},p_=so.exports,Nu;function g_(){return Nu||(Nu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(p_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,E,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!R)){try{window.localStorage[R]=b;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!R)){try{h=window.localStorage[R]}catch{}if(typeof h===n)try{var b=window.document.cookie,A=encodeURIComponent(R),P=b.indexOf(A+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+A.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return E??k??C},y.setLevel=function(h,b){return E=p(h),b!==!1&&O(E),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){E=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(E=p(g)),d.call(y)}r=new m,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var w=o[v];return w||(w=o[v]=new m(v,r.methodFactory)),w};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(so)),so.exports}var m_=g_();const v_=Mu(m_),y_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Re=v_.getLogger("telnyx-ai-agent"),__=Re.methodFactory;Re.methodFactory=(t,e,n)=>{const i=__(t,e,n);return function(...s){i(y_(),"-",...s)}},Re.setLevel("info");function b_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const w_=10,S_=500,C_=100,Fu=20;class x_{constructor(e){Q(this,"remoteIntervalId",null);Q(this,"localIntervalId",null);Q(this,"remoteStream",null);Q(this,"localStream",null);Q(this,"remoteAudioContext",null);Q(this,"remoteSource",null);Q(this,"remoteAnalyser",null);Q(this,"localAudioContext",null);Q(this,"localSource",null);Q(this,"localAnalyser",null);Q(this,"thinkingStartTime",null);Q(this,"lastState",null);Q(this,"userIsSpeaking",!1);Q(this,"lastUserAudioTime",null);Q(this,"userSpeechStartTime",null);Q(this,"userSilenceStartTime",null);Q(this,"isFirstAgentSpeech",!0);Q(this,"monitorStartTime",null);Q(this,"volumeThreshold");Q(this,"silenceDurationMs");Q(this,"minSpeechDurationMs");Q(this,"maxLatencyMs");Q(this,"updateAgentState",b_(e=>{Re.debug("AudioStreamMonitor updateAgentState",e),Re.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ts.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??w_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??S_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??C_,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Re.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Re.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Re.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Re.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Re.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=r};this.remoteIntervalId=window.setInterval(s,Fu)}startLocalMonitor(){if(!this.localStream){Re.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Re.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Re.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Re.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Fu)}destroy(){this.stopAudioStreamMonitor()}}function k_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function T_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function E_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function A_(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function I_(t){return T_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function R_(t){if(!E_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class L_ extends io{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcript",[]);Q(this,"onSocketMessage",n=>{if(k_(n))switch(n.params.type){case"response.text.delta":{const i=I_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),ts.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(A_(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=R_(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(V.SocketMessage,this.onSocketMessage)}}class P_ extends io{constructor(n){super();Q(this,"telnyxRTC");Q(this,"transcription");Q(this,"agentId");Q(this,"versionId");Q(this,"conversationId");Q(this,"debug");Q(this,"audioStreamMonitor");Q(this,"activeCall");Q(this,"chatMode");Q(this,"onClientReady",()=>{this.emit("agent.connected")});Q(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Q(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Q(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Q(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Re.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new u_({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(V.Ready,this.onClientReady),this.telnyxRTC.on(V.Error,this.onClientOrSocketError),this.telnyxRTC.on(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(V.Notification,this.onNotification),this.transcription=new L_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ts.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new x_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(V.Ready,this.onClientReady),this.telnyxRTC.off(V.Error,this.onClientOrSocketError),this.telnyxRTC.off(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(V.Notification,this.onNotification),this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ts.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Re.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,d;if(!this.telnyxRTC){Re.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:d.find(u=>u.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Vu={exports:{}},oi={},Bu;function M_(){if(Bu)return oi;Bu=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return oi.Fragment=e,oi.jsx=n,oi.jsxs=n,oi}var ju;function D_(){return ju||(ju=1,Vu.exports=M_()),Vu.exports}D_(),vt(void 0),vt(null);const O_=(t,e,n,i,s,o,r,a,l)=>new P_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l}),N_=(t,e,n,i,s,o,r,a,l)=>{const[c,d]=Ce(null),[u,f]=Ce(!1),[m,_]=Ce(null);return xe(()=>{if(!t)return;const v=O_(t,e,n,i,s,o,r,a,l),w=()=>{f(!0),_(null)},y=()=>{f(!1)},C=k=>{_(k),Te.error("AI Agent error:",k)};return v.on("agent.connected",w),v.on("agent.disconnected",y),v.on("agent.error",C),v.connect(),d(v),()=>{v.off("agent.connected",w),v.off("agent.disconnected",y),v.off("agent.error",C),v.disconnect()}},[t,e,n,i,s,o,r,a,l]),{client:c,isConnected:u,error:m}},F_="telnyx-ai-agent",Kt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function Uu(){const t=document.querySelector(F_);return t instanceof HTMLElement?t:null}function Xt(t,e,n){const i=n||Uu();if(!i){Te.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Te.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const V_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=me(null);xe(()=>{r.current=Uu()},[]),xe(()=>{if(!t)return;const a=r.current,l=()=>{n(),Xt(Kt.AGENT_CONNECTED,void 0,a)},c=()=>{Xt(Kt.AGENT_DISCONNECTED,void 0,a)},d=C=>{s(C);const k={message:C.message,name:C.name};Xt(Kt.AGENT_ERROR,k,a)},u=C=>{var k;i(C),Xt(Kt.CONVERSATION_UPDATE,{type:C.type,callState:(k=C.call)==null?void 0:k.state},a)},f=C=>{Xt(Kt.TRANSCRIPT_ITEM,C,a)},m=C=>{Xt(Kt.CONVERSATION_AGENT_STATE,C,a)},_=C=>{Xt(Kt.AGENT_AUDIO_MUTE,{muted:C},a)},w=t.telnyxRTC,y=C=>{o(C)};return w&&typeof w=="object"&&w.on(V.SocketMessage,y),t.on("agent.connected",l),t.on("agent.disconnected",c),t.on("agent.error",d),t.on("conversation.update",u),t.on("transcript.item",f),t.on("conversation.agent.state",m),t.on("agent.audio.mute",_),()=>{t.off("agent.connected",l),t.off("agent.disconnected",c),t.off("agent.error",d),t.off("conversation.update",u),t.off("transcript.item",f),t.off("conversation.agent.state",m),t.off("agent.audio.mute",_),w&&typeof w=="object"&&w.off(V.SocketMessage,y)}},[t,n,i,s,o])},B_=2e3;async function j_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function $u(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const U_=(t,e)=>{const[n,i]=Ce([]),[,s]=jr(),o=me(e);xe(()=>{o.current=e},[e]);const r=me(void 0),a=me(void 0);return xe(()=>{if(!t)return;const c=f=>{i(m=>{const _=m[m.length-1];if(f.role==="assistant"&&_&&$u(_.id)===$u(f.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,w=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,y={..._,content:_.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const y={...f,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...m,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=m.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...m];return y[v]={...m[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<B_){const C={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),C]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},d=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:_,thinkingStartedAt:v})=>{(m!==void 0||_!==void 0)&&Te.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),m!==void 0&&(r.current=m),_!==void 0&&(a.current=_)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var _;const m=(_=f.call)==null?void 0:_.state;(m==="destroy"||m==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",d),t.on("conversation.update",u),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",d),t.off("conversation.update",u)}},[t,s]),{transcript:n,sendMessage:async(c,d)=>{if(!t)return;const u=[];if(d&&d.length>0)for(const f of d)try{const m=await j_(f);u.push(m)}catch(m){throw Te.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,u)}}},$_=({call:t,client:e,latencySettings:n,chatMode:i})=>{const s=Wt(),[o,r]=Ce(i?"expanded":s.default_state),a=()=>r("expanded"),l=()=>r("collapsed"),{transcript:c}=U_(e,n),d=me(!1);switch(xe(()=>{if(i&&t&&!d.current){const u="remoteStream"in t?t.remoteStream:null;u&&(d.current=!0,u.getAudioTracks().forEach(f=>{f.enabled=!1,Te.info(`[ChatMode] Disabled remote audio track: ${f.label}`)}))}},[i,t]),o){case"collapsed":return I(Gd,{onExpand:a,call:t,client:e,chatMode:i});case"expanded":return I(by,{transcript:c,onCollapse:l,call:t,chatMode:i});default:return I(Gd,{onExpand:a,call:t,client:e,chatMode:i})}},ro=()=>I(gn.div,{layoutId:Jn,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:I("div",{className:"rounded-full animate-spin",children:I(Jv,{})})}),H_=({call:t,client:e,latencySettings:n,chatMode:i})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return I(ro,{});case"done":case"purged":case"destroy":return null;case"active":return I($_,{client:e,call:t,latencySettings:n,chatMode:i});default:return I(ro,{})}},G_=({className:t})=>I("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:[I("g",{clipPath:"url(#:R5lfm:)",children:[I("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"}),I("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"}),I("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"}),I("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"}),I("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"})]}),I("defs",{children:I("clipPath",{id:":R5lfm:",children:I("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Hu(){const t=Wt();return t.logo_icon_url?I("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:I("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):I(G_,{className:"w-8 h-8 mr-2"})}const W_=({client:t,callProps:e,chatMode:n})=>{const i=Wt(),s=me(!1),o=yt(()=>{if(!t){Te.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return xe(()=>{n&&t&&!s.current&&(s.current=!0,Te.info("[ChatMode] Auto-starting conversation"),o())},[n,t,o]),n?I(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[I(Hu,{}),"Connecting..."]}):I(gn.button,{layoutId:Jn,onClick:o,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:[I(Hu,{}),i.start_call_text]})},z_='@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-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline-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)}}',q_=({children:t})=>I("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:I("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),K_={duration:.1,ease:"circOut"},X_=({children:t,position:e="fixed"})=>{const n=Wt(),s=(e??n.position??"fixed")==="fixed"?I(q_,{children:t}):t;return I("div",{className:wt(n.theme==="dark"&&"dark"),children:I($p,{transition:K_,children:[I("style",{children:z_}),s]})})},Y_=t=>I(gn.div,{layoutId:Jn,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:[I(Xv,{className:"w-8 h-8 text-red-400"}),I("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),I("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[I("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),I("li",{children:["Make sure that the"," ",I("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"," ",I(iy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function ai(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function J_({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":d,"conversation-id":u,"chat-mode":f,region:m,environment:_,position:v="fixed","version-id":w}){const y=ai(e),C=ai(n),k=ai(f),E=ze(()=>{if(l)try{return JSON.parse(l)}catch(U){Te.error("Invalid JSON for vad attribute:",l,U);return}},[l]),R=ze(()=>({showUserPerceivedLatency:ai(c),showGreetingLatency:ai(d)}),[c,d]),{client:O}=N_(t,_,w,y,C,E,u,k,m),[S,x]=Ce(null),[p,g]=Ce(!1),[h,b]=Ce(!1),[A,P]=Ce(!1),[L,D]=Ce(!1),M=Es($d),N=Sv(),W={};if(i&&(W.destinationNumber=i),s&&(W.callerNumber=s),o&&(W.callerName=o),r)try{W.customHeaders=JSON.parse(r)}catch(U){Te.error("Invalid JSON for call-custom-headers attribute:",r,U)}if(a)try{W.audio=JSON.parse(a);const U=W.audio;if(typeof U=="object"){const q=navigator.mediaDevices.getSupportedConstraints();Object.keys(U).forEach(J=>{q[J]||Te.warn(`Audio constraint not supported by browser: ${J}`)})}}catch(U){Te.error("Invalid JSON for call-audio attribute:",a,U)}const j=yt(()=>{g(!1)},[]),re=yt(U=>{var q;if(((q=U.call)==null?void 0:q.state)==="destroy")return M(!1),D(!0),x(null);x(U)},[M]),te=yt(()=>{g(!1),b(!0)},[]),$=yt(U=>{if(wv(U)){const q=U.params.widget_settings;q&&Object.keys(q).length>0&&(N(q),P(!0))}},[N]);return V_(O,{onReady:j,onConversationUpdate:re,onError:te,onConfigMessage:$}),I(X_,{position:v,children:t?h?I(Y_,{agentId:t}):p?I(ro,{}):S!=null&&S.call?I(H_,{call:S.call,client:O,latencySettings:R,chatMode:k}):A?I(W_,{client:O,callProps:W,chatMode:k&&!L}):null:I("div",{children:"Please provide an assistant ID."})})}oh(J_,"telnyx-ai-agent",_v,{shadow:!0})})();
114
+ `)}))}),A.info(i)}),2e3)}}class d_ extends Yy{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,n=!0){return B(this,void 0,void 0,function*(){try{const i=yield Qi({audio:e,video:n});return si(i),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){Object.keys(this.calls).forEach(n=>this.calls[n].setState(X.Purge)),this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((n,i)=>{if(cu(V.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;n({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return i(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return ri().catch(e=>(J(V.MediaError,e,this.uuid),[]))}getVideoDevices(){return ri(ht.Video).catch(e=>(J(V.MediaError,e,this.uuid),[]))}getAudioInDevices(){return ri(ht.AudioIn).catch(e=>(J(V.MediaError,e,this.uuid),[]))}getAudioOutDevices(){return ri(ht.AudioOut).catch(e=>(A.error("getAudioOutDevices",e),J(V.MediaError,e,this.uuid),[]))}validateDeviceId(e,n,i){return es(e,n,i)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(n=>B(void 0,void 0,void 0,function*(){const i=[],s=yield Qi({video:{deviceId:{exact:n}}}),o=s.getVideoTracks()[0];for(let r=0;r<wu.length;r++){const[a,l]=wu[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&i.push({resolution:`${a}x${l}`,width:a,height:l})}return si(s),i}))(e)}catch(n){throw n}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:n,micLabel:i}=e,s=zi(e,["micId","micLabel"]);return Zy(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const d=yield es(o,r,a).catch(u=>null);d&&(l.deviceId={exact:d})}return l}))(n,i,"audioinput",s),this.micId=n,this.micLabel=i,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const n=this.options.env==="development";this._iceServers=n?Ay:Ty}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=Yi(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=Yi(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 zy({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 B(this,void 0,void 0,function*(){if(!(n=n.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new qy({sessid:this.sessionid,eventChannel:n});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=no(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,i,l)),o})}vertoUnsubscribe({nodeId:e,channels:n=[]}){return B(this,void 0,void 0,function*(){if(!(n=n.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const i=new Ky({sessid:this.sessionid,eventChannel:n});e&&(i.targetNodeId=e);const s=yield this.execute(i),{unsubscribed:o=[],notSubscribed:r=[]}=no(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&&(A.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,A.debug(`Network connectivity lost for session ${this.sessionid}`)},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 Xt.setStateTelnyx(e)}}class Mu{constructor(e,n){this.code=n,this.message=e}}class u_{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0,this.receivedAuthenticationRequired=0}_ack(e,n){const i=new $y(e,n);this.nodeId&&(i.targetNodeId=this.nodeId),this.session.execute(i)}reconnectDelay(){return 1e3*ou(2,6)}handleMessage(e){var n,i,s;const{session:o}=this,{id:r,method:a,params:l={},voice_sdk_id:c}=e,d=l==null?void 0:l.callID,u=l==null?void 0:l.eventChannel,f=l==null?void 0:l.eventType,m=o.calls[d],_=(n=m==null?void 0:m.peer)===null||n===void 0?void 0:n.isConnectionHealthy();if(f==="channelPvtData")return this._handlePvtEvent(l.pvtData);const v=(C=!1)=>{var k,T,E,D,S,x;const p={audio:!0,video:o.options.video,remoteSdp:l.sdp,destinationNumber:l.callee_id_number,remoteCallerName:l.caller_id_name,remoteCallerNumber:l.caller_id_number,callerName:l.callee_id_name,callerNumber:l.callee_id_number,attach:a===ee.Attach,mediaSettings:l.mediaSettings,debug:(k=o.options.debug)!==null&&k!==void 0&&k,debugOutput:(T=o.options.debugOutput)!==null&&T!==void 0?T:"socket",trickleIce:a!==ee.Attach&&(E=o.options.trickleIce)!==null&&E!==void 0&&E,prefetchIceCandidates:(D=o.options.prefetchIceCandidates)===null||D===void 0||D,forceRelayCandidate:(S=o.options.forceRelayCandidate)!==null&&S!==void 0&&S,keepConnectionAliveOnSocketClose:(x=o.options.keepConnectionAliveOnSocketClose)!==null&&x!==void 0&&x};d&&(p.id=d),l.telnyx_call_control_id&&(p.telnyxCallControlId=l.telnyx_call_control_id),l.telnyx_session_id&&(p.telnyxSessionId=l.telnyx_session_id),l.telnyx_leg_id&&(p.telnyxLegId=l.telnyx_leg_id),l.client_state&&(p.clientState=l.client_state),l.dialogParams&&l.dialogParams.custom_headers&&l.dialogParams.custom_headers.length&&(p.customHeaders=l.dialogParams.custom_headers);const g=new Xt(o,p,C);return g.nodeId=this.nodeId,g},w=new fu(c),y=new pu(c);switch(a){case ee.Answer:case ee.Display:case ee.Candidate:case ee.Ringing:case ee.Bye:case ee.Media:if(!d||!m)return void A.error(`Received ${a} for non existing call:`,l);m.handleMessage(e),this._ack(r,a);break;case ee.Ping:this.session.setPingReceived(),this.session.execute(y).then(()=>{this.receivedAuthenticationRequired=0}).catch(T=>B(this,void 0,void 0,function*(){T.code===this.session.authenticationRequiredErrorCode&&this.receivedAuthenticationRequired>=0&&(this.receivedAuthenticationRequired+=1,this.receivedAuthenticationRequired>1&&this.session.hasAutoReconnect()&&(A.warn("Ping failed twice with Authentication Required. Re-logging in..."),this.session.login(),this.receivedAuthenticationRequired=-1))}));break;case ee.Punt:o.options.keepConnectionAliveOnSocketClose&&_?(A.info(`[${new Date().toISOString()}][${d}] keeping session calls alive due to PUNT and keepConnectionAliveOnSocketClose. Disconnecting base session...`),o.socketDisconnect(),this._ack(r,a)):o.disconnect();break;case ee.Invite:{const T=v();T.direction=ut.Inbound,T.playRingtone(),T.setState(X.Ringing),this._ack(r,a);break}case ee.Attach:{if(!m)return v().answer(),void this._ack(r,a);const T=!!m;A.info(`[${new Date().toISOString()}][${d}] closing existing call on ATTACH.`),m.hangup({isRecovering:T},!1),A.info(`[${new Date().toISOString()}][${d}] Attach: Creating new call for recovery`),v(T).answer(),this._ack(r,a);break}case ee.Event:case"webrtc.event":if(!u)return void A.error("Verto received an unknown event:",l);const C=o.relayProtocol,k=u.split(".")[0];o._existsSubscription(C,u)?J(C,l,u):u===o.sessionid?this._handleSessionEvent(l.eventData):o._existsSubscription(C,k)?J(C,l,k):o.calls.hasOwnProperty(u)?o.calls[u].handleMessage(e):J(V.Notification,l,o.uuid);break;case ee.Info:l.type=Je.generic,J(V.Notification,l,o.uuid);break;case ee.ClientReady:this.session.execute(w);break;default:{const T=Xr(e);if(T){switch(T){case Ne.REGISTER:case Ne.REGED:if(o.connection.previousGatewayState!==Ne.REGED&&o.connection.previousGatewayState!==Ne.REGISTER){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0;const E=(s=(i=e==null?void 0:e.result)===null||i===void 0?void 0:i.params)===null||s===void 0?void 0:s.call_report_id;E&&(o.callReportId=E,A.debug("Captured call_report_id from REGED:",E)),l.type=Je.vertoClientReady,J(V.Ready,l,o.uuid)}break;case Ne.UNREGED:case Ne.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0,J(V.Error,{error:new Mu("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{this.session.execute(w)},this.reconnectDelay());break;case Ne.FAILED:case Ne.FAIL_WAIT:if(o.connection.previousGatewayState!==Ne.FAILED&&o.connection.previousGatewayState!==Ne.FAIL_WAIT){if(!this.session.hasAutoReconnect()){this.retriedConnect=0,J(V.Error,{error:new Mu("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT"),sessionId:o.sessionid},o.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,J(V.Error,{error:new Error("Connection Retry Failed"),sessionId:o.sessionid},o.uuid);break}setTimeout(()=>{if(A.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(o.calls).some(E=>{var D;return((D=E.peer)===null||D===void 0?void 0:D.instance)&&!E.signalingStateClosed}))return A.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();A.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:A.warn("GatewayState message unknown method:",e)}break}A.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 B(this,void 0,void 0,function*(){const{session:n}=this,i=n.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:d,role:u,callID:f}=e;switch(s){case"conference-liveArray-join":{const m=()=>{n.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const y=f||this._retrieveCallId(w,o);if(y&&n.calls.hasOwnProperty(y)){const C=n.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(k=>{k==="INVALID_PACKET"&&m()})}}},v=yield n.vertoSubscribe(_).catch(w=>{A.error("liveArray subscription error:",w)});to(v,o)&&m();break}case"conference-liveArray-part":{let m=null;if(o&&n._existsSubscription(i,o)){const{callId:v=null}=n.subscriptions[i][o];if(m=n.calls[v]||null,v!==null){const w={type:Je.conferenceUpdate,action:He.Leave,conferenceName:r,participantId:Number(d),role:u};J(V.Notification,w,v,!1)||J(V.Notification,w,n.uuid),m===null&&Pt(V.Notification,null,v)}}const _=[o,a,l,c];n.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{m&&(m.channels=m.channels.filter(w=>!v.includes(w)))}).catch(v=>{A.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Ru(this.session,e);break;case"logo-info":{const n={type:Je.conferenceUpdate,action:He.LogoInfo,logo:e.logoURL};J(V.Notification,n,this.session.uuid);break}}}}class h_ extends d_{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:n=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=n}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new u_(this),window.addEventListener("beforeunload",n=>{this.calls&&Object.keys(this.calls).forEach(i=>{this.calls[i]&&(A.info(`Hanging up call due to window unload: ${i}`),this.calls[i].hangup({},!0))})})}validateOptions(){return Ji(this.options)||ei(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 Xt(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!!ei(this.options)||!!e.destinationNumber}_onSocketOpen(){return B(this,void 0,void 0,function*(){return Ji(this.options)?this.handleLoginOnSocketOpen():ei(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class f_ extends h_{constructor(e){super(e),A.info(`SDK version: ${gu}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return e_()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:_e.not_supported},{browserName:"Firefox",supported:_e.not_supported},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",supported:_e.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",features:["video","audio"],supported:_e.full},{browserName:"Edge",features:["audio"],supported:_e.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:_e.full},{browserName:"Firefox",features:["audio"],supported:_e.partial},{browserName:"Safari",supported:_e.not_supported},{browserName:"Edge",features:["audio"],supported:_e.partial}]}]}}function Du(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ou={exports:{}},Nu;function p_(){return Nu||(Nu=1,function(t){var e=Object.prototype.hasOwnProperty,n="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(n=!1));function s(l,c,d){this.fn=l,this.context=c,this.once=d||!1}function o(l,c,d,u,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new s(d,u||l,f),_=n?n+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],m]:l._events[_].push(m):(l._events[_]=m,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new i:delete l._events[c]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,m=new Array(f);u<f;u++)m[u]=d[u].fn;return m},a.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,f,m){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],w=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),w){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,u),!0;case 5:return v.fn.call(v.context,c,d,u,f),!0;case 6:return v.fn.call(v.context,c,d,u,f,m),!0}for(C=1,y=new Array(w-1);C<w;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var k=v.length,T;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),w){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,d);break;case 4:v[C].fn.call(v[C].context,c,d,u);break;default:if(!y)for(T=1,y=new Array(w-1);T<w;T++)y[T-1]=arguments[T];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,d){return o(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return o(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var f=n?n+l:l;if(!this._events[f])return this;if(!c)return r(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!u||m.once)&&(!d||m.context===d)&&r(this,f);else{for(var _=0,v=[],w=m.length;_<w;_++)(m[_].fn!==c||u&&!m[_].once||d&&m[_].context!==d)&&v.push(m[_]);v.length?this._events[f]=v.length===1?v[0]:v:r(this,f)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&r(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a}(Ou)),Ou.exports}var g_=p_();const so=Du(g_),is=new so;var ro={exports:{}},m_=ro.exports,Fu;function v_(){return Fu||(Fu=1,function(t){(function(e,n){t.exports?t.exports=n():e.log=n()})(m_,function(){var e=function(){},n="undefined",i=typeof window!==n&&typeof window.navigator!==n&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,w){var y=v[w];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===n?!1:v==="trace"&&i?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function d(){for(var v=this.getLevel(),w=0;w<s.length;w++){var y=s[w];this[y]=w<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===n&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==n&&(d.call(this),this[v].apply(this,arguments))}}function f(v,w,y){return c(v)||u.apply(this,arguments)}function m(v,w){var y=this,C,k,T,E="loglevel";typeof v=="string"?E+=":"+v:typeof v=="symbol"&&(E=void 0);function D(h){var b=(s[h]||"silent").toUpperCase();if(!(typeof window===n||!E)){try{window.localStorage[E]=b;return}catch{}try{window.document.cookie=encodeURIComponent(E)+"="+b+";"}catch{}}}function S(){var h;if(!(typeof window===n||!E)){try{h=window.localStorage[E]}catch{}if(typeof h===n)try{var b=window.document.cookie,I=encodeURIComponent(E),P=b.indexOf(I+"=");P!==-1&&(h=/^([^;]+)/.exec(b.slice(P+I.length+1))[1])}catch{}return y.levels[h]===void 0&&(h=void 0),h}}function x(){if(!(typeof window===n||!E)){try{window.localStorage.removeItem(E)}catch{}try{window.document.cookie=encodeURIComponent(E)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(h){var b=h;if(typeof b=="string"&&y.levels[b.toUpperCase()]!==void 0&&(b=y.levels[b.toUpperCase()]),typeof b=="number"&&b>=0&&b<=y.levels.SILENT)return b;throw new TypeError("log.setLevel() called with invalid level: "+h)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||f,y.getLevel=function(){return T??k??C},y.setLevel=function(h,b){return T=p(h),b!==!1&&D(T),d.call(y)},y.setDefaultLevel=function(h){k=p(h),S()||y.setLevel(h,!1)},y.resetLevel=function(){T=null,x(),d.call(y)},y.enableAll=function(h){y.setLevel(y.levels.TRACE,h)},y.disableAll=function(h){y.setLevel(y.levels.SILENT,h)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),d.call(y),r===y)for(var h in o)o[h].rebuild()},C=p(r?r.getLevel():"WARN");var g=S();g!=null&&(T=p(g)),d.call(y)}r=new m,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var w=o[v];return w||(w=o[v]=new m(v,r.methodFactory)),w};var _=typeof window!==n?window.log:void 0;return r.noConflict=function(){return typeof window!==n&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(ro)),ro.exports}var y_=v_();const __=Du(y_),b_=()=>new Date().toISOString().replace("T"," ").replace("Z",""),Re=__.getLogger("telnyx-ai-agent"),w_=Re.methodFactory;Re.methodFactory=(t,e,n)=>{const i=w_(t,e,n);return function(...s){i(b_(),"-",...s)}},Re.setLevel("info");function S_(t,e){let n=0;return(...i)=>{const s=Date.now();s-n>=e&&(n=s,t(...i))}}const C_=10,x_=500,k_=100,Vu=20;class T_{constructor(e){Y(this,"remoteIntervalId",null);Y(this,"localIntervalId",null);Y(this,"remoteStream",null);Y(this,"localStream",null);Y(this,"remoteAudioContext",null);Y(this,"remoteSource",null);Y(this,"remoteAnalyser",null);Y(this,"localAudioContext",null);Y(this,"localSource",null);Y(this,"localAnalyser",null);Y(this,"thinkingStartTime",null);Y(this,"lastState",null);Y(this,"userIsSpeaking",!1);Y(this,"lastUserAudioTime",null);Y(this,"userSpeechStartTime",null);Y(this,"userSilenceStartTime",null);Y(this,"isFirstAgentSpeech",!0);Y(this,"monitorStartTime",null);Y(this,"volumeThreshold");Y(this,"silenceDurationMs");Y(this,"minSpeechDurationMs");Y(this,"maxLatencyMs");Y(this,"updateAgentState",S_(e=>{Re.debug("AudioStreamMonitor updateAgentState",e),Re.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,is.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??C_,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??x_,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??k_,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs}setRemoteStream(e){this.remoteStream&&this.stopRemoteMonitor(),this.remoteStream=e,this.startRemoteMonitor()}setLocalStream(e){this.localStream&&this.stopLocalMonitor(),this.localStream=e,this.startLocalMonitor()}setMonitoredAudioStream(e){this.setRemoteStream(e)}stopRemoteMonitor(){var e,n;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(n=this.remoteAudioContext)==null||n.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,n;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(n=this.localAudioContext)==null||n.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){Re.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,Re.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(Re.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;Re.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const n=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let i=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(n);const o=n.reduce((l,c)=>l+c,0)/n.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&Re.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(i)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});i=r};this.remoteIntervalId=window.setInterval(s,Vu)}startLocalMonitor(){if(!this.localStream){Re.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,Re.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(Re.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),n=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const i=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&Re.debug("Local audio volume:",i),i>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(n,Vu)}destroy(){this.stopAudioStreamMonitor()}}function A_(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function E_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function I_(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function R_(t){var n;if(!t||typeof t!="object")return!1;const e=t;return((n=e.params)==null?void 0:n.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}function L_(t){return E_(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function P_(t){if(!I_(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",n=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((i,s)=>(s.type==="text"&&(i+=s.text),i),""),n=t.params.item.content.reduce((i,s)=>(s.type==="image_url"&&s.image_url.url&&i.push({type:"image",url:s.image_url.url}),i),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:n}}class M_ extends so{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcript",[]);Y(this,"onSocketMessage",n=>{if(A_(n))switch(n.params.type){case"response.text.delta":{const i=L_(n);i&&(this.transcript.push(i),this.emit("transcript.item",i),is.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(R_(n)){const i=n.params.item_id,s=this.transcript.findIndex(o=>o.id===i);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const i=P_(n);if(i){const s=this.transcript.findIndex(o=>o.id===i.id);s!==-1?this.transcript[s]=i:this.transcript.push(i),this.emit("transcript.item",i)}return}}});this.telnyxRTC=n,this.telnyxRTC.on(V.SocketMessage,this.onSocketMessage)}}class D_ extends so{constructor(n){super();Y(this,"telnyxRTC");Y(this,"transcription");Y(this,"agentId");Y(this,"versionId");Y(this,"conversationId");Y(this,"debug");Y(this,"audioStreamMonitor");Y(this,"activeCall");Y(this,"chatMode");Y(this,"dc",null);Y(this,"region",null);Y(this,"callReportId",null);Y(this,"onClientReady",()=>{const n=this.telnyxRTC;this.dc=n.dc??null,this.region=n.region??null,this.callReportId=n.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});Y(this,"onClientOrSocketError",n=>{this.emit("agent.error",n)});Y(this,"onNotification",n=>{n.type!=="callUpdate"||!n.call||(this.emit("conversation.update",n),n.call.state==="active"?(this.activeCall=n.call,n.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(n.call.remoteStream),n.call.localStream&&this.audioStreamMonitor.setLocalStream(n.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});Y(this,"onTranscriptItem",n=>{this.emit("transcript.item",n)});Y(this,"onAgentStateChange",n=>{this.emit("conversation.agent.state",n)});this.agentId=n.agentId,this.versionId=n.versionId||"main",this.conversationId=n.conversationId,this.debug=n.debug||!1,this.chatMode=n.chatMode||!1,this.activeCall=null,Re.setLevel(this.debug?"debug":"info");const i={target_id:n.agentId,target_type:"ai_assistant",target_version_id:n.versionId};n.conversationId&&(i.target_params={conversation_id:n.conversationId}),this.telnyxRTC=new f_({env:n.environment||"production",anonymous_login:i,debug:n.debug||!1,trickleIce:n.trickleIce,region:n.region}),this.telnyxRTC.on(V.Ready,this.onClientReady),this.telnyxRTC.on(V.Error,this.onClientOrSocketError),this.telnyxRTC.on(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(V.Notification,this.onNotification),this.transcription=new M_(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),is.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new T_(n.vad)}async connect(){return this.telnyxRTC.connect()}async disconnect(){this.audioStreamMonitor.destroy(),this.telnyxRTC.disconnect(),this.telnyxRTC.off(V.Ready,this.onClientReady),this.telnyxRTC.off(V.Error,this.onClientOrSocketError),this.telnyxRTC.off(V.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(V.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),is.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(n,i=[]){if(!this.activeCall){Re.error("No active call to send message.");return}this.activeCall.sendConversationMessage(n,i)}get transcript(){return this.transcription.transcript}async startConversation(n){var c,d;if(!this.telnyxRTC){Re.error("Client is not initialized.");return}const i=(d=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:d.find(u=>u.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=n||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[i],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var n;return(n=this.activeCall)==null?void 0:n.hangup()}setRemoteStream(n){this.audioStreamMonitor.setRemoteStream(n)}}var Bu={exports:{}},oi={},ju;function O_(){if(ju)return oi;ju=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(i,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:i,key:r,ref:s!==void 0?s:null,props:o}}return oi.Fragment=e,oi.jsx=n,oi.jsxs=n,oi}var Uu;function N_(){return Uu||(Uu=1,Bu.exports=O_()),Bu.exports}N_(),vt(void 0),vt(null);const F_=(t,e,n,i,s,o,r,a,l)=>new D_({agentId:t,environment:e,versionId:n,debug:i,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l}),V_=(t,e,n,i,s,o,r,a,l)=>{const[c,d]=xe(null),[u,f]=xe(!1),[m,_]=xe(null);return ke(()=>{if(!t)return;const v=F_(t,e,n,i,s,o,r,a,l),w=()=>{f(!0),_(null)},y=()=>{f(!1)},C=k=>{_(k),Ce.error("AI Agent error:",k)};return v.on("agent.connected",w),v.on("agent.disconnected",y),v.on("agent.error",C),v.connect(),d(v),()=>{v.off("agent.connected",w),v.off("agent.disconnected",y),v.off("agent.error",C),v.disconnect()}},[t,e,n,i,s,o,r,a,l]),{client:c,isConnected:u,error:m}},B_="telnyx-ai-agent",Mt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute"};function $u(){const t=document.querySelector(B_);return t instanceof HTMLElement?t:null}function Dt(t,e,n){const i=n||$u();if(!i){Ce.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});i.dispatchEvent(s),Ce.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const j_=(t,e)=>{const{onReady:n,onConversationUpdate:i,onError:s,onConfigMessage:o}=e,r=me(null),a=wi(Wd);ke(()=>{r.current=$u()},[]),ke(()=>{if(!t)return;const l=r.current,c=()=>{n();const E=t.telnyxRTC,D={dc:(E==null?void 0:E.dc)??null,region:(E==null?void 0:E.region)??null,callReportId:(E==null?void 0:E.callReportId)??null};a(D),Dt(Mt.AGENT_CONNECTED,D,l)},d=()=>{a(null),Dt(Mt.AGENT_DISCONNECTED,void 0,l)},u=T=>{s(T);const E={message:T.message,name:T.name};Dt(Mt.AGENT_ERROR,E,l)},f=T=>{var E;i(T),Dt(Mt.CONVERSATION_UPDATE,{type:T.type,callState:(E=T.call)==null?void 0:E.state},l)},m=T=>{Dt(Mt.TRANSCRIPT_ITEM,T,l)},_=T=>{Dt(Mt.CONVERSATION_AGENT_STATE,T,l)},v=T=>{Dt(Mt.AGENT_AUDIO_MUTE,{muted:T},l)},y=t.telnyxRTC,C=T=>{o(T)},k=T=>{const E=T,D={code:E==null?void 0:E.code,reason:E==null?void 0:E.reason,wasClean:E==null?void 0:E.wasClean,timestamp:new Date().toISOString()};Ce.info("[socket.close]",D),Dt(Mt.SOCKET_CLOSE,D,l)};return y&&typeof y=="object"&&(y.on(V.SocketMessage,C),y.on(V.SocketClose,k)),t.on("agent.connected",c),t.on("agent.disconnected",d),t.on("agent.error",u),t.on("conversation.update",f),t.on("transcript.item",m),t.on("conversation.agent.state",_),t.on("agent.audio.mute",v),()=>{t.off("agent.connected",c),t.off("agent.disconnected",d),t.off("agent.error",u),t.off("conversation.update",f),t.off("transcript.item",m),t.off("conversation.agent.state",_),t.off("agent.audio.mute",v),y&&typeof y=="object"&&(y.off(V.SocketMessage,C),y.off(V.SocketClose,k))}},[t,n,i,s,o,a])},U_=2e3;async function $_(t){return new Promise((e,n)=>{const i=new FileReader;i.readAsDataURL(t),i.onload=()=>e(i.result),i.onerror=s=>n(s)})}function Hu(t){const e=t.split("-"),n=e[e.length-1];return n&&n.length===13&&/^\d+$/.test(n)?e.slice(0,-1).join("-"):t}const H_=(t,e)=>{const[n,i]=xe([]),[,s]=Ur(),o=me(e);ke(()=>{o.current=e},[e]);const r=me(void 0),a=me(void 0);return ke(()=>{if(!t)return;const c=f=>{i(m=>{const _=m[m.length-1];if(f.role==="assistant"&&_&&Hu(_.id)===Hu(f.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,w=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,y={..._,content:_.content+f.content,timestamp:f.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...m.slice(0,-1),y]}if(f.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const y={...f,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...m,y]}r.current=void 0,a.current=void 0}if(f.role==="user"){const v=m.findIndex(y=>y.id===f.id);if(v!==-1){const y=[...m];return y[v]={...m[v],content:f.content,timestamp:f.timestamp,attachments:f.attachments},y}if(_&&_.role==="user"&&f.timestamp.getTime()-_.timestamp.getTime()<U_){const C={..._,id:f.id,content:_.content+" "+f.content,timestamp:f.timestamp,attachments:[..._.attachments||[],...f.attachments||[]]};return[...m.slice(0,-1),C]}const w=f.attachments&&f.attachments.length>0;s(w?"processing_image":"thinking")}return[...m,f]})},d=({state:f,userPerceivedLatencyMs:m,greetingLatencyMs:_,thinkingStartedAt:v})=>{(m!==void 0||_!==void 0)&&Ce.info(`[AgentState] state=${f} userPerceivedLatencyMs=${m} greetingLatencyMs=${_} thinkingStartedAt=${v}`),f==="speaking"?(s("speaking"),m!==void 0&&(r.current=m),_!==void 0&&(a.current=_)):f==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},u=f=>{var _;const m=(_=f.call)==null?void 0:_.state;(m==="destroy"||m==="done")&&i([])};return t.on("transcript.item",c),t.on("conversation.agent.state",d),t.on("conversation.update",u),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",d),t.off("conversation.update",u)}},[t,s]),{transcript:n,sendMessage:async(c,d)=>{if(!t)return;const u=[];if(d&&d.length>0)for(const f of d)try{const m=await $_(f);u.push(m)}catch(m){throw Ce.error("Failed to convert file to base64:",m),m}t.sendConversationMessage(c,u)}}},G_=({call:t,client:e,latencySettings:n,chatMode:i})=>{const s=qt(),[o,r]=xe(i?"expanded":s.default_state),a=()=>r("expanded"),l=()=>r("collapsed"),{transcript:c}=H_(e,n),d=me(!1);switch(ke(()=>{if(i&&t&&!d.current){const u="remoteStream"in t?t.remoteStream:null;u&&(d.current=!0,u.getAudioTracks().forEach(f=>{f.enabled=!1,Ce.info(`[ChatMode] Disabled remote audio track: ${f.label}`)}))}},[i,t]),o){case"collapsed":return R(Gd,{onExpand:a,call:t,client:e,chatMode:i});case"expanded":return R(Sy,{transcript:c,onCollapse:l,call:t,chatMode:i});default:return R(Gd,{onExpand:a,call:t,client:e,chatMode:i})}},oo=()=>R(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:R("div",{className:"rounded-full animate-spin",children:R(Zv,{})})}),W_=({call:t,client:e,latencySettings:n,chatMode:i})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return R(oo,{});case"done":case"purged":case"destroy":return null;case"active":return R(G_,{client:e,call:t,latencySettings:n,chatMode:i});default:return R(oo,{})}},z_=({className:t})=>R("svg",{className:t,width:"236",height:"211",viewBox:"0 0 236 211",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:[R("g",{clipPath:"url(#:R5lfm:)",children:[R("path",{d:"M231.927 194.514C235.881 187.393 237.006 179.067 235.083 171.168C234.531 168.984 233.769 166.858 232.806 164.819C232.502 164.15 232.156 163.501 231.771 162.874L200.418 104.252H168.341L201.143 165.69C202.172 167.475 202.714 169.496 202.714 171.552C202.714 173.608 202.172 175.628 201.143 177.414C200.139 179.082 198.715 180.464 197.01 181.424C195.305 182.385 193.378 182.89 191.416 182.892H154.009C153.595 188.612 151.801 194.15 148.776 199.041C145.751 203.931 141.584 208.033 136.625 211H205.385C209.975 210.698 214.443 209.405 218.475 207.211C224.164 204.438 228.859 200.007 231.927 194.514Z",fill:"currentColor"}),R("path",{d:"M56.0698 65.9049H88.1473L104.134 36.466C105.487 33.9253 107.515 31.7984 109.999 30.3146C112.484 28.8309 115.331 28.0467 118.233 28.0467C121.135 28.0467 123.982 28.8309 126.466 30.3146C128.951 31.7984 130.979 33.9253 132.331 36.466L147.853 65.9049H179.93L157.166 23.3081C153.391 16.2702 147.751 10.3822 140.851 6.27586C133.951 2.16956 126.052 0 118 0C109.948 0 102.049 2.16956 95.1487 6.27586C88.2488 10.3822 82.6089 16.2702 78.8345 23.3081L56.0698 65.9049Z",fill:"currentColor"}),R("path",{d:"M81.9387 99.1324C82.275 93.4362 83.9987 87.9051 86.9627 83.0107C89.9266 78.1164 94.0429 74.0041 98.9604 71.0247H36.875V99.1324H81.9387Z",fill:"currentColor"}),R("path",{d:"M87.0591 101.18V177.977H101.649C104.692 177.944 107.64 176.924 110.041 175.075C112.443 173.226 114.165 170.648 114.946 167.738C115.26 166.621 115.416 165.467 115.411 164.308V118.229C115.425 113.227 117.432 108.432 120.997 104.885C124.561 101.338 129.396 99.3264 134.451 99.286H199.382V71.0247H117.481C109.408 71.0382 101.67 74.2213 95.9663 79.8751C90.2626 85.5289 87.0591 93.1914 87.0591 101.18Z",fill:"currentColor"}),R("path",{d:"M3.1927 164.819C2.23008 166.858 1.46775 168.984 0.916237 171.168C-1.00574 179.084 0.119328 187.425 4.07225 194.565C7.14854 200.039 11.8422 204.452 17.5241 207.211C21.5555 209.405 26.0233 210.698 30.6138 211H117.999C126.232 211 134.128 207.764 139.949 202.003C145.771 196.242 149.042 188.428 149.042 180.281V104.201H134.245C130.607 104.294 127.148 105.782 124.6 108.352C122.051 110.922 120.611 114.372 120.586 117.973V164.051C120.572 169.053 118.555 173.845 114.976 177.377C111.397 180.909 106.549 182.892 101.495 182.892H44.8417C42.8798 182.89 40.9521 182.385 39.2471 181.424C37.5421 180.464 36.1182 179.082 35.1149 177.414C34.0855 175.619 33.5443 173.59 33.5443 171.526C33.5443 169.462 34.0855 167.434 35.1149 165.638L67.9167 104.201H35.5806L4.22746 162.823C3.86529 163.539 3.50313 164.154 3.1927 164.819Z",fill:"currentColor"})]}),R("defs",{children:R("clipPath",{id:":R5lfm:",children:R("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Gu(){const t=qt();return t.logo_icon_url?R("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:R("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):R(z_,{className:"w-8 h-8 mr-2"})}const q_=({client:t,callProps:e,chatMode:n})=>{const i=qt(),s=me(!1),o=yt(()=>{if(!t){Ce.error("Client is not initialized.");return}t.startConversation({...e})},[t,e]);return ke(()=>{n&&t&&!s.current&&(s.current=!0,Ce.info("[ChatMode] Auto-starting conversation"),o())},[n,t,o]),n?R(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[R(Gu,{}),"Connecting..."]}):R(gn.button,{layoutId:Jn,onClick:o,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer dark:bg-black dark:text-white ",children:[R(Gu,{}),i.start_call_text]})},K_='@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-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline-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}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-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)}}',X_=({children:t})=>R("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:R("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),Y_={duration:.1,ease:"circOut"},J_=({children:t,position:e="fixed"})=>{const n=qt(),s=(e??n.position??"fixed")==="fixed"?R(X_,{children:t}):t;return R("div",{className:wt(n.theme==="dark"&&"dark"),children:R(Hp,{transition:Y_,children:[R("style",{children:K_}),s]})})},Z_=t=>R(gn.div,{layoutId:Jn,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[R(Yv,{className:"w-8 h-8 text-red-400"}),R("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),R("ul",{className:"gap-4 ml-4 text-sm list-disc",children:[R("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),R("li",{children:["Make sure that the"," ",R("a",{href:`https://portal.telnyx.com/#/ai/assistants/edit/${t.agentId}?tab=telephony`,className:"inline-flex items-center gap-1 font-medium text-green-400 underline",target:"_blank",rel:"noopener noreferrer",children:["Support Unauthenticated Web Calls"," ",R(sy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]})]});function ai(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Q_({"agent-id":t,debug:e,"trickle-ice":n,"call-destination-number":i,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":d,"conversation-id":u,"chat-mode":f,region:m,environment:_,position:v="fixed","version-id":w}){const y=ai(e),C=ai(n),k=ai(f),T=ze(()=>{if(l)try{return JSON.parse(l)}catch(U){Ce.error("Invalid JSON for vad attribute:",l,U);return}},[l]),E=ze(()=>({showUserPerceivedLatency:ai(c),showGreetingLatency:ai(d)}),[c,d]),{client:D}=V_(t,_,w,y,C,T,u,k,m),[S,x]=xe(null),[p,g]=xe(!1),[h,b]=xe(!1),[I,P]=xe(!1),[L,O]=xe(!1),M=wi($d),N=Cv(),W={};if(i&&(W.destinationNumber=i),s&&(W.callerNumber=s),o&&(W.callerName=o),r)try{W.customHeaders=JSON.parse(r)}catch(U){Ce.error("Invalid JSON for call-custom-headers attribute:",r,U)}if(a)try{W.audio=JSON.parse(a);const U=W.audio;if(typeof U=="object"){const q=navigator.mediaDevices.getSupportedConstraints();Object.keys(U).forEach(Z=>{q[Z]||Ce.warn(`Audio constraint not supported by browser: ${Z}`)})}}catch(U){Ce.error("Invalid JSON for call-audio attribute:",a,U)}const j=yt(()=>{g(!1)},[]),re=yt(U=>{var q;if(((q=U.call)==null?void 0:q.state)==="destroy")return M(!1),O(!0),x(null);x(U)},[M]),te=yt(()=>{g(!1),b(!0)},[]),$=yt(U=>{if(Sv(U)){const q=U.params.widget_settings;q&&Object.keys(q).length>0&&(N(q),P(!0))}},[N]);return j_(D,{onReady:j,onConversationUpdate:re,onError:te,onConfigMessage:$}),R(J_,{position:v,children:t?h?R(Z_,{agentId:t}):p?R(oo,{}):S!=null&&S.call?R(W_,{call:S.call,client:D,latencySettings:E,chatMode:k}):I?R(q_,{client:D,callProps:W,chatMode:k&&!L}):null:R("div",{children:"Please provide an assistant ID."})})}ah(Q_,"telnyx-ai-agent",bv,{shadow:!0})})();