@telnyx/ai-agent-widget 0.33.8-beta.0 → 0.33.8-beta.1

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 +29 -29
  2. package/package.json +3 -6
@@ -1,120 +1,120 @@
1
- var iw=Object.defineProperty;var nw=(ot,z,Ht)=>z in ot?iw(ot,z,{enumerable:!0,configurable:!0,writable:!0,value:Ht}):ot[z]=Ht;var W=(ot,z,Ht)=>nw(ot,typeof z!="symbol"?z+"":z,Ht);(function(){"use strict";var ot,z,Ht,Gt,$r,jr,Hr,Gr,Ts,Es,ks,Wr,Oi={},qr=[],Bh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ni=Array.isArray;function ut(t,e){for(var i in e)t[i]=e[i];return t}function Is(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Xe(t,e,i){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?ot.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Fi(t,r,n,s,null)}function Fi(t,e,i,n,s){var o={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Ht,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function ht(t){return t.children}function rt(t,e){this.props=t,this.context=e}function ai(t,e){if(e==null)return t.__?ai(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?ai(t):null}function zr(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return zr(t)}}function xs(t){(!t.__d&&(t.__d=!0)&&Gt.push(t)&&!Cn.__r++||$r!=z.debounceRendering)&&(($r=z.debounceRendering)||jr)(Cn)}function Cn(){for(var t,e,i,n,s,o,r,a=1;Gt.length;)Gt.length>a&&Gt.sort(Hr),t=Gt.shift(),a=Gt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=ut({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),As(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??ai(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,Qr(o,i,r),i.__e!=s&&zr(i)));Cn.__r=0}function Kr(t,e,i,n,s,o,r,a,l,c,u){var d,h,g,y,v,b,_=n&&n.__k||qr,C=e.length;for(l=$h(i,e,_,l,C),d=0;d<C;d++)(g=i.__k[d])!=null&&(h=g.__i==-1?Oi:_[g.__i]||Oi,g.__i=d,b=As(t,g,h,s,o,r,a,l,c,u),y=g.__e,g.ref&&h.ref!=g.ref&&(h.ref&&Rs(h.ref,null,g),u.push(g.ref,g.__c||y,g)),v==null&&y!=null&&(v=y),4&g.__u||h.__k===g.__k?l=Yr(g,l,t):typeof g.type=="function"&&b!==void 0?l=b:y&&(l=y.nextSibling),g.__u&=-7);return i.__e=v,l}function $h(t,e,i,n,s){var o,r,a,l,c,u=i.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Fi(null,r,null,null,null):Ni(r)?Fi(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Fi(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=jh(r,i,l,d))!=-1&&(d--,(a=i[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=i[o])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=ai(a)),ea(a,a));return n}function Yr(t,e,i){var n,s;if(typeof t.type=="function"){for(n=t.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=t,e=Yr(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=ai(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ft(t,e){return e=e||[],t==null||typeof t=="boolean"||(Ni(t)?t.some(function(i){ft(i,e)}):e.push(t)),e}function jh(t,e,i,n){var s,o,r=t.key,a=t.type,l=e[i];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return i;if(n>(l!=null&&(2&l.__u)==0?1:0))for(s=i-1,o=i+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function Xr(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Bh.test(e)?i:i+"px"}function Tn(t,e,i,n,s){var o,r;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||Xr(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||Xr(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Gr,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=i,i?n?i.u=n.u:(i.u=Ts,t.addEventListener(e,o?ks:Es,o)):t.removeEventListener(e,o?ks:Es,o);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function Jr(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Ts++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function As(t,e,i,n,s,o,r,a,l,c){var u,d,h,g,y,v,b,_,C,k,A,x,N,T,E,p,m,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(_=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],A=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(_,A):(e.__c=d=new rt(_,A),d.constructor=f,d.render=Gh),k&&k.sub(d),d.props=_,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ut({},d.__s)),ut(d.__s,f.getDerivedStateFromProps(_,d.__s))),g=d.props,y=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&_!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(_,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(_,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=_,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(w){w&&(w.__=e)}),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(_,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,v)})}if(d.context=A,d.props=_,d.__P=t,d.__e=!1,N=z.__r,T=0,C){for(d.state=d.__s,d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),E=0;E<d._sb.length;E++)d.__h.push(d._sb[E]);d._sb=[]}else do d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++T<25);d.state=d.__s,d.getChildContext!=null&&(n=ut(ut({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(g,y)),p=u,u!=null&&u.type===ht&&u.key==null&&(p=Zr(u.props.children)),a=Kr(t,Ni(p)?p:[p],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(w){if(e.__v=null,l||o!=null)if(w.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(m=o.length;m--;)Is(o[m]);else e.__e=i.__e,e.__k=i.__k;z.__e(w,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Hh(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function Qr(t,e,i){for(var n=0;n<i.length;n++)Rs(i[n],i[++n],i[++n]);z.__c&&z.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){z.__e(o,s.__v)}})}function Zr(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ni(t)?t.map(Zr):ut({},t)}function Hh(t,e,i,n,s,o,r,a,l){var c,u,d,h,g,y,v,b=i.props,_=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!C&&(C?g.localName==C:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(_);t=document.createElementNS(s,C,_.is&&_),a&&(z.__m&&z.__m(e,o),a=!1),o=null}if(C==null)b===_||a&&t.data==_||(t.data=_);else{if(o=o&&ot.call(t.childNodes),b=i.props||Oi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(g=t.attributes[c]).name]=g.value;for(c in b)if(g=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in _)){if(c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _)continue;Tn(t,c,null,g,s)}}for(c in _)g=_[c],c=="children"?h=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?y=g:c=="checked"?v=g:a&&typeof g!="function"||b[c]===g||Tn(t,c,g,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Kr(e.type=="template"?t.content:t,Ni(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&ai(i,0),a,l),o!=null)for(c=o.length;c--;)Is(o[c]);a||(c="value",C=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[c]||C=="progress"&&!y||C=="option"&&y!=b[c])&&Tn(t,c,y,b[c],s),c="checked",v!=null&&v!=t[c]&&Tn(t,c,v,b[c],s))}return t}function Rs(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){z.__e(s,i)}}function ea(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Rs(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&ea(n[s],e,i||typeof t.type!="function");i||Is(t.__e),t.__c=t.__=t.__e=void 0}function Gh(t,e,i){return this.constructor(t,i)}function En(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],As(e,t=(!n&&i||e).__k=Xe(ht,null,[t]),s||Oi,Oi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?ot.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),Qr(o,t,r)}function ta(t,e){En(t,e,ta)}function Ls(t,e,i){var n,s,o,r,a=ut({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?n=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?ot.call(arguments,2):i),Fi(t.type,a,n||t.key,s||t.ref,null)}function Tt(t){function e(i){var n,s;return this.getChildContext||(n=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&n.forEach(function(r){r.__e=!0,xs(r)})},this.sub=function(o){n.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){n&&n.delete(o),r&&r.call(o)}}),i.children}return e.__c="__cC"+Wr++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}ot=qr.slice,z={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Ht=0,rt.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ut({},this.state),typeof t=="function"&&(t=t(ut({},i),this.props)),t&&ut(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),xs(this))},rt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),xs(this))},rt.prototype.render=ht,Gt=[],jr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Hr=function(t,e){return t.__v.__b-e.__v.__b},Cn.__r=0,Gr=/(PointerCapture)$|Capture$/i,Ts=0,Es=Jr(!1),ks=Jr(!0),Wr=0;var Wh=0;function D(t,e,i,n,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Wh,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return z.vnode&&z.vnode(c),c}function Ds(){return(Ds=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t}).apply(this,arguments)}var qh=["context","children"];function zh(t){this.getChildContext=function(){return t.context};var e=t.children,i=function(n,s){if(n==null)return{};var o,r,a={},l=Object.keys(n);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=n[o]);return a}(t,qh);return Ls(e,i)}function Kh(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Xe(zh,Ds({},this._props,{context:t.detail.context}),function e(i,n){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;var s=[],o={},r=0,a=i.attributes,l=i.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[ia(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Xe(na,{name:u},c):s[r]=c}var d=n?Xe(na,null,s):s;return Xe(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?ta:En)(this._vdom,this._root)}function ia(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function Yh(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[ia(t)]=i,this._vdom=Ls(this._vdom,n),En(this._vdom,this._root)}}function Xh(){En(this._vdom=null,this._root)}function na(t,e){var i=this;return Xe("slot",Ds({},t,{ref:function(n){n?(i.ref=n,i._listener||(i._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function Jh(t,e,i,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=Kh,s.prototype.attributeChangedCallback=Yh,s.prototype.disconnectedCallback=Xh,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=i,i.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var Pt,_e,Ps,sa,Vi=0,oa=[],Se=z,ra=Se.__b,aa=Se.__r,la=Se.diffed,ca=Se.__c,da=Se.unmount,ua=Se.__;function li(t,e){Se.__h&&Se.__h(_e,t,Vi||e),Vi=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return Vi=1,ha(pa,t)}function ha(t,e,i){var n=li(Pt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):pa(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=_e,!_e.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},_e.shouldComponentUpdate=s}return n.__N||n.__}function Re(t,e){var i=li(Pt++,3);!Se.__s&&Fs(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Ms(t,e){var i=li(Pt++,4);!Se.__s&&Fs(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function de(t){return Vi=5,Je(function(){return{current:t}},[])}function Je(t,e){var i=li(Pt++,7);return Fs(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function He(t,e){return Vi=8,Je(function(){return t},e)}function Le(t){var e=_e.context[t.__c],i=li(Pt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function Qh(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Os(){var t=li(Pt++,11);if(!t.__){for(var e=_e.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var i=e.__m||(e.__m=[0,0]);t.__="P"+i[0]+"-"+i[1]++}return t.__}function Zh(){for(var t;t=oa.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(kn),t.__H.__h.forEach(Ns),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,ra&&ra(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),ua&&ua(t,e)},Se.__r=function(t){aa&&aa(t),Pt=0;var e=(_e=t.__c).__H;e&&(Ps===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(kn),e.__h.forEach(Ns),e.__h=[],Pt=0)),Ps=_e},Se.diffed=function(t){la&&la(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(oa.push(e)!==1&&sa===Se.requestAnimationFrame||((sa=Se.requestAnimationFrame)||ef)(Zh)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Ps=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(kn),i.__h=i.__h.filter(function(n){return!n.__||Ns(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),ca&&ca(t,e)},Se.unmount=function(t){da&&da(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{kn(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var fa=typeof requestAnimationFrame=="function";function ef(t){var e,i=function(){clearTimeout(n),fa&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);fa&&(e=requestAnimationFrame(i))}function kn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Ns(t){var e=_e;t.__c=t.__(),_e=e}function Fs(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function pa(t,e){return typeof e=="function"?e(t):e}const Ui={},ga=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ma=t=>"init"in t,Vs=t=>!!t.write,va=t=>"v"in t||"e"in t,In=t=>{if("e"in t)throw t.e;if((Ui?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},xn=new WeakMap,_a=t=>{var e;return An(t)&&!!((e=xn.get(t))!=null&&e[0])},tf=t=>{const e=xn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},ya=(t,e)=>{let i=xn.get(t);if(!i){i=[!0,new Set],xn.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},An=t=>typeof(t==null?void 0:t.then)=="function",ba=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},Us=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(An(e))for(const r of n.d.keys())ba(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,An(o)&&tf(o))},wa=(t,e,i)=>{var n;const s=new Set;for(const o of((n=i.get(t))==null?void 0:n.t)||[])i.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},nf=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Bs=()=>{const t={},e=new WeakMap,i=n=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(n)),(o=e.get(n))==null||o.forEach(r=>r())};return i.add=(n,s)=>{const o=n||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},i},sf=t=>(t.c||(t.c=Bs()),t.m||(t.m=Bs()),t.u||(t.u=Bs()),t.f||(t.f=nf()),t),of=Symbol(),Sa=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...g)=>h.read(...g),l=(h,...g)=>h.write(...g),c=(h,g)=>{var y;return(y=h.unstable_onInit)==null?void 0:y.call(h,g)},u=(h,g)=>{var y;return(y=h.onMount)==null?void 0:y.call(h,g)},...d)=>{const h=d[0]||(T=>{if((Ui?"production":void 0)!=="production"&&!T)throw new Error("Atom is undefined or null");let E=t.get(T);return E||(E={d:new Map,p:new Set,n:0},t.set(T,E),c==null||c(T,N)),E}),g=d[1]||(()=>{const T=[],E=p=>{try{p()}catch(m){T.push(m)}};do{r.f&&E(r.f);const p=new Set,m=p.add.bind(p);n.forEach(f=>{var w;return(w=e.get(f))==null?void 0:w.l.forEach(m)}),n.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),p.forEach(E),n.size&&y()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),y=d[2]||(()=>{const T=[],E=new WeakSet,p=new WeakSet,m=Array.from(n);for(;m.length;){const f=m[m.length-1],w=h(f);if(p.has(f)){m.pop();continue}if(E.has(f)){if(i.get(f)===w.n)T.push([f,w]);else if((Ui?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");p.add(f),m.pop();continue}E.add(f);for(const I of wa(f,w,e))E.has(I)||m.push(I)}for(let f=T.length-1;f>=0;--f){const[w,I]=T[f];let L=!1;for(const R of I.d.keys())if(R!==w&&n.has(R)){L=!0;break}L&&(v(w),C(w)),i.delete(w)}}),v=d[3]||(T=>{var E;const p=h(T);if(va(p)&&(e.has(T)&&i.get(T)!==p.n||Array.from(p.d).every(([P,F])=>v(P).n===F)))return p;p.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),y(),g())},w=P=>{var F;if(ga(T,P)){const $=h(P);if(!va($))if(ma(P))Us(P,P.init,h);else throw new Error("no atom init");return In($)}const H=v(P);try{return In(H)}finally{p.d.set(P,H.n),_a(p.v)&&ba(T,p.v,H),(F=e.get(P))==null||F.t.add(T),m||f()}};let I,L;const R={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Ui?"production":void 0)!=="production"&&!Vs(T)&&console.warn("setSelf function cannot be used with read-only atom"),!L&&Vs(T)&&(L=(...P)=>{if((Ui?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return _(T,...P)}finally{y(),g()}}),L}},O=p.n;try{const P=a(T,w,R);return Us(T,P,h),An(P)&&(ya(P,()=>I==null?void 0:I.abort()),P.then(f,f)),p}catch(P){return delete p.v,p.e=P,++p.n,p}finally{m=!1,O!==p.n&&i.get(T)===O&&(i.set(T,p.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const p=E.pop(),m=h(p);for(const f of wa(p,m,e)){const w=h(f);i.set(f,w.n),E.push(f)}}}),_=d[5]||((T,...E)=>{let p=!0;const m=w=>In(v(w)),f=(w,...I)=>{var L;const R=h(w);try{if(ga(T,w)){if(!ma(w))throw new Error("atom not writable");const O=R.n,P=I[0];Us(w,P,h),C(w),O!==R.n&&(n.add(w),(L=r.c)==null||L.call(r,w),b(w));return}else return _(w,...I)}finally{p||(y(),g())}};try{return l(T,m,f,...E)}finally{p=!1}}),C=d[6]||(T=>{var E;const p=h(T),m=e.get(T);if(m&&!_a(p.v)){for(const[f,w]of p.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(T),m.d.add(f),w!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of m.d||[])if(!p.d.has(f)){m.d.delete(f);const w=A(f);w==null||w.t.delete(T)}}}),k=d[7]||(T=>{var E;const p=h(T);let m=e.get(T);if(!m){v(T);for(const f of p.d.keys())k(f).t.add(T);if(m={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(T,m),(E=r.m)==null||E.call(r,T),Vs(T)){const f=()=>{let w=!0;const I=(...L)=>{try{return _(T,...L)}finally{w||(y(),g())}};try{const L=u(T,I);L&&(m.u=()=>{w=!0;try{L()}finally{w=!1}})}finally{w=!1}};s.add(f)}}return m}),A=d[8]||(T=>{var E;const p=h(T);let m=e.get(T);if(m&&!m.l.size&&!Array.from(m.t).some(f=>{var w;return(w=e.get(f))==null?void 0:w.d.has(T)})){m.u&&o.add(m.u),m=void 0,e.delete(T),(E=r.u)==null||E.call(r,T);for(const f of p.d.keys()){const w=A(f);w==null||w.t.delete(T)}return}return m}),x=[t,e,i,n,s,o,r,a,l,c,u,h,g,y,v,b,_,C,k,A],N={get:T=>In(v(T)),set:(T,...E)=>{try{return _(T,...E)}finally{y(),g()}},sub:(T,E)=>{const m=k(T).l;return m.add(E),g(),()=>{m.delete(E),A(T),g()}}};return Object.defineProperty(N,of,{value:x}),N},rf=sf,Ca=ya,$s={};let af=0;function Rn(t,e){const i=`atom${++af}`,n={toString(){return($s?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=lf,n.write=cf),n}function lf(t){return t(this)}function cf(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const df=()=>{let t=0;const e=rf({}),i=new WeakMap,n=new WeakMap,s=Sa(i,n,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=i.get(a);l.m=n.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=i.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),i),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function uf(){return($s?"production":void 0)!=="production"?df():Sa()}let Bi;function hf(){return Bi||(Bi=uf(),($s?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Bi),globalThis.__JOTAI_DEFAULT_STORE__!==Bi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Bi}function Ta(t,e){for(var i in e)t[i]=e[i];return t}function Ea(t,e){for(var i in t)if(i!=="__source"&&!(i in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}var ka=Ms;function Ia(t,e){this.props=t,this.context=e}(Ia.prototype=new rt).isPureReactComponent=!0,Ia.prototype.shouldComponentUpdate=function(t,e){return Ea(this.props,t)||Ea(this.state,e)};var xa=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),xa&&xa(t)};var ff=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function pf(t){function e(i){var n=Ta({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=ff,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Aa=function(t,e){return t==null?null:ft(ft(t).map(e))},gf={map:Aa,forEach:Aa,count:function(t){return t?ft(t).length:0},only:function(t){var e=ft(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ft},mf=z.__e;z.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}mf(t,e,i,n)};var Ra=z.unmount;function La(t,e,i){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=Ta({},t)).__c!=null&&(t.__c.__P===i&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return La(n,e,i)})),t}function Da(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Da(n,e,i)}),t.__c&&t.__c.__P===e&&(t.__e&&i.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=i)),t}function js(){this.__u=0,this.o=null,this.__b=null}function Pa(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Ln(){this.i=null,this.l=null}z.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Ra&&Ra(t)},(js.prototype=new rt).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Pa(n.__v),o=!1,r=function(){o||(o=!0,i.__R=null,s?s(a):a())};i.__R=r;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=Da(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(r,r)},js.prototype.componentWillUnmount=function(){this.o=[]},js.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var i=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=La(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Xe(ht,null,t.fallback);return s&&(s.__u&=-33),[Xe(ht,null,e.__a?null:t.children),s]};var Ma=function(t,e,i){if(++i[1]===i[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(i=t.i;i;){for(;i.length>3;)i.pop()();if(i[1]<i[0])break;t.i=i=i[2]}};(Ln.prototype=new rt).__a=function(t){var e=this,i=Pa(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Ma(e,t,n)):s()};i?i(o):o()}},Ln.prototype.render=function(t){this.i=null,this.l=new Map;var e=ft(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var i=e.length;i--;)this.l.set(e[i],this.i=[1,0,this.i]);return t.children},Ln.prototype.componentDidUpdate=Ln.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Ma(t,i,e)})};var Oa=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,vf=/^(?: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]/,_f=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,yf=/[A-Z0-9]/g,bf=typeof document<"u",wf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};rt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(rt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Na=z.event;function Sf(){}function Cf(){return this.cancelBubble}function Tf(){return this.defaultPrevented}z.event=function(t){return Na&&(t=Na(t)),t.persist=Sf,t.isPropagationStopped=Cf,t.isDefaultPrevented=Tf,t.nativeEvent=t};var Ef={enumerable:!1,configurable:!0,get:function(){return this.class}},Fa=z.vnode;z.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||bf&&r==="children"&&n==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in i&&i.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||n!=="input"&&n!=="textarea"||wf(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":_f.test(r)&&(r=l):l=r="oninput":o&&vf.test(r)?r=r.replace(yf,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}n=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),i.class&&!i.className?(s.class=i.class,Object.defineProperty(s,"className",Ef)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=Oa,Fa&&Fa(t)};var Va=z.__r;z.__r=function(t){Va&&Va(t),t.__c};var Ua=z.diffed;z.diffed=function(t){Ua&&Ua(t);var e=t.props,i=t.__e;i!=null&&t.type==="textarea"&&"value"in e&&e.value!==i.value&&(i.value=e.value==null?"":e.value)};function Ba(t){return!!t&&t.$$typeof===Oa}function kf(t){return Ba(t)?Ls.apply(null,arguments):t}var $a={};const If={},xf=Tt(void 0);function ja(t){return Le(xf)||hf()}const Hs=t=>typeof(t==null?void 0:t.then)=="function",Gs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Af=$a.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Gs(t),t)}),Ws=new WeakMap,Ha=(t,e)=>{let i=Ws.get(t);return i||(i=new Promise((n,s)=>{let o=t;const r=c=>u=>{o===c&&n(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();Hs(c)?(Ws.set(c,i),o=c,c.then(r(c),a(c)),Ca(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),Ca(t,l)}),Ws.set(t,i)),i};function qs(t,e){const{delay:i,unstable_promiseStatus:n=!$a.use}={},s=ja(),[[o,r,a],l]=ha(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),Re(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);Hs(d)&&Gs(Ha(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),Qh(c),Hs(c)){const u=Ha(c,()=>s.get(t));return n&&Gs(u),Af(u)}return c}function Dn(t,e){const i=ja();return He((...s)=>{if((If?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Ga(t,e){return[qs(t),Dn(t)]}const zs=Tt({});function Pn(t){const e=de(null);return e.current===null&&(e.current=t()),e.current}const Ks=typeof window<"u",Wa=Ks?Ms:Re,Mn=Tt(null);function Ys(t,e){t.indexOf(e)===-1&&t.push(e)}function Xs(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const Et=(t,e,i)=>i>e?e:i<t?t:i;let Js=()=>{};const kt={},qa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function za(t){return typeof t=="object"&&t!==null}const Ka=t=>/^0[^.\s]+$/u.test(t);function Qs(t){let e;return()=>(e===void 0&&(e=t()),e)}const Qe=t=>t,Rf=(t,e)=>i=>e(t(i)),$i=(...t)=>t.reduce(Rf),ji=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class Zs{constructor(){this.subscriptions=[]}add(e){return Ys(this.subscriptions,e),()=>Xs(this.subscriptions,e)}notify(e,i,n){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,i,n);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,i,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const pt=t=>t*1e3,gt=t=>t/1e3;function Ya(t,e){return e?t*(1e3/e):0}const Xa=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Lf=1e-7,Df=12;function Pf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=Xa(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Lf&&++a<Df);return r}function Hi(t,e,i,n){if(t===e&&i===n)return Qe;const s=o=>Pf(o,0,1,t,i);return o=>o===0||o===1?o:Xa(s(o),e,n)}const Ja=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Qa=t=>e=>1-t(1-e),Za=Hi(.33,1.53,.69,.99),eo=Qa(Za),el=Ja(eo),tl=t=>(t*=2)<1?.5*eo(t):.5*(2-Math.pow(2,-10*(t-1))),to=t=>1-Math.sin(Math.acos(t)),il=Qa(to),nl=Ja(to),Mf=Hi(.42,0,1,1),Of=Hi(0,0,.58,1),sl=Hi(.42,0,.58,1),Nf=t=>Array.isArray(t)&&typeof t[0]!="number",ol=t=>Array.isArray(t)&&typeof t[0]=="number",Ff={linear:Qe,easeIn:Mf,easeInOut:sl,easeOut:Of,circIn:to,circInOut:nl,circOut:il,backIn:eo,backInOut:el,backOut:Za,anticipate:tl},Vf=t=>typeof t=="string",rl=t=>{if(ol(t)){Js(t.length===4);const[e,i,n,s]=t;return Hi(e,i,n,s)}else if(Vf(t))return Ff[t];return t},On=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],al={value:null};function Uf(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,g=!1)=>{const v=g&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&al.value&&al.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Bf=40;function ll(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=On.reduce((k,A)=>(k[A]=Uf(o,e?A:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:g,postRender:y}=r,v=()=>{const k=kt.useManualTiming?s.timestamp:performance.now();i=!1,kt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Bf),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),g.process(s),y.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:On.reduce((k,A)=>{const x=r[A];return k[A]=(N,T=!1,E=!1)=>(i||b(),x.schedule(N,T,E)),k},{}),cancel:k=>{for(let A=0;A<On.length;A++)r[On[A]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Mt,state:Oe,steps:io}=ll(typeof requestAnimationFrame<"u"?requestAnimationFrame:Qe,!0);let Nn;function $f(){Nn=void 0}const Ge={now:()=>(Nn===void 0&&Ge.set(Oe.isProcessing||kt.useManualTiming?Oe.timestamp:performance.now()),Nn),set:t=>{Nn=t,queueMicrotask($f)}},cl=t=>e=>typeof e=="string"&&e.startsWith(t),no=cl("--"),jf=cl("var(--"),so=t=>jf(t)?Hf.test(t.split("/*")[0].trim()):!1,Hf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ci={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},Gi={...ci,transform:t=>Et(0,1,t)},Fn={...ci,default:1},Wi=t=>Math.round(t*1e5)/1e5,oo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Gf(t){return t==null}const Wf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ro=(t,e)=>i=>!!(typeof i=="string"&&Wf.test(i)&&i.startsWith(t)||e&&!Gf(i)&&Object.prototype.hasOwnProperty.call(i,e)),dl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(oo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},qf=t=>Et(0,255,t),ao={...ci,transform:t=>Math.round(qf(t))},Wt={test:ro("rgb","red"),parse:dl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+ao.transform(t)+", "+ao.transform(e)+", "+ao.transform(i)+", "+Wi(Gi.transform(n))+")"};function zf(t){let e="",i="",n="",s="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),n=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),n=t.substring(3,4),s=t.substring(4,5),e+=e,i+=i,n+=n,s+=s),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:s?parseInt(s,16)/255:1}}const lo={test:ro("#"),parse:zf,transform:Wt.transform},qi=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Ot=qi("deg"),mt=qi("%"),K=qi("px"),Kf=qi("vh"),Yf=qi("vw"),ul={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},di={test:ro("hsl","hue"),parse:dl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(Wi(e))+", "+mt.transform(Wi(i))+", "+Wi(Gi.transform(n))+")"},Ie={test:t=>Wt.test(t)||lo.test(t)||di.test(t),parse:t=>Wt.test(t)?Wt.parse(t):di.test(t)?di.parse(t):lo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Wt.transform(t):di.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},Xf=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function Jf(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(oo))==null?void 0:e.length)||0)+(((i=t.match(Xf))==null?void 0:i.length)||0)>0}const hl="number",fl="color",Qf="var",Zf="var(",pl="${}",ep=/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 zi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(ep,l=>(Ie.test(l)?(n.color.push(o),s.push(fl),i.push(Ie.parse(l))):l.startsWith(Zf)?(n.var.push(o),s.push(Qf),i.push(l)):(n.number.push(o),s.push(hl),i.push(parseFloat(l))),++o,pl)).split(pl);return{values:i,split:a,indexes:n,types:s}}function gl(t){return zi(t).values}function ml(t){const{split:e,types:i}=zi(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===hl?o+=Wi(s[r]):a===fl?o+=Ie.transform(s[r]):o+=s[r]}return o}}const tp=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function ip(t){const e=gl(t);return ml(t)(e.map(tp))}const Nt={test:Jf,parse:gl,createTransformer:ml,getAnimatableNone:ip};function co(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function np({hue:t,saturation:e,lightness:i,alpha:n}){t/=360,e/=100,i/=100;let s=0,o=0,r=0;if(!e)s=o=r=i;else{const a=i<.5?i*(1+e):i+e-i*e,l=2*i-a;s=co(l,a,t+1/3),o=co(l,a,t),r=co(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Vn(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,uo=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},sp=[lo,Wt,di],op=t=>sp.find(e=>e.test(t));function vl(t){const e=op(t);if(!e)return!1;let i=e.parse(t);return e===di&&(i=np(i)),i}const _l=(t,e)=>{const i=vl(t),n=vl(e);if(!i||!n)return Vn(t,e);const s={...i};return o=>(s.red=uo(i.red,n.red,o),s.green=uo(i.green,n.green,o),s.blue=uo(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),Wt.transform(s))},ho=new Set(["none","hidden"]);function rp(t,e){return ho.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function ap(t,e){return i=>Ce(t,e,i)}function fo(t){return typeof t=="number"?ap:typeof t=="string"?so(t)?Vn:Ie.test(t)?_l:dp:Array.isArray(t)?yl:typeof t=="object"?Ie.test(t)?_l:lp:Vn}function yl(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>fo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function lp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=fo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function cp(t,e){const i=[],n={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][n[o]],a=t.values[r]??0;i[s]=a,n[o]++}return i}const dp=(t,e)=>{const i=Nt.createTransformer(e),n=zi(t),s=zi(e);return n.indexes.var.length===s.indexes.var.length&&n.indexes.color.length===s.indexes.color.length&&n.indexes.number.length>=s.indexes.number.length?ho.has(t)&&!s.values.length||ho.has(e)&&!n.values.length?rp(t,e):$i(yl(cp(n,s),s.values),i):Vn(t,e)};function bl(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):fo(t)(t,e)}const up=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Mt(e),now:()=>Oe.isProcessing?Oe.timestamp:Ge.now()}},wl=(t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let o=0;o<s;o++)n+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${n.substring(0,n.length-2)})`},Un=2e4;function po(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<Un;)e+=i,n=t.next(e);return e>=Un?1/0:e}function hp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(po(n),Un);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const fp=5;function Sl(t,e,i){const n=Math.max(e-fp,0);return Ya(i-t(n),e-n)}const Te={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},go=.001;function pp({duration:t=Te.duration,bounce:e=Te.bounce,velocity:i=Te.velocity,mass:n=Te.mass}){let s,o,r=1-e;r=Et(Te.minDamping,Te.maxDamping,r),t=Et(Te.minDuration,Te.maxDuration,gt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,g=mo(c,r),y=Math.exp(-d);return go-h/g*y},o=c=>{const d=c*r*t,h=d*i+i,g=Math.pow(r,2)*Math.pow(c,2)*t,y=Math.exp(-d),v=mo(Math.pow(c,2),r);return(-s(c)+go>0?-1:1)*((h-g)*y)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-go+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=mp(s,o,a);if(t=pt(t),isNaN(l))return{stiffness:Te.stiffness,damping:Te.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const gp=12;function mp(t,e,i){let n=i;for(let s=1;s<gp;s++)n=n-t(n)/e(n);return n}function mo(t,e){return t*Math.sqrt(1-e*e)}const vp=["duration","bounce"],_p=["stiffness","damping","mass"];function Cl(t,e){return e.some(i=>t[i]!==void 0)}function yp(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!Cl(t,_p)&&Cl(t,vp))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*Et(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Te.mass,stiffness:s,damping:o}}else{const i=pp(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function Bn(t=Te.visualDuration,e=Te.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:g}=yp({...i,velocity:-gt(i.velocity||0)}),y=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,_=gt(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Te.restSpeed.granular:Te.restSpeed.default),s||(s=C?Te.restDelta.granular:Te.restDelta.default);let k;if(v<1){const x=mo(_,v);k=N=>{const T=Math.exp(-v*_*N);return r-T*((y+v*_*b)/x*Math.sin(x*N)+b*Math.cos(x*N))}}else if(v===1)k=x=>r-Math.exp(-_*x)*(b+(y+_*b)*x);else{const x=_*Math.sqrt(v*v-1);k=N=>{const T=Math.exp(-v*_*N),E=Math.min(x*N,300);return r-T*((y+v*_*b)*Math.sinh(E)+x*b*Math.cosh(E))/x}}const A={calculatedDuration:g&&d||null,next:x=>{const N=k(x);if(g)a.done=x>=d;else{let T=x===0?y:0;v<1&&(T=x===0?pt(y):Sl(k,x,N));const E=Math.abs(T)<=n,p=Math.abs(r-N)<=s;a.done=E&&p}return a.value=a.done?r:N,a},toString:()=>{const x=Math.min(po(A),Un),N=wl(T=>A.next(x*T).value,x,30);return x+"ms "+N},toTransition:()=>{}};return A}Bn.applyToOptions=t=>{const e=hp(t,100,Bn);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function vo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},g=E=>a!==void 0&&E<a||l!==void 0&&E>l,y=E=>a===void 0?l:l===void 0||Math.abs(a-E)<Math.abs(l-E)?a:l;let v=i*e;const b=d+v,_=r===void 0?b:r(b);_!==b&&(v=_-d);const C=E=>-v*Math.exp(-E/n),k=E=>_+C(E),A=E=>{const p=C(E),m=k(E);h.done=Math.abs(p)<=c,h.value=h.done?_:m};let x,N;const T=E=>{g(h.value)&&(x=E,N=Bn({keyframes:[h.value,y(h.value)],velocity:Sl(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let p=!1;return!N&&x===void 0&&(p=!0,A(E),T(E)),x!==void 0&&E>=x?N.next(E-x):(!p&&A(E),h)}}}function bp(t,e,i){const n=[],s=i||kt.mix||bl,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=$i(l,a)}n.push(a)}return n}function wp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(Js(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=bp(e,n,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=ji(t[d],t[d+1],u);return a[d](h)};return i?u=>c(Et(t[0],t[o-1],u)):c}function Sp(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=ji(0,e,n);t.push(Ce(i,1,s))}}function Cp(t){const e=[0];return Sp(e,t.length-1),e}function Tp(t,e){return t.map(i=>i*e)}function Ep(t,e){return t.map(()=>e||sl).splice(0,t.length-1)}function Ki({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Nf(n)?n.map(rl):rl(n),o={done:!1,value:e[0]},r=Tp(i&&i.length===e.length?i:Cp(e),t),a=wp(r,e,{ease:Array.isArray(s)?s:Ep(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const kp=t=>t!==null;function _o(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(kp),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Ip={decay:vo,inertia:vo,tween:Ki,keyframes:Ki,spring:Bn};function Tl(t){typeof t.type=="string"&&(t.type=Ip[t.type])}class yo{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const xp=t=>t/100;class bo extends yo{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==Ge.now()&&this.tick(Ge.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(n=this.options).onStop)==null||s.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Tl(e);const{type:i=Ki,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Ki;l!==Ki&&typeof a[0]!="number"&&(this.mixKeyframes=$i(xp,bl(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=po(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:g,type:y,onUpdate:v,finalKeyframe:b}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-s/this.speed,this.startTime)),i?this.currentTime=e:this.updateTime(e);const _=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?_<0:_>s;this.currentTime=Math.max(_,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,A=n;if(d){const E=Math.min(this.currentTime,s)/a;let p=Math.floor(E),m=E%1;!m&&E>=1&&(m=1),m===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(h==="reverse"?(m=1-m,g&&(m-=g/a)):h==="mirror"&&(A=r)),k=Et(0,1,m)*a}const x=C?{done:!1,value:u[0]}:A.next(k);o&&(x.value=o(x.value));let{done:N}=x;!C&&l!==null&&(N=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return T&&y!==vo&&(x.value=_o(u,this.options,b,this.speed)),v&&v(x.value),T&&this.finish(),x}then(e,i){return this.finished.then(e,i)}get duration(){return gt(this.calculatedDuration)}get time(){return gt(this.currentTime)}set time(e){var i;e=pt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(i=this.driver)==null||i.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Ge.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=gt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=up,startTime:i}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=i??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ge.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function Ap(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const qt=t=>t*180/Math.PI,wo=t=>{const e=qt(Math.atan2(t[1],t[0]));return So(e)},Rp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:wo,rotateZ:wo,skewX:t=>qt(Math.atan(t[1])),skewY:t=>qt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},So=t=>(t=t%360,t<0&&(t+=360),t),El=wo,kl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Il=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Lp={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:kl,scaleY:Il,scale:t=>(kl(t)+Il(t))/2,rotateX:t=>So(qt(Math.atan2(t[6],t[5]))),rotateY:t=>So(qt(Math.atan2(-t[2],t[0]))),rotateZ:El,rotate:El,skewX:t=>qt(Math.atan(t[4])),skewY:t=>qt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Co(t){return t.includes("scale")?1:0}function To(t,e){if(!t||t==="none")return Co(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Lp,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Rp,s=a}if(!s)return Co(e);const o=n[e],r=s[1].split(",").map(Pp);return typeof o=="function"?o(r):r[o]}const Dp=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return To(i,e)};function Pp(t){return parseFloat(t.trim())}const ui=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],hi=new Set(ui),xl=t=>t===ci||t===K,Mp=new Set(["x","y","z"]),Op=ui.filter(t=>!Mp.has(t));function Np(t){const e=[];return Op.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const zt={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>To(e,"x"),y:(t,{transform:e})=>To(e,"y")};zt.translateX=zt.x,zt.translateY=zt.y;const Kt=new Set;let Eo=!1,ko=!1,Io=!1;function Al(){if(ko){const t=Array.from(Kt).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=Np(n);s.length&&(i.set(n,s),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const s=i.get(n);s&&s.forEach(([o,r])=>{var a;(a=n.getValue(o))==null||a.set(r)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}ko=!1,Eo=!1,Kt.forEach(t=>t.complete(Io)),Kt.clear()}function Rl(){Kt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(ko=!0)})}function Fp(){Io=!0,Rl(),Al(),Io=!1}class xo{constructor(e,i,n,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=n,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Kt.add(this),Eo||(Eo=!0,we.read(Rl),we.resolveKeyframes(Al))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:n,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(n&&i){const a=n.readValue(i,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Ap(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Kt.delete(this)}cancel(){this.state==="scheduled"&&(Kt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Vp=t=>t.startsWith("--");function Up(t,e,i){Vp(e)?t.style.setProperty(e,i):t.style[e]=i}const Bp=Qs(()=>window.ScrollTimeline!==void 0),$p={};function jp(t,e){const i=Qs(t);return()=>$p[e]??i()}const Ll=jp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Yi=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,Dl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Yi([0,.65,.55,1]),circOut:Yi([.55,0,1,.45]),backIn:Yi([.31,.01,.66,-.59]),backOut:Yi([.33,1.53,.69,.99])};function Pl(t,e){if(t)return typeof t=="function"?Ll()?wl(t,e):"ease-out":ol(t)?Yi(t):Array.isArray(t)?t.map(i=>Pl(i,e)||Dl.easeOut):Dl[t]}function Hp(t,e,i,{delay:n=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:i};l&&(u.offset=l);const d=Pl(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function Ml(t){return typeof t=="function"&&"applyToOptions"in t}function Gp({type:t,...e}){return Ml(t)&&Ll()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Wp extends yo{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Js(typeof e.type!="string");const c=Gp(e);this.animation=Hp(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=_o(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Up(i,n,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,i;this.isPseudoElement||(i=(e=this.animation).commitStyles)==null||i.call(e)}get duration(){var i,n;const e=((n=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:n.call(i).duration)||0;return gt(Number(e))}get time(){return gt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=pt(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:i}){var n;return this.allowFlatten&&((n=this.animation.effect)==null||n.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&Bp()?(this.animation.timeline=e,Qe):i(this)}}const Ol={anticipate:tl,backInOut:el,circInOut:nl};function qp(t){return t in Ol}function zp(t){typeof t.ease=="string"&&qp(t.ease)&&(t.ease=Ol[t.ease])}const Nl=10;class Kp extends Wp{constructor(e){zp(e),Tl(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:n,onComplete:s,element:o,...r}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const a=new bo({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Nl).value,a.sample(l).value,Nl),a.stop()}}const Fl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Nt.test(t)||t==="0")&&!t.startsWith("url("));function Yp(t){const e=t[0];if(t.length===1)return!0;for(let i=0;i<t.length;i++)if(t[i]!==e)return!0}function Xp(t,e,i,n){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=Fl(s,e),a=Fl(o,e);return!r||!a?!1:Yp(t)||(i==="spring"||Ml(i))&&n}function Ao(t){return za(t)&&"offsetHeight"in t}const Jp=new Set(["opacity","clipPath","filter","transform"]),Qp=Qs(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function Zp(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Ao((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return Qp()&&i&&Jp.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const eg=40;class tg extends yo{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var y;super(),this.stop=()=>{var v,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=Ge.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||xo;this.keyframeResolver=new g(a,(v,b,_)=>this.onKeyframesResolved(v,b,h,!_),l,c,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(e,i,n,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=n;this.resolvedAt=Ge.now(),Xp(e,o,r,a)||((kt.instantAnimations||!l)&&(u==null||u(_o(e,n,i))),e[0]=e[e.length-1],n.duration=0,n.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>eg?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},g=!c&&Zp(h)?new Kp({...h,element:h.motionValue.owner.current}):new bo(h);g.finished.then(()=>this.notifyFinished()).catch(Qe),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Fp()),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 ig=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function ng(t){const e=ig.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Vl(t,e,i=1){const[n,s]=ng(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return qa(r)?parseFloat(r):r}return so(s)?Vl(s,e,i+1):s}function Ro(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Ul=new Set(["width","height","top","left","right","bottom",...ui]),sg={test:t=>t==="auto",parse:t=>t},Bl=t=>e=>e.test(t),$l=[ci,K,mt,Ot,Yf,Kf,sg],jl=t=>$l.find(Bl(t));function og(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Ka(t):!0}const rg=new Set(["brightness","contrast","saturate","opacity"]);function ag(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(oo)||[];if(!n)return t;const s=i.replace(n,"");let o=rg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const lg=/\b([a-z-]*)\(.*?\)/gu,Lo={...Nt,getAnimatableNone:t=>{const e=t.match(lg);return e?e.map(ag).join(" "):t}},Hl={...ci,transform:Math.round},Do={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Ot,rotateX:Ot,rotateY:Ot,rotateZ:Ot,scale:Fn,scaleX:Fn,scaleY:Fn,scaleZ:Fn,skew:Ot,skewX:Ot,skewY:Ot,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:Gi,originX:ul,originY:ul,originZ:K},zIndex:Hl,fillOpacity:Gi,strokeOpacity:Gi,numOctaves:Hl},cg={...Do,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:Lo,WebkitFilter:Lo},Gl=t=>cg[t];function Wl(t,e){let i=Gl(t);return i!==Lo&&(i=Nt),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const dg=new Set(["auto","none","0"]);function ug(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!dg.has(o)&&zi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Wl(i,s)}class hg extends xo{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),so(c))){const u=Vl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ul.has(n)||e.length!==2)return;const[s,o]=e,r=jl(s),a=jl(o);if(r!==a)if(xl(r)&&xl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else zt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||og(e[s]))&&n.push(s);n.length&&ug(e,n,i)}measureInitialState(){const{element:e,unresolvedKeyframes:i,name:n}=this;if(!e||!e.current)return;n==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=zt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i[0]=this.measuredOrigin;const s=i[i.length-1];s!==void 0&&e.getValue(n,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:i,unresolvedKeyframes:n}=this;if(!e||!e.current)return;const s=e.getValue(i);s&&s.jump(this.measuredOrigin,!1);const o=n.length-1,r=n[o];n[o]=zt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function fg(t,e,i){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let n=document;const s=(i==null?void 0:i[t])??n.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const ql=(t,e)=>e&&typeof t=="number"?e.transform(t):t,zl=30,pg=t=>!isNaN(parseFloat(t));class gg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=Ge.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=i.owner}setCurrent(e){this.current=e,this.updatedAt=Ge.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=pg(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new Zs);const n=this.events[e].add(i);return e==="change"?()=>{n(),we.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e,i=!0){!i||!this.passiveEffect?this.updateAndNotify(e,i):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,i,n){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Ge.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>zl)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,zl);return Ya(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function fi(t,e){return new gg(t,e)}const{schedule:Po}=ll(queueMicrotask,!1),at={x:!1,y:!1};function Kl(){return at.x||at.y}function mg(t){return t==="x"||t==="y"?at[t]?null:(at[t]=!0,()=>{at[t]=!1}):at.x||at.y?null:(at.x=at.y=!0,()=>{at.x=at.y=!1})}function Yl(t,e){const i=fg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function Xl(t){return!(t.pointerType==="touch"||Kl())}function vg(t,e,i={}){const[n,s,o]=Yl(t,i),r=a=>{if(!Xl(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Xl(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Jl=(t,e)=>e?t===e?!0:Jl(t,e.parentElement):!1,Mo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,_g=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function yg(t){return _g.has(t.tagName)||t.tabIndex!==-1}const $n=new WeakSet;function Ql(t){return e=>{e.key==="Enter"&&t(e)}}function Oo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const bg=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=Ql(()=>{if($n.has(i))return;Oo(i,"down");const s=Ql(()=>{Oo(i,"up")}),o=()=>Oo(i,"cancel");i.addEventListener("keyup",s,e),i.addEventListener("blur",o,e)});i.addEventListener("keydown",n,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),e)};function Zl(t){return Mo(t)&&!Kl()}function wg(t,e,i={}){const[n,s,o]=Yl(t,i),r=a=>{const l=a.currentTarget;if(!Zl(a))return;$n.add(l);const c=e(l,a),u=(g,y)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),$n.has(l)&&$n.delete(l),Zl(g)&&typeof c=="function"&&c(g,{success:y})},d=g=>{u(g,l===window||l===document||i.useGlobalTarget||Jl(l,g.target))},h=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Ao(a)&&(a.addEventListener("focus",c=>bg(c,s)),!yg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ec(t){return za(t)&&"ownerSVGElement"in t}function Sg(t){return ec(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),Cg=[...$l,Ie,Nt],Tg=t=>Cg.find(Bl(t)),Xi=Tt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Eg extends rt{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Ao(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=i.offsetHeight||0,o.width=i.offsetWidth||0,o.top=i.offsetTop,o.left=i.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function kg({children:t,isPresent:e,anchorX:i,root:n}){const s=Os(),o=de(null),r=de({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Le(Xi);return ka(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const g=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const y=document.createElement("style");a&&(y.nonce=a);const v=n??document.head;return v.appendChild(y),y.sheet&&y.sheet.insertRule(`
1
+ var uw=Object.defineProperty;var hw=(ot,z,Gt)=>z in ot?uw(ot,z,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):ot[z]=Gt;var G=(ot,z,Gt)=>hw(ot,typeof z!="symbol"?z+"":z,Gt);(function(){"use strict";var ot,z,Gt,qt,Kr,Yr,Xr,Jr,Is,Es,Rs,Zr,Fi={},Qr=[],zh=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Vi=Array.isArray;function ut(t,e){for(var i in e)t[i]=e[i];return t}function As(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Xe(t,e,i){var n,s,o,r={};for(o in e)o=="key"?n=e[o]:o=="ref"?s=e[o]:r[o]=e[o];if(arguments.length>2&&(r.children=arguments.length>3?ot.call(arguments,2):i),typeof t=="function"&&t.defaultProps!=null)for(o in t.defaultProps)r[o]===void 0&&(r[o]=t.defaultProps[o]);return Bi(t,r,n,s,null)}function Bi(t,e,i,n,s){var o={type:t,props:e,key:i,ref:n,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:s??++Gt,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function ht(t){return t.children}function rt(t,e){this.props=t,this.context=e}function ci(t,e){if(e==null)return t.__?ci(t.__,t.__i+1):null;for(var i;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null)return i.__e;return typeof t.type=="function"?ci(t):null}function ea(t){var e,i;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((i=t.__k[e])!=null&&i.__e!=null){t.__e=t.__c.base=i.__e;break}return ea(t)}}function xs(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!Tn.__r++||Kr!=z.debounceRendering)&&((Kr=z.debounceRendering)||Yr)(Tn)}function Tn(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(Xr),t=qt.shift(),a=qt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=ut({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),Ls(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??ci(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,oa(o,i,r),i.__e!=s&&ea(i)));Tn.__r=0}function ta(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,_,v,w,y=n&&n.__k||Qr,C=e.length;for(l=Kh(i,e,y,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Fi:y[p.__i]||Fi,p.__i=d,w=Ls(t,p,h,s,o,r,a,l,c,u),_=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Ds(h.ref,null,p),u.push(p.ref,p.__c||_,p)),v==null&&_!=null&&(v=_),4&p.__u||h.__k===p.__k?l=ia(p,l,t):typeof p.type=="function"&&w!==void 0?l=w:_&&(l=_.nextSibling),p.__u&=-7);return i.__e=v,l}function Kh(t,e,i,n,s){var o,r,a,l,c,u=i.length,d=u,h=0;for(t.__k=new Array(s),o=0;o<s;o++)(r=e[o])!=null&&typeof r!="boolean"&&typeof r!="function"?(l=o+h,(r=t.__k[o]=typeof r=="string"||typeof r=="number"||typeof r=="bigint"||r.constructor==String?Bi(null,r,null,null,null):Vi(r)?Bi(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Bi(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=Yh(r,i,l,d))!=-1&&(d--,(a=i[c])&&(a.__u|=2)),a==null||a.__v==null?(c==-1&&(s>u?h--:s<u&&h++),typeof r.type!="function"&&(r.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,r.__u|=4))):t.__k[o]=null;if(d)for(o=0;o<u;o++)(a=i[o])!=null&&(2&a.__u)==0&&(a.__e==n&&(n=ci(a)),aa(a,a));return n}function ia(t,e,i){var n,s;if(typeof t.type=="function"){for(n=t.__k,s=0;n&&s<n.length;s++)n[s]&&(n[s].__=t,e=ia(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=ci(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ft(t,e){return e=e||[],t==null||typeof t=="boolean"||(Vi(t)?t.some(function(i){ft(i,e)}):e.push(t)),e}function Yh(t,e,i,n){var s,o,r=t.key,a=t.type,l=e[i];if(l===null&&t.key==null||l&&r==l.key&&a==l.type&&(2&l.__u)==0)return i;if(n>(l!=null&&(2&l.__u)==0?1:0))for(s=i-1,o=i+1;s>=0||o<e.length;){if(s>=0){if((l=e[s])&&(2&l.__u)==0&&r==l.key&&a==l.type)return s;s--}if(o<e.length){if((l=e[o])&&(2&l.__u)==0&&r==l.key&&a==l.type)return o;o++}}return-1}function na(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||zh.test(e)?i:i+"px"}function kn(t,e,i,n,s){var o,r;e:if(e=="style")if(typeof i=="string")t.style.cssText=i;else{if(typeof n=="string"&&(t.style.cssText=n=""),n)for(e in n)i&&e in i||na(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||na(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(Jr,"$1")),r=e.toLowerCase(),e=r in t||e=="onFocusOut"||e=="onFocusIn"?r.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+o]=i,i?n?i.u=n.u:(i.u=Is,t.addEventListener(e,o?Rs:Es,o)):t.removeEventListener(e,o?Rs:Es,o);else{if(s=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=i??"";break e}catch{}typeof i=="function"||(i==null||i===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&i==1?"":i))}}function sa(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Is++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function Ls(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,_,v,w,y,C,I,A,R,P,T,k,g,m,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(y=e.props,C="prototype"in f&&f.prototype.render,I=(u=f.contextType)&&n[u.__c],A=u?I?I.props.value:u.__:n,i.__c?w=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(y,A):(e.__c=d=new rt(y,A),d.constructor=f,d.render=Jh),I&&I.sub(d),d.props=y,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ut({},d.__s)),ut(d.__s,f.getDerivedStateFromProps(y,d.__s))),p=d.props,_=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&y!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,_,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,P=z.__r,T=0,C){for(d.state=d.__s,d.__d=!1,P&&P(e),u=d.render(d.props,d.state,d.context),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[]}else do d.__d=!1,P&&P(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++T<25);d.state=d.__s,d.getChildContext!=null&&(n=ut(ut({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,_)),g=u,u!=null&&u.type===ht&&u.key==null&&(g=ra(u.props.children)),a=ta(t,Vi(g)?g:[g],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),w&&(d.__E=d.__=null)}catch(S){if(e.__v=null,l||o!=null)if(S.then){for(e.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;o[o.indexOf(a)]=null,e.__e=a}else for(m=o.length;m--;)As(o[m]);else e.__e=i.__e,e.__k=i.__k;z.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Xh(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function oa(t,e,i){for(var n=0;n<i.length;n++)Ds(i[n],i[++n],i[++n]);z.__c&&z.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){z.__e(o,s.__v)}})}function ra(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Vi(t)?t.map(ra):ut({},t)}function Xh(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,_,v,w=i.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(z.__m&&z.__m(e,o),a=!1),o=null}if(C==null)w===y||a&&t.data==y||(t.data=y);else{if(o=o&&ot.call(t.childNodes),w=i.props||Fi,!a&&o!=null)for(w={},c=0;c<t.attributes.length;c++)w[(p=t.attributes[c]).name]=p.value;for(c in w)if(p=w[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;kn(t,c,null,p,s)}}for(c in y)p=y[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?_=p:c=="checked"?v=p:a&&typeof p!="function"||w[c]===p||kn(t,c,p,w[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),ta(e.type=="template"?t.content:t,Vi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&ci(i,0),a,l),o!=null)for(c=o.length;c--;)As(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=w[c])&&kn(t,c,_,w[c],s),c="checked",v!=null&&v!=t[c]&&kn(t,c,v,w[c],s))}return t}function Ds(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){z.__e(s,i)}}function aa(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Ds(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&aa(n[s],e,i||typeof t.type!="function");i||As(t.__e),t.__c=t.__=t.__e=void 0}function Jh(t,e,i){return this.constructor(t,i)}function In(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ls(e,t=(!n&&i||e).__k=Xe(ht,null,[t]),s||Fi,Fi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?ot.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),oa(o,t,r)}function la(t,e){In(t,e,la)}function Os(t,e,i){var n,s,o,r,a=ut({},t.props);for(o in t.type&&t.type.defaultProps&&(r=t.type.defaultProps),e)o=="key"?n=e[o]:o=="ref"?s=e[o]:a[o]=e[o]===void 0&&r!=null?r[o]:e[o];return arguments.length>2&&(a.children=arguments.length>3?ot.call(arguments,2):i),Bi(t.type,a,n||t.key,s||t.ref,null)}function kt(t){function e(i){var n,s;return this.getChildContext||(n=new Set,(s={})[e.__c]=this,this.getChildContext=function(){return s},this.componentWillUnmount=function(){n=null},this.shouldComponentUpdate=function(o){this.props.value!=o.value&&n.forEach(function(r){r.__e=!0,xs(r)})},this.sub=function(o){n.add(o);var r=o.componentWillUnmount;o.componentWillUnmount=function(){n&&n.delete(o),r&&r.call(o)}}),i.children}return e.__c="__cC"+Zr++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}ot=Qr.slice,z={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Gt=0,rt.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ut({},this.state),typeof t=="function"&&(t=t(ut({},i),this.props)),t&&ut(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),xs(this))},rt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),xs(this))},rt.prototype.render=ht,qt=[],Yr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Xr=function(t,e){return t.__v.__b-e.__v.__b},Tn.__r=0,Jr=/(PointerCapture)$|Capture$/i,Is=0,Es=sa(!1),Rs=sa(!0),Zr=0;var Zh=0;function D(t,e,i,n,s,o){e||(e={});var r,a,l=e;if("ref"in l)for(a in l={},e)a=="ref"?r=e[a]:l[a]=e[a];var c={type:t,props:l,key:i,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Zh,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return z.vnode&&z.vnode(c),c}function Ms(){return(Ms=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(t[n]=i[n])}return t}).apply(this,arguments)}var Qh=["context","children"];function ef(t){this.getChildContext=function(){return t.context};var e=t.children,i=function(n,s){if(n==null)return{};var o,r,a={},l=Object.keys(n);for(r=0;r<l.length;r++)s.indexOf(o=l[r])>=0||(a[o]=n[o]);return a}(t,Qh);return Os(e,i)}function tf(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Xe(ef,Ms({},this._props,{context:t.detail.context}),function e(i,n){if(i.nodeType===3)return i.data;if(i.nodeType!==1)return null;var s=[],o={},r=0,a=i.attributes,l=i.childNodes;for(r=a.length;r--;)a[r].name!=="slot"&&(o[a[r].name]=a[r].value,o[ca(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Xe(da,{name:u},c):s[r]=c}var d=n?Xe(da,null,s):s;return Xe(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?la:In)(this._vdom,this._root)}function ca(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function nf(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[ca(t)]=i,this._vdom=Os(this._vdom,n),In(this._vdom,this._root)}}function sf(){In(this._vdom=null,this._root)}function da(t,e){var i=this;return Xe("slot",Ms({},t,{ref:function(n){n?(i.ref=n,i._listener||(i._listener=function(s){s.stopPropagation(),s.detail.context=e},n.addEventListener("_preact",i._listener))):i.ref.removeEventListener("_preact",i._listener)}}))}function of(t,e,i,n){function s(){var o=Reflect.construct(HTMLElement,[],s);return o._vdomComponent=t,o._root=n&&n.shadow?o.attachShadow({mode:n.mode||"open"}):o,o}return(s.prototype=Object.create(HTMLElement.prototype)).constructor=s,s.prototype.connectedCallback=tf,s.prototype.attributeChangedCallback=nf,s.prototype.disconnectedCallback=sf,i=i||t.observedAttributes||Object.keys(t.propTypes||{}),s.observedAttributes=i,i.forEach(function(o){Object.defineProperty(s.prototype,o,{get:function(){return this._vdom.props[o]},set:function(r){this._vdom?this.attributeChangedCallback(o,null,r):(this._props||(this._props={}),this._props[o]=r,this.connectedCallback());var a=typeof r;r!=null&&a!=="string"&&a!=="boolean"&&a!=="number"||this.setAttribute(o,r)}})}),customElements.define(e,s)}var Mt,_e,Ps,ua,Ui=0,ha=[],Se=z,fa=Se.__b,pa=Se.__r,ga=Se.diffed,ma=Se.__c,va=Se.unmount,_a=Se.__;function di(t,e){Se.__h&&Se.__h(_e,t,Ui||e),Ui=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return Ui=1,ya(wa,t)}function ya(t,e,i){var n=di(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):wa(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=_e,!_e.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var p=h.__[0];h.__=h.__N,h.__N=void 0,p!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=di(Mt++,3);!Se.__s&&Bs(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Ns(t,e){var i=di(Mt++,4);!Se.__s&&Bs(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function de(t){return Ui=5,Je(function(){return{current:t}},[])}function Je(t,e){var i=di(Mt++,7);return Bs(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function He(t,e){return Ui=8,Je(function(){return t},e)}function Le(t){var e=_e.context[t.__c],i=di(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function rf(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Fs(){var t=di(Mt++,11);if(!t.__){for(var e=_e.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var i=e.__m||(e.__m=[0,0]);t.__="P"+i[0]+"-"+i[1]++}return t.__}function af(){for(var t;t=ha.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(En),t.__H.__h.forEach(Vs),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,fa&&fa(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),_a&&_a(t,e)},Se.__r=function(t){pa&&pa(t),Mt=0;var e=(_e=t.__c).__H;e&&(Ps===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(En),e.__h.forEach(Vs),e.__h=[],Mt=0)),Ps=_e},Se.diffed=function(t){ga&&ga(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ha.push(e)!==1&&ua===Se.requestAnimationFrame||((ua=Se.requestAnimationFrame)||lf)(af)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Ps=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(En),i.__h=i.__h.filter(function(n){return!n.__||Vs(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),ma&&ma(t,e)},Se.unmount=function(t){va&&va(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{En(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var ba=typeof requestAnimationFrame=="function";function lf(t){var e,i=function(){clearTimeout(n),ba&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);ba&&(e=requestAnimationFrame(i))}function En(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Vs(t){var e=_e;t.__c=t.__(),_e=e}function Bs(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function wa(t,e){return typeof e=="function"?e(t):e}const $i={},Sa=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ca=t=>"init"in t,Us=t=>!!t.write,Ta=t=>"v"in t||"e"in t,Rn=t=>{if("e"in t)throw t.e;if(($i?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},An=new WeakMap,ka=t=>{var e;return xn(t)&&!!((e=An.get(t))!=null&&e[0])},cf=t=>{const e=An.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},Ia=(t,e)=>{let i=An.get(t);if(!i){i=[!0,new Set],An.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},xn=t=>typeof(t==null?void 0:t.then)=="function",Ea=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},$s=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(xn(e))for(const r of n.d.keys())Ea(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,xn(o)&&cf(o))},Ra=(t,e,i)=>{var n;const s=new Set;for(const o of((n=i.get(t))==null?void 0:n.t)||[])i.has(o)&&s.add(o);for(const o of e.p)s.add(o);return s},df=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},js=()=>{const t={},e=new WeakMap,i=n=>{var s,o;(s=e.get(t))==null||s.forEach(r=>r(n)),(o=e.get(n))==null||o.forEach(r=>r())};return i.add=(n,s)=>{const o=n||t,r=(e.has(o)?e:e.set(o,new Set)).get(o);return r.add(s),()=>{r==null||r.delete(s),r.size||e.delete(o)}},i},uf=t=>(t.c||(t.c=js()),t.m||(t.m=js()),t.u||(t.u=js()),t.f||(t.f=df()),t),hf=Symbol(),Aa=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...p)=>h.read(...p),l=(h,...p)=>h.write(...p),c=(h,p)=>{var _;return(_=h.unstable_onInit)==null?void 0:_.call(h,p)},u=(h,p)=>{var _;return(_=h.onMount)==null?void 0:_.call(h,p)},...d)=>{const h=d[0]||(T=>{if(($i?"production":void 0)!=="production"&&!T)throw new Error("Atom is undefined or null");let k=t.get(T);return k||(k={d:new Map,p:new Set,n:0},t.set(T,k),c==null||c(T,P)),k}),p=d[1]||(()=>{const T=[],k=g=>{try{g()}catch(m){T.push(m)}};do{r.f&&k(r.f);const g=new Set,m=g.add.bind(g);n.forEach(f=>{var S;return(S=e.get(f))==null?void 0:S.l.forEach(m)}),n.clear(),o.forEach(m),o.clear(),s.forEach(m),s.clear(),g.forEach(k),n.size&&_()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),_=d[2]||(()=>{const T=[],k=new WeakSet,g=new WeakSet,m=Array.from(n);for(;m.length;){const f=m[m.length-1],S=h(f);if(g.has(f)){m.pop();continue}if(k.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if(($i?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");g.add(f),m.pop();continue}k.add(f);for(const E of Ra(f,S,e))k.has(E)||m.push(E)}for(let f=T.length-1;f>=0;--f){const[S,E]=T[f];let x=!1;for(const L of E.d.keys())if(L!==S&&n.has(L)){x=!0;break}x&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var k;const g=h(T);if(Ta(g)&&(e.has(T)&&i.get(T)!==g.n||Array.from(g.d).every(([O,F])=>v(O).n===F)))return g;g.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),_(),p())},S=O=>{var F;if(Sa(T,O)){const $=h(O);if(!Ta($))if(Ca(O))$s(O,O.init,h);else throw new Error("no atom init");return Rn($)}const W=v(O);try{return Rn(W)}finally{g.d.set(O,W.n),ka(g.v)&&Ea(T,g.v,W),(F=e.get(O))==null||F.t.add(T),m||f()}};let E,x;const L={get signal(){return E||(E=new AbortController),E.signal},get setSelf(){return($i?"production":void 0)!=="production"&&!Us(T)&&console.warn("setSelf function cannot be used with read-only atom"),!x&&Us(T)&&(x=(...O)=>{if(($i?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return y(T,...O)}finally{_(),p()}}),x}},N=g.n;try{const O=a(T,S,L);return $s(T,O,h),xn(O)&&(Ia(O,()=>E==null?void 0:E.abort()),O.then(f,f)),g}catch(O){return delete g.v,g.e=O,++g.n,g}finally{m=!1,N!==g.n&&i.get(T)===N&&(i.set(T,g.n),n.add(T),(k=r.c)==null||k.call(r,T))}}),w=d[4]||(T=>{const k=[T];for(;k.length;){const g=k.pop(),m=h(g);for(const f of Ra(g,m,e)){const S=h(f);i.set(f,S.n),k.push(f)}}}),y=d[5]||((T,...k)=>{let g=!0;const m=S=>Rn(v(S)),f=(S,...E)=>{var x;const L=h(S);try{if(Sa(T,S)){if(!Ca(S))throw new Error("atom not writable");const N=L.n,O=E[0];$s(S,O,h),C(S),N!==L.n&&(n.add(S),(x=r.c)==null||x.call(r,S),w(S));return}else return y(S,...E)}finally{g||(_(),p())}};try{return l(T,m,f,...k)}finally{g=!1}}),C=d[6]||(T=>{var k;const g=h(T),m=e.get(T);if(m&&!ka(g.v)){for(const[f,S]of g.d)if(!m.d.has(f)){const E=h(f);I(f).t.add(T),m.d.add(f),S!==E.n&&(n.add(f),(k=r.c)==null||k.call(r,f),w(f))}for(const f of m.d||[])if(!g.d.has(f)){m.d.delete(f);const S=A(f);S==null||S.t.delete(T)}}}),I=d[7]||(T=>{var k;const g=h(T);let m=e.get(T);if(!m){v(T);for(const f of g.d.keys())I(f).t.add(T);if(m={l:new Set,d:new Set(g.d.keys()),t:new Set},e.set(T,m),(k=r.m)==null||k.call(r,T),Us(T)){const f=()=>{let S=!0;const E=(...x)=>{try{return y(T,...x)}finally{S||(_(),p())}};try{const x=u(T,E);x&&(m.u=()=>{S=!0;try{x()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return m}),A=d[8]||(T=>{var k;const g=h(T);let m=e.get(T);if(m&&!m.l.size&&!Array.from(m.t).some(f=>{var S;return(S=e.get(f))==null?void 0:S.d.has(T)})){m.u&&o.add(m.u),m=void 0,e.delete(T),(k=r.u)==null||k.call(r,T);for(const f of g.d.keys()){const S=A(f);S==null||S.t.delete(T)}return}return m}),R=[t,e,i,n,s,o,r,a,l,c,u,h,p,_,v,w,y,C,I,A],P={get:T=>Rn(v(T)),set:(T,...k)=>{try{return y(T,...k)}finally{_(),p()}},sub:(T,k)=>{const m=I(T).l;return m.add(k),p(),()=>{m.delete(k),A(T),p()}}};return Object.defineProperty(P,hf,{value:R}),P},ff=uf,xa=Ia,Ws={};let pf=0;function Ln(t,e){const i=`atom${++pf}`,n={toString(){return(Ws?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=gf,n.write=mf),n}function gf(t){return t(this)}function mf(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const vf=()=>{let t=0;const e=ff({}),i=new WeakMap,n=new WeakMap,s=Aa(i,n,void 0,void 0,void 0,void 0,e,void 0,(a,l,c,...u)=>t?c(a,...u):a.write(l,c,...u)),o=new Set;return e.m.add(void 0,a=>{o.add(a);const l=i.get(a);l.m=n.get(a)}),e.u.add(void 0,a=>{o.delete(a);const l=i.get(a);delete l.m}),Object.assign(s,{dev4_get_internal_weak_map:()=>(console.log("Deprecated: Use devstore from the devtools library"),i),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:a=>{const l={read:()=>null,write:(c,u)=>{++t;try{for(const[d,h]of a)"init"in d&&u(d,h)}finally{--t}}};s.set(l)}})};function _f(){return(Ws?"production":void 0)!=="production"?vf():Aa()}let ji;function yf(){return ji||(ji=_f(),(Ws?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=ji),globalThis.__JOTAI_DEFAULT_STORE__!==ji&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),ji}function La(t,e){for(var i in e)t[i]=e[i];return t}function Da(t,e){for(var i in t)if(i!=="__source"&&!(i in e))return!0;for(var n in e)if(n!=="__source"&&t[n]!==e[n])return!0;return!1}var Oa=Ns;function Ma(t,e){this.props=t,this.context=e}(Ma.prototype=new rt).isPureReactComponent=!0,Ma.prototype.shouldComponentUpdate=function(t,e){return Da(this.props,t)||Da(this.state,e)};var Pa=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Pa&&Pa(t)};var bf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function wf(t){function e(i){var n=La({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=bf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Na=function(t,e){return t==null?null:ft(ft(t).map(e))},Sf={map:Na,forEach:Na,count:function(t){return t?ft(t).length:0},only:function(t){var e=ft(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ft},Cf=z.__e;z.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}Cf(t,e,i,n)};var Fa=z.unmount;function Va(t,e,i){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(n){typeof n.__c=="function"&&n.__c()}),t.__c.__H=null),(t=La({},t)).__c!=null&&(t.__c.__P===i&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(n){return Va(n,e,i)})),t}function Ba(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Ba(n,e,i)}),t.__c&&t.__c.__P===e&&(t.__e&&i.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=i)),t}function Hs(){this.__u=0,this.o=null,this.__b=null}function Ua(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Dn(){this.i=null,this.l=null}z.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Fa&&Fa(t)},(Hs.prototype=new rt).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Ua(n.__v),o=!1,r=function(){o||(o=!0,i.__R=null,s?s(a):a())};i.__R=r;var a=function(){if(!--n.__u){if(n.state.__a){var l=n.state.__a;n.__v.__k[0]=Ba(l,l.__c.__P,l.__c.__O)}var c;for(n.setState({__a:n.__b=null});c=n.o.pop();)c.forceUpdate()}};n.__u++||32&e.__u||n.setState({__a:n.__b=n.__v.__k[0]}),t.then(r,r)},Hs.prototype.componentWillUnmount=function(){this.o=[]},Hs.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var i=document.createElement("div"),n=this.__v.__k[0].__c;this.__v.__k[0]=Va(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Xe(ht,null,t.fallback);return s&&(s.__u&=-33),[Xe(ht,null,e.__a?null:t.children),s]};var $a=function(t,e,i){if(++i[1]===i[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(i=t.i;i;){for(;i.length>3;)i.pop()();if(i[1]<i[0])break;t.i=i=i[2]}};(Dn.prototype=new rt).__a=function(t){var e=this,i=Ua(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),$a(e,t,n)):s()};i?i(o):o()}},Dn.prototype.render=function(t){this.i=null,this.l=new Map;var e=ft(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var i=e.length;i--;)this.l.set(e[i],this.i=[1,0,this.i]);return t.children},Dn.prototype.componentDidUpdate=Dn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){$a(t,i,e)})};var ja=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Tf=/^(?: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]/,kf=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,If=/[A-Z0-9]/g,Ef=typeof document<"u",Rf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};rt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(rt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Wa=z.event;function Af(){}function xf(){return this.cancelBubble}function Lf(){return this.defaultPrevented}z.event=function(t){return Wa&&(t=Wa(t)),t.persist=Af,t.isPropagationStopped=xf,t.isDefaultPrevented=Lf,t.nativeEvent=t};var Df={enumerable:!1,configurable:!0,get:function(){return this.class}},Ha=z.vnode;z.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||Ef&&r==="children"&&n==="noscript"||r==="class"||r==="className")){var l=r.toLowerCase();r==="defaultValue"&&"value"in i&&i.value==null?r="value":r==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?r="ondblclick":l!=="onchange"||n!=="input"&&n!=="textarea"||Rf(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":kf.test(r)&&(r=l):l=r="oninput":o&&Tf.test(r)?r=r.replace(If,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&s[r=l]&&(r="oninputCapture"),s[r]=a}}n=="select"&&s.multiple&&Array.isArray(s.value)&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=ft(i.children).forEach(function(c){c.props.selected=s.multiple?s.defaultValue.indexOf(c.props.value)!=-1:s.defaultValue==c.props.value})),i.class&&!i.className?(s.class=i.class,Object.defineProperty(s,"className",Df)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=ja,Ha&&Ha(t)};var Ga=z.__r;z.__r=function(t){Ga&&Ga(t),t.__c};var qa=z.diffed;z.diffed=function(t){qa&&qa(t);var e=t.props,i=t.__e;i!=null&&t.type==="textarea"&&"value"in e&&e.value!==i.value&&(i.value=e.value==null?"":e.value)};function za(t){return!!t&&t.$$typeof===ja}function Of(t){return za(t)?Os.apply(null,arguments):t}var Ka={};const Mf={},Pf=kt(void 0);function Ya(t){return Le(Pf)||yf()}const Gs=t=>typeof(t==null?void 0:t.then)=="function",qs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Nf=Ka.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(qs(t),t)}),zs=new WeakMap,Xa=(t,e)=>{let i=zs.get(t);return i||(i=new Promise((n,s)=>{let o=t;const r=c=>u=>{o===c&&n(u)},a=c=>u=>{o===c&&s(u)},l=()=>{try{const c=e();Gs(c)?(zs.set(c,i),o=c,c.then(r(c),a(c)),xa(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),xa(t,l)}),zs.set(t,i)),i};function Ks(t,e){const{delay:i,unstable_promiseStatus:n=!Ka.use}={},s=Ya(),[[o,r,a],l]=ya(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);Gs(d)&&qs(Xa(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),rf(c),Gs(c)){const u=Xa(c,()=>s.get(t));return n&&qs(u),Nf(u)}return c}function On(t,e){const i=Ya();return He((...s)=>{if((Mf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Ja(t,e){return[Ks(t),On(t)]}const Ys=kt({});function Mn(t){const e=de(null);return e.current===null&&(e.current=t()),e.current}const Xs=typeof window<"u",Za=Xs?Ns:xe,Pn=kt(null);function Js(t,e){t.indexOf(e)===-1&&t.push(e)}function Zs(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const It=(t,e,i)=>i>e?e:i<t?t:i;let Qs=()=>{};const Et={},Qa=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function el(t){return typeof t=="object"&&t!==null}const tl=t=>/^0[^.\s]+$/u.test(t);function eo(t){let e;return()=>(e===void 0&&(e=t()),e)}const Ze=t=>t,Ff=(t,e)=>i=>e(t(i)),Wi=(...t)=>t.reduce(Ff),Hi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class to{constructor(){this.subscriptions=[]}add(e){return Js(this.subscriptions,e),()=>Zs(this.subscriptions,e)}notify(e,i,n){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](e,i,n);else for(let o=0;o<s;o++){const r=this.subscriptions[o];r&&r(e,i,n)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const pt=t=>t*1e3,gt=t=>t/1e3;function il(t,e){return e?t*(1e3/e):0}const nl=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Vf=1e-7,Bf=12;function Uf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=nl(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Vf&&++a<Bf);return r}function Gi(t,e,i,n){if(t===e&&i===n)return Ze;const s=o=>Uf(o,0,1,t,i);return o=>o===0||o===1?o:nl(s(o),e,n)}const sl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ol=t=>e=>1-t(1-e),rl=Gi(.33,1.53,.69,.99),io=ol(rl),al=sl(io),ll=t=>(t*=2)<1?.5*io(t):.5*(2-Math.pow(2,-10*(t-1))),no=t=>1-Math.sin(Math.acos(t)),cl=ol(no),dl=sl(no),$f=Gi(.42,0,1,1),jf=Gi(0,0,.58,1),ul=Gi(.42,0,.58,1),Wf=t=>Array.isArray(t)&&typeof t[0]!="number",hl=t=>Array.isArray(t)&&typeof t[0]=="number",Hf={linear:Ze,easeIn:$f,easeInOut:ul,easeOut:jf,circIn:no,circInOut:dl,circOut:cl,backIn:io,backInOut:al,backOut:rl,anticipate:ll},Gf=t=>typeof t=="string",fl=t=>{if(hl(t)){Qs(t.length===4);const[e,i,n,s]=t;return Gi(e,i,n,s)}else if(Gf(t))return Hf[t];return t},Nn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],pl={value:null};function qf(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,p=!1)=>{const v=p&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&pl.value&&pl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const zf=40;function gl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Nn.reduce((I,A)=>(I[A]=qf(o,e?A:void 0),I),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:_}=r,v=()=>{const I=Et.useManualTiming?s.timestamp:performance.now();i=!1,Et.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(I-s.timestamp,zf),1)),s.timestamp=I,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),_.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},w=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:Nn.reduce((I,A)=>{const R=r[A];return I[A]=(P,T=!1,k=!1)=>(i||w(),R.schedule(P,T,k)),I},{}),cancel:I=>{for(let A=0;A<Nn.length;A++)r[Nn[A]].cancel(I)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:so}=gl(typeof requestAnimationFrame<"u"?requestAnimationFrame:Ze,!0);let Fn;function Kf(){Fn=void 0}const Ge={now:()=>(Fn===void 0&&Ge.set(Pe.isProcessing||Et.useManualTiming?Pe.timestamp:performance.now()),Fn),set:t=>{Fn=t,queueMicrotask(Kf)}},ml=t=>e=>typeof e=="string"&&e.startsWith(t),oo=ml("--"),Yf=ml("var(--"),ro=t=>Yf(t)?Xf.test(t.split("/*")[0].trim()):!1,Xf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,ui={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},qi={...ui,transform:t=>It(0,1,t)},Vn={...ui,default:1},zi=t=>Math.round(t*1e5)/1e5,ao=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Jf(t){return t==null}const Zf=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,lo=(t,e)=>i=>!!(typeof i=="string"&&Zf.test(i)&&i.startsWith(t)||e&&!Jf(i)&&Object.prototype.hasOwnProperty.call(i,e)),vl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(ao);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Qf=t=>It(0,255,t),co={...ui,transform:t=>Math.round(Qf(t))},zt={test:lo("rgb","red"),parse:vl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+co.transform(t)+", "+co.transform(e)+", "+co.transform(i)+", "+zi(qi.transform(n))+")"};function ep(t){let e="",i="",n="",s="";return t.length>5?(e=t.substring(1,3),i=t.substring(3,5),n=t.substring(5,7),s=t.substring(7,9)):(e=t.substring(1,2),i=t.substring(2,3),n=t.substring(3,4),s=t.substring(4,5),e+=e,i+=i,n+=n,s+=s),{red:parseInt(e,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:s?parseInt(s,16)/255:1}}const uo={test:lo("#"),parse:ep,transform:zt.transform},Ki=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Ki("deg"),mt=Ki("%"),K=Ki("px"),tp=Ki("vh"),ip=Ki("vw"),_l={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},hi={test:lo("hsl","hue"),parse:vl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(zi(e))+", "+mt.transform(zi(i))+", "+zi(qi.transform(n))+")"},Ee={test:t=>zt.test(t)||uo.test(t)||hi.test(t),parse:t=>zt.test(t)?zt.parse(t):hi.test(t)?hi.parse(t):uo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):hi.transform(t),getAnimatableNone:t=>{const e=Ee.parse(t);return e.alpha=0,Ee.transform(e)}},np=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function sp(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(ao))==null?void 0:e.length)||0)+(((i=t.match(np))==null?void 0:i.length)||0)>0}const yl="number",bl="color",op="var",rp="var(",wl="${}",ap=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function Yi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(ap,l=>(Ee.test(l)?(n.color.push(o),s.push(bl),i.push(Ee.parse(l))):l.startsWith(rp)?(n.var.push(o),s.push(op),i.push(l)):(n.number.push(o),s.push(yl),i.push(parseFloat(l))),++o,wl)).split(wl);return{values:i,split:a,indexes:n,types:s}}function Sl(t){return Yi(t).values}function Cl(t){const{split:e,types:i}=Yi(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===yl?o+=zi(s[r]):a===bl?o+=Ee.transform(s[r]):o+=s[r]}return o}}const lp=t=>typeof t=="number"?0:Ee.test(t)?Ee.getAnimatableNone(t):t;function cp(t){const e=Sl(t);return Cl(t)(e.map(lp))}const Ft={test:sp,parse:Sl,createTransformer:Cl,getAnimatableNone:cp};function ho(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+(e-t)*6*i:i<1/2?e:i<2/3?t+(e-t)*(2/3-i)*6:t}function dp({hue:t,saturation:e,lightness:i,alpha:n}){t/=360,e/=100,i/=100;let s=0,o=0,r=0;if(!e)s=o=r=i;else{const a=i<.5?i*(1+e):i+e-i*e,l=2*i-a;s=ho(l,a,t+1/3),o=ho(l,a,t),r=ho(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Bn(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,fo=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},up=[uo,zt,hi],hp=t=>up.find(e=>e.test(t));function Tl(t){const e=hp(t);if(!e)return!1;let i=e.parse(t);return e===hi&&(i=dp(i)),i}const kl=(t,e)=>{const i=Tl(t),n=Tl(e);if(!i||!n)return Bn(t,e);const s={...i};return o=>(s.red=fo(i.red,n.red,o),s.green=fo(i.green,n.green,o),s.blue=fo(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},po=new Set(["none","hidden"]);function fp(t,e){return po.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function pp(t,e){return i=>Ce(t,e,i)}function go(t){return typeof t=="number"?pp:typeof t=="string"?ro(t)?Bn:Ee.test(t)?kl:vp:Array.isArray(t)?Il:typeof t=="object"?Ee.test(t)?kl:gp:Bn}function Il(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>go(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function gp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=go(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function mp(t,e){const i=[],n={color:0,var:0,number:0};for(let s=0;s<e.values.length;s++){const o=e.types[s],r=t.indexes[o][n[o]],a=t.values[r]??0;i[s]=a,n[o]++}return i}const vp=(t,e)=>{const i=Ft.createTransformer(e),n=Yi(t),s=Yi(e);return n.indexes.var.length===s.indexes.var.length&&n.indexes.color.length===s.indexes.color.length&&n.indexes.number.length>=s.indexes.number.length?po.has(t)&&!s.values.length||po.has(e)&&!n.values.length?fp(t,e):Wi(Il(mp(n,s),s.values),i):Bn(t,e)};function El(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):go(t)(t,e)}const _p=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:Ge.now()}},Rl=(t,e,i=10)=>{let n="";const s=Math.max(Math.round(e/i),2);for(let o=0;o<s;o++)n+=Math.round(t(o/(s-1))*1e4)/1e4+", ";return`linear(${n.substring(0,n.length-2)})`},Un=2e4;function mo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<Un;)e+=i,n=t.next(e);return e>=Un?1/0:e}function yp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(mo(n),Un);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const bp=5;function Al(t,e,i){const n=Math.max(e-bp,0);return il(i-t(n),e-n)}const Te={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},vo=.001;function wp({duration:t=Te.duration,bounce:e=Te.bounce,velocity:i=Te.velocity,mass:n=Te.mass}){let s,o,r=1-e;r=It(Te.minDamping,Te.maxDamping,r),t=It(Te.minDuration,Te.maxDuration,gt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,p=_o(c,r),_=Math.exp(-d);return vo-h/p*_},o=c=>{const d=c*r*t,h=d*i+i,p=Math.pow(r,2)*Math.pow(c,2)*t,_=Math.exp(-d),v=_o(Math.pow(c,2),r);return(-s(c)+vo>0?-1:1)*((h-p)*_)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-vo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Cp(s,o,a);if(t=pt(t),isNaN(l))return{stiffness:Te.stiffness,damping:Te.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const Sp=12;function Cp(t,e,i){let n=i;for(let s=1;s<Sp;s++)n=n-t(n)/e(n);return n}function _o(t,e){return t*Math.sqrt(1-e*e)}const Tp=["duration","bounce"],kp=["stiffness","damping","mass"];function xl(t,e){return e.some(i=>t[i]!==void 0)}function Ip(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!xl(t,kp)&&xl(t,Tp))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*It(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Te.mass,stiffness:s,damping:o}}else{const i=wp(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function $n(t=Te.visualDuration,e=Te.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:p}=Ip({...i,velocity:-gt(i.velocity||0)}),_=h||0,v=c/(2*Math.sqrt(l*u)),w=r-o,y=gt(Math.sqrt(l/u)),C=Math.abs(w)<5;n||(n=C?Te.restSpeed.granular:Te.restSpeed.default),s||(s=C?Te.restDelta.granular:Te.restDelta.default);let I;if(v<1){const R=_o(y,v);I=P=>{const T=Math.exp(-v*y*P);return r-T*((_+v*y*w)/R*Math.sin(R*P)+w*Math.cos(R*P))}}else if(v===1)I=R=>r-Math.exp(-y*R)*(w+(_+y*w)*R);else{const R=y*Math.sqrt(v*v-1);I=P=>{const T=Math.exp(-v*y*P),k=Math.min(R*P,300);return r-T*((_+v*y*w)*Math.sinh(k)+R*w*Math.cosh(k))/R}}const A={calculatedDuration:p&&d||null,next:R=>{const P=I(R);if(p)a.done=R>=d;else{let T=R===0?_:0;v<1&&(T=R===0?pt(_):Al(I,R,P));const k=Math.abs(T)<=n,g=Math.abs(r-P)<=s;a.done=k&&g}return a.value=a.done?r:P,a},toString:()=>{const R=Math.min(mo(A),Un),P=Rl(T=>A.next(R*T).value,R,30);return R+"ms "+P},toTransition:()=>{}};return A}$n.applyToOptions=t=>{const e=yp(t,100,$n);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function yo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=k=>a!==void 0&&k<a||l!==void 0&&k>l,_=k=>a===void 0?l:l===void 0||Math.abs(a-k)<Math.abs(l-k)?a:l;let v=i*e;const w=d+v,y=r===void 0?w:r(w);y!==w&&(v=y-d);const C=k=>-v*Math.exp(-k/n),I=k=>y+C(k),A=k=>{const g=C(k),m=I(k);h.done=Math.abs(g)<=c,h.value=h.done?y:m};let R,P;const T=k=>{p(h.value)&&(R=k,P=$n({keyframes:[h.value,_(h.value)],velocity:Al(I,k,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:k=>{let g=!1;return!P&&R===void 0&&(g=!0,A(k),T(k)),R!==void 0&&k>=R?P.next(k-R):(!g&&A(k),h)}}}function Ep(t,e,i){const n=[],s=i||Et.mix||El,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]||Ze:e;a=Wi(l,a)}n.push(a)}return n}function Rp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(Qs(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=Ep(e,n,s),l=a.length,c=u=>{if(r&&u<t[0])return e[0];let d=0;if(l>1)for(;d<t.length-2&&!(u<t[d+1]);d++);const h=Hi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Ap(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Hi(0,e,n);t.push(Ce(i,1,s))}}function xp(t){const e=[0];return Ap(e,t.length-1),e}function Lp(t,e){return t.map(i=>i*e)}function Dp(t,e){return t.map(()=>e||ul).splice(0,t.length-1)}function Xi({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Wf(n)?n.map(fl):fl(n),o={done:!1,value:e[0]},r=Lp(i&&i.length===e.length?i:xp(e),t),a=Rp(r,e,{ease:Array.isArray(s)?s:Dp(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Op=t=>t!==null;function bo(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Op),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Mp={decay:yo,inertia:yo,tween:Xi,keyframes:Xi,spring:$n};function Ll(t){typeof t.type=="string"&&(t.type=Mp[t.type])}class wo{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const Pp=t=>t/100;class So extends wo{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==Ge.now()&&this.tick(Ge.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(s=(n=this.options).onStop)==null||s.call(n))},this.options=e,this.initAnimation(),this.play(),e.autoplay===!1&&this.pause()}initAnimation(){const{options:e}=this;Ll(e);const{type:i=Xi,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Xi;l!==Xi&&typeof a[0]!="number"&&(this.mixKeyframes=Wi(Pp,El(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=mo(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:p,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)),i?this.currentTime=e:this.updateTime(e);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let I=this.currentTime,A=n;if(d){const k=Math.min(this.currentTime,s)/a;let g=Math.floor(k),m=k%1;!m&&k>=1&&(m=1),m===1&&g--,g=Math.min(g,d+1),!!(g%2)&&(h==="reverse"?(m=1-m,p&&(m-=p/a)):h==="mirror"&&(A=r)),I=It(0,1,m)*a}const R=C?{done:!1,value:u[0]}:A.next(I);o&&(R.value=o(R.value));let{done:P}=R;!C&&l!==null&&(P=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&P);return T&&_!==yo&&(R.value=bo(u,this.options,w,this.speed)),v&&v(R.value),T&&this.finish(),R}then(e,i){return this.finished.then(e,i)}get duration(){return gt(this.calculatedDuration)}get time(){return gt(this.currentTime)}set time(e){var i;e=pt(e),this.currentTime=e,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.playbackSpeed),(i=this.driver)==null||i.start(!1)}get speed(){return this.playbackSpeed}set speed(e){this.updateTime(Ge.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=gt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=_p,startTime:i}=this.options;this.driver||(this.driver=e(r=>this.tick(r))),(o=(s=this.options).onPlay)==null||o.call(s);const n=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=n):this.holdTime!==null?this.startTime=n-this.holdTime:this.startTime||(this.startTime=i??n),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ge.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var e,i;this.notifyFinished(),this.teardown(),this.state="finished",(i=(e=this.options).onComplete)==null||i.call(e)}cancel(){var e,i;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(i=(e=this.options).onCancel)==null||i.call(e)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}attachTimeline(e){var i;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(i=this.driver)==null||i.stop(),e.observe(this)}}function Np(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,Co=t=>{const e=Kt(Math.atan2(t[1],t[0]));return To(e)},Fp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Co,rotateZ:Co,skewX:t=>Kt(Math.atan(t[1])),skewY:t=>Kt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},To=t=>(t=t%360,t<0&&(t+=360),t),Dl=Co,Ol=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Ml=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Vp={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Ol,scaleY:Ml,scale:t=>(Ol(t)+Ml(t))/2,rotateX:t=>To(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>To(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Dl,rotate:Dl,skewX:t=>Kt(Math.atan(t[4])),skewY:t=>Kt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function ko(t){return t.includes("scale")?1:0}function Io(t,e){if(!t||t==="none")return ko(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Vp,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Fp,s=a}if(!s)return ko(e);const o=n[e],r=s[1].split(",").map(Up);return typeof o=="function"?o(r):r[o]}const Bp=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Io(i,e)};function Up(t){return parseFloat(t.trim())}const fi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],pi=new Set(fi),Pl=t=>t===ui||t===K,$p=new Set(["x","y","z"]),jp=fi.filter(t=>!$p.has(t));function Wp(t){const e=[];return jp.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Yt={width:({x:t},{paddingLeft:e="0",paddingRight:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),height:({y:t},{paddingTop:e="0",paddingBottom:i="0"})=>t.max-t.min-parseFloat(e)-parseFloat(i),top:(t,{top:e})=>parseFloat(e),left:(t,{left:e})=>parseFloat(e),bottom:({y:t},{top:e})=>parseFloat(e)+(t.max-t.min),right:({x:t},{left:e})=>parseFloat(e)+(t.max-t.min),x:(t,{transform:e})=>Io(e,"x"),y:(t,{transform:e})=>Io(e,"y")};Yt.translateX=Yt.x,Yt.translateY=Yt.y;const Xt=new Set;let Eo=!1,Ro=!1,Ao=!1;function Nl(){if(Ro){const t=Array.from(Xt).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=Wp(n);s.length&&(i.set(n,s),n.render())}),t.forEach(n=>n.measureInitialState()),e.forEach(n=>{n.render();const s=i.get(n);s&&s.forEach(([o,r])=>{var a;(a=n.getValue(o))==null||a.set(r)})}),t.forEach(n=>n.measureEndState()),t.forEach(n=>{n.suspendedScrollY!==void 0&&window.scrollTo(0,n.suspendedScrollY)})}Ro=!1,Eo=!1,Xt.forEach(t=>t.complete(Ao)),Xt.clear()}function Fl(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ro=!0)})}function Hp(){Ao=!0,Fl(),Nl(),Ao=!1}class xo{constructor(e,i,n,s,o,r=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...e],this.onComplete=i,this.name=n,this.motionValue=s,this.element=o,this.isAsync=r}scheduleResolve(){this.state="scheduled",this.isAsync?(Xt.add(this),Eo||(Eo=!0,we.read(Fl),we.resolveKeyframes(Nl))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:e,name:i,element:n,motionValue:s}=this;if(e[0]===null){const o=s==null?void 0:s.get(),r=e[e.length-1];if(o!==void 0)e[0]=o;else if(n&&i){const a=n.readValue(i,r);a!=null&&(e[0]=a)}e[0]===void 0&&(e[0]=r),s&&o===void 0&&s.set(e[0])}Np(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),Xt.delete(this)}cancel(){this.state==="scheduled"&&(Xt.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Gp=t=>t.startsWith("--");function qp(t,e,i){Gp(e)?t.style.setProperty(e,i):t.style[e]=i}const zp=eo(()=>window.ScrollTimeline!==void 0),Kp={};function Yp(t,e){const i=eo(t);return()=>Kp[e]??i()}const Vl=Yp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Ji=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,Bl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Ji([0,.65,.55,1]),circOut:Ji([.55,0,1,.45]),backIn:Ji([.31,.01,.66,-.59]),backOut:Ji([.33,1.53,.69,.99])};function Ul(t,e){if(t)return typeof t=="function"?Vl()?Rl(t,e):"ease-out":hl(t)?Ji(t):Array.isArray(t)?t.map(i=>Ul(i,e)||Bl.easeOut):Bl[t]}function Xp(t,e,i,{delay:n=0,duration:s=300,repeat:o=0,repeatType:r="loop",ease:a="easeOut",times:l}={},c=void 0){const u={[e]:i};l&&(u.offset=l);const d=Ul(a,s);Array.isArray(d)&&(u.easing=d);const h={delay:n,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:o+1,direction:r==="reverse"?"alternate":"normal"};return c&&(h.pseudoElement=c),t.animate(u,h)}function $l(t){return typeof t=="function"&&"applyToOptions"in t}function Jp({type:t,...e}){return $l(t)&&Vl()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Zp extends wo{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Qs(typeof e.type!="string");const c=Jp(e);this.animation=Xp(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=bo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):qp(i,n,u),this.animation.cancel()}l==null||l(),this.notifyFinished()}}play(){this.isStopped||(this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var e,i;(i=(e=this.animation).finish)==null||i.call(e)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:e}=this;e==="idle"||e==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var e,i;this.isPseudoElement||(i=(e=this.animation).commitStyles)==null||i.call(e)}get duration(){var i,n;const e=((n=(i=this.animation.effect)==null?void 0:i.getComputedTiming)==null?void 0:n.call(i).duration)||0;return gt(Number(e))}get time(){return gt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=pt(e)}get speed(){return this.animation.playbackRate}set speed(e){e<0&&(this.finishedTime=null),this.animation.playbackRate=e}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return Number(this.animation.startTime)}set startTime(e){this.animation.startTime=e}attachTimeline({timeline:e,observe:i}){var n;return this.allowFlatten&&((n=this.animation.effect)==null||n.updateTiming({easing:"linear"})),this.animation.onfinish=null,e&&zp()?(this.animation.timeline=e,Ze):i(this)}}const jl={anticipate:ll,backInOut:al,circInOut:dl};function Qp(t){return t in jl}function eg(t){typeof t.ease=="string"&&Qp(t.ease)&&(t.ease=jl[t.ease])}const Wl=10;class tg extends Zp{constructor(e){eg(e),Ll(e),super(e),e.startTime&&(this.startTime=e.startTime),this.options=e}updateMotionValue(e){const{motionValue:i,onUpdate:n,onComplete:s,element:o,...r}=this.options;if(!i)return;if(e!==void 0){i.set(e);return}const a=new So({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Wl).value,a.sample(l).value,Wl),a.stop()}}const Hl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function ig(t){const e=t[0];if(t.length===1)return!0;for(let i=0;i<t.length;i++)if(t[i]!==e)return!0}function ng(t,e,i,n){const s=t[0];if(s===null)return!1;if(e==="display"||e==="visibility")return!0;const o=t[t.length-1],r=Hl(s,e),a=Hl(o,e);return!r||!a?!1:ig(t)||(i==="spring"||$l(i))&&n}function Lo(t){return el(t)&&"offsetHeight"in t}const sg=new Set(["opacity","clipPath","filter","transform"]),og=eo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function rg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Lo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return og()&&i&&sg.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const ag=40;class lg extends wo{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var _;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=Ge.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},p=(u==null?void 0:u.KeyframeResolver)||xo;this.keyframeResolver=new p(a,(v,w,y)=>this.onKeyframesResolved(v,w,h,!y),l,c,u),(_=this.keyframeResolver)==null||_.scheduleResolve()}onKeyframesResolved(e,i,n,s){this.keyframeResolver=void 0;const{name:o,type:r,velocity:a,delay:l,isHandoff:c,onUpdate:u}=n;this.resolvedAt=Ge.now(),ng(e,o,r,a)||((Et.instantAnimations||!l)&&(u==null||u(bo(e,n,i))),e[0]=e[e.length-1],n.duration=0,n.repeat=0);const h={startTime:s?this.resolvedAt?this.resolvedAt-this.createdAt>ag?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&rg(h)?new tg({...h,element:h.motionValue.owner.current}):new So(h);p.finished.then(()=>this.notifyFinished()).catch(Ze),this.pendingTimeline&&(this.stopTimeline=p.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=p}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),Hp()),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 cg=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function dg(t){const e=cg.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Gl(t,e,i=1){const[n,s]=dg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Qa(r)?parseFloat(r):r}return ro(s)?Gl(s,e,i+1):s}function Do(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const ql=new Set(["width","height","top","left","right","bottom",...fi]),ug={test:t=>t==="auto",parse:t=>t},zl=t=>e=>e.test(t),Kl=[ui,K,mt,Nt,ip,tp,ug],Yl=t=>Kl.find(zl(t));function hg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||tl(t):!0}const fg=new Set(["brightness","contrast","saturate","opacity"]);function pg(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(ao)||[];if(!n)return t;const s=i.replace(n,"");let o=fg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const gg=/\b([a-z-]*)\(.*?\)/gu,Oo={...Ft,getAnimatableNone:t=>{const e=t.match(gg);return e?e.map(pg).join(" "):t}},Xl={...ui,transform:Math.round},Mo={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Vn,scaleX:Vn,scaleY:Vn,scaleZ:Vn,skew:Nt,skewX:Nt,skewY:Nt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:qi,originX:_l,originY:_l,originZ:K},zIndex:Xl,fillOpacity:qi,strokeOpacity:qi,numOctaves:Xl},mg={...Mo,color:Ee,backgroundColor:Ee,outlineColor:Ee,fill:Ee,stroke:Ee,borderColor:Ee,borderTopColor:Ee,borderRightColor:Ee,borderBottomColor:Ee,borderLeftColor:Ee,filter:Oo,WebkitFilter:Oo},Jl=t=>mg[t];function Zl(t,e){let i=Jl(t);return i!==Oo&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const vg=new Set(["auto","none","0"]);function _g(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!vg.has(o)&&Yi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Zl(i,s)}class yg extends xo{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),ro(c))){const u=Gl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!ql.has(n)||e.length!==2)return;const[s,o]=e,r=Yl(s),a=Yl(o);if(r!==a)if(Pl(r)&&Pl(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Yt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||hg(e[s]))&&n.push(s);n.length&&_g(e,n,i)}measureInitialState(){const{element:e,unresolvedKeyframes:i,name:n}=this;if(!e||!e.current)return;n==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Yt[n](e.measureViewportBox(),window.getComputedStyle(e.current)),i[0]=this.measuredOrigin;const s=i[i.length-1];s!==void 0&&e.getValue(n,s).jump(s,!1)}measureEndState(){var a;const{element:e,name:i,unresolvedKeyframes:n}=this;if(!e||!e.current)return;const s=e.getValue(i);s&&s.jump(this.measuredOrigin,!1);const o=n.length-1,r=n[o];n[o]=Yt[i](e.measureViewportBox(),window.getComputedStyle(e.current)),r!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=r),(a=this.removedTransforms)!=null&&a.length&&this.removedTransforms.forEach(([l,c])=>{e.getValue(l).set(c)}),this.resolveNoneKeyframes()}}function bg(t,e,i){if(t instanceof EventTarget)return[t];if(typeof t=="string"){let n=document;const s=(i==null?void 0:i[t])??n.querySelectorAll(t);return s?Array.from(s):[]}return Array.from(t)}const Ql=(t,e)=>e&&typeof t=="number"?e.transform(t):t,ec=30,wg=t=>!isNaN(parseFloat(t));class Sg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=Ge.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(n),this.current!==this.prev&&((r=this.events.change)==null||r.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty();s&&((a=this.events.renderRequest)==null||a.notify(this.current))},this.hasAnimated=!1,this.setCurrent(e),this.owner=i.owner}setCurrent(e){this.current=e,this.updatedAt=Ge.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=wg(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new to);const n=this.events[e].add(i);return e==="change"?()=>{n(),we.read(()=>{this.events.change.getSize()||this.stop()})}:n}clearListeners(){for(const e in this.events)this.events[e].clear()}attach(e,i){this.passiveEffect=e,this.stopPassiveEffect=i}set(e,i=!0){!i||!this.passiveEffect?this.updateAndNotify(e,i):this.passiveEffect(e,this.updateAndNotify)}setWithVelocity(e,i,n){this.set(i),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-n}jump(e,i=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,i&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var e;(e=this.events.change)==null||e.notify(this.current)}addDependent(e){this.dependents||(this.dependents=new Set),this.dependents.add(e)}removeDependent(e){this.dependents&&this.dependents.delete(e)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const e=Ge.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>ec)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,ec);return il(parseFloat(this.current)-parseFloat(this.prevFrameValue),i)}start(e){return this.stop(),new Promise(i=>{this.hasAnimated=!0,this.animation=e(i),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var e,i;(e=this.dependents)==null||e.clear(),(i=this.events.destroy)==null||i.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function gi(t,e){return new Sg(t,e)}const{schedule:Po}=gl(queueMicrotask,!1),at={x:!1,y:!1};function tc(){return at.x||at.y}function Cg(t){return t==="x"||t==="y"?at[t]?null:(at[t]=!0,()=>{at[t]=!1}):at.x||at.y?null:(at.x=at.y=!0,()=>{at.x=at.y=!1})}function ic(t,e){const i=bg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function nc(t){return!(t.pointerType==="touch"||tc())}function Tg(t,e,i={}){const[n,s,o]=ic(t,i),r=a=>{if(!nc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{nc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const sc=(t,e)=>e?t===e?!0:sc(t,e.parentElement):!1,No=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,kg=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Ig(t){return kg.has(t.tagName)||t.tabIndex!==-1}const jn=new WeakSet;function oc(t){return e=>{e.key==="Enter"&&t(e)}}function Fo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Eg=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=oc(()=>{if(jn.has(i))return;Fo(i,"down");const s=oc(()=>{Fo(i,"up")}),o=()=>Fo(i,"cancel");i.addEventListener("keyup",s,e),i.addEventListener("blur",o,e)});i.addEventListener("keydown",n,e),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),e)};function rc(t){return No(t)&&!tc()}function Rg(t,e,i={}){const[n,s,o]=ic(t,i),r=a=>{const l=a.currentTarget;if(!rc(a))return;jn.add(l);const c=e(l,a),u=(p,_)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),jn.has(l)&&jn.delete(l),rc(p)&&typeof c=="function"&&c(p,{success:_})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||sc(l,p.target))},h=p=>{u(p,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),Lo(a)&&(a.addEventListener("focus",c=>Eg(c,s)),!Ig(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function ac(t){return el(t)&&"ownerSVGElement"in t}function Ag(t){return ac(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),xg=[...Kl,Ee,Ft],Lg=t=>xg.find(zl(t)),Zi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Dg extends rt{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Lo(n)&&n.offsetWidth||0,o=this.props.sizeRef.current;o.height=i.offsetHeight||0,o.width=i.offsetWidth||0,o.top=i.offsetTop,o.left=i.offsetLeft,o.right=s-o.width-o.left}return null}componentDidUpdate(){}render(){return this.props.children}}function Og({children:t,isPresent:e,anchorX:i,root:n}){const s=Fs(),o=de(null),r=de({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Le(Zi);return Oa(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const p=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const _=document.createElement("style");a&&(_.nonce=a);const v=n??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;
5
5
  height: ${c}px !important;
6
- ${g}px !important;
6
+ ${p}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{v.removeChild(y),v.contains(y)&&v.removeChild(y)}},[e]),D(Eg,{isPresent:e,childRef:o,sizeRef:r,children:kf(t,{ref:o})})}const Ig=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Pn(xg),u=Os();let d=!0,h=Je(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:g=>{c.set(g,!0);for(const y of c.values())if(!y)return;n&&n()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[i,c,n]);return o&&d&&(h={...h}),Je(()=>{c.forEach((g,y)=>c.set(y,!1))},[i]),Re(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(kg,{isPresent:i,anchorX:a,root:l,children:t})),D(Mn.Provider,{value:h,children:t})};function xg(){return new Map}function tc(t=!0){const e=Le(Mn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Os();Re(()=>{if(t)return s(o)},[t]);const r=He(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const jn=t=>t.key||"";function ic(t){const e=[];return gf.forEach(t,i=>{Ba(i)&&e.push(i)}),e}const Ag=({children:t,custom:e,initial:i=!0,onExitComplete:n,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=tc(r),d=Je(()=>ic(t),[t]),h=r&&!c?[]:d.map(jn),g=de(!0),y=de(d),v=Pn(()=>new Map),[b,_]=Ae(d),[C,k]=Ae(d);Wa(()=>{g.current=!1,y.current=d;for(let N=0;N<C.length;N++){const T=jn(C[N]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let N=[...d];for(let T=0;T<C.length;T++){const E=C[T],p=jn(E);h.includes(p)||(N.splice(T,0,E),A.push(E))}return o==="wait"&&A.length&&(N=A),k(ic(N)),_(d),null}const{forceRender:x}=Le(zs);return D(ht,{children:C.map(N=>{const T=jn(N),E=r&&!c?!1:d===C||h.includes(T),p=()=>{if(v.has(T))v.set(T,!0);else return;let m=!0;v.forEach(f=>{f||(m=!1)}),m&&(x==null||x(),k(y.current),r&&(u==null||u()),n&&n())};return D(Ig,{isPresent:E,initial:!g.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:p,anchorX:a,children:N},T)})})},nc=Tt({strict:!1}),sc={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"]},pi={};for(const t in sc)pi[t]={isEnabled:e=>sc[t].some(i=>!!e[i])};function Rg(t){for(const e in t)pi[e]={...pi[e],...t[e]}}const Lg=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 Hn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Lg.has(t)}let oc=t=>!Hn(t);function rc(t){typeof t=="function"&&(oc=e=>e.startsWith("on")?!Hn(e):t(e))}try{rc(require("@emotion/is-prop-valid").default)}catch{}function Dg(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(oc(s)||i===!0&&Hn(s)||!e&&!Hn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Pg({children:t,isValidProp:e,...i}){e&&rc(e),i={...Le(Xi),...i},i.isStatic=Pn(()=>i.isStatic);const n=Je(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Xi.Provider,{value:n,children:t})}function Mg(t){if(typeof Proxy>"u")return t;const e=new Map,i=(...n)=>t(...n);return new Proxy(i,{get:(n,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const Gn=Tt({});function Wn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Ji(t){return typeof t=="string"||Array.isArray(t)}const No=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Fo=["initial",...No];function qn(t){return Wn(t.animate)||Fo.some(e=>Ji(t[e]))}function ac(t){return!!(qn(t)||t.variants)}function Og(t,e){if(qn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||Ji(i)?i:void 0,animate:Ji(n)?n:void 0}}return t.inherit!==!1?e:{}}function Ng(t){const{initial:e,animate:i}=Og(t,Le(Gn));return Je(()=>({initial:e,animate:i}),[lc(e),lc(i)])}function lc(t){return Array.isArray(t)?t.join(" "):t}const Fg=Symbol.for("motionComponentSymbol");function gi(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Vg(t,e,i){return He(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):gi(i)&&(i.current=n))},[e])}const Vo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),cc="data-"+Vo("framerAppearId"),dc=Tt({});function Ug(t,e,i,n,s){var v,b;const{visualElement:o}=Le(Gn),r=Le(nc),a=Le(Mn),l=Le(Xi).reducedMotion,c=de(null);n=n||r.renderer,!c.current&&n&&(c.current=n(t,{visualState:e,parent:o,props:i,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Le(dc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Bg(c.current,i,s,d);const h=de(!1);ka(()=>{u&&h.current&&u.update(i,a)});const g=i[cc],y=de(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,g)));return Wa(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Po.render(u.render),y.current&&u.animationState&&u.animationState.animateChanges())}),Re(()=>{u&&(!y.current&&u.animationState&&u.animationState.animateChanges(),y.current&&(queueMicrotask(()=>{var _;(_=window.MotionHandoffMarkAsComplete)==null||_.call(window,g)}),y.current=!1))}),u}function Bg(t,e,i,n){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new i(t.latestValues,e["data-framer-portal-id"]?void 0:uc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&gi(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function uc(t){if(t)return t.options.allowProjection!==!1?t.projection:uc(t.parent)}function $g({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Rg(t);function o(a,l){let c;const u={...Le(Xi),...a,layoutId:jg(a)},{isStatic:d}=u,h=Ng(a),g=n(a,d);if(!d&&Ks){Hg();const y=Gg(u);c=y.MeasureLayout,h.visualElement=Ug(s,g,u,e,y.ProjectionNode)}return D(Gn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,Vg(g,h.visualElement,l),g,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=pf(o);return r[Fg]=s,r}function jg({layoutId:t}){const e=Le(zs).id;return e&&t!==void 0?e+"-"+t:t}function Hg(t,e){Le(nc).strict}function Gg(t){const{drag:e,layout:i}=pi;if(!e&&!i)return{};const n={...e,...i};return{MeasureLayout:e!=null&&e.isEnabled(t)||i!=null&&i.isEnabled(t)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}const Qi={};function Wg(t){for(const e in t)Qi[e]=t[e],no(e)&&(Qi[e].isCSSVariable=!0)}function hc(t,{layout:e,layoutId:i}){return hi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!Qi[t]||t==="opacity")}const qg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},zg=ui.length;function Kg(t,e,i){let n="",s=!0;for(let o=0;o<zg;o++){const r=ui[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||i){const c=ql(a,Do[r]);if(!l){s=!1;const u=qg[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function Uo(t,e,i){const{style:n,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(hi.has(l)){r=!0;continue}else if(no(l)){s[l]=c;continue}else{const u=ql(c,Do[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=Kg(e,t.transform,i):n.transform&&(n.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;n.transformOrigin=`${l} ${c} ${u}`}}const Bo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function fc(t,e,i){for(const n in e)!Ve(e[n])&&!hc(n,i)&&(t[n]=e[n])}function Yg({transformTemplate:t},e){return Je(()=>{const i=Bo();return Uo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function Xg(t,e){const i=t.style||{},n={};return fc(n,i,t),Object.assign(n,Yg(t,e)),n}function Jg(t,e){const i={},n=Xg(t,e);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=n,i}const Qg={offset:"stroke-dashoffset",array:"stroke-dasharray"},Zg={offset:"strokeDashoffset",array:"strokeDasharray"};function em(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?Qg:Zg;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function pc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(Uo(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),i!==void 0&&(d.y=i),n!==void 0&&(d.scale=n),s!==void 0&&em(d,s,o,r,!1)}const gc=()=>({...Bo(),attrs:{}}),mc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function tm(t,e,i,n){const s=Je(()=>{const o=gc();return pc(o,e,mc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};fc(o,t.style,t),s.style={...o,...s.style}}return s}const im=["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 $o(t){return typeof t!="string"||t.includes("-")?!1:!!(im.indexOf(t)>-1||/[A-Z]/u.test(t))}function nm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=($o(i)?tm:Jg)(n,o,r,i),c=Dg(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Je(()=>Ve(d)?d.get():d,[d]);return Xe(i,{...u,children:h})}}function vc(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function jo(t,e,i,n){if(typeof e=="function"){const[s,o]=vc(n);e=e(i!==void 0?i:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=vc(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function zn(t){return Ve(t)?t.get():t}function sm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:om(i,n,s,t),renderState:e()}}const _c=t=>(e,i)=>{const n=Le(Gn),s=Le(Mn),o=()=>sm(t,e,n,s);return i?o():Pn(o)};function om(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=zn(o[h]);let{initial:r,animate:a}=t;const l=qn(t),c=ac(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=i?i.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!Wn(d)){const h=Array.isArray(d)?d:[d];for(let g=0;g<h.length;g++){const y=jo(t,h[g]);if(y){const{transitionEnd:v,transition:b,..._}=y;for(const C in _){let k=_[C];if(Array.isArray(k)){const A=u?k.length-1:0;k=k[A]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function Ho(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||hc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const rm={useVisualState:_c({scrapeMotionValuesFromProps:Ho,createRenderState:Bo})};function yc(t,e,i){const n=Ho(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=ui.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const am={useVisualState:_c({scrapeMotionValuesFromProps:yc,createRenderState:gc})};function lm(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...$o(n)?am:rm,preloadedFeatures:t,useRender:nm(s),createVisualElement:e,Component:n};return $g(r)}}function Zi(t,e,i){const n=t.getProps();return jo(n,e,i!==void 0?i:n.custom,t)}const Go=t=>Array.isArray(t);function cm(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,fi(i))}function dm(t){return Go(t)?t[t.length-1]||0:t}function um(t,e){const i=Zi(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=dm(o[r]);cm(t,r,a)}}function hm(t){return!!(Ve(t)&&t.add)}function Wo(t,e){const i=t.getValue("willChange");if(hm(i))return i.add(e);if(!i&&kt.WillChange){const n=new kt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function bc(t){return t.props[cc]}const fm=t=>t!==null;function pm(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(fm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const gm={type:"spring",stiffness:500,damping:25,restSpeed:10},mm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),vm={type:"keyframes",duration:.8},_m={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},ym=(t,{keyframes:e})=>e.length>2?vm:hi.has(t)?t.startsWith("scale")?mm(e[1]):gm:_m;function bm({when:t,delay:e,delayChildren:i,staggerChildren:n,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const qo=(t,e,i,n={},s,o)=>r=>{const a=Ro(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-pt(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};bm(a)||Object.assign(u,ym(t,u)),u.duration&&(u.duration=pt(u.duration)),u.repeatDelay&&(u.repeatDelay=pt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(kt.instantAnimations||kt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=pm(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new bo(u):new tg(u)};function wm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function wc(t,e,{delay:i=0,transitionOverride:n,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;n&&(o=n);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&wm(c,u))continue;const g={delay:i,...Ro(o||{},u)},y=d.get();if(y!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===y&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const _=bc(t);if(_){const C=window.MotionHandoffAnimation(_,u,we);C!==null&&(g.startTime=C,v=!0)}}Wo(t,u),d.start(qo(u,d,h,t.shouldReduceMotion&&Ul.has(u)?{type:!1}:g,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&um(t,r)})}),l}function zo(t,e,i={}){var l;const n=Zi(t,e,i.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=n||{};i.transitionOverride&&(s=i.transitionOverride);const o=n?()=>Promise.all(wc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Sm(t,e,c,u,d,h,i)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(i.delay)])}function Sm(t,e,i=0,n=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof n=="function",d=u?h=>n(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(Cm).forEach((h,g)=>{h.notify("AnimationStart",e),a.push(zo(h,e,{...r,delay:i+(u?0:n)+d(g)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Cm(t,e){return t.sortNodePosition(e)}function Tm(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>zo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=zo(t,e,i);else{const s=typeof e=="function"?Zi(t,e,i.custom):e;n=Promise.all(wc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Sc(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(e[n]!==t[n])return!1;return!0}const Em=Fo.length;function Cc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?Cc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Em;i++){const n=Fo[i],s=t.props[n];(Ji(s)||s===!1)&&(e[n]=s)}return e}const km=[...No].reverse(),Im=No.length;function xm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Tm(t,i,n)))}function Am(t){let e=xm(t),i=Tc(),n=!0;const s=l=>(c,u)=>{var h;const d=Zi(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:g,transitionEnd:y,...v}=d;c={...c,...v,...y}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=Cc(t.parent)||{},d=[],h=new Set;let g={},y=1/0;for(let b=0;b<Im;b++){const _=km[b],C=i[_],k=c[_]!==void 0?c[_]:u[_],A=Ji(k),x=_===l?C.isActive:null;x===!1&&(y=b);let N=k===u[_]&&k!==c[_]&&A;if(N&&n&&t.manuallyAnimateOnMount&&(N=!1),C.protectedKeys={...g},!C.isActive&&x===null||!k&&!C.prevProp||Wn(k)||typeof k=="boolean")continue;const T=Rm(C.prevProp,k);let E=T||_===l&&C.isActive&&!N&&A||b>y&&A,p=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(_),{});x===!1&&(f={});const{prevResolvedValues:w={}}=C,I={...w,...f},L=P=>{E=!0,h.has(P)&&(p=!0,h.delete(P)),C.needsAnimating[P]=!0;const F=t.getValue(P);F&&(F.liveStyle=!1)};for(const P in I){const F=f[P],H=w[P];if(g.hasOwnProperty(P))continue;let $=!1;Go(F)&&Go(H)?$=!Sc(F,H):$=F!==H,$?F!=null?L(P):h.add(P):F!==void 0&&h.has(P)?L(P):C.protectedKeys[P]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(g={...g,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(N&&T)||p)&&d.push(...m.map(P=>({animation:P,options:{type:_}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const _=Zi(t,Array.isArray(c.initial)?c.initial[0]:c.initial);_&&_.transition&&(b.transition=_.transition)}h.forEach(_=>{const C=t.getBaseTarget(_),k=t.getValue(_);k&&(k.liveStyle=!0),b[_]=C??null}),d.push({animation:b})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var g;return(g=h.animationState)==null?void 0:g.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=Tc(),n=!0}}}function Rm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Sc(e,t):!1}function Yt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Tc(){return{animate:Yt(!0),whileInView:Yt(),whileHover:Yt(),whileTap:Yt(),whileDrag:Yt(),whileFocus:Yt(),exit:Yt()}}class Ft{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Lm extends Ft{constructor(e){super(e),e.animationState||(e.animationState=Am(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();Wn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Dm=0;class Pm extends Ft{constructor(){super(...arguments),this.id=Dm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const s=this.node.animationState.setActive("exit",!e);i&&!e&&s.then(()=>{i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const Mm={animation:{Feature:Lm},exit:{Feature:Pm}};function en(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function tn(t){return{point:{x:t.pageX,y:t.pageY}}}const Om=t=>e=>Mo(e)&&t(e,tn(e));function nn(t,e,i,n){return en(t,e,Om(i),n)}function Ec({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Nm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Fm(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}const kc=1e-4,Vm=1-kc,Um=1+kc,Ic=.01,Bm=0-Ic,$m=0+Ic;function Be(t){return t.max-t.min}function jm(t,e,i){return Math.abs(t-e)<=i}function xc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=Be(i)/Be(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Vm&&t.scale<=Um||isNaN(t.scale))&&(t.scale=1),(t.translate>=Bm&&t.translate<=$m||isNaN(t.translate))&&(t.translate=0)}function sn(t,e,i,n){xc(t.x,e.x,i.x,n?n.originX:void 0),xc(t.y,e.y,i.y,n?n.originY:void 0)}function Ac(t,e,i){t.min=i.min+e.min,t.max=t.min+Be(e)}function Hm(t,e,i){Ac(t.x,e.x,i.x),Ac(t.y,e.y,i.y)}function Rc(t,e,i){t.min=e.min-i.min,t.max=t.min+Be(e)}function on(t,e,i){Rc(t.x,e.x,i.x),Rc(t.y,e.y,i.y)}const Lc=()=>({translate:0,scale:1,origin:0,originPoint:0}),mi=()=>({x:Lc(),y:Lc()}),Dc=()=>({min:0,max:0}),ke=()=>({x:Dc(),y:Dc()});function Ze(t){return[t("x"),t("y")]}function Ko(t){return t===void 0||t===1}function Yo({scale:t,scaleX:e,scaleY:i}){return!Ko(t)||!Ko(e)||!Ko(i)}function Xt(t){return Yo(t)||Pc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Pc(t){return Mc(t.x)||Mc(t.y)}function Mc(t){return t&&t!=="0%"}function Kn(t,e,i){const n=t-i,s=e*n;return i+s}function Oc(t,e,i,n,s){return s!==void 0&&(t=Kn(t,s,n)),Kn(t,i,n)+e}function Xo(t,e=0,i=1,n,s){t.min=Oc(t.min,e,i,n,s),t.max=Oc(t.max,e,i,n,s)}function Nc(t,{x:e,y:i}){Xo(t.x,e.translate,e.scale,e.originPoint),Xo(t.y,i.translate,i.scale,i.originPoint)}const Fc=.999999999999,Vc=1.0000000000001;function Gm(t,e,i,n=!1){const s=i.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=i[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(n&&o.options.layoutScroll&&o.scroll&&o!==o.root&&_i(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Nc(t,r)),n&&Xt(o.latestValues)&&_i(t,o.latestValues))}e.x<Vc&&e.x>Fc&&(e.x=1),e.y<Vc&&e.y>Fc&&(e.y=1)}function vi(t,e){t.min=t.min+e,t.max=t.max+e}function Uc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);Xo(t,e,i,o,n)}function _i(t,e){Uc(t.x,e.x,e.scaleX,e.scale,e.originX),Uc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Bc(t,e){return Ec(Fm(t.getBoundingClientRect(),e))}function Wm(t,e,i){const n=Bc(t,i),{scroll:s}=e;return s&&(vi(n.x,s.offset.x),vi(n.y,s.offset.y)),n}const $c=({current:t})=>t?t.ownerDocument.defaultView:null,jc=(t,e)=>Math.abs(t-e);function qm(t,e){const i=jc(t.x,e.x),n=jc(t.y,e.y);return Math.sqrt(i**2+n**2)}class Hc{constructor(e,i,{transformPagePoint:n,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=Qo(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,y=qm(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!y)return;const{point:v}=h,{timestamp:b}=Oe;this.history.push({...v,timestamp:b});const{onStart:_,onMove:C}=this.handlers;g||(_&&_(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Jo(g,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const _=Qo(h.type==="pointercancel"?this.lastMoveEventInfo:Jo(g,this.transformPagePoint),this.history);this.startEvent&&y&&y(h,_),v&&v(h,_)},!Mo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=tn(e),l=Jo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Oe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,Qo(l,this.history)),this.removeListeners=$i(nn(this.contextWindow,"pointermove",this.handlePointerMove),nn(this.contextWindow,"pointerup",this.handlePointerUp),nn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Mt(this.updatePoint)}}function Jo(t,e){return e?{point:e(t.point)}:t}function Gc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Qo({point:t},e){return{point:t,delta:Gc(t,Wc(e)),offset:Gc(t,zm(e)),velocity:Km(e,.1)}}function zm(t){return t[0]}function Wc(t){return t[t.length-1]}function Km(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Wc(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>pt(e)));)i--;if(!n)return{x:0,y:0};const o=gt(s.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-n.x)/o,y:(s.y-n.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function Ym(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Ce(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Ce(i,t,n.max):Math.min(t,i)),t}function qc(t,e,i){return{min:e!==void 0?t.min+e:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function Xm(t,{top:e,left:i,bottom:n,right:s}){return{x:qc(t.x,i,s),y:qc(t.y,e,n)}}function zc(t,e){let i=e.min-t.min,n=e.max-t.max;return e.max-e.min<t.max-t.min&&([i,n]=[n,i]),{min:i,max:n}}function Jm(t,e){return{x:zc(t.x,e.x),y:zc(t.y,e.y)}}function Qm(t,e){let i=.5;const n=Be(t),s=Be(e);return s>n?i=ji(e.min,e.max-n,t.min):n>s&&(i=ji(t.min,t.max-s,e.min)),Et(0,1,i)}function Zm(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const Zo=.35;function ev(t=Zo){return t===!1?t=0:t===!0&&(t=Zo),{x:Kc(t,"left","right"),y:Kc(t,"top","bottom")}}function Kc(t,e,i){return{min:Yc(t,e),max:Yc(t,i)}}function Yc(t,e){return typeof t=="number"?t:t[e]||0}const tv=new WeakMap;class iv{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ke(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:n}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),i&&this.snapToCursor(tn(d).point)},r=(d,h)=>{const{drag:g,dragPropagation:y,onDragStart:v}=this.getProps();if(g&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=mg(g),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Ze(_=>{let C=this.getAxisMotionValue(_).get()||0;if(mt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[_];A&&(C=Be(A)*(parseFloat(C)/100))}}this.originPoint[_]=C}),v&&we.postRender(()=>v(d,h)),Wo(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:y,onDirectionLock:v,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:_}=h;if(y&&this.currentDirection===null){this.currentDirection=nv(_),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,_),this.updateAxis("y",h.point,_),this.visualElement.render(),b&&b(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Ze(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Hc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:$c(this.visualElement)})}stop(e,i){const n=e||this.latestPointerEvent,s=i||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!n)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&we.postRender(()=>a(n,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}updateAxis(e,i,n){const{drag:s}=this.getProps();if(!n||!Yn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=Ym(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:i}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;e&&gi(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=Xm(n.layoutBox,e):this.constraints=!1,this.elastic=ev(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&Ze(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=Zm(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!gi(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Wm(n,s.root,this.visualElement.getTransformPagePoint());let r=Jm(s.layout.layoutBox,o);if(i){const a=i(Nm(r));this.hasMutatedConstraints=!!a,a&&(r=Ec(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Ze(u=>{if(!Yn(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,g=s?40:1e7,y={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,y)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return Wo(this.visualElement,e),n.start(qo(e,n,0,i,this.visualElement,!1))}stopAnimation(){Ze(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Ze(e=>{var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.pause()})}getAnimationState(e){var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.state}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),s=n[i];return s||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){Ze(i=>{const{drag:n}=this.getProps();if(!Yn(i,n,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(i);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[i];o.set(e[i]-Ce(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!gi(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Ze(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=Qm({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),Ze(r=>{if(!Yn(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Ce(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;tv.set(this.visualElement,this);const e=this.visualElement.current,i=nn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();gi(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",n);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),we.read(n);const r=en(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Ze(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Zo,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Yn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function nv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class sv extends Ft{constructor(e){super(e),this.removeGroupControls=Qe,this.removeListeners=Qe,this.controls=new iv(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 Xc=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class ov extends Ft{constructor(){super(...arguments),this.removePointerDownListener=Qe}onPointerDown(e){this.session=new Hc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:$c(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:Xc(e),onStart:Xc(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=nn(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 Xn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Jc(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const rn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=Jc(t,e.target.x),n=Jc(t,e.target.y);return`${i}% ${n}%`}},rv={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Nt.parse(t);if(s.length>5)return n;const o=Nt.createTransformer(t),r=typeof s[0]!="number"?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=Ce(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Qc=!1;class av extends rt{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;Wg(lv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),Qc&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Xn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,Qc=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||we.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Po.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(s),n&&n.deregister&&n.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function Zc(t){const[e,i]=tc(),n=Le(zs);return D(av,{...t,layoutGroup:n,switchLayoutGroup:Le(dc),isPresent:e,safeToRemove:i})}const lv={borderRadius:{...rn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:rn,borderTopRightRadius:rn,borderBottomLeftRadius:rn,borderBottomRightRadius:rn,boxShadow:rv};function cv(t,e,i){const n=Ve(t)?t:fi(t);return n.start(qo("",n,e,i)),n.animation}const dv=(t,e)=>t.depth-e.depth;class uv{constructor(){this.children=[],this.isDirty=!1}add(e){Ys(this.children,e),this.isDirty=!0}remove(e){Xs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(dv),this.isDirty=!1,this.children.forEach(e)}}function hv(t,e){const i=Ge.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Mt(n),t(o-e))};return we.setup(n,!0),()=>Mt(n)}const ed=["TopLeft","TopRight","BottomLeft","BottomRight"],fv=ed.length,td=t=>typeof t=="string"?parseFloat(t):t,id=t=>typeof t=="number"||K.test(t);function pv(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,gv(n)),t.opacityExit=Ce(e.opacity??1,0,mv(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<fv;r++){const a=`border${ed[r]}Radius`;let l=nd(e,a),c=nd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||id(l)===id(c)?(t[a]=Math.max(Ce(td(l),td(c),n),0),(mt.test(c)||mt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Ce(e.rotate||0,i.rotate||0,n))}function nd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const gv=sd(0,.5,il),mv=sd(.5,.95,Qe);function sd(t,e,i){return n=>n<t?0:n>e?1:i(ji(t,e,n))}function od(t,e){t.min=e.min,t.max=e.max}function et(t,e){od(t.x,e.x),od(t.y,e.y)}function rd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function ad(t,e,i,n,s){return t-=e,t=Kn(t,1/i,n),s!==void 0&&(t=Kn(t,1/s,n)),t}function vv(t,e=0,i=1,n=.5,s,o=t,r=t){if(mt.test(e)&&(e=parseFloat(e),e=Ce(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Ce(o.min,o.max,n);t===o&&(a-=e),t.min=ad(t.min,e,i,a,s),t.max=ad(t.max,e,i,a,s)}function ld(t,e,[i,n,s],o,r){vv(t,e[i],e[n],e[s],e.scale,o,r)}const _v=["x","scaleX","originX"],yv=["y","scaleY","originY"];function cd(t,e,i,n){ld(t.x,e,_v,i?i.x:void 0,n?n.x:void 0),ld(t.y,e,yv,i?i.y:void 0,n?n.y:void 0)}function dd(t){return t.translate===0&&t.scale===1}function ud(t){return dd(t.x)&&dd(t.y)}function hd(t,e){return t.min===e.min&&t.max===e.max}function bv(t,e){return hd(t.x,e.x)&&hd(t.y,e.y)}function fd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function pd(t,e){return fd(t.x,e.x)&&fd(t.y,e.y)}function gd(t){return Be(t.x)/Be(t.y)}function md(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class wv{constructor(){this.members=[]}add(e){Ys(this.members,e),e.scheduleRender()}remove(e){if(Xs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){const i=this.members.findIndex(s=>e===s);if(i===0)return!1;let n;for(let s=i;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){n=o;break}}return n?(this.promote(n),!0):!1}promote(e,i){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,i&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:i,resumingFrom:n}=e;i.onExitComplete&&i.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Sv(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:g,skewY:y}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),g&&(n+=`skewX(${g}deg) `),y&&(n+=`skewY(${y}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(n+=`scale(${a}, ${l})`),n||"none"}const er=["","X","Y","Z"],Cv=1e3;let Tv=0;function tr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function vd(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=bc(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",we,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&vd(n)}function _d({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Tv++,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(Iv),this.nodes.forEach(Lv),this.nodes.forEach(Dv),this.nodes.forEach(xv)},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 uv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new Zs),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=ec(r)&&!Sg(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;we.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=hv(h,250),Xn.hasAnimatedSinceResize&&(Xn.hasAnimatedSinceResize=!1,this.nodes.forEach(wd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||c.getDefaultTransition()||Fv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),_=!this.targetLayout||!pd(this.targetLayout,g),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(_||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Ro(y,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(k.delay=0,k.type=!1),this.startAnimation(k),this.setAnimationOrigin(u,C)}else d||wd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Mt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Pv),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&&vd(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(yd);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(bd);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Rv),this.nodes.forEach(Ev),this.nodes.forEach(kv)):this.nodes.forEach(bd),this.clearAllSnapshots();const a=Ge.now();Oe.delta=Et(0,1e3/60,a-Oe.timestamp),Oe.timestamp=a,Oe.isProcessing=!0,io.update.process(Oe),io.preRender.process(Oe),io.render.process(Oe),Oe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Po.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Av),this.sharedNodes.forEach(Mv)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,we.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){we.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Be(this.snapshot.measuredBox.x)&&!Be(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l<this.path.length;l++)this.path[l].updateScroll();const r=this.layout;this.layout=this.measure(!1),this.layoutCorrected=ke(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=n(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:i(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!ud(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Xt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),Vv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return ke();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(Uv))){const{scroll:u}=this.root;u&&(vi(a.x,u.offset.x),vi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(et(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&et(a,r),vi(a.x,d.offset.x),vi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();et(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&_i(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Xt(u.latestValues)&&_i(l,u.latestValues)}return Xt(this.latestValues)&&_i(l,this.latestValues),l}removeTransform(r){const a=ke();et(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Xt(c.latestValues))continue;Yo(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();et(u,d),cd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Xt(this.latestValues)&&cd(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Oe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Oe.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),on(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=ke(),this.targetWithTransforms=ke()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Hm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):et(this.target,this.layout.layoutBox),Nc(this.target,this.targetDelta)):et(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),on(this.relativeTargetOrigin,this.target,g.target),et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Yo(this.parent.latestValues)||Pc(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var y;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(y=this.parent)!=null&&y.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Oe.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;et(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Gm(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=ke());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(rd(this.prevProjectionDelta.x,this.projectionDelta.x),rd(this.prevProjectionDelta.y,this.projectionDelta.y)),sn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!md(this.projectionDelta.x,this.prevProjectionDelta.x)||!md(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=mi(),this.projectionDelta=mi(),this.projectionDeltaWithTransform=mi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=mi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),g=l?l.source:void 0,y=this.layout?this.layout.source:void 0,v=g!==y,b=this.getStack(),_=!b||b.members.length<=1,C=!!(v&&!_&&this.options.crossfade===!0&&!this.path.some(Nv));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const x=A/1e3;Sd(d.x,r.x,x),Sd(d.y,r.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(on(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Ov(this.relativeTarget,this.relativeTargetOrigin,h,x),k&&bv(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),et(k,this.relativeTarget)),v&&(this.animationValues=u,pv(u,c,this.latestValues,x,C,_)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Mt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=we.update(()=>{Xn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=fi(0)),this.currentAnimation=cv(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Cv),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&Id(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=Be(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=Be(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}et(a,l),_i(a,u),sn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new wv),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&&tr("z",r,c,this.animationValues);for(let u=0;u<er.length;u++)tr(`rotate${er[u]}`,r,c,this.animationValues),tr(`skew${er[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=zn(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=zn(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Xt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Sv(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:g}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const y in Qi){if(u[y]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:_}=Qi[y],C=d==="none"?u[y]:v(u[y],c);if(b){const k=b.length;for(let A=0;A<k;A++)r[b[A]]=C}else _?this.options.visualElement.renderState.vars[y]=C:r[y]=C}this.options.layoutId&&(r.pointerEvents=c===this?zn(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(yd),this.root.sharedNodes.clear()}}}function Ev(t){t.updateLayout()}function kv(t){var i;const e=((i=t.resumeFrom)==null?void 0:i.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?Ze(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=Be(h);h.min=n[d].min,h.max=h.min+g}):Id(o,e.layoutBox,n)&&Ze(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=Be(n[d]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=mi();sn(a,n,e.layoutBox);const l=mi();r?sn(l,t.applyTransform(s,!0),e.measuredBox):sn(l,n,e.layoutBox);const c=!ud(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:g}=d;if(h&&g){const y=ke();on(y,e.layoutBox,h.layoutBox);const v=ke();on(v,n,g.layoutBox),pd(y,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=y,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Iv(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 xv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Av(t){t.clearSnapshot()}function yd(t){t.clearMeasurements()}function bd(t){t.isLayoutDirty=!1}function Rv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function wd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Lv(t){t.resolveTargetDelta()}function Dv(t){t.calcProjection()}function Pv(t){t.resetSkewAndRotation()}function Mv(t){t.removeLeadSnapshot()}function Sd(t,e,i){t.translate=Ce(e.translate,0,i),t.scale=Ce(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function Cd(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function Ov(t,e,i,n){Cd(t.x,e.x,i.x,n),Cd(t.y,e.y,i.y,n)}function Nv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Fv={duration:.45,ease:[.4,0,.1,1]},Td=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Ed=Td("applewebkit/")&&!Td("chrome/")?Math.round:Qe;function kd(t){t.min=Ed(t.min),t.max=Ed(t.max)}function Vv(t){kd(t.x),kd(t.y)}function Id(t,e,i){return t==="position"||t==="preserve-aspect"&&!jm(gd(e),gd(i),.2)}function Uv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Bv=_d({attachResizeListener:(t,e)=>en(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ir={current:void 0},xd=_d({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ir.current){const t=new Bv({});t.mount(window),t.setOptions({layoutScroll:!0}),ir.current=t}return ir.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),$v={pan:{Feature:ov},drag:{Feature:sv,ProjectionNode:xd,MeasureLayout:Zc}};function Ad(t,e,i){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",i==="Start");const s="onHover"+i,o=n[s];o&&we.postRender(()=>o(e,tn(e)))}class jv extends Ft{mount(){const{current:e}=this.node;e&&(this.unmount=vg(e,(i,n)=>(Ad(this.node,n,"Start"),s=>Ad(this.node,s,"End"))))}unmount(){}}class Hv extends Ft{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch{e=!0}!e||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=$i(en(this.node.current,"focus",()=>this.onFocus()),en(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Rd(t,e,i){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",i==="Start");const s="onTap"+(i==="End"?"":i),o=n[s];o&&we.postRender(()=>o(e,tn(e)))}class Gv extends Ft{mount(){const{current:e}=this.node;e&&(this.unmount=wg(e,(i,n)=>(Rd(this.node,n,"Start"),(s,{success:o})=>Rd(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const nr=new WeakMap,sr=new WeakMap,Wv=t=>{const e=nr.get(t.target);e&&e(t)},qv=t=>{t.forEach(Wv)};function zv({root:t,...e}){const i=t||document;sr.has(i)||sr.set(i,{});const n=sr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(qv,{root:t,...e})),n[s]}function Kv(t,e,i){const n=zv(e);return nr.set(t,i),n.observe(t),()=>{nr.delete(t),n.unobserve(t)}}const Yv={some:0,all:1};class Xv extends Ft{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:i,margin:n,amount:s="some",once:o}=e,r={root:i?i.current:void 0,rootMargin:n,threshold:typeof s=="number"?s:Yv[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return Kv(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(Jv(e,i))&&this.startObserver()}unmount(){}}function Jv({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const Qv={inView:{Feature:Xv},tap:{Feature:Gv},focus:{Feature:Hv},hover:{Feature:jv}},Zv={layout:{ProjectionNode:xd,MeasureLayout:Zc}},or={current:null},Ld={current:!1};function e_(){if(Ld.current=!0,!!Ks)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>or.current=t.matches;t.addEventListener("change",e),e()}else or.current=!1}const t_=new WeakMap;function i_(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ve(s))t.addValue(n,s);else if(Ve(o))t.addValue(n,fi(s,{owner:t}));else if(o!==s)if(t.hasValue(n)){const r=t.getValue(n);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(n);t.addValue(n,fi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const Dd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class n_{scrapeMotionValuesFromProps(e,i,n){return{}}constructor({parent:e,props:i,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=xo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=Ge.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,we.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=i.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=i,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=qn(i),this.isVariantNode=ac(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const g=d[h];l[h]!==void 0&&Ve(g)&&g.set(l[h],!1)}}mount(e){this.current=e,t_.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,n)=>this.bindToMotionValue(n,i)),Ld.current||e_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:or.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Mt(this.notifyUpdate),Mt(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const i=this.features[e];i&&(i.unmount(),i.isMounted=!1)}this.current=null}bindToMotionValue(e,i){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=hi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&we.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),o=i.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),i.owner&&i.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in pi){const i=pi[e];if(!i)continue;const{isEnabled:n,Feature:s}=i;if(!this.features[e]&&s&&n(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ke()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let n=0;n<Dd.length;n++){const s=Dd[n];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=i_(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const i=this.getClosestVariantNode();if(i)return i.variantChildren&&i.variantChildren.add(e),()=>i.variantChildren.delete(e)}addValue(e,i){const n=this.values.get(e);i!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&i!==void 0&&(n=fi(i===null?void 0:i,{owner:this}),this.addValue(e,n)),n}readValue(e,i){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(qa(n)||Ka(n))?n=parseFloat(n):!Tg(n)&&Nt.test(i)&&(n=Wl(e,i)),this.setBaseTarget(e,Ve(n)?n.get():n)),Ve(n)?n.get():n}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var o;const{initial:i}=this.props;let n;if(typeof i=="string"||typeof i=="object"){const r=jo(this.props,i,(o=this.presenceContext)==null?void 0:o.custom);r&&(n=r[e])}if(i&&n!==void 0)return n;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ve(s)?s:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new Zs),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Pd extends n_{constructor(){super(...arguments),this.KeyframeResolver=hg}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){return e.style?e.style[i]:void 0}removeValueFromRenderState(e,{vars:i,style:n}){delete i[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ve(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function Md(t,{style:e,vars:i},n,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,n);for(r in i)o.setProperty(r,i[r])}function s_(t){return window.getComputedStyle(t)}class o_ extends Pd{constructor(){super(...arguments),this.type="html",this.renderInstance=Md}readValueFromInstance(e,i){var n;if(hi.has(i))return(n=this.projection)!=null&&n.isProjecting?Co(i):Dp(e,i);{const s=s_(e),o=(no(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Bc(e,i)}build(e,i,n){Uo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return Ho(e,i,n)}}const Od=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 r_(t,e,i,n){Md(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(Od.has(s)?s:Vo(s),e.attrs[s])}class a_ extends Pd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(hi.has(i)){const n=Gl(i);return n&&n.default||0}return i=Od.has(i)?i:Vo(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return yc(e,i,n)}build(e,i,n){pc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){r_(e,i,n,s)}mount(e){this.isSVGTag=mc(e.tagName),super.mount(e)}}const l_=(t,e)=>$o(t)?new a_(e):new o_(e,{allowProjection:t!==ht}),c_=lm({...Mm,...Qv,...$v,...Zv},l_),yi=Mg(c_),d_=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region","skip-last-voice-sdk-id"],an="widget-layout-id";function Nd(t){var e,i,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=Nd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function It(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=Nd(t))&&(n&&(n+=" "),n+=e);return n}const u_=Rn("listening"),rr=()=>Ga(u_);function h_(t){var i;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((i=e.params)==null?void 0:i.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Jn={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=Rn(Jn),f_=()=>{const t=Dn(Fd);return He(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Jn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Jn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Jn.speak_to_interrupt_text),i}),[t])},Jt=()=>qs(Fd),Vd=({size:t="large",className:e})=>{const i=Jt(),[n]=rr();return D("h1",{className:It({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Ud=({stream:t,chatMode:e})=>{const i=de(null);return Re(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
9
+ `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),D(Dg,{isPresent:e,childRef:o,sizeRef:r,children:Of(t,{ref:o})})}const Mg=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Mn(Pg),u=Fs();let d=!0,h=Je(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:p=>{c.set(p,!0);for(const _ of c.values())if(!_)return;n&&n()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[i,c,n]);return o&&d&&(h={...h}),Je(()=>{c.forEach((p,_)=>c.set(_,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Og,{isPresent:i,anchorX:a,root:l,children:t})),D(Pn.Provider,{value:h,children:t})};function Pg(){return new Map}function lc(t=!0){const e=Le(Pn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Fs();xe(()=>{if(t)return s(o)},[t]);const r=He(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Wn=t=>t.key||"";function cc(t){const e=[];return Sf.forEach(t,i=>{za(i)&&e.push(i)}),e}const Ng=({children:t,custom:e,initial:i=!0,onExitComplete:n,presenceAffectsLayout:s=!0,mode:o="sync",propagate:r=!1,anchorX:a="left",root:l})=>{const[c,u]=lc(r),d=Je(()=>cc(t),[t]),h=r&&!c?[]:d.map(Wn),p=de(!0),_=de(d),v=Mn(()=>new Map),[w,y]=Ae(d),[C,I]=Ae(d);Za(()=>{p.current=!1,_.current=d;for(let P=0;P<C.length;P++){const T=Wn(C[P]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==w){let P=[...d];for(let T=0;T<C.length;T++){const k=C[T],g=Wn(k);h.includes(g)||(P.splice(T,0,k),A.push(k))}return o==="wait"&&A.length&&(P=A),I(cc(P)),y(d),null}const{forceRender:R}=Le(Ys);return D(ht,{children:C.map(P=>{const T=Wn(P),k=r&&!c?!1:d===C||h.includes(T),g=()=>{if(v.has(T))v.set(T,!0);else return;let m=!0;v.forEach(f=>{f||(m=!1)}),m&&(R==null||R(),I(_.current),r&&(u==null||u()),n&&n())};return D(Mg,{isPresent:k,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:k?void 0:g,anchorX:a,children:P},T)})})},dc=kt({strict:!1}),uc={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"]},mi={};for(const t in uc)mi[t]={isEnabled:e=>uc[t].some(i=>!!e[i])};function Fg(t){for(const e in t)mi[e]={...mi[e],...t[e]}}const Vg=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 Hn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Vg.has(t)}let hc=t=>!Hn(t);function fc(t){typeof t=="function"&&(hc=e=>e.startsWith("on")?!Hn(e):t(e))}try{fc(require("@emotion/is-prop-valid").default)}catch{}function Bg(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(hc(s)||i===!0&&Hn(s)||!e&&!Hn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Ug({children:t,isValidProp:e,...i}){e&&fc(e),i={...Le(Zi),...i},i.isStatic=Mn(()=>i.isStatic);const n=Je(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Zi.Provider,{value:n,children:t})}function $g(t){if(typeof Proxy>"u")return t;const e=new Map,i=(...n)=>t(...n);return new Proxy(i,{get:(n,s)=>s==="create"?t:(e.has(s)||e.set(s,t(s)),e.get(s))})}const Gn=kt({});function qn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function Qi(t){return typeof t=="string"||Array.isArray(t)}const Vo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Bo=["initial",...Vo];function zn(t){return qn(t.animate)||Bo.some(e=>Qi(t[e]))}function pc(t){return!!(zn(t)||t.variants)}function jg(t,e){if(zn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||Qi(i)?i:void 0,animate:Qi(n)?n:void 0}}return t.inherit!==!1?e:{}}function Wg(t){const{initial:e,animate:i}=jg(t,Le(Gn));return Je(()=>({initial:e,animate:i}),[gc(e),gc(i)])}function gc(t){return Array.isArray(t)?t.join(" "):t}const Hg=Symbol.for("motionComponentSymbol");function vi(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Gg(t,e,i){return He(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):vi(i)&&(i.current=n))},[e])}const Uo=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),mc="data-"+Uo("framerAppearId"),vc=kt({});function qg(t,e,i,n,s){var v,w;const{visualElement:o}=Le(Gn),r=Le(dc),a=Le(Pn),l=Le(Zi).reducedMotion,c=de(null);n=n||r.renderer,!c.current&&n&&(c.current=n(t,{visualState:e,parent:o,props:i,presenceContext:a,blockInitialAnimation:a?a.initial===!1:!1,reducedMotionConfig:l}));const u=c.current,d=Le(vc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&zg(c.current,i,s,d);const h=de(!1);Oa(()=>{u&&h.current&&u.update(i,a)});const p=i[mc],_=de(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((w=window.MotionHasOptimisedAnimation)==null?void 0:w.call(window,p)));return Za(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Po.render(u.render),_.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!_.current&&u.animationState&&u.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),_.current=!1))}),u}function zg(t,e,i,n){const{layoutId:s,layout:o,drag:r,dragConstraints:a,layoutScroll:l,layoutRoot:c,layoutCrossfade:u}=e;t.projection=new i(t.latestValues,e["data-framer-portal-id"]?void 0:_c(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&vi(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function _c(t){if(t)return t.options.allowProjection!==!1?t.projection:_c(t.parent)}function Kg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Fg(t);function o(a,l){let c;const u={...Le(Zi),...a,layoutId:Yg(a)},{isStatic:d}=u,h=Wg(a),p=n(a,d);if(!d&&Xs){Xg();const _=Jg(u);c=_.MeasureLayout,h.visualElement=qg(s,p,u,e,_.ProjectionNode)}return D(Gn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,Gg(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=wf(o);return r[Hg]=s,r}function Yg({layoutId:t}){const e=Le(Ys).id;return e&&t!==void 0?e+"-"+t:t}function Xg(t,e){Le(dc).strict}function Jg(t){const{drag:e,layout:i}=mi;if(!e&&!i)return{};const n={...e,...i};return{MeasureLayout:e!=null&&e.isEnabled(t)||i!=null&&i.isEnabled(t)?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}const en={};function Zg(t){for(const e in t)en[e]=t[e],oo(e)&&(en[e].isCSSVariable=!0)}function yc(t,{layout:e,layoutId:i}){return pi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!en[t]||t==="opacity")}const Qg={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},em=fi.length;function tm(t,e,i){let n="",s=!0;for(let o=0;o<em;o++){const r=fi[o],a=t[r];if(a===void 0)continue;let l=!0;if(typeof a=="number"?l=a===(r.startsWith("scale")?1:0):l=parseFloat(a)===0,!l||i){const c=Ql(a,Mo[r]);if(!l){s=!1;const u=Qg[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function $o(t,e,i){const{style:n,vars:s,transformOrigin:o}=t;let r=!1,a=!1;for(const l in e){const c=e[l];if(pi.has(l)){r=!0;continue}else if(oo(l)){s[l]=c;continue}else{const u=Ql(c,Mo[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=tm(e,t.transform,i):n.transform&&(n.transform="none")),a){const{originX:l="50%",originY:c="50%",originZ:u=0}=o;n.transformOrigin=`${l} ${c} ${u}`}}const jo=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function bc(t,e,i){for(const n in e)!Ve(e[n])&&!yc(n,i)&&(t[n]=e[n])}function im({transformTemplate:t},e){return Je(()=>{const i=jo();return $o(i,e,t),Object.assign({},i.vars,i.style)},[e])}function nm(t,e){const i=t.style||{},n={};return bc(n,i,t),Object.assign(n,im(t,e)),n}function sm(t,e){const i={},n=nm(t,e);return t.drag&&t.dragListener!==!1&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=t.drag===!0?"none":`pan-${t.drag==="x"?"y":"x"}`),t.tabIndex===void 0&&(t.onTap||t.onTapStart||t.whileTap)&&(i.tabIndex=0),i.style=n,i}const om={offset:"stroke-dashoffset",array:"stroke-dasharray"},rm={offset:"strokeDashoffset",array:"strokeDasharray"};function am(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?om:rm;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function wc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if($o(t,a,c),l){t.style.viewBox&&(t.attrs.viewBox=t.style.viewBox);return}t.attrs=t.style,t.style={};const{attrs:d,style:h}=t;d.transform&&(h.transform=d.transform,delete d.transform),(h.transform||d.transformOrigin)&&(h.transformOrigin=d.transformOrigin??"50% 50%",delete d.transformOrigin),h.transform&&(h.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete d.transformBox),e!==void 0&&(d.x=e),i!==void 0&&(d.y=i),n!==void 0&&(d.scale=n),s!==void 0&&am(d,s,o,r,!1)}const Sc=()=>({...jo(),attrs:{}}),Cc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function lm(t,e,i,n){const s=Je(()=>{const o=Sc();return wc(o,e,Cc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};bc(o,t.style,t),s.style={...o,...s.style}}return s}const cm=["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 Wo(t){return typeof t!="string"||t.includes("-")?!1:!!(cm.indexOf(t)>-1||/[A-Z]/u.test(t))}function dm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(Wo(i)?lm:sm)(n,o,r,i),c=Bg(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Je(()=>Ve(d)?d.get():d,[d]);return Xe(i,{...u,children:h})}}function Tc(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function Ho(t,e,i,n){if(typeof e=="function"){const[s,o]=Tc(n);e=e(i!==void 0?i:t.custom,s,o)}if(typeof e=="string"&&(e=t.variants&&t.variants[e]),typeof e=="function"){const[s,o]=Tc(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Kn(t){return Ve(t)?t.get():t}function um({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:hm(i,n,s,t),renderState:e()}}const kc=t=>(e,i)=>{const n=Le(Gn),s=Le(Pn),o=()=>um(t,e,n,s);return i?o():Mn(o)};function hm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Kn(o[h]);let{initial:r,animate:a}=t;const l=zn(t),c=pc(t);e&&c&&!l&&t.inherit!==!1&&(r===void 0&&(r=e.initial),a===void 0&&(a=e.animate));let u=i?i.initial===!1:!1;u=u||r===!1;const d=u?a:r;if(d&&typeof d!="boolean"&&!qn(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const _=Ho(t,h[p]);if(_){const{transitionEnd:v,transition:w,...y}=_;for(const C in y){let I=y[C];if(Array.isArray(I)){const A=u?I.length-1:0;I=I[A]}I!==null&&(s[C]=I)}for(const C in v)s[C]=v[C]}}}return s}function Go(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||yc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const fm={useVisualState:kc({scrapeMotionValuesFromProps:Go,createRenderState:jo})};function Ic(t,e,i){const n=Go(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=fi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const pm={useVisualState:kc({scrapeMotionValuesFromProps:Ic,createRenderState:Sc})};function gm(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Wo(n)?pm:fm,preloadedFeatures:t,useRender:dm(s),createVisualElement:e,Component:n};return Kg(r)}}function tn(t,e,i){const n=t.getProps();return Ho(n,e,i!==void 0?i:n.custom,t)}const qo=t=>Array.isArray(t);function mm(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,gi(i))}function vm(t){return qo(t)?t[t.length-1]||0:t}function _m(t,e){const i=tn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=vm(o[r]);mm(t,r,a)}}function ym(t){return!!(Ve(t)&&t.add)}function zo(t,e){const i=t.getValue("willChange");if(ym(i))return i.add(e);if(!i&&Et.WillChange){const n=new Et.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function Ec(t){return t.props[mc]}const bm=t=>t!==null;function wm(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(bm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Sm={type:"spring",stiffness:500,damping:25,restSpeed:10},Cm=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Tm={type:"keyframes",duration:.8},km={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Im=(t,{keyframes:e})=>e.length>2?Tm:pi.has(t)?t.startsWith("scale")?Cm(e[1]):Sm:km;function Em({when:t,delay:e,delayChildren:i,staggerChildren:n,staggerDirection:s,repeat:o,repeatType:r,repeatDelay:a,from:l,elapsed:c,...u}){return!!Object.keys(u).length}const Ko=(t,e,i,n={},s,o)=>r=>{const a=Do(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-pt(l);const u={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:e.getVelocity(),...a,delay:-c,onUpdate:h=>{e.set(h),a.onUpdate&&a.onUpdate(h)},onComplete:()=>{r(),a.onComplete&&a.onComplete()},name:t,motionValue:e,element:o?void 0:s};Em(a)||Object.assign(u,Im(t,u)),u.duration&&(u.duration=pt(u.duration)),u.repeatDelay&&(u.repeatDelay=pt(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let d=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(u.duration=0,u.delay===0&&(d=!0)),(Et.instantAnimations||Et.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=wm(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new So(u):new lg(u)};function Rm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Rc(t,e,{delay:i=0,transitionOverride:n,type:s}={}){let{transition:o=t.getDefaultTransition(),transitionEnd:r,...a}=e;n&&(o=n);const l=[],c=s&&t.animationState&&t.animationState.getState()[s];for(const u in a){const d=t.getValue(u,t.latestValues[u]??null),h=a[u];if(h===void 0||c&&Rm(c,u))continue;const p={delay:i,...Do(o||{},u)},_=d.get();if(_!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===_&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=Ec(t);if(y){const C=window.MotionHandoffAnimation(y,u,we);C!==null&&(p.startTime=C,v=!0)}}zo(t,u),d.start(Ko(u,d,h,t.shouldReduceMotion&&ql.has(u)?{type:!1}:p,t,v));const w=d.animation;w&&l.push(w)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&_m(t,r)})}),l}function Yo(t,e,i={}){var l;const n=tn(t,e,i.type==="exit"?(l=t.presenceContext)==null?void 0:l.custom:void 0);let{transition:s=t.getDefaultTransition()||{}}=n||{};i.transitionOverride&&(s=i.transitionOverride);const o=n?()=>Promise.all(Rc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Am(t,e,c,u,d,h,i)}:()=>Promise.resolve(),{when:a}=s;if(a){const[c,u]=a==="beforeChildren"?[o,r]:[r,o];return c().then(()=>u())}else return Promise.all([o(),r(i.delay)])}function Am(t,e,i=0,n=0,s=0,o=1,r){const a=[],l=t.variantChildren.size,c=(l-1)*s,u=typeof n=="function",d=u?h=>n(h,l):o===1?(h=0)=>h*s:(h=0)=>c-h*s;return Array.from(t.variantChildren).sort(xm).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(Yo(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function xm(t,e){return t.sortNodePosition(e)}function Lm(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>Yo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=Yo(t,e,i);else{const s=typeof e=="function"?tn(t,e,i.custom):e;n=Promise.all(Rc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Ac(t,e){if(!Array.isArray(e))return!1;const i=e.length;if(i!==t.length)return!1;for(let n=0;n<i;n++)if(e[n]!==t[n])return!1;return!0}const Dm=Bo.length;function xc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?xc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Dm;i++){const n=Bo[i],s=t.props[n];(Qi(s)||s===!1)&&(e[n]=s)}return e}const Om=[...Vo].reverse(),Mm=Vo.length;function Pm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Lm(t,i,n)))}function Nm(t){let e=Pm(t),i=Lc(),n=!0;const s=l=>(c,u)=>{var h;const d=tn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:_,...v}=d;c={...c,...v,..._}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=xc(t.parent)||{},d=[],h=new Set;let p={},_=1/0;for(let w=0;w<Mm;w++){const y=Om[w],C=i[y],I=c[y]!==void 0?c[y]:u[y],A=Qi(I),R=y===l?C.isActive:null;R===!1&&(_=w);let P=I===u[y]&&I!==c[y]&&A;if(P&&n&&t.manuallyAnimateOnMount&&(P=!1),C.protectedKeys={...p},!C.isActive&&R===null||!I&&!C.prevProp||qn(I)||typeof I=="boolean")continue;const T=Fm(C.prevProp,I);let k=T||y===l&&C.isActive&&!P&&A||w>_&&A,g=!1;const m=Array.isArray(I)?I:[I];let f=m.reduce(s(y),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,E={...S,...f},x=O=>{k=!0,h.has(O)&&(g=!0,h.delete(O)),C.needsAnimating[O]=!0;const F=t.getValue(O);F&&(F.liveStyle=!1)};for(const O in E){const F=f[O],W=S[O];if(p.hasOwnProperty(O))continue;let $=!1;qo(F)&&qo(W)?$=!Ac(F,W):$=F!==W,$?F!=null?x(O):h.add(O):F!==void 0&&h.has(O)?x(O):C.protectedKeys[O]=!0}C.prevProp=I,C.prevResolvedValues=f,C.isActive&&(p={...p,...f}),n&&t.blockInitialAnimation&&(k=!1),k&&(!(P&&T)||g)&&d.push(...m.map(O=>({animation:O,options:{type:y}})))}if(h.size){const w={};if(typeof c.initial!="boolean"){const y=tn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(w.transition=y.transition)}h.forEach(y=>{const C=t.getBaseTarget(y),I=t.getValue(y);I&&(I.liveStyle=!0),w[y]=C??null}),d.push({animation:w})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var p;return(p=h.animationState)==null?void 0:p.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=Lc(),n=!0}}}function Fm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Ac(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Lc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Vt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Vm extends Vt{constructor(e){super(e),e.animationState||(e.animationState=Nm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();qn(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:e}=this.node.getProps(),{animate:i}=this.node.prevProps||{};e!==i&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),(e=this.unmountControls)==null||e.call(this)}}let Bm=0;class Um extends Vt{constructor(){super(...arguments),this.id=Bm++}update(){if(!this.node.presenceContext)return;const{isPresent:e,onExitComplete:i}=this.node.presenceContext,{isPresent:n}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===n)return;const s=this.node.animationState.setActive("exit",!e);i&&!e&&s.then(()=>{i(this.id)})}mount(){const{register:e,onExitComplete:i}=this.node.presenceContext||{};i&&i(this.id),e&&(this.unmount=e(this.id))}unmount(){}}const $m={animation:{Feature:Vm},exit:{Feature:Um}};function nn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function sn(t){return{point:{x:t.pageX,y:t.pageY}}}const jm=t=>e=>No(e)&&t(e,sn(e));function on(t,e,i,n){return nn(t,e,jm(i),n)}function Dc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Wm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Hm(t,e){if(!e)return t;const i=e({x:t.left,y:t.top}),n=e({x:t.right,y:t.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}const Oc=1e-4,Gm=1-Oc,qm=1+Oc,Mc=.01,zm=0-Mc,Km=0+Mc;function $e(t){return t.max-t.min}function Ym(t,e,i){return Math.abs(t-e)<=i}function Pc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=$e(i)/$e(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Gm&&t.scale<=qm||isNaN(t.scale))&&(t.scale=1),(t.translate>=zm&&t.translate<=Km||isNaN(t.translate))&&(t.translate=0)}function rn(t,e,i,n){Pc(t.x,e.x,i.x,n?n.originX:void 0),Pc(t.y,e.y,i.y,n?n.originY:void 0)}function Nc(t,e,i){t.min=i.min+e.min,t.max=t.min+$e(e)}function Xm(t,e,i){Nc(t.x,e.x,i.x),Nc(t.y,e.y,i.y)}function Fc(t,e,i){t.min=e.min-i.min,t.max=t.min+$e(e)}function an(t,e,i){Fc(t.x,e.x,i.x),Fc(t.y,e.y,i.y)}const Vc=()=>({translate:0,scale:1,origin:0,originPoint:0}),_i=()=>({x:Vc(),y:Vc()}),Bc=()=>({min:0,max:0}),Ie=()=>({x:Bc(),y:Bc()});function Qe(t){return[t("x"),t("y")]}function Xo(t){return t===void 0||t===1}function Jo({scale:t,scaleX:e,scaleY:i}){return!Xo(t)||!Xo(e)||!Xo(i)}function Zt(t){return Jo(t)||Uc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Uc(t){return $c(t.x)||$c(t.y)}function $c(t){return t&&t!=="0%"}function Yn(t,e,i){const n=t-i,s=e*n;return i+s}function jc(t,e,i,n,s){return s!==void 0&&(t=Yn(t,s,n)),Yn(t,i,n)+e}function Zo(t,e=0,i=1,n,s){t.min=jc(t.min,e,i,n,s),t.max=jc(t.max,e,i,n,s)}function Wc(t,{x:e,y:i}){Zo(t.x,e.translate,e.scale,e.originPoint),Zo(t.y,i.translate,i.scale,i.originPoint)}const Hc=.999999999999,Gc=1.0000000000001;function Jm(t,e,i,n=!1){const s=i.length;if(!s)return;e.x=e.y=1;let o,r;for(let a=0;a<s;a++){o=i[a],r=o.projectionDelta;const{visualElement:l}=o.options;l&&l.props.style&&l.props.style.display==="contents"||(n&&o.options.layoutScroll&&o.scroll&&o!==o.root&&bi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Wc(t,r)),n&&Zt(o.latestValues)&&bi(t,o.latestValues))}e.x<Gc&&e.x>Hc&&(e.x=1),e.y<Gc&&e.y>Hc&&(e.y=1)}function yi(t,e){t.min=t.min+e,t.max=t.max+e}function qc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);Zo(t,e,i,o,n)}function bi(t,e){qc(t.x,e.x,e.scaleX,e.scale,e.originX),qc(t.y,e.y,e.scaleY,e.scale,e.originY)}function zc(t,e){return Dc(Hm(t.getBoundingClientRect(),e))}function Zm(t,e,i){const n=zc(t,i),{scroll:s}=e;return s&&(yi(n.x,s.offset.x),yi(n.y,s.offset.y)),n}const Kc=({current:t})=>t?t.ownerDocument.defaultView:null,Yc=(t,e)=>Math.abs(t-e);function Qm(t,e){const i=Yc(t.x,e.x),n=Yc(t.y,e.y);return Math.sqrt(i**2+n**2)}class Xc{constructor(e,i,{transformPagePoint:n,contextWindow:s=window,dragSnapToOrigin:o=!1,distanceThreshold:r=3}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const h=er(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,_=Qm(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!_)return;const{point:v}=h,{timestamp:w}=Pe;this.history.push({...v,timestamp:w});const{onStart:y,onMove:C}=this.handlers;p||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Qo(p,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:w}=this.handlers;if(this.dragSnapToOrigin&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=er(h.type==="pointercancel"?this.lastMoveEventInfo:Qo(p,this.transformPagePoint),this.history);this.startEvent&&_&&_(h,y),v&&v(h,y)},!No(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=sn(e),l=Qo(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,er(l,this.history)),this.removeListeners=Wi(on(this.contextWindow,"pointermove",this.handlePointerMove),on(this.contextWindow,"pointerup",this.handlePointerUp),on(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function Qo(t,e){return e?{point:e(t.point)}:t}function Jc(t,e){return{x:t.x-e.x,y:t.y-e.y}}function er({point:t},e){return{point:t,delta:Jc(t,Zc(e)),offset:Jc(t,ev(e)),velocity:tv(e,.1)}}function ev(t){return t[0]}function Zc(t){return t[t.length-1]}function tv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Zc(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>pt(e)));)i--;if(!n)return{x:0,y:0};const o=gt(s.timestamp-n.timestamp);if(o===0)return{x:0,y:0};const r={x:(s.x-n.x)/o,y:(s.y-n.y)/o};return r.x===1/0&&(r.x=0),r.y===1/0&&(r.y=0),r}function iv(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Ce(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Ce(i,t,n.max):Math.min(t,i)),t}function Qc(t,e,i){return{min:e!==void 0?t.min+e:void 0,max:i!==void 0?t.max+i-(t.max-t.min):void 0}}function nv(t,{top:e,left:i,bottom:n,right:s}){return{x:Qc(t.x,i,s),y:Qc(t.y,e,n)}}function ed(t,e){let i=e.min-t.min,n=e.max-t.max;return e.max-e.min<t.max-t.min&&([i,n]=[n,i]),{min:i,max:n}}function sv(t,e){return{x:ed(t.x,e.x),y:ed(t.y,e.y)}}function ov(t,e){let i=.5;const n=$e(t),s=$e(e);return s>n?i=Hi(e.min,e.max-n,t.min):n>s&&(i=Hi(t.min,t.max-s,e.min)),It(0,1,i)}function rv(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const tr=.35;function av(t=tr){return t===!1?t=0:t===!0&&(t=tr),{x:td(t,"left","right"),y:td(t,"top","bottom")}}function td(t,e,i){return{min:id(t,e),max:id(t,i)}}function id(t,e){return typeof t=="number"?t:t[e]||0}const lv=new WeakMap;class cv{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=Ie(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=e}start(e,{snapToCursor:i=!1,distanceThreshold:n}={}){const{presenceContext:s}=this.visualElement;if(s&&s.isPresent===!1)return;const o=d=>{const{dragSnapToOrigin:h}=this.getProps();h?this.pauseAnimation():this.stopAnimation(),i&&this.snapToCursor(sn(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:_,onDragStart:v}=this.getProps();if(p&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Cg(p),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),Qe(y=>{let C=this.getAxisMotionValue(y).get()||0;if(mt.test(C)){const{projection:I}=this.visualElement;if(I&&I.layout){const A=I.layout.layoutBox[y];A&&(C=$e(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&we.postRender(()=>v(d,h)),zo(this.visualElement,"transform");const{animationState:w}=this.visualElement;w&&w.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:_,onDirectionLock:v,onDrag:w}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=h;if(_&&this.currentDirection===null){this.currentDirection=dv(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),this.visualElement.render(),w&&w(d,h)},l=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h,this.stop(d,h),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>Qe(d=>{var h;return this.getAnimationState(d)==="paused"&&((h=this.getAxisMotionValue(d).animation)==null?void 0:h.play())}),{dragSnapToOrigin:u}=this.getProps();this.panSession=new Xc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Kc(this.visualElement)})}stop(e,i){const n=e||this.latestPointerEvent,s=i||this.latestPanInfo,o=this.isDragging;if(this.cancel(),!o||!s||!n)return;const{velocity:r}=s;this.startAnimation(r);const{onDragEnd:a}=this.getProps();a&&we.postRender(()=>a(n,s))}cancel(){this.isDragging=!1;const{projection:e,animationState:i}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:n}=this.getProps();!n&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),i&&i.setActive("whileDrag",!1)}updateAxis(e,i,n){const{drag:s}=this.getProps();if(!n||!Xn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=iv(r,this.constraints[e],this.elastic[e])),o.set(r)}resolveConstraints(){var o;const{dragConstraints:e,dragElastic:i}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(o=this.visualElement.projection)==null?void 0:o.layout,s=this.constraints;e&&vi(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=nv(n.layoutBox,e):this.constraints=!1,this.elastic=av(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&Qe(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=rv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!vi(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Zm(n,s.root,this.visualElement.getTransformPagePoint());let r=sv(s.layout.layoutBox,o);if(i){const a=i(Wm(r));this.hasMutatedConstraints=!!a,a&&(r=Dc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=Qe(u=>{if(!Xn(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,p=s?40:1e7,_={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,_)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return zo(this.visualElement,e),n.start(Ko(e,n,0,i,this.visualElement,!1))}stopAnimation(){Qe(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){Qe(e=>{var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.pause()})}getAnimationState(e){var i;return(i=this.getAxisMotionValue(e).animation)==null?void 0:i.state}getAxisMotionValue(e){const i=`_drag${e.toUpperCase()}`,n=this.visualElement.getProps(),s=n[i];return s||this.visualElement.getValue(e,(n.initial?n.initial[e]:void 0)||0)}snapToCursor(e){Qe(i=>{const{drag:n}=this.getProps();if(!Xn(i,n,this.currentDirection))return;const{projection:s}=this.visualElement,o=this.getAxisMotionValue(i);if(s&&s.layout){const{min:r,max:a}=s.layout.layoutBox[i];o.set(e[i]-Ce(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!vi(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};Qe(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=ov({min:l,max:l},this.constraints[r])}});const{transformTemplate:o}=this.visualElement.getProps();this.visualElement.current.style.transform=o?o({},""):"none",n.root&&n.root.updateScroll(),n.updateLayout(),this.resolveConstraints(),Qe(r=>{if(!Xn(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Ce(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;lv.set(this.visualElement,this);const e=this.visualElement.current,i=on(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();vi(l)&&l.current&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,o=s.addEventListener("measure",n);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),we.read(n);const r=nn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(Qe(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=tr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Xn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function dv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class uv extends Vt{constructor(e){super(e),this.removeGroupControls=Ze,this.removeListeners=Ze,this.controls=new cv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Ze}unmount(){this.removeGroupControls(),this.removeListeners()}}const nd=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class hv extends Vt{constructor(){super(...arguments),this.removePointerDownListener=Ze}onPointerDown(e){this.session=new Xc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Kc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:nd(e),onStart:nd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=on(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const Jn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function sd(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const ln={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=sd(t,e.target.x),n=sd(t,e.target.y);return`${i}% ${n}%`}},fv={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Ft.parse(t);if(s.length>5)return n;const o=Ft.createTransformer(t),r=typeof s[0]!="number"?1:0,a=i.x.scale*e.x,l=i.y.scale*e.y;s[0+r]/=a,s[1+r]/=l;const c=Ce(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let od=!1;class pv extends rt{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;Zg(gv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),od&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Jn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,od=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||we.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Po.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n}=this.props,{projection:s}=e;s&&(s.scheduleCheckAfterUnmount(),i&&i.group&&i.group.remove(s),n&&n.deregister&&n.deregister(s))}safeToRemove(){const{safeToRemove:e}=this.props;e&&e()}render(){return null}}function rd(t){const[e,i]=lc(),n=Le(Ys);return D(pv,{...t,layoutGroup:n,switchLayoutGroup:Le(vc),isPresent:e,safeToRemove:i})}const gv={borderRadius:{...ln,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:ln,borderTopRightRadius:ln,borderBottomLeftRadius:ln,borderBottomRightRadius:ln,boxShadow:fv};function mv(t,e,i){const n=Ve(t)?t:gi(t);return n.start(Ko("",n,e,i)),n.animation}const vv=(t,e)=>t.depth-e.depth;class _v{constructor(){this.children=[],this.isDirty=!1}add(e){Js(this.children,e),this.isDirty=!0}remove(e){Zs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(vv),this.isDirty=!1,this.children.forEach(e)}}function yv(t,e){const i=Ge.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const ad=["TopLeft","TopRight","BottomLeft","BottomRight"],bv=ad.length,ld=t=>typeof t=="string"?parseFloat(t):t,cd=t=>typeof t=="number"||K.test(t);function wv(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,Sv(n)),t.opacityExit=Ce(e.opacity??1,0,Cv(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<bv;r++){const a=`border${ad[r]}Radius`;let l=dd(e,a),c=dd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||cd(l)===cd(c)?(t[a]=Math.max(Ce(ld(l),ld(c),n),0),(mt.test(c)||mt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Ce(e.rotate||0,i.rotate||0,n))}function dd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Sv=ud(0,.5,cl),Cv=ud(.5,.95,Ze);function ud(t,e,i){return n=>n<t?0:n>e?1:i(Hi(t,e,n))}function hd(t,e){t.min=e.min,t.max=e.max}function et(t,e){hd(t.x,e.x),hd(t.y,e.y)}function fd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function pd(t,e,i,n,s){return t-=e,t=Yn(t,1/i,n),s!==void 0&&(t=Yn(t,1/s,n)),t}function Tv(t,e=0,i=1,n=.5,s,o=t,r=t){if(mt.test(e)&&(e=parseFloat(e),e=Ce(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Ce(o.min,o.max,n);t===o&&(a-=e),t.min=pd(t.min,e,i,a,s),t.max=pd(t.max,e,i,a,s)}function gd(t,e,[i,n,s],o,r){Tv(t,e[i],e[n],e[s],e.scale,o,r)}const kv=["x","scaleX","originX"],Iv=["y","scaleY","originY"];function md(t,e,i,n){gd(t.x,e,kv,i?i.x:void 0,n?n.x:void 0),gd(t.y,e,Iv,i?i.y:void 0,n?n.y:void 0)}function vd(t){return t.translate===0&&t.scale===1}function _d(t){return vd(t.x)&&vd(t.y)}function yd(t,e){return t.min===e.min&&t.max===e.max}function Ev(t,e){return yd(t.x,e.x)&&yd(t.y,e.y)}function bd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function wd(t,e){return bd(t.x,e.x)&&bd(t.y,e.y)}function Sd(t){return $e(t.x)/$e(t.y)}function Cd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Rv{constructor(){this.members=[]}add(e){Js(this.members,e),e.scheduleRender()}remove(e){if(Zs(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){const i=this.members[this.members.length-1];i&&this.promote(i)}}relegate(e){const i=this.members.findIndex(s=>e===s);if(i===0)return!1;let n;for(let s=i;s>=0;s--){const o=this.members[s];if(o.isPresent!==!1){n=o;break}}return n?(this.promote(n),!0):!1}promote(e,i){const n=this.lead;if(e!==n&&(this.prevLead=n,this.lead=e,e.show(),n)){n.instance&&n.scheduleRender(),e.scheduleRender(),e.resumeFrom=n,i&&(e.resumeFrom.preserveOpacity=!0),n.snapshot&&(e.snapshot=n.snapshot,e.snapshot.latestValues=n.animationValues||n.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);const{crossfade:s}=e.options;s===!1&&n.hide()}}exitAnimationComplete(){this.members.forEach(e=>{const{options:i,resumingFrom:n}=e;i.onExitComplete&&i.onExitComplete(),n&&n.options.onExitComplete&&n.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Av(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:p,skewY:_}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),p&&(n+=`skewX(${p}deg) `),_&&(n+=`skewY(${_}deg) `)}const a=t.x.scale*e.x,l=t.y.scale*e.y;return(a!==1||l!==1)&&(n+=`scale(${a}, ${l})`),n||"none"}const ir=["","X","Y","Z"],xv=1e3;let Lv=0;function nr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Td(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=Ec(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",we,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&Td(n)}function kd({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Lv++,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(Mv),this.nodes.forEach(Vv),this.nodes.forEach(Bv),this.nodes.forEach(Pv)},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 _v)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new to),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=ac(r)&&!Ag(r),this.instance=r;const{layoutId:a,layout:l,visualElement:c}=this.options;if(c&&!c.current&&c.mount(r),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(l||a)&&(this.isLayoutDirty=!0),t){let u,d=0;const h=()=>this.root.updateBlockedByResize=!1;we.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=yv(h,250),Jn.hasAnimatedSinceResize&&(Jn.hasAnimatedSinceResize=!1,this.nodes.forEach(Rd)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const _=this.options.transition||c.getDefaultTransition()||Hv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:w}=c.getProps(),y=!this.targetLayout||!wd(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const I={...Do(_,"layout"),onPlay:v,onComplete:w};(c.shouldReduceMotion||this.options.layoutRoot)&&(I.delay=0,I.type=!1),this.startAnimation(I),this.setAnimationOrigin(u,C)}else d||Rd(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Pt(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(Uv),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&&Td(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const d=this.path[u];d.shouldResetTransform=!0,d.updateScroll("snapshot"),d.options.layoutRoot&&d.willUpdate(!1)}const{layoutId:a,layout:l}=this.options;if(a===void 0&&!l)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),r&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(Id);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Ed);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Fv),this.nodes.forEach(Dv),this.nodes.forEach(Ov)):this.nodes.forEach(Ed),this.clearAllSnapshots();const a=Ge.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,so.update.process(Pe),so.preRender.process(Pe),so.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Po.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Nv),this.sharedNodes.forEach($v)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,we.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){we.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!$e(this.snapshot.measuredBox.x)&&!$e(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=Ie(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:a}=this.options;a&&a.notify("LayoutMeasure",this.layout.layoutBox,r?r.layoutBox:void 0)}updateScroll(r="measure"){let a=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===r&&(a=!1),a&&this.instance){const l=n(this.instance);this.scroll={animationId:this.root.animationId,phase:r,isRoot:l,offset:i(this.instance),wasRoot:this.scroll?this.scroll.isRoot:l}}}resetTransform(){if(!s)return;const r=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,a=this.projectionDelta&&!_d(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||Zt(this.latestValues)||u)&&(s(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(r=!0){const a=this.measurePageBox();let l=this.removeElementScroll(a);return r&&(l=this.removeTransform(l)),Gv(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return Ie();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(qv))){const{scroll:u}=this.root;u&&(yi(a.x,u.offset.x),yi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=Ie();if(et(a,r),(l=this.scroll)!=null&&l.wasRoot)return a;for(let c=0;c<this.path.length;c++){const u=this.path[c],{scroll:d,options:h}=u;u!==this.root&&d&&h.layoutScroll&&(d.wasRoot&&et(a,r),yi(a.x,d.offset.x),yi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=Ie();et(l,r);for(let c=0;c<this.path.length;c++){const u=this.path[c];!a&&u.options.layoutScroll&&u.scroll&&u!==u.root&&bi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&bi(l,u.latestValues)}return Zt(this.latestValues)&&bi(l,this.latestValues),l}removeTransform(r){const a=Ie();et(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;Jo(c.latestValues)&&c.updateSnapshot();const u=Ie(),d=c.measurePageBox();et(u,d),md(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&md(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Pe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Pe.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ie(),this.relativeTargetOrigin=Ie(),an(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=Ie(),this.targetWithTransforms=Ie()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),Xm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):et(this.target,this.layout.layoutBox),Wc(this.target,this.targetDelta)):et(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const p=this.getClosestProjectingParent();p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=Ie(),this.relativeTargetOrigin=Ie(),an(this.relativeTargetOrigin,this.target,p.target),et(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Jo(this.parent.latestValues)||Uc(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===Pe.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;et(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Jm(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=Ie());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(fd(this.prevProjectionDelta.x,this.projectionDelta.x),fd(this.prevProjectionDelta.y,this.projectionDelta.y)),rn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Cd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Cd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",p))}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=_i(),this.projectionDelta=_i(),this.projectionDeltaWithTransform=_i()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=_i();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=Ie(),p=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=p!==_,w=this.getStack(),y=!w||w.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Wv));this.animationProgress=0;let I;this.mixTargetDelta=A=>{const R=A/1e3;Ad(d.x,r.x,R),Ad(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(an(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),jv(this.relativeTarget,this.relativeTargetOrigin,h,R),I&&Ev(this.relativeTarget,I)&&(this.isProjectionDirty=!1),I||(I=Ie()),et(I,this.relativeTarget)),v&&(this.animationValues=u,wv(u,c,this.latestValues,R,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Pt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=we.update(()=>{Jn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=gi(0)),this.currentAnimation=mv(this.motionValue,[0,1e3],{...r,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),r.onUpdate&&r.onUpdate(u)},onStop:()=>{},onComplete:()=>{r.onComplete&&r.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const r=this.getStack();r&&r.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(xv),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const r=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:u}=r;if(!(!a||!l||!c)){if(this!==r&&this.layout&&c&&Md(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||Ie();const d=$e(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=$e(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}et(a,l),bi(a,u),rn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Rv),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 u=0;u<ir.length;u++)nr(`rotate${ir[u]}`,r,c,this.animationValues),nr(`skew${ir[u]}`,r,c,this.animationValues);r.render();for(const u in c)r.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);r.scheduleRender()}applyProjectionStyles(r,a){if(!this.instance||this.isSVG)return;if(!this.isVisible){r.visibility="hidden";return}const l=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,r.visibility="",r.opacity="",r.pointerEvents=Kn(a==null?void 0:a.pointerEvents)||"",r.transform=l?l(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(r.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,r.pointerEvents=Kn(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!Zt(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=Av(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:p}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${p.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const _ in en){if(u[_]===void 0)continue;const{correct:v,applyTo:w,isCSSVariable:y}=en[_],C=d==="none"?u[_]:v(u[_],c);if(w){const I=w.length;for(let A=0;A<I;A++)r[w[A]]=C}else y?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Kn(a==null?void 0:a.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(r=>{var a;return(a=r.currentAnimation)==null?void 0:a.stop()}),this.root.nodes.forEach(Id),this.root.sharedNodes.clear()}}}function Dv(t){t.updateLayout()}function Ov(t){var i;const e=((i=t.resumeFrom)==null?void 0:i.snapshot)||t.snapshot;if(t.isLead()&&t.layout&&e&&t.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=t.layout,{animationType:o}=t.options,r=e.source!==t.layout.source;o==="size"?Qe(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=$e(h);h.min=n[d].min,h.max=h.min+p}):Md(o,e.layoutBox,n)&&Qe(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=$e(n[d]);h.max=h.min+p,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+p)});const a=_i();rn(a,n,e.layoutBox);const l=_i();r?rn(l,t.applyTransform(s,!0),e.measuredBox):rn(l,n,e.layoutBox);const c=!_d(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:p}=d;if(h&&p){const _=Ie();an(_,e.layoutBox,h.layoutBox);const v=Ie();an(v,n,p.layoutBox),wd(_,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=_,t.relativeParent=d)}}}t.notifyListeners("didUpdate",{layout:n,snapshot:e,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeLayoutChanged:u})}else if(t.isLead()){const{onExitComplete:n}=t.options;n&&n()}t.options.transition=void 0}function Mv(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 Pv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Nv(t){t.clearSnapshot()}function Id(t){t.clearMeasurements()}function Ed(t){t.isLayoutDirty=!1}function Fv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Rd(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Vv(t){t.resolveTargetDelta()}function Bv(t){t.calcProjection()}function Uv(t){t.resetSkewAndRotation()}function $v(t){t.removeLeadSnapshot()}function Ad(t,e,i){t.translate=Ce(e.translate,0,i),t.scale=Ce(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function xd(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function jv(t,e,i,n){xd(t.x,e.x,i.x,n),xd(t.y,e.y,i.y,n)}function Wv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Hv={duration:.45,ease:[.4,0,.1,1]},Ld=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Dd=Ld("applewebkit/")&&!Ld("chrome/")?Math.round:Ze;function Od(t){t.min=Dd(t.min),t.max=Dd(t.max)}function Gv(t){Od(t.x),Od(t.y)}function Md(t,e,i){return t==="position"||t==="preserve-aspect"&&!Ym(Sd(e),Sd(i),.2)}function qv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const zv=kd({attachResizeListener:(t,e)=>nn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),sr={current:void 0},Pd=kd({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!sr.current){const t=new zv({});t.mount(window),t.setOptions({layoutScroll:!0}),sr.current=t}return sr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Kv={pan:{Feature:hv},drag:{Feature:uv,ProjectionNode:Pd,MeasureLayout:rd}};function Nd(t,e,i){const{props:n}=t;t.animationState&&n.whileHover&&t.animationState.setActive("whileHover",i==="Start");const s="onHover"+i,o=n[s];o&&we.postRender(()=>o(e,sn(e)))}class Yv extends Vt{mount(){const{current:e}=this.node;e&&(this.unmount=Tg(e,(i,n)=>(Nd(this.node,n,"Start"),s=>Nd(this.node,s,"End"))))}unmount(){}}class Xv extends Vt{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=Wi(nn(this.node.current,"focus",()=>this.onFocus()),nn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Fd(t,e,i){const{props:n}=t;if(t.current instanceof HTMLButtonElement&&t.current.disabled)return;t.animationState&&n.whileTap&&t.animationState.setActive("whileTap",i==="Start");const s="onTap"+(i==="End"?"":i),o=n[s];o&&we.postRender(()=>o(e,sn(e)))}class Jv extends Vt{mount(){const{current:e}=this.node;e&&(this.unmount=Rg(e,(i,n)=>(Fd(this.node,n,"Start"),(s,{success:o})=>Fd(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const or=new WeakMap,rr=new WeakMap,Zv=t=>{const e=or.get(t.target);e&&e(t)},Qv=t=>{t.forEach(Zv)};function e_({root:t,...e}){const i=t||document;rr.has(i)||rr.set(i,{});const n=rr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(Qv,{root:t,...e})),n[s]}function t_(t,e,i){const n=e_(e);return or.set(t,i),n.observe(t),()=>{or.delete(t),n.unobserve(t)}}const i_={some:0,all:1};class n_ extends Vt{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:e={}}=this.node.getProps(),{root:i,margin:n,amount:s="some",once:o}=e,r={root:i?i.current:void 0,rootMargin:n,threshold:typeof s=="number"?s:i_[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,o&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:d}=this.node.getProps(),h=c?u:d;h&&h(l)};return t_(this.node.current,r,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:e,prevProps:i}=this.node;["amount","margin","root"].some(s_(e,i))&&this.startObserver()}unmount(){}}function s_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const o_={inView:{Feature:n_},tap:{Feature:Jv},focus:{Feature:Xv},hover:{Feature:Yv}},r_={layout:{ProjectionNode:Pd,MeasureLayout:rd}},ar={current:null},Vd={current:!1};function a_(){if(Vd.current=!0,!!Xs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>ar.current=t.matches;t.addEventListener("change",e),e()}else ar.current=!1}const l_=new WeakMap;function c_(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ve(s))t.addValue(n,s);else if(Ve(o))t.addValue(n,gi(s,{owner:t}));else if(o!==s)if(t.hasValue(n)){const r=t.getValue(n);r.liveStyle===!0?r.jump(s):r.hasAnimated||r.set(s)}else{const r=t.getStaticValue(n);t.addValue(n,gi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const Bd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class d_{scrapeMotionValuesFromProps(e,i,n){return{}}constructor({parent:e,props:i,presenceContext:n,reducedMotionConfig:s,blockInitialAnimation:o,visualState:r},a={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=xo,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const h=Ge.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,we.render(this.render,!1,!0))};const{latestValues:l,renderState:c}=r;this.latestValues=l,this.baseTarget={...l},this.initialValues=i.initial?{...l}:{},this.renderState=c,this.parent=e,this.props=i,this.presenceContext=n,this.depth=e?e.depth+1:0,this.reducedMotionConfig=s,this.options=a,this.blockInitialAnimation=!!o,this.isControllingVariants=zn(i),this.isVariantNode=pc(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const p=d[h];l[h]!==void 0&&Ve(p)&&p.set(l[h],!1)}}mount(e){this.current=e,l_.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((i,n)=>this.bindToMotionValue(n,i)),Vd.current||a_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ar.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Pt(this.notifyUpdate),Pt(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const e in this.events)this.events[e].clear();for(const e in this.features){const i=this.features[e];i&&(i.unmount(),i.isMounted=!1)}this.current=null}bindToMotionValue(e,i){this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();const n=pi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&we.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),o=i.on("renderRequest",this.scheduleRender);let r;window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,e,i)),this.valueSubscriptions.set(e,()=>{s(),o(),r&&r(),i.owner&&i.stop()})}sortNodePosition(e){return!this.current||!this.sortInstanceNodePosition||this.type!==e.type?0:this.sortInstanceNodePosition(this.current,e.current)}updateFeatures(){let e="animation";for(e in mi){const i=mi[e];if(!i)continue;const{isEnabled:n,Feature:s}=i;if(!this.features[e]&&s&&n(this.props)&&(this.features[e]=new s(this)),this.features[e]){const o=this.features[e];o.isMounted?o.update():(o.mount(),o.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Ie()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,i){this.latestValues[e]=i}update(e,i){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=i;for(let n=0;n<Bd.length;n++){const s=Bd[n];this.propEventSubscriptions[s]&&(this.propEventSubscriptions[s](),delete this.propEventSubscriptions[s]);const o="on"+s,r=e[o];r&&(this.propEventSubscriptions[s]=this.on(s,r))}this.prevMotionValues=c_(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){const i=this.getClosestVariantNode();if(i)return i.variantChildren&&i.variantChildren.add(e),()=>i.variantChildren.delete(e)}addValue(e,i){const n=this.values.get(e);i!==n&&(n&&this.removeValue(e),this.bindToMotionValue(e,i),this.values.set(e,i),this.latestValues[e]=i.get())}removeValue(e){this.values.delete(e);const i=this.valueSubscriptions.get(e);i&&(i(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,i){if(this.props.values&&this.props.values[e])return this.props.values[e];let n=this.values.get(e);return n===void 0&&i!==void 0&&(n=gi(i===null?void 0:i,{owner:this}),this.addValue(e,n)),n}readValue(e,i){let n=this.latestValues[e]!==void 0||!this.current?this.latestValues[e]:this.getBaseTargetFromProps(this.props,e)??this.readValueFromInstance(this.current,e,this.options);return n!=null&&(typeof n=="string"&&(Qa(n)||tl(n))?n=parseFloat(n):!Lg(n)&&Ft.test(i)&&(n=Zl(e,i)),this.setBaseTarget(e,Ve(n)?n.get():n)),Ve(n)?n.get():n}setBaseTarget(e,i){this.baseTarget[e]=i}getBaseTarget(e){var o;const{initial:i}=this.props;let n;if(typeof i=="string"||typeof i=="object"){const r=Ho(this.props,i,(o=this.presenceContext)==null?void 0:o.custom);r&&(n=r[e])}if(i&&n!==void 0)return n;const s=this.getBaseTargetFromProps(this.props,e);return s!==void 0&&!Ve(s)?s:this.initialValues[e]!==void 0&&n===void 0?void 0:this.baseTarget[e]}on(e,i){return this.events[e]||(this.events[e]=new to),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Ud extends d_{constructor(){super(...arguments),this.KeyframeResolver=yg}sortInstanceNodePosition(e,i){return e.compareDocumentPosition(i)&2?1:-1}getBaseTargetFromProps(e,i){return e.style?e.style[i]:void 0}removeValueFromRenderState(e,{vars:i,style:n}){delete i[e],delete n[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:e}=this.props;Ve(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function $d(t,{style:e,vars:i},n,s){const o=t.style;let r;for(r in e)o[r]=e[r];s==null||s.applyProjectionStyles(o,n);for(r in i)o.setProperty(r,i[r])}function u_(t){return window.getComputedStyle(t)}class h_ extends Ud{constructor(){super(...arguments),this.type="html",this.renderInstance=$d}readValueFromInstance(e,i){var n;if(pi.has(i))return(n=this.projection)!=null&&n.isProjecting?ko(i):Bp(e,i);{const s=u_(e),o=(oo(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return zc(e,i)}build(e,i,n){$o(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return Go(e,i,n)}}const jd=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 f_(t,e,i,n){$d(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(jd.has(s)?s:Uo(s),e.attrs[s])}class p_ extends Ud{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Ie}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(pi.has(i)){const n=Jl(i);return n&&n.default||0}return i=jd.has(i)?i:Uo(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return Ic(e,i,n)}build(e,i,n){wc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){f_(e,i,n,s)}mount(e){this.isSVGTag=Cc(e.tagName),super.mount(e)}}const g_=(t,e)=>Wo(t)?new p_(e):new h_(e,{allowProjection:t!==ht}),m_=gm({...$m,...o_,...Kv,...r_},g_),wi=$g(m_),v_=["agent-id","debug","environment","position","version-id","trickle-ice","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","region","skip-last-voice-sdk-id"],cn="widget-layout-id";function Wd(t){var e,i,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(i=Wd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function Rt(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=Wd(t))&&(n&&(n+=" "),n+=e);return n}const __=Ln("listening"),lr=()=>Ja(__);function y_(t){var i;if(typeof t!="object"||t===null)return!1;const e=t;return e.method==="ai_conversation"&&((i=e.params)==null?void 0:i.type)==="widget_settings"&&typeof e.params.widget_settings=="object"}const Zn={theme:"dark",audio_visualizer_config:{color:"verdant",preset:"roundBars"},start_call_text:"Let's chat",default_state:"collapsed",position:"fixed",view_history_url:null,report_issue_url:null,give_feedback_url:null,agent_thinking_text:"Thinking...",speak_to_interrupt_text:"Speak to interrupt",logo_icon_url:null},Hd=Ln(Zn),b_=()=>{const t=On(Hd);return He(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Zn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Zn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Zn.speak_to_interrupt_text),i}),[t])},Qt=()=>Ks(Hd),Gd=({size:t="large",className:e})=>{const i=Qt(),[n]=lr();return D("h1",{className:Rt({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},qd=({stream:t,chatMode:e})=>{const i=de(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:D("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
10
10
  * audioMotion-analyzer
11
11
  * High-resolution real-time graphic audio spectrum analyzer JS module
12
12
  *
13
13
  * @version 4.5.1
14
14
  * @author Henrique Avila Vianna <hvianna@gmail.com> <https://henriquevianna.com>
15
15
  * @license AGPL-3.0-or-later
16
- */const p_="4.5.1",ar=Math.PI,bi=2*ar,lr=ar/2,Bd=8.17579892,$d="dual-combined",Qn="dual-horizontal",xt="single",vt="dual-vertical",jd="bar-index",Hd="bar-level",Zn="gradient",Gd=60,Wd="click",g_="fullscreenchange",qd="resize",m_="#111",zd="",Kd="A",Yd="B",Xd="C",Jd="D",Qd="468",es="sans-serif",v_="#0f0",__="#7f7f7f22",wi=10,Zd="create",eu="fschange",y_="lores",b_=qd,cr="user",w_="#000c",tu="#fff",S_="#4f4",iu="#888",C_="#555",dr="bark",ln="linear",Si="log",ur="mel",nu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],su=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:nu}],["rainbow",{dir:"h",colorStops:["#817",...nu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],cn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:Zn,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Si,gradient:su[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:zd,width:void 0},T_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],E_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],k_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],hr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],I_=["ERR_INVALID_MODE","Invalid mode"],x_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],A_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],R_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],L_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],D_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class tt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const ou=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),ru=t=>{for(const e in t)return!1;return!0},ts=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],P_=(t,e,i,n,s)=>e+(n-e)*(s-t)/(i-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class M_{constructor(e,i={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(ru(i)&&!ru(e)&&(i=e),e=null),this._ownCanvas=!(i.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):i.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[d,h]of su)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(i.source&&(s=i.source.context))){if(!(s=i.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new tt(T_)}}if(!s.createGain)throw new tt(E_);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),i.source&&this.connectInput(i.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),i.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=i.fsElement||n;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(b_),this._fsTimeout=0)},Gd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(qd,l,{signal:c}),n.addEventListener(g_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(eu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Gd)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Wd,u))};window.addEventListener(Wd,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(i,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(Zd)}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=ts(e,[xt,Qn,vt,$d]),this._input.disconnect(),this._input.connect(this._chLayout!=xt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=xt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=ts(e,[Zn,jd,Hd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const i=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(i),new Float32Array(i)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=ts(e,[Si,dr,ur,ln]),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||cn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(cr)}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(y_)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const i of[0,1])this._analyzer[i].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new tt(hr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const i of[0,1])this._analyzer[i].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new tt(hr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const i=e|0;if(i>=0&&i<=10&&i!=9)this._mode=i,this._calcBars(),this._makeGrad();else throw new tt(I_,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||cn.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 tt(x_);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const i of[0,1])this._analyzer[i].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-lr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return ou("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){ou("stereo","channelLayout"),this.channelLayout=e?vt:xt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=ts(e,[zd,Kd,Yd,Xd,Jd,Qd],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(cr)}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 p_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new tt(A_);const n=i?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const i of[0,1])this._analyzer[i].connect(this._chLayout==xt&&!i?this._output:this._merger,0,i)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:i,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&i.remove(),this._calcBars()}disconnectInput(e,i){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(i&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(i=>i!==e):[],this._outNodes.length==0))for(const i of[0,1])this._analyzer[i].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,i){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,i]=a[e]}const n=this._freqToBin(e),s=i?this._freqToBin(i):n,o=this._chLayout==xt?1:2;let r=0;for(let a=0;a<o;a++)for(let l=n;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let i={};for(const n of Object.keys(cn))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(i.gradientLeft=this.gradientLeft,i.gradientRight=this.gradientRight):n!="start"&&(i[n]=this[n]));return i}registerGradient(e,i){if(typeof e!="string"||e.trim().length==0)throw new tt(R_);if(typeof i!="object")throw new tt(L_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new tt(D_);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?n[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(n[a].level=1-a/s)}),n.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:i.bgColor||m_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(cr)}setFreqRange(e,i){if(e<1||i<1)throw new tt(hr);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,g=s.width>>1,y=s.height>>1,v=o==vt&&!u,b=o==Qn,_=c%10!=0,C=_&&this._frequencyScale==Si,k=this._showLeds&&_&&!u,A=this._lumiBars&&_&&!u,x=this._alphaBars&&!A&&c!=wi,N=this._outlineBars&&_&&!A&&!k,T=this._roundBars&&_&&!A&&!k,E=o!=vt||h>0&&!A,p=s.height-(v&&!k?.5:0)>>v,m=p*(A||u?1:1-h)|0,f=s.width-g*(b||l!=0),w=v?s.height-p*2:0,I=g*(l==-1&&!b&&!u);let L=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,R=Math.min(g,y);d&&o!=vt&&([L,R]=[R,L]);const O=X=>e.push({...X,peak:[0,0],hold:[0],alpha:[0],value:[0]}),P=X=>{const ee=this._freqToBin(X,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),me=Math.log2(X/te)/Math.log2(ie/te);return[ee,me]};let F,H,$;if(C){const X=(ne,pe,fe)=>+ne.toPrecision(fe?Math.max(pe,1+Math.log10(ne)|0):pe),ee=ne=>{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],fe=Math.log10(ne)|0,bt=ne/10**fe;let ct=1;for(;ct<pe.length&&bt>pe[ct];)ct++;return bt-pe[ct-1]<pe[ct]-bt&&ct--,(pe[ct]*10**(fe+5)|0)/1e5},te=[0,24,12,8,6,4,3,2,1][c],ie=i?10**(3/(te*10)):2**(1/te),me=ie**.5;let Pe=i?7.94328235/(te%2?1:me):Bd;do{let ne=Pe;const pe=X(ne/me,4,!0),fe=X(ne*me,4,!0),[bt,ct]=P(pe),[yn,wt]=P(fe);i?ne=te<4?ee(ne):X(ne,ne.toString()[0]<5?3:2):ne=X(ne,4,!0),ne>=a&&O({posX:0,freq:ne,freqLo:pe,freqHi:fe,binLo:bt,binHi:yn,ratioLo:ct,ratioHi:wt}),Pe*=ie}while(Pe<=r);F=f/e.length,e.forEach((ne,pe)=>ne.posX=I+pe*F);const ye=e[0],he=e[e.length-1];H=this._freqScaling(ye.freqLo),$=f/(this._freqScaling(he.freqHi)-H),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=P(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=P(r))}else if(_){const X=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case dr:return 1960/(26.81/(te+.53)-1);case ur:return 700*(2**te-1);case ln:return te}};F=f/X,H=this._freqScaling(a),$=f/(this._freqScaling(r)-H);for(let te=0,ie=0;te<X;te++,ie+=F){const me=ee(H+ie/$),Pe=ee(H+(ie+F/2)/$),ye=ee(H+(ie+F)/$),[he,ne]=P(me),[pe,fe]=P(ye);O({posX:I+ie,freq:Pe,freqLo:me,freqHi:ye,binLo:he,binHi:pe,ratioLo:ne,ratioHi:fe})}}else{F=1,H=this._freqScaling(a),$=f/(this._freqScaling(r)-H);const X=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=X;ie<=ee;ie++){const me=this._binToFreq(ie),Pe=I+Math.round($*(this._freqScaling(me)-H));if(Pe>te)O({posX:Pe,freq:me,freqLo:me,freqHi:me,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Pe;else if(e.length){const ye=e[e.length-1];ye.binHi=ie,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let ue=0,J=0;if(k){const X=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),ee=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],te=this._ledParams,[ie,me,Pe]=te||ee[c];let ye,he=m;if(te){const ne=2*X;let pe;ye=ie+1;do ye--,pe=he/ye/(1+me),J=pe*me;while((pe<ne||J<ne)&&ye>1)}else{const ne=540/me;J=Math.min(me*X,Math.max(2,he/ne+.1|0))}E&&(he+=J),te||(ye=Math.min(ie,he/(J*2)|0)),ue=Pe>=1?Pe:F*Pe,this._leds=[ye,ue,J,he/ye-J]}const G=Math.min(F-1,n*(n>0&&n<1?F:1));_&&(F-=Math.max(k?ue:0,G)),e.forEach((X,ee)=>{let te=X.posX,ie=F;_&&(n==0&&!k?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(k?ue:0,G)/2,X.posX=te),X.barCenter=te+(F==1?0:ie/2),X.width=ie});const le=[];for(const X of[0,1]){const ee=o==vt?(p+w)*X:0,te=ee+p,ie=ee+m-(!k||E?0:J);le.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:g,centerY:y,channelCoords:le,channelHeight:p,channelGap:w,initialX:I,innerRadius:L,outerRadius:R,scaleMin:H,unitWidth:$},this._flg={isAlpha:x,isBands:_,isLeds:k,isLumi:A,isOctaves:C,isOutline:N,isRound:T,noLedGap:E},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,g=d.canvas,y=h.canvas,v=[],b=this._chLayout==Qn,_=this._chLayout==vt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,x=g.height>>1,N=A>>1,T=x*(c?.7:1.5),E=N*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=Si))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==ln?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let R=Bd;for(let O=-1;O<11;O++)for(let P=0;P<12;P++){if(R>=this._minFreq&&R<=this._maxFreq){const F=k[P],H=F=="C";(F&&c&&!l&&!b||H)&&v.push(c?[R,F+(H?O:"")]:R)}R*=p}}y.width=y.height=Math.max(C*.15,(n<<1)+_*A);const m=y.width>>1,f=m-A*.7,w=(R,O)=>{const P=bi*(R/r.width),F=P-lr,H=f*Math.cos(F),$=f*Math.sin(F);h.save(),h.translate(m+H,m+$),h.rotate(P),h.fillText(O,0,0),h.restore()};g.width|=0,d.fillStyle=h.strokeStyle=w_,d.fillRect(0,0,g.width,g.height),h.arc(m,m,m-A/2,0,bi),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=tu,d.font=`${x}px ${es}`,h.font=`${N}px ${es}`,d.textAlign=h.textAlign="center";let I=-T/4,L=-E;for(const R of v){const[O,P]=Array.isArray(R)?R:[R,R<1e3?R|0:`${(R/100|0)/10}k`],F=o*(this._freqScaling(O)-s),H=g.height*.75,$=P[0]=="C",ue=x*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?S_:tu,c){const J=a==Si,G=a==ln;let le=["C"];if((J||O>2e3||!G&&O>250||(!u||_)&&(!G&&O>125||O>1e3))&&le.push("G"),(J||O>4e3||!G&&O>500||(!u||_)&&(!G&&O>250||O>2e3))&&le.push("E"),(G&&O>4e3||(!u||_)&&(J||O>2e3||!G&&O>500))&&le.push("D","F","A","B"),!le.includes(P[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(P,b&&l==-1?e-F:i+F,H,ue),(b||l&&(F>T||l==1))&&d.fillText(P,b&&l!=1?e+F:(i||r.width)-F,H,ue),I=F+Math.min(ue,d.measureText(P).width)/2),F>=L+E&&F<e-E&&(w(b&&l==1?e-F:F,P),(b||l&&(F>E||l==1))&&w(b&&l!=-1?e+F:-F,P),L=F)}}_draw(e){this._runId=requestAnimationFrame(B=>this._draw(B));const i=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,i>=1e3&&(this._fps=this._frames/i*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:g,centerX:y,centerY:v,channelCoords:b,channelHeight:_,channelGap:C,initialX:k,innerRadius:A,outerRadius:x}=this._aux,{_bars:N,canvas:T,_canvasGradients:E,_chLayout:p,_colorMode:m,_ctx:f,_energy:w,_fadePeaks:I,fillAlpha:L,_fps:R,_linearAmplitude:O,_lineWidth:P,maxDecibels:F,minDecibels:H,_mirror:$,_mode:ue,overlay:J,_radial:G,showBgColor:le,showPeaks:X,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,me=this._scaleR.canvas,Pe=R*this._peakFadeTime/1e3,ye=R**2,he=this._gravity*1e3,ne=R*this._peakHoldTime/1e3,pe=p==$d,fe=p==Qn,bt=p==vt,ct=p==xt,yn=a&&this._trueLeds&&m==Zn,wt=G?T.width:this._aux.analyzerWidth,Pr=k+wt,bn=X&&this._peakLine&&ue==wi,Ut=G?x-A:g,Xb=Ut/this._pixelRatio,[Jb,aw,wn,Mr]=this._leds||[];w.val>0&&R>0&&(this._spinAngle+=this._spinSpeed*bi/60/R);const Qb=B=>{if(this._reflexRatio>0&&!l&&!G){let ce,St;this.reflexFit||bt?(ce=bt&&B==0?_+C:0,St=_-g):(ce=T.height-g*2,St=g),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,b[B].channelTop,T.width,g,0,ce,T.width,St),f.restore()}},Zb=()=>{this.showScaleX&&(G?(f.save(),f.translate(y,v),this._spinSpeed&&f.rotate(this._spinAngle+lr),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ie,0,T.height-ie.height))},ew=B=>{const ce=B**2,St=424.36,Fe=11599.29,ws=25122.25,Bt=544496.41,Dt=148693636,ii=ni=>20*Math.log10(ni);switch(te){case Kd:const ni=Dt*ce**2/((ce+St)*Math.sqrt((ce+Fe)*(ce+Bt))*(ce+Dt));return 2+ii(ni);case Yd:const si=Dt*ce*B/((ce+St)*Math.sqrt(ce+ws)*(ce+Dt));return .17+ii(si);case Xd:const Fr=Dt*ce/((ce+St)*(ce+Dt));return .06+ii(Fr);case Jd:const Ss=((103791848e-2-ce)**2+108076816e-2*ce)/((9837328-ce)**2+11723776*ce),Vr=B/68966888496476e-18*Math.sqrt(Ss/((ce+79919.29)*(ce+1345600)));return ii(Vr);case Qd:const Cs=-4737338981378384e-39*B**6+2043828333606125e-30*B**4-1363894795463638e-22*ce+1,oi=1306612257412824e-34*B**5-2118150887518656e-26*B**3+.0005559488023498642*B,Ye=.0001246332637532143*B/Math.hypot(Cs,oi);return 18.2+ii(Ye)}return 0},Or=(B,ce,St)=>{f.beginPath(),f.moveTo(B,ce),f.lineTo(B,St),f.stroke()},Nr=B=>{if(B&&P){const ce=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=ce}},ti=B=>Math.max(0,(B*Jb|0)*(Mr+wn)-wn),tw=B=>{w.val=B,w.peak>0&&(w.hold--,w.hold<0&&(w.peak+=w.hold*he/ye/T.height*this._pixelRatio)),B>=w.peak&&(w.peak=B,w.hold=ne)};J&&f.clearRect(0,0,T.width,T.height);let Oh=0;const Nh=N.length,Fh=ct?1:2;for(let B=0;B<Fh;B++){const{channelTop:ce,channelBottom:St,analyzerBottom:Fe}=b[B],ws=this._gradients[this._selectedGrads[B]],Bt=ws.colorStops,Dt=Bt.length,ii=!le||a&&!J?"#000":ws.bgColor,ni=bt&&G&&B?-1:1,si=!B&&$==-1||B&&$==1,Fr=!fe||B&&$!=1?0:wt>>(B||!si),Ss=fe&&si?-1:1,Vr=()=>{const q=ie.height,Y=q>>1,Z=O?100:F,be=O?0:H,xe=O?20:5,qe=g/(Z-be),Ct=$!=-1&&(!fe||B==0||$==1),$t=$!=1&&(!fe||B!=$);f.save(),f.fillStyle=iu,f.font=`${Y}px ${es}`,f.textAlign="right",f.lineWidth=1;for(let jt=Z;jt>be;jt-=xe){const Pi=ce+(Z-jt)*qe,Me=jt%2==0|0;if(Me){const je=Pi+Y*(Pi==ce?.8:.35);Ct&&f.fillText(jt,q*.85,je),$t&&f.fillText(jt,(fe?wt:T.width)-q*.1,je),f.strokeStyle=iu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=C_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+q*Me*Ct,~~Pi+.5),f.lineTo(Pr-q*Me*$t,~~Pi+.5),f.stroke()}f.restore()},Cs=(q,Y)=>{const Z=dt[q]+(q<dt.length-1?(dt[q+1]-dt[q])*Y:0);return isNaN(Z)?-1/0:Z},oi=(q,Y=Ss)=>Y*bi*((q+Fr)/T.width)+this._spinAngle,Ye=(q,Y,Z)=>{const be=A+Y*ni,xe=oi(q,Z);return[y+be*Math.cos(xe),v+be*Math.sin(xe)]},Ur=(q,Y,Z,be,xe)=>{f.beginPath();for(const qe of $&&!fe?[1,-1]:[Ss]){const[Ct,$t]=d?[oi(q,qe),oi(q+Z,qe)]:[];f.moveTo(...Ye(q,Y,qe)),f.lineTo(...Ye(q,Y+be,qe)),d?f.arc(y,v,A+(Y+be)*ni,Ct,$t,qe!=1):f.lineTo(...Ye(q+Z,Y+be,qe)),f.lineTo(...Ye(q+Z,Y,qe)),d&&!xe&&f.arc(y,v,A+Y*ni,$t,Ct,qe==1)}Nr(xe),f.fill()},Br=(q=0,Y=0)=>{let Z;if(m==Zn&&!yn||ue==wi)Z=E[B];else{const be=m==jd?Y%Dt:Bt.findLastIndex(xe=>a?ti(q)<=ti(xe.level):q<=xe.level);Z=Bt[be].color}f.fillStyle=f.strokeStyle=Z};if(ee){if(fe&&!G){const q=wt*(B+si),Y=si?-1:1;f.setTransform(Y,0,0,1,q,0)}if((!J||le)&&(J&&(f.globalAlpha=this.bgAlpha),f.fillStyle=ii,(B==0||!G&&!pe)&&f.fillRect(k,ce-C,wt,(J&&this.reflexAlpha==1?g:_)+C),f.globalAlpha=1),this.showScaleY&&!l&&!G&&(B==0||!pe)&&Vr(),a?(f.setLineDash([Mr,wn]),f.lineWidth=N[0].width):f.lineWidth=u?Math.min(P,N[0].width/2):P,f.save(),!G){const q=new Path2D;q.rect(0,ce,T.width,g),f.clip(q)}}let dt=this._fftData[B];this._analyzer[B].getFloatFrequencyData(dt),te&&(dt=dt.map((q,Y)=>q+ew(this._binToFreq(Y)))),f.beginPath();let Sn=[];for(let q=0;q<Nh;q++){const Y=N[q],{posX:Z,barCenter:be,width:xe,freq:qe,binLo:Ct,binHi:$t,ratioLo:jt,ratioHi:Pi}=Y;let Me=Math.max(Cs(Ct,jt),Cs($t,Pi));for(let ve=Ct+1;ve<$t;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),Y.value[B]=Me,Oh+=Me,Y.peak[B]>0&&Y.alpha[B]>0&&(Y.hold[B]--,Y.hold[B]<0)){if(I&&!bn){const ve=!o||u&&P>0?1:o?Y.peak[B]:L;Y.alpha[B]=ve*(1+Y.hold[B]/Pe)}else Y.peak[B]+=Y.hold[B]*he/ye/Xb;Y.alpha[B]<=0&&(Y.peak[B]=0)}if(Me>=Y.peak[B]&&(Y.peak[B]=Me,Y.hold[B]=ne,Y.alpha[B]=!o||u&&P>0?1:o?Me:L),!ee)continue;f.globalAlpha=l||o?Me:u?L:1,Br(Me,q);const je=l?Ut:a?ti(Me):Me*Ut|0;if(ue==wi){const ve=q?0:(this._normalizedB(dt[N[1].binLo])*Ut+je)/2;if(G){if(q==0&&(fe&&f.moveTo(...Ye(0,0)),f.lineTo(...Ye(0,Z<0?ve:je))),Z>=0){const st=[Z,je];f.lineTo(...Ye(...st)),Sn.push(st)}}else{if(q==0)if($==-1&&!fe)f.moveTo(k,Fe-(Z<k?ve:je));else{const st=Ct?this._normalizedB(dt[Ct-1])*Ut:je;f.moveTo(k-P,Fe-st)}(fe||$!=-1||Z>=k)&&f.lineTo(Z,Fe-je)}}else if(a){if(le&&!J&&(B==0||!pe)){const ve=f.globalAlpha;f.strokeStyle=__,f.globalAlpha=1,Or(be,ce,Fe),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(yn){const ve=l?0:Bt.findLastIndex(ri=>ti(Me)<=ti(ri.level));let st=Fe;for(let ri=Dt-1;ri>=ve;ri--){f.strokeStyle=Bt[ri].color;let Uh=Fe-(ri==ve?je:ti(Bt[ri].level));Or(be,st,Uh),st=Uh-wn}}else Or(be,Fe,Fe-je)}else if(Z>=k)if(G)Ur(Z,0,xe,je,u);else if(d){const ve=xe/2,st=Fe+ve;f.beginPath(),f.moveTo(Z,st),f.lineTo(Z,st-je),f.arc(be,st-je,ve,ar,bi),f.lineTo(Z+xe,st),Nr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(Z,Fe+ve,xe,-je-ve),Nr(u),f.fill()}const Mi=Y.peak[B],Vh=Y.alpha[B];if(Mi>0&&Vh>0&&X&&!bn&&!l&&Z>=k&&Z<Pr){if(I?f.globalAlpha=Vh:u&&P>0?f.globalAlpha=1:o&&(f.globalAlpha=Mi),(m==Hd||yn)&&Br(Mi),a){const ve=ti(Mi);ve>=wn&&f.fillRect(Z,Fe-ve,xe,Mr)}else if(!G)f.fillRect(Z,Fe-Mi*Ut,xe,2);else if(ue!=wi){const ve=Mi*Ut;Ur(Z,ve,xe,!this._radialInvert||bt||ve+A>=2?-2:2)}}}if(ee){if(f.globalAlpha=1,ue==wi){if(Br(),G&&!fe){if($){let q;for(;q=Sn.pop();)f.lineTo(...Ye(...q,-1))}f.closePath()}if(P>0&&f.stroke(),L>0){if(G){const q=fe?oi(wt>>1):0,Y=fe?oi(wt):bi;f.moveTo(...Ye(fe?wt>>1:0,0)),f.arc(y,v,A,q,Y,fe?!si:!0)}else f.lineTo(Pr,Fe),f.lineTo(k,Fe);f.globalAlpha=L,f.fill(),f.globalAlpha=1}if((bn||G&&X)&&(Sn=[],f.beginPath(),N.forEach((q,Y)=>{let Z=q.posX,be=q.peak[B],xe=Y?"lineTo":"moveTo";if(G&&Z<0){const qe=N[Y+1];be=P_(Z,be,qe.posX,qe.peak[B],0),Z=0}be*=Ut,bn?(f[xe](...G?Ye(Z,be):[Z,Fe-be]),G&&$&&!fe&&Sn.push([Z,be])):be>0&&Ur(Z,be,1,-2)}),bn)){let q;for(;q=Sn.pop();)f.lineTo(...Ye(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),fe&&!G&&f.setTransform(1,0,0,1,0,0),(!fe&&!pe||B)&&Qb(B)}}if(tw(Oh/(Nh<<Fh-1)),ee&&($&&!G&&!fe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,y,T.height,0,0,y,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),Zb()),this.showFPS){const B=ie.height;f.font=`bold ${B}px ${es}`,f.fillStyle=v_,f.textAlign="right",f.fillText(Math.round(R),T.width-B,B*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=E[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:E}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case Si:return Math.log2(e);case dr:return 26.81*e/(1960+e)-.53;case ur:return Math.log2(1+e/700);case ln:return e}}_freqToBin(e,i="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[i](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:i,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==vt,g=1-s,y=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],_=b.colorStops,C=b.dir=="h";let k;if(n?k=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):k=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,y]),_){const A=h&&!this._splitGradient&&(!C||n);for(let x=0;x<1+A;x++){const N=_.length-1;_.forEach((T,E)=>{let p=T.pos;if(A&&(p/=2),h&&!d&&!n&&!C&&(p*=g,!A&&p>.5*g&&(p+=.5*s)),x==1)if(n||d){const m=N-E;T=_[m],p=1-T.pos/2}else E==0&&p>0&&k.addColorStop(.5,T.color),p+=.5;k.addColorStop(p,T.color),h&&E==N&&p<.5&&k.addColorStop(.5,T.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Zd&&i.width==u&&i.height==d)&&(i.width=u,i.height=d,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,u,d)),n.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=eu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new tt(k_,e);[0,1].includes(i)||(this._selectedGrads[1]=e,i=0),this._selectedGrads[i]=e,this._makeGrad()}_setProps(e,i){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(cn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...cn,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const O_={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}]}},au=({stream:t,className:e,onClick:i})=>{var o;const n=de(null),s=Jt();return Re(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new M_(n.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",O_[((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]),D("div",{onClick:i,className:It("w-full",e),ref:n})},lu=Rn(null),cu=({className:t,debug:e=!1})=>{const i=qs(lu);return!e||!i||!(i.region||i.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&D("span",{children:" · "}),i.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
16
+ */const w_="4.5.1",cr=Math.PI,Si=2*cr,dr=cr/2,zd=8.17579892,Kd="dual-combined",Qn="dual-horizontal",At="single",vt="dual-vertical",Yd="bar-index",Xd="bar-level",es="gradient",Jd=60,Zd="click",S_="fullscreenchange",Qd="resize",C_="#111",eu="",tu="A",iu="B",nu="C",su="D",ou="468",ts="sans-serif",T_="#0f0",k_="#7f7f7f22",Ci=10,ru="create",au="fschange",I_="lores",E_=Qd,ur="user",R_="#000c",lu="#fff",A_="#4f4",cu="#888",x_="#555",hr="bark",dn="linear",Ti="log",fr="mel",du=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],uu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:du}],["rainbow",{dir:"h",colorStops:["#817",...du,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],un={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:At,colorMode:es,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ti,gradient:uu[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:eu,width:void 0},L_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],D_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],O_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],pr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],M_=["ERR_INVALID_MODE","Invalid mode"],P_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],N_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],F_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],V_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],B_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class tt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const hu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),fu=t=>{for(const e in t)return!1;return!0},is=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],U_=(t,e,i,n,s)=>e+(n-e)*(s-t)/(i-t);Array.prototype.findLastIndex||(Array.prototype.findLastIndex=function(t){let e=this.length;for(;e-- >0;)if(t(this[e]))return e;return-1});class $_{constructor(e,i={}){this._ready=!1,this._aux={},this._canvasGradients=[],this._destroyed=!1,this._energy={val:0,peak:0,hold:0},this._flg={},this._fps=0,this._gradients={},this._last=0,this._outNodes=[],this._ownContext=!1,this._selectedGrads=[],this._sources=[],e instanceof Element||(fu(i)&&!fu(e)&&(i=e),e=null),this._ownCanvas=!(i.canvas instanceof HTMLCanvasElement);const n=this._ownCanvas?document.createElement("canvas"):i.canvas;n.style="max-width: 100%;",this._ctx=n.getContext("2d");for(const[d,h]of uu)this.registerGradient(d,h);this._container=e||!this._ownCanvas&&n.parentElement||document.body,this._defaultWidth=this._container.clientWidth||640,this._defaultHeight=this._container.clientHeight||270;let s;if(!(i.source&&(s=i.source.context))){if(!(s=i.audioCtx))try{s=new(window.AudioContext||window.webkitAudioContext),this._ownContext=!0}catch{throw new tt(L_)}}if(!s.createGain)throw new tt(D_);const o=this._analyzer=[s.createAnalyser(),s.createAnalyser()],r=this._splitter=s.createChannelSplitter(2),a=this._merger=s.createChannelMerger(2);this._input=s.createGain(),this._output=s.createGain(),i.source&&this.connectInput(i.source);for(const d of[0,1])r.connect(o[d],d);a.connect(this._output),i.connectSpeakers!==!1&&this.connectOutput();for(const d of["_scaleX","_scaleR"])this[d]=document.createElement("canvas").getContext("2d");this._fsEl=i.fsElement||n;const l=()=>{this._fsTimeout||(this._fsTimeout=window.setTimeout(()=>{this._fsChanging||(this._setCanvas(E_),this._fsTimeout=0)},Jd))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Qd,l,{signal:c}),n.addEventListener(S_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(au),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Jd)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Zd,u))};window.addEventListener(Zd,u),document.addEventListener("visibilitychange",()=>{document.visibilityState!="hidden"&&(this._frames=0,this._time=performance.now())},{signal:c}),this._setProps(i,!0),this.useCanvas&&this._ownCanvas&&this._container.appendChild(n),this._ready=!0,this._setCanvas(ru)}get alphaBars(){return this._alphaBars}set alphaBars(e){this._alphaBars=!!e,this._calcBars()}get ansiBands(){return this._ansiBands}set ansiBands(e){this._ansiBands=!!e,this._calcBars()}get barSpace(){return this._barSpace}set barSpace(e){this._barSpace=+e||0,this._calcBars()}get channelLayout(){return this._chLayout}set channelLayout(e){this._chLayout=is(e,[At,Qn,vt,Kd]),this._input.disconnect(),this._input.connect(this._chLayout!=At?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=At?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=is(e,[es,Yd,Xd])}get fadePeaks(){return this._fadePeaks}set fadePeaks(e){this._fadePeaks=!!e}get fftSize(){return this._analyzer[0].fftSize}set fftSize(e){for(const n of[0,1])this._analyzer[n].fftSize=e;const i=this._analyzer[0].frequencyBinCount;this._fftData=[new Float32Array(i),new Float32Array(i)],this._calcBars()}get frequencyScale(){return this._frequencyScale}set frequencyScale(e){this._frequencyScale=is(e,[Ti,hr,fr,dn]),this._calcBars()}get gradient(){return this._selectedGrads[0]}set gradient(e){this._setGradient(e)}get gradientLeft(){return this._selectedGrads[0]}set gradientLeft(e){this._setGradient(e,0)}get gradientRight(){return this._selectedGrads[1]}set gradientRight(e){this._setGradient(e,1)}get gravity(){return this._gravity}set gravity(e){this._gravity=e>0?+e:this._gravity||un.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(ur)}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(I_)}get lumiBars(){return this._lumiBars}set lumiBars(e){this._lumiBars=!!e,this._calcBars(),this._makeGrad()}get maxDecibels(){return this._analyzer[0].maxDecibels}set maxDecibels(e){for(const i of[0,1])this._analyzer[i].maxDecibels=e}get maxFPS(){return this._maxFPS}set maxFPS(e){this._maxFPS=e<0?0:+e||0}get maxFreq(){return this._maxFreq}set maxFreq(e){if(e<1)throw new tt(pr);this._maxFreq=Math.min(e,this.audioCtx.sampleRate/2),this._calcBars()}get minDecibels(){return this._analyzer[0].minDecibels}set minDecibels(e){for(const i of[0,1])this._analyzer[i].minDecibels=e}get minFreq(){return this._minFreq}set minFreq(e){if(e<1)throw new tt(pr);this._minFreq=+e,this._calcBars()}get mirror(){return this._mirror}set mirror(e){this._mirror=Math.sign(e)|0,this._calcBars(),this._makeGrad()}get mode(){return this._mode}set mode(e){const i=e|0;if(i>=0&&i<=10&&i!=9)this._mode=i,this._calcBars(),this._makeGrad();else throw new tt(M_,e)}get noteLabels(){return this._noteLabels}set noteLabels(e){this._noteLabels=!!e,this._createScales()}get outlineBars(){return this._outlineBars}set outlineBars(e){this._outlineBars=!!e,this._calcBars()}get peakFadeTime(){return this._peakFadeTime}set peakFadeTime(e){this._peakFadeTime=e>=0?+e:this._peakFadeTime||un.peakFadeTime}get peakHoldTime(){return this._peakHoldTime}set peakHoldTime(e){this._peakHoldTime=+e||0}get peakLine(){return this._peakLine}set peakLine(e){this._peakLine=!!e}get radial(){return this._radial}set radial(e){this._radial=!!e,this._calcBars(),this._makeGrad()}get radialInvert(){return this._radialInvert}set radialInvert(e){this._radialInvert=!!e,this._calcBars(),this._makeGrad()}get radius(){return this._radius}set radius(e){this._radius=+e||0,this._calcBars(),this._makeGrad()}get reflexRatio(){return this._reflexRatio}set reflexRatio(e){if(e=+e||0,e<0||e>=1)throw new tt(P_);this._reflexRatio=e,this._calcBars(),this._makeGrad()}get roundBars(){return this._roundBars}set roundBars(e){this._roundBars=!!e,this._calcBars()}get smoothing(){return this._analyzer[0].smoothingTimeConstant}set smoothing(e){for(const i of[0,1])this._analyzer[i].smoothingTimeConstant=e}get spinSpeed(){return this._spinSpeed}set spinSpeed(e){e=+e||0,(this._spinSpeed===void 0||e==0)&&(this._spinAngle=-dr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return hu("stereo","channelLayout"),this._chLayout!=At}set stereo(e){hu("stereo","channelLayout"),this.channelLayout=e?vt:At}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=is(e,[eu,tu,iu,nu,su,ou],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(ur)}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 w_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new tt(N_);const n=i?this.audioCtx.createMediaElementSource(e):e;return this._sources.includes(n)||(n.connect(this._input),this._sources.push(n)),n}connectOutput(e=this.audioCtx.destination){if(!this._outNodes.includes(e)&&(this._output.connect(e),this._outNodes.push(e),this._outNodes.length==1))for(const i of[0,1])this._analyzer[i].connect(this._chLayout==At&&!i?this._output:this._merger,0,i)}destroy(){if(!this._ready)return;const{audioCtx:e,canvas:i,_controller:n,_input:s,_merger:o,_observer:r,_ownCanvas:a,_ownContext:l,_splitter:c}=this;this._destroyed=!0,this._ready=!1,this.stop(),n.abort(),r&&r.disconnect(),this.onCanvasResize=null,this.onCanvasDraw=null,this._fsEl=null,this.disconnectInput(),this.disconnectOutput(),s.disconnect(),c.disconnect(),o.disconnect(),l&&e.close(),a&&i.remove(),this._calcBars()}disconnectInput(e,i){e?Array.isArray(e)||(e=[e]):e=Array.from(this._sources);for(const n of e){const s=this._sources.indexOf(n);if(i&&n.mediaStream)for(const o of n.mediaStream.getAudioTracks())o.stop();s>=0&&(n.disconnect(this._input),this._sources.splice(s,1))}}disconnectOutput(e){if(!(e&&!this._outNodes.includes(e))&&(this._output.disconnect(e),this._outNodes=e?this._outNodes.filter(i=>i!==e):[],this._outNodes.length==0))for(const i of[0,1])this._analyzer[i].disconnect()}getBars(){return Array.from(this._bars,({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a})=>({posX:e,freq:i,freqLo:n,freqHi:s,hold:o,peak:r,value:a}))}getEnergy(e,i){if(e===void 0)return this._energy.val;if(e!=+e){if(e=="peak")return this._energy.peak;const a={bass:[20,250],lowMid:[250,500],mid:[500,2e3],highMid:[2e3,4e3],treble:[4e3,16e3]};if(!a[e])return null;[e,i]=a[e]}const n=this._freqToBin(e),s=i?this._freqToBin(i):n,o=this._chLayout==At?1:2;let r=0;for(let a=0;a<o;a++)for(let l=n;l<=s;l++)r+=this._normalizedB(this._fftData[a][l]);return r/(s-n+1)/o}getOptions(e){Array.isArray(e)||(e=[e]);let i={};for(const n of Object.keys(un))e.includes(n)||(n=="gradient"&&this.gradientLeft!=this.gradientRight?(i.gradientLeft=this.gradientLeft,i.gradientRight=this.gradientRight):n!="start"&&(i[n]=this[n]));return i}registerGradient(e,i){if(typeof e!="string"||e.trim().length==0)throw new tt(F_);if(typeof i!="object")throw new tt(V_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new tt(B_);const s=n.length,o=r=>+r!=r||r<0||r>1;n.forEach((r,a)=>{const l=a/Math.max(1,s-1);typeof r!="object"?n[a]={pos:l,color:r}:o(r.pos)&&(r.pos=l),o(r.level)&&(n[a].level=1-a/s)}),n.sort((r,a)=>r.level<a.level?1:r.level>a.level?-1:0),n[0].level=1,this._gradients[e]={bgColor:i.bgColor||C_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(ur)}setFreqRange(e,i){if(e<1||i<1)throw new tt(pr);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,p=s.width>>1,_=s.height>>1,v=o==vt&&!u,w=o==Qn,y=c%10!=0,C=y&&this._frequencyScale==Ti,I=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,R=this._alphaBars&&!A&&c!=Ci,P=this._outlineBars&&y&&!A&&!I,T=this._roundBars&&y&&!A&&!I,k=o!=vt||h>0&&!A,g=s.height-(v&&!I?.5:0)>>v,m=g*(A||u?1:1-h)|0,f=s.width-p*(w||l!=0),S=v?s.height-g*2:0,E=p*(l==-1&&!w&&!u);let x=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,L=Math.min(p,_);d&&o!=vt&&([x,L]=[L,x]);const N=X=>e.push({...X,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=X=>{const ee=this._freqToBin(X,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),me=Math.log2(X/te)/Math.log2(ie/te);return[ee,me]};let F,W,$;if(C){const X=(se,pe,fe)=>+se.toPrecision(fe?Math.max(pe,1+Math.log10(se)|0):pe),ee=se=>{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],fe=Math.log10(se)|0,wt=se/10**fe;let ct=1;for(;ct<pe.length&&wt>pe[ct];)ct++;return wt-pe[ct-1]<pe[ct]-wt&&ct--,(pe[ct]*10**(fe+5)|0)/1e5},te=[0,24,12,8,6,4,3,2,1][c],ie=i?10**(3/(te*10)):2**(1/te),me=ie**.5;let Oe=i?7.94328235/(te%2?1:me):zd;do{let se=Oe;const pe=X(se/me,4,!0),fe=X(se*me,4,!0),[wt,ct]=O(pe),[bn,St]=O(fe);i?se=te<4?ee(se):X(se,se.toString()[0]<5?3:2):se=X(se,4,!0),se>=a&&N({posX:0,freq:se,freqLo:pe,freqHi:fe,binLo:wt,binHi:bn,ratioLo:ct,ratioHi:St}),Oe*=ie}while(Oe<=r);F=f/e.length,e.forEach((se,pe)=>se.posX=E+pe*F);const ye=e[0],he=e[e.length-1];W=this._freqScaling(ye.freqLo),$=f/(this._freqScaling(he.freqHi)-W),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=O(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=O(r))}else if(y){const X=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case hr:return 1960/(26.81/(te+.53)-1);case fr:return 700*(2**te-1);case dn:return te}};F=f/X,W=this._freqScaling(a),$=f/(this._freqScaling(r)-W);for(let te=0,ie=0;te<X;te++,ie+=F){const me=ee(W+ie/$),Oe=ee(W+(ie+F/2)/$),ye=ee(W+(ie+F)/$),[he,se]=O(me),[pe,fe]=O(ye);N({posX:E+ie,freq:Oe,freqLo:me,freqHi:ye,binLo:he,binHi:pe,ratioLo:se,ratioHi:fe})}}else{F=1,W=this._freqScaling(a),$=f/(this._freqScaling(r)-W);const X=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=X;ie<=ee;ie++){const me=this._binToFreq(ie),Oe=E+Math.round($*(this._freqScaling(me)-W));if(Oe>te)N({posX:Oe,freq:me,freqLo:me,freqHi:me,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Oe;else if(e.length){const ye=e[e.length-1];ye.binHi=ie,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let ue=0,J=0;if(I){const X=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),ee=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],te=this._ledParams,[ie,me,Oe]=te||ee[c];let ye,he=m;if(te){const se=2*X;let pe;ye=ie+1;do ye--,pe=he/ye/(1+me),J=pe*me;while((pe<se||J<se)&&ye>1)}else{const se=540/me;J=Math.min(me*X,Math.max(2,he/se+.1|0))}k&&(he+=J),te||(ye=Math.min(ie,he/(J*2)|0)),ue=Oe>=1?Oe:F*Oe,this._leds=[ye,ue,J,he/ye-J]}const H=Math.min(F-1,n*(n>0&&n<1?F:1));y&&(F-=Math.max(I?ue:0,H)),e.forEach((X,ee)=>{let te=X.posX,ie=F;y&&(n==0&&!I?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(I?ue:0,H)/2,X.posX=te),X.barCenter=te+(F==1?0:ie/2),X.width=ie});const le=[];for(const X of[0,1]){const ee=o==vt?(g+S)*X:0,te=ee+g,ie=ee+m-(!I||k?0:J);le.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:p,centerY:_,channelCoords:le,channelHeight:g,channelGap:S,initialX:E,innerRadius:x,outerRadius:L,scaleMin:W,unitWidth:$},this._flg={isAlpha:R,isBands:y,isLeds:I,isLumi:A,isOctaves:C,isOutline:P,isRound:T,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,_=h.canvas,v=[],w=this._chLayout==Qn,y=this._chLayout==vt,C=Math.min(r.width,r.height),I=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,R=p.height>>1,P=A>>1,T=R*(c?.7:1.5),k=P*(c?1:2),g=2**(1/12);if(!c&&(this._ansiBands||a!=Ti))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==dn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let L=zd;for(let N=-1;N<11;N++)for(let O=0;O<12;O++){if(L>=this._minFreq&&L<=this._maxFreq){const F=I[O],W=F=="C";(F&&c&&!l&&!w||W)&&v.push(c?[L,F+(W?N:"")]:L)}L*=g}}_.width=_.height=Math.max(C*.15,(n<<1)+y*A);const m=_.width>>1,f=m-A*.7,S=(L,N)=>{const O=Si*(L/r.width),F=O-dr,W=f*Math.cos(F),$=f*Math.sin(F);h.save(),h.translate(m+W,m+$),h.rotate(O),h.fillText(N,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=R_,d.fillRect(0,0,p.width,p.height),h.arc(m,m,m-A/2,0,Si),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=lu,d.font=`${R}px ${ts}`,h.font=`${P}px ${ts}`,d.textAlign=h.textAlign="center";let E=-T/4,x=-k;for(const L of v){const[N,O]=Array.isArray(L)?L:[L,L<1e3?L|0:`${(L/100|0)/10}k`],F=o*(this._freqScaling(N)-s),W=p.height*.75,$=O[0]=="C",ue=R*(c&&!l&&!w?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!w?A_:lu,c){const J=a==Ti,H=a==dn;let le=["C"];if((J||N>2e3||!H&&N>250||(!u||y)&&(!H&&N>125||N>1e3))&&le.push("G"),(J||N>4e3||!H&&N>500||(!u||y)&&(!H&&N>250||N>2e3))&&le.push("E"),(H&&N>4e3||(!u||y)&&(J||N>2e3||!H&&N>500))&&le.push("D","F","A","B"),!le.includes(O[0]))continue}F>=E+T/2&&F<=e&&(d.fillText(O,w&&l==-1?e-F:i+F,W,ue),(w||l&&(F>T||l==1))&&d.fillText(O,w&&l!=1?e+F:(i||r.width)-F,W,ue),E=F+Math.min(ue,d.measureText(O).width)/2),F>=x+k&&F<e-k&&(S(w&&l==1?e-F:F,O),(w||l&&(F>k||l==1))&&S(w&&l!=-1?e+F:-F,O),x=F)}}_draw(e){this._runId=requestAnimationFrame(U=>this._draw(U));const i=e-this._time,n=e-this._last,s=this._maxFPS?975/this._maxFPS:0;if(n<s)return;this._last=e-(s?n%s:0),this._frames++,i>=1e3&&(this._fps=this._frames/i*1e3,this._frames=0,this._time=e);const{isAlpha:o,isBands:r,isLeds:a,isLumi:l,isOctaves:c,isOutline:u,isRound:d,noLedGap:h}=this._flg,{analyzerHeight:p,centerX:_,centerY:v,channelCoords:w,channelHeight:y,channelGap:C,initialX:I,innerRadius:A,outerRadius:R}=this._aux,{_bars:P,canvas:T,_canvasGradients:k,_chLayout:g,_colorMode:m,_ctx:f,_energy:S,_fadePeaks:E,fillAlpha:x,_fps:L,_linearAmplitude:N,_lineWidth:O,maxDecibels:F,minDecibels:W,_mirror:$,_mode:ue,overlay:J,_radial:H,showBgColor:le,showPeaks:X,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,me=this._scaleR.canvas,Oe=L*this._peakFadeTime/1e3,ye=L**2,he=this._gravity*1e3,se=L*this._peakHoldTime/1e3,pe=g==Kd,fe=g==Qn,wt=g==vt,ct=g==At,bn=a&&this._trueLeds&&m==es,St=H?T.width:this._aux.analyzerWidth,Ur=I+St,wn=X&&this._peakLine&&ue==Ci,$t=H?R-A:p,ow=$t/this._pixelRatio,[rw,mw,Sn,$r]=this._leds||[];S.val>0&&L>0&&(this._spinAngle+=this._spinSpeed*Si/60/L);const aw=U=>{if(this._reflexRatio>0&&!l&&!H){let ce,Ct;this.reflexFit||wt?(ce=wt&&U==0?y+C:0,Ct=y-p):(ce=T.height-p*2,Ct=p),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,w[U].channelTop,T.width,p,0,ce,T.width,Ct),f.restore()}},lw=()=>{this.showScaleX&&(H?(f.save(),f.translate(_,v),this._spinSpeed&&f.rotate(this._spinAngle+dr),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ie,0,T.height-ie.height))},cw=U=>{const ce=U**2,Ct=424.36,Fe=11599.29,Cs=25122.25,jt=544496.41,Ot=148693636,si=oi=>20*Math.log10(oi);switch(te){case tu:const oi=Ot*ce**2/((ce+Ct)*Math.sqrt((ce+Fe)*(ce+jt))*(ce+Ot));return 2+si(oi);case iu:const ri=Ot*ce*U/((ce+Ct)*Math.sqrt(ce+Cs)*(ce+Ot));return .17+si(ri);case nu:const Hr=Ot*ce/((ce+Ct)*(ce+Ot));return .06+si(Hr);case su:const Ts=((103791848e-2-ce)**2+108076816e-2*ce)/((9837328-ce)**2+11723776*ce),Gr=U/68966888496476e-18*Math.sqrt(Ts/((ce+79919.29)*(ce+1345600)));return si(Gr);case ou:const ks=-4737338981378384e-39*U**6+2043828333606125e-30*U**4-1363894795463638e-22*ce+1,ai=1306612257412824e-34*U**5-2118150887518656e-26*U**3+.0005559488023498642*U,Ye=.0001246332637532143*U/Math.hypot(ks,ai);return 18.2+si(Ye)}return 0},jr=(U,ce,Ct)=>{f.beginPath(),f.moveTo(U,ce),f.lineTo(U,Ct),f.stroke()},Wr=U=>{if(U&&O){const ce=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=ce}},ni=U=>Math.max(0,(U*rw|0)*($r+Sn)-Sn),dw=U=>{S.val=U,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*he/ye/T.height*this._pixelRatio)),U>=S.peak&&(S.peak=U,S.hold=se)};J&&f.clearRect(0,0,T.width,T.height);let jh=0;const Wh=P.length,Hh=ct?1:2;for(let U=0;U<Hh;U++){const{channelTop:ce,channelBottom:Ct,analyzerBottom:Fe}=w[U],Cs=this._gradients[this._selectedGrads[U]],jt=Cs.colorStops,Ot=jt.length,si=!le||a&&!J?"#000":Cs.bgColor,oi=wt&&H&&U?-1:1,ri=!U&&$==-1||U&&$==1,Hr=!fe||U&&$!=1?0:St>>(U||!ri),Ts=fe&&ri?-1:1,Gr=()=>{const q=ie.height,Y=q>>1,Q=N?100:F,be=N?0:W,Re=N?20:5,ze=p/(Q-be),Tt=$!=-1&&(!fe||U==0||$==1),Wt=$!=1&&(!fe||U!=$);f.save(),f.fillStyle=cu,f.font=`${Y}px ${ts}`,f.textAlign="right",f.lineWidth=1;for(let Ht=Q;Ht>be;Ht-=Re){const Pi=ce+(Q-Ht)*ze,Me=Ht%2==0|0;if(Me){const We=Pi+Y*(Pi==ce?.8:.35);Tt&&f.fillText(Ht,q*.85,We),Wt&&f.fillText(Ht,(fe?St:T.width)-q*.1,We),f.strokeStyle=cu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=x_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(I+q*Me*Tt,~~Pi+.5),f.lineTo(Ur-q*Me*Wt,~~Pi+.5),f.stroke()}f.restore()},ks=(q,Y)=>{const Q=dt[q]+(q<dt.length-1?(dt[q+1]-dt[q])*Y:0);return isNaN(Q)?-1/0:Q},ai=(q,Y=Ts)=>Y*Si*((q+Hr)/T.width)+this._spinAngle,Ye=(q,Y,Q)=>{const be=A+Y*oi,Re=ai(q,Q);return[_+be*Math.cos(Re),v+be*Math.sin(Re)]},qr=(q,Y,Q,be,Re)=>{f.beginPath();for(const ze of $&&!fe?[1,-1]:[Ts]){const[Tt,Wt]=d?[ai(q,ze),ai(q+Q,ze)]:[];f.moveTo(...Ye(q,Y,ze)),f.lineTo(...Ye(q,Y+be,ze)),d?f.arc(_,v,A+(Y+be)*oi,Tt,Wt,ze!=1):f.lineTo(...Ye(q+Q,Y+be,ze)),f.lineTo(...Ye(q+Q,Y,ze)),d&&!Re&&f.arc(_,v,A+Y*oi,Wt,Tt,ze==1)}Wr(Re),f.fill()},zr=(q=0,Y=0)=>{let Q;if(m==es&&!bn||ue==Ci)Q=k[U];else{const be=m==Yd?Y%Ot:jt.findLastIndex(Re=>a?ni(q)<=ni(Re.level):q<=Re.level);Q=jt[be].color}f.fillStyle=f.strokeStyle=Q};if(ee){if(fe&&!H){const q=St*(U+ri),Y=ri?-1:1;f.setTransform(Y,0,0,1,q,0)}if((!J||le)&&(J&&(f.globalAlpha=this.bgAlpha),f.fillStyle=si,(U==0||!H&&!pe)&&f.fillRect(I,ce-C,St,(J&&this.reflexAlpha==1?p:y)+C),f.globalAlpha=1),this.showScaleY&&!l&&!H&&(U==0||!pe)&&Gr(),a?(f.setLineDash([$r,Sn]),f.lineWidth=P[0].width):f.lineWidth=u?Math.min(O,P[0].width/2):O,f.save(),!H){const q=new Path2D;q.rect(0,ce,T.width,p),f.clip(q)}}let dt=this._fftData[U];this._analyzer[U].getFloatFrequencyData(dt),te&&(dt=dt.map((q,Y)=>q+cw(this._binToFreq(Y)))),f.beginPath();let Cn=[];for(let q=0;q<Wh;q++){const Y=P[q],{posX:Q,barCenter:be,width:Re,freq:ze,binLo:Tt,binHi:Wt,ratioLo:Ht,ratioHi:Pi}=Y;let Me=Math.max(ks(Tt,Ht),ks(Wt,Pi));for(let ve=Tt+1;ve<Wt;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),Y.value[U]=Me,jh+=Me,Y.peak[U]>0&&Y.alpha[U]>0&&(Y.hold[U]--,Y.hold[U]<0)){if(E&&!wn){const ve=!o||u&&O>0?1:o?Y.peak[U]:x;Y.alpha[U]=ve*(1+Y.hold[U]/Oe)}else Y.peak[U]+=Y.hold[U]*he/ye/ow;Y.alpha[U]<=0&&(Y.peak[U]=0)}if(Me>=Y.peak[U]&&(Y.peak[U]=Me,Y.hold[U]=se,Y.alpha[U]=!o||u&&O>0?1:o?Me:x),!ee)continue;f.globalAlpha=l||o?Me:u?x:1,zr(Me,q);const We=l?$t:a?ni(Me):Me*$t|0;if(ue==Ci){const ve=q?0:(this._normalizedB(dt[P[1].binLo])*$t+We)/2;if(H){if(q==0&&(fe&&f.moveTo(...Ye(0,0)),f.lineTo(...Ye(0,Q<0?ve:We))),Q>=0){const st=[Q,We];f.lineTo(...Ye(...st)),Cn.push(st)}}else{if(q==0)if($==-1&&!fe)f.moveTo(I,Fe-(Q<I?ve:We));else{const st=Tt?this._normalizedB(dt[Tt-1])*$t:We;f.moveTo(I-O,Fe-st)}(fe||$!=-1||Q>=I)&&f.lineTo(Q,Fe-We)}}else if(a){if(le&&!J&&(U==0||!pe)){const ve=f.globalAlpha;f.strokeStyle=k_,f.globalAlpha=1,jr(be,ce,Fe),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(bn){const ve=l?0:jt.findLastIndex(li=>ni(Me)<=ni(li.level));let st=Fe;for(let li=Ot-1;li>=ve;li--){f.strokeStyle=jt[li].color;let qh=Fe-(li==ve?We:ni(jt[li].level));jr(be,st,qh),st=qh-Sn}}else jr(be,Fe,Fe-We)}else if(Q>=I)if(H)qr(Q,0,Re,We,u);else if(d){const ve=Re/2,st=Fe+ve;f.beginPath(),f.moveTo(Q,st),f.lineTo(Q,st-We),f.arc(be,st-We,ve,cr,Si),f.lineTo(Q+Re,st),Wr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(Q,Fe+ve,Re,-We-ve),Wr(u),f.fill()}const Ni=Y.peak[U],Gh=Y.alpha[U];if(Ni>0&&Gh>0&&X&&!wn&&!l&&Q>=I&&Q<Ur){if(E?f.globalAlpha=Gh:u&&O>0?f.globalAlpha=1:o&&(f.globalAlpha=Ni),(m==Xd||bn)&&zr(Ni),a){const ve=ni(Ni);ve>=Sn&&f.fillRect(Q,Fe-ve,Re,$r)}else if(!H)f.fillRect(Q,Fe-Ni*$t,Re,2);else if(ue!=Ci){const ve=Ni*$t;qr(Q,ve,Re,!this._radialInvert||wt||ve+A>=2?-2:2)}}}if(ee){if(f.globalAlpha=1,ue==Ci){if(zr(),H&&!fe){if($){let q;for(;q=Cn.pop();)f.lineTo(...Ye(...q,-1))}f.closePath()}if(O>0&&f.stroke(),x>0){if(H){const q=fe?ai(St>>1):0,Y=fe?ai(St):Si;f.moveTo(...Ye(fe?St>>1:0,0)),f.arc(_,v,A,q,Y,fe?!ri:!0)}else f.lineTo(Ur,Fe),f.lineTo(I,Fe);f.globalAlpha=x,f.fill(),f.globalAlpha=1}if((wn||H&&X)&&(Cn=[],f.beginPath(),P.forEach((q,Y)=>{let Q=q.posX,be=q.peak[U],Re=Y?"lineTo":"moveTo";if(H&&Q<0){const ze=P[Y+1];be=U_(Q,be,ze.posX,ze.peak[U],0),Q=0}be*=$t,wn?(f[Re](...H?Ye(Q,be):[Q,Fe-be]),H&&$&&!fe&&Cn.push([Q,be])):be>0&&qr(Q,be,1,-2)}),wn)){let q;for(;q=Cn.pop();)f.lineTo(...Ye(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),fe&&!H&&f.setTransform(1,0,0,1,0,0),(!fe&&!pe||U)&&aw(U)}}if(dw(jh/(Wh<<Hh-1)),ee&&($&&!H&&!fe&&(f.setTransform(-1,0,0,1,T.width-I,0),f.drawImage(T,I,0,_,T.height,0,0,_,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),lw()),this.showFPS){const U=ie.height;f.font=`bold ${U}px ${ts}`,f.fillStyle=T_,f.textAlign="right",f.fillText(Math.round(L),T.width-U,U*2)}this.onCanvasDraw&&(f.save(),f.fillStyle=f.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),f.restore())}_freqScaling(e){switch(this._frequencyScale){case Ti:return Math.log2(e);case hr:return 26.81*e/(1960+e)-.53;case fr:return Math.log2(1+e/700);case dn:return e}}_freqToBin(e,i="round"){const n=this._analyzer[0].frequencyBinCount-1,s=Math[i](e*this.fftSize/this.audioCtx.sampleRate);return s<n?s:n}_makeGrad(){if(!this._ready)return;const{canvas:e,_ctx:i,_radial:n,_reflexRatio:s}=this,{analyzerWidth:o,centerX:r,centerY:a,initialX:l,innerRadius:c,outerRadius:u}=this._aux,{isLumi:d}=this._flg,h=this._chLayout==vt,p=1-s,_=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const w=this._gradients[this._selectedGrads[v]],y=w.colorStops,C=w.dir=="h";let I;if(n?I=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):I=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,_]),y){const A=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+A;R++){const P=y.length-1;y.forEach((T,k)=>{let g=T.pos;if(A&&(g/=2),h&&!d&&!n&&!C&&(g*=p,!A&&g>.5*p&&(g+=.5*s)),R==1)if(n||d){const m=P-k;T=y[m],g=1-T.pos/2}else k==0&&g>0&&I.addColorStop(.5,T.color),g+=.5;I.addColorStop(g,T.color),h&&k==P&&g<.5&&I.addColorStop(.5,T.color)})}}this._canvasGradients[v]=I}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=ru&&i.width==u&&i.height==d)&&(i.width=u,i.height=d,this.overlay||(n.fillStyle="#000",n.fillRect(0,0,u,d)),n.lineJoin="bevel",s.width=u,s.height=Math.max(20*o,Math.min(u,d)/32|0),this._calcBars(),this._makeGrad(),this._fsStatus!==void 0&&this._fsStatus!==l&&(e=au),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new tt(O_,e);[0,1].includes(i)||(this._selectedGrads[1]=e,i=0),this._selectedGrads[i]=e,this._makeGrad()}_setProps(e,i){const n=["onCanvasDraw","onCanvasResize"],s=["gradientLeft","gradientRight","stereo"],o=Object.keys(un).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...un,...e});for(const r of Object.keys(e))n.includes(r)&&typeof e[r]!="function"?this[r]=void 0:o.includes(r)&&(this[r]=e[r]);e.start!==void 0&&this.toggleAnalyzer(e.start)}}const j_={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}]}},pu=({stream:t,className:e,onClick:i})=>{var o;const n=de(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new $_(n.current,{source:a,audioCtx:r,alphaBars:!1,ansiBands:!1,barSpace:.25,bgAlpha:0,channelLayout:"single",colorMode:"gradient",fadePeaks:!1,fftSize:2048,fillAlpha:0,frequencyScale:"log",gravity:3.8,ledBars:!1,linearAmplitude:!0,linearBoost:2,lineWidth:1.5,loRes:!1,lumiBars:!1,maxDecibels:-20,maxFPS:0,maxFreq:16e3,minDecibels:-90,minFreq:30,mirror:0,mode:7,noteLabels:!1,outlineBars:!1,overlay:!0,peakFadeTime:750,peakHoldTime:500,peakLine:!1,radial:!1,radialInvert:!1,radius:.7,reflexAlpha:1,reflexBright:1,reflexFit:!0,reflexRatio:.5,roundBars:!0,showBgColor:!1,showFPS:!1,showPeaks:!1,showScaleX:!1,showScaleY:!1,smoothing:.7,spinSpeed:0,splitGradient:!1,trueLeds:!1,useCanvas:!0,volume:1,weightingFilter:"D"});return l.registerGradient("gradient",j_[((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]),D("div",{onClick:i,className:Rt("w-full",e),ref:n})},gu=Ln(null),mu=({className:t,debug:e=!1})=>{const i=Ks(gu);return!e||!i||!(i.region||i.dc)?null:D("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&D("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&D("span",{children:" · "}),i.dc&&D("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
17
17
  * @license lucide-preact v0.515.0 - ISC
18
18
  *
19
19
  * This source code is licensed under the ISC license.
20
20
  * See the LICENSE file in the root directory of this source tree.
21
- */const du=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),N_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),uu=t=>{const e=N_(t);return e.charAt(0).toUpperCase()+e.slice(1)},F_=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
21
+ */const vu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),W_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),_u=t=>{const e=W_(t);return e.charAt(0).toUpperCase()+e.slice(1)},H_=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
22
22
  * @license lucide-preact v0.515.0 - ISC
23
23
  *
24
24
  * This source code is licensed under the ISC license.
25
25
  * See the LICENSE file in the root directory of this source tree.
26
- */var V_={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 G_={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 U_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Xe("svg",{...V_,width:String(e),height:e,stroke:t,"stroke-width":n?Number(i)*24/Number(e):i,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Xe(l,c)),...ft(s)]);/**
31
+ */const q_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Xe("svg",{...G_,width:String(e),height:e,stroke:t,"stroke-width":n?Number(i)*24/Number(e):i,class:["lucide",r].join(" "),...a},[...o.map(([l,c])=>Xe(l,c)),...ft(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 $e=(t,e)=>{const i=({class:n="",children:s,...o})=>Xe(U_,{...o,iconNode:e,class:F_(`lucide-${du(uu(t))}`,`lucide-${du(t)}`,n)},s);return i.displayName=uu(t),i};/**
36
+ */const je=(t,e)=>{const i=({class:n="",children:s,...o})=>Xe(q_,{...o,iconNode:e,class:H_(`lucide-${vu(_u(t))}`,`lucide-${vu(t)}`,n)},s);return i.displayName=_u(t),i};/**
37
37
  * @license lucide-preact v0.515.0 - ISC
38
38
  *
39
39
  * This source code is licensed under the ISC license.
40
40
  * See the LICENSE file in the root directory of this source tree.
41
- */const hu=$e("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
41
+ */const yu=je("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const B_=$e("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 z_=je("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
47
47
  * @license lucide-preact v0.515.0 - ISC
48
48
  *
49
49
  * This source code is licensed under the ISC license.
50
50
  * See the LICENSE file in the root directory of this source tree.
51
- */const fu=$e("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
51
+ */const bu=je("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/**
52
52
  * @license lucide-preact v0.515.0 - ISC
53
53
  *
54
54
  * This source code is licensed under the ISC license.
55
55
  * See the LICENSE file in the root directory of this source tree.
56
- */const $_=$e("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 K_=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 j_=$e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const Y_=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 H_=$e("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 X_=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 G_=$e("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 J_=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 W_=$e("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 Z_=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 q_=$e("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 Q_=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 z_=$e("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
86
+ */const ey=je("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
87
87
  * @license lucide-preact v0.515.0 - ISC
88
88
  *
89
89
  * This source code is licensed under the ISC license.
90
90
  * See the LICENSE file in the root directory of this source tree.
91
- */const K_=$e("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
91
+ */const ty=je("send-horizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/**
92
92
  * @license lucide-preact v0.515.0 - ISC
93
93
  *
94
94
  * This source code is licensed under the ISC license.
95
95
  * See the LICENSE file in the root directory of this source tree.
96
- */const Y_=$e("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
96
+ */const iy=je("square-arrow-out-up-right",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/**
97
97
  * @license lucide-preact v0.515.0 - ISC
98
98
  *
99
99
  * This source code is licensed under the ISC license.
100
100
  * See the LICENSE file in the root directory of this source tree.
101
- */const X_=$e("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
101
+ */const ny=je("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const J_=$e("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
106
+ */const sy=je("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/**
107
107
  * @license lucide-preact v0.515.0 - ISC
108
108
  *
109
109
  * This source code is licensed under the ISC license.
110
110
  * See the LICENSE file in the root directory of this source tree.
111
- */const fr=$e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),pu=Rn(!1),Q_=()=>Ga(pu),At=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:It("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),gu=({call:t,chatMode:e})=>{const[i,n]=Q_(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(At,{tooltip:i?"Unmute":"Mute",onClick:s,className:It(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(H_,{className:"w-5 h-5 text-black dark:text-white"}):D(G_,{className:"w-5 h-5 text-black dark:text-white"})}),D(At,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(q_,{className:"w-4 h-4 text-black dark:text-white"})})]})},mu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(yi.div,{layoutId:an,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!i&&D(au,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Ud,{stream:t.remoteStream,chatMode:i}),D(Vd,{size:"small"}),D(gu,{call:t,chatMode:i}),D(cu,{debug:n})]});function Z_(){const[t,e]=Ae(!1),i=Jt();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(At,{tooltip:"More",onClick:()=>e(!t),children:D(fu,{className:"text-black dark:text-white"})}),t&&D("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:[D(At,{tooltip:"More",onClick:()=>e(!t),children:D(fu,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(X_,{className:"w-4 h-4"})]}),i.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(J_,{className:"w-4 h-4"})]}),i.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D($_,{className:"w-4 h-4"})]})]})]})]})}function ey(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var is={exports:{}},ty=is.exports,vu;function iy(){return vu||(vu=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(ty,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var _=v[b];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var _=s[b];this[_]=b<v?e:this.methodFactory(_,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,_){return c(v)||d.apply(this,arguments)}function g(v,b){var _=this,C,k,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(f){var w=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=w;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+w+";"}catch{}}}function T(){var f;if(!(typeof window===i||!x)){try{f=window.localStorage[x]}catch{}if(typeof f===i)try{var w=window.document.cookie,I=encodeURIComponent(x),L=w.indexOf(I+"=");L!==-1&&(f=/^([^;]+)/.exec(w.slice(L+I.length+1))[1])}catch{}return _.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var w=f;if(typeof w=="string"&&_.levels[w.toUpperCase()]!==void 0&&(w=_.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=_.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+f)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=b||h,_.getLevel=function(){return A??k??C},_.setLevel=function(f,w){return A=p(f),w!==!1&&N(A),u.call(_)},_.setDefaultLevel=function(f){k=p(f),T()||_.setLevel(f,!1)},_.resetLevel=function(){A=null,E(),u.call(_)},_.enableAll=function(f){_.setLevel(_.levels.TRACE,f)},_.disableAll=function(f){_.setLevel(_.levels.SILENT,f)},_.rebuild=function(){if(r!==_&&(C=p(r.getLevel())),u.call(_),r===_)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var m=T();m!=null&&(A=p(m)),u.call(_)}r=new g,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var _=o[b];return _||(_=o[b]=new g(b,r.methodFactory)),_};var y=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(is)),is.exports}var ny=iy();const sy=ey(ny),oy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ry="[ai-agent-widget]",se=sy.getLogger("telnyx-ai-agent-widget"),ay=se.methodFactory;se.methodFactory=(t,e,i)=>{const n=ay(t,e,i);return function(...s){n(oy(),ry,...s)}},se.setLevel("info");function ly({onCapture:t,onClose:e}){const i=de(null),n=de(null),s=de(null),[o,r]=Ae(null),[a,l]=Ae(!0);Re(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,i.current&&(i.current.srcObject=h,l(!1))}catch(h){se.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,g=h.getContext("2d");if(!g)return;h.width=d.videoWidth,h.height=d.videoHeight,g.drawImage(d,0,0,h.width,h.height);const y=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(y),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("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:[D("div",{className:"absolute top-2 right-2 z-10",children:D(At,{tooltip:"Close",onClick:u,children:D(fr,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(ht,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:It("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("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:[D(hu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const pr=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],cy=["audio","lang","mark","p","s","sub","w"],_u=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function yu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function bu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const wu=pr.filter(t=>!cy.includes(t)),dy=yu(pr,"gi"),Su=yu(wu,"gi"),uy=bu(pr,"i"),hy=bu(wu,"i"),fy=new RegExp(`${Su.source}|${_u.source}`,"i");function py(t){const e=fy.test(t),i=e?dy:Su,n=e?uy:hy;return t.replace(i,"").replace(n,"").replace(_u,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function gy({item:t,containerRef:e}){const i=de(null),n=t.role==="assistant"?py(t.content):t.content;return Re(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:It("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:It("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),n&&D("p",{className:It("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const my=({transcript:t,call:e})=>{const i=de(null),n=de(null),s=de(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=rr();Re(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),Re(()=>{if(c.length===0)return;const T=t.filter(E=>E.role==="user"&&!E.id.startsWith("optimistic-"));if(T.length>0){const E=T[T.length-1];u(p=>p.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,p)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=p,m.readAsDataURL(T)}),g=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),p=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:E,preview:p};r(f=>[...f,m])}catch(E){se.error("Error processing image:",E)}},y=T=>{r(E=>{const p=E.find(m=>m.id===T);return p&&URL.revokeObjectURL(p.preview),E.filter(m=>m.id!==T)})},v=T=>{const E=T.target,p=E.files;p&&p.length>0&&(Array.from(p).forEach(g),E.value="")},b=T=>{var p;const E=(p=T.clipboardData)==null?void 0:p.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&g(f)}})},_=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const p=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(E=>{se.error("Error processing camera capture:",E)})},A=async()=>{var p;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){const m=((p=i.current)==null?void 0:p.value)||"",f=new Date,w={id:`optimistic-${f.getTime()}`,role:"user",content:m,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,w]),E&&d("processing_image"),e.sendConversationMessage(m,o.map(I=>I.base64)),i.current&&(i.current.value=""),o.forEach(I=>URL.revokeObjectURL(I.preview)),r([])}},x=T=>{T.key==="Enter"&&(T.preventDefault(),A())},N=[...t,...c];return D("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:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:N.map((T,E)=>D(gy,{item:T,containerRef:s},T.id+E))}),o.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>D("div",{className:"relative",children:[D("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>y(T.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:D(fr,{className:"w-3 h-3"})})]},T.id))}),D("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:[D("input",{ref:i,type:"text",onKeyDown:x,onPaste:b,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),D("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),D(At,{tooltip:"Attach image",onClick:_,children:D(W_,{className:"text-[#969696] w-4 h-4"})}),D(At,{tooltip:"Take photo",onClick:C,children:D(hu,{className:"text-[#969696] w-4 h-4"})}),D(At,{tooltip:"Send",children:D(K_,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&D(ly,{onCapture:k,onClose:()=>l(!1)})]})};function vy({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(Z_,{}),D(At,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(fr,{className:"text-black dark:text-white"})})]})}const _y=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Ag,{children:D(yi.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:[D("div",{className:"p-4 text-center",children:[D(vy,{onCollapse:e}),!n&&D(au,{className:"h-[144px]",stream:t.remoteStream}),D(Vd,{size:"large",className:"mb-4"}),D(gu,{call:t,chatMode:n}),D(cu,{className:"mt-2",debug:s})]}),D(Ud,{stream:t.remoteStream,chatMode:n}),D(my,{call:t,transcript:i})]})});function Cu(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function U(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var Tu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),yy=new Uint8Array(16);function by(){if(!Tu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Tu(yy)}for(var Eu=[],ns=0;ns<256;++ns)Eu[ns]=(ns+256).toString(16).substr(1);function Ci(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||by)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,a){var l=0,c=Eu;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 wy={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},Sy={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,DUPLICATE_INBOUND_ANSWER:33007,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_HEALTH_PROBE_TIMEOUT:36001,SIGNALING_REQUEST_TIMEOUT:36002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004},{SDP_CREATE_OFFER_FAILED:Cy,SDP_CREATE_ANSWER_FAILED:Ty,SDP_SET_LOCAL_DESCRIPTION_FAILED:Ey,SDP_SET_REMOTE_DESCRIPTION_FAILED:ku,SDP_SEND_FAILED:Iu,MEDIA_MICROPHONE_PERMISSION_DENIED:ky,MEDIA_DEVICE_NOT_FOUND:Iy,MEDIA_GET_USER_MEDIA_FAILED:xu,HOLD_FAILED:xy,INVALID_CALL_PARAMETERS:Ay,BYE_SEND_FAILED:Ry,SUBSCRIBE_FAILED:Ly,PEER_CLOSED_DURING_INIT:gr,WEBSOCKET_CONNECTION_FAILED:Dy,WEBSOCKET_ERROR:Py,RECONNECTION_EXHAUSTED:Au,GATEWAY_FAILED:My,LOGIN_FAILED:Ru,INVALID_CREDENTIALS:Oy,AUTHENTICATION_REQUIRED:Ny,ICE_RESTART_FAILED:Fy,NETWORK_OFFLINE:Vy,SESSION_NOT_REATTACHED:Uy,UNEXPECTED_ERROR:Lu}=wy,{HIGH_RTT:By,HIGH_JITTER:$y,HIGH_PACKET_LOSS:jy,LOW_MOS:Du,LOW_LOCAL_AUDIO:ss,LOW_BYTES_RECEIVED:Pu,LOW_BYTES_SENT:Mu,ICE_CONNECTIVITY_LOST:Hy,ICE_GATHERING_TIMEOUT:Gy,ICE_GATHERING_EMPTY:Wy,PEER_CONNECTION_FAILED:qy,ONLY_HOST_ICE_CANDIDATES:zy,ANSWER_WHILE_PEER_ACTIVE:Ky,ICE_CANDIDATE_PAIR_CHANGED:Yy,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:Xy,DUPLICATE_INBOUND_ANSWER:Jy,TOKEN_EXPIRING_SOON:Qy,UNKNOWN_REATTACHED_SESSION:Zy,SIGNALING_HEALTH_PROBE_TIMEOUT:e0,SIGNALING_REQUEST_TIMEOUT:t0,SIGNALING_RECOVERY_REQUIRED:i0,MEDIA_RECOVERY_REQUIRED:n0}=Sy,s0=/^a=candidate:.+typ (srflx|prflx|relay)/m,Ou="wss://rtc.telnyx.com",Nu={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Fu={urls:"stun:stun.l.google.com:19302"},o0=[{urls:"stun:stun.telnyx.com:3478"},Fu,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],r0=[{urls:"stun:stundev.telnyx.com:3478"},Fu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var M;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(M||(M={}));const a0={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"]},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"]},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"]},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"]},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"]},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"]},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"]},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"]},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"]},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"]},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"]},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"]},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"]},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"]},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"]},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"]},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"]},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"]},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"]},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"]},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"]},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"]},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"]},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"]}},l0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36001:{name:"SIGNALING_HEALTH_PROBE_TIMEOUT",message:"Signaling health probe timed out",description:"A signaling liveness probe (Ping) was sent during an active call but no response was received within the timeout window. This indicates the WebSocket may be half-dead — the browser reports it as OPEN but data is not flowing. The SDK will force-close the socket to trigger reconnection.",causes:["Network interface removed mid-call while another interface remains","TCP connection bound to a removed IP/route became half-dead","Firewall or NAT state expired silently","WebSocket proxy or load balancer dropped the connection without a close frame"],solutions:["The SDK will automatically force-close the socket and reconnect","Check for network interface changes during the call","Verify firewall/NAT timeout settings"]},36002:{name:"SIGNALING_REQUEST_TIMEOUT",message:"Signaling request timed out",description:"A signaling-critical JSON-RPC request (e.g. ICE restart Modify) did not receive a response within the timeout window while the socket reports OPEN. This may indicate the WebSocket is half-dead or the server is unresponsive. The SDK will mark signaling as unhealthy and force reconnection.",causes:["Half-dead WebSocket (browser reports OPEN but data does not flow)","Server unresponsive or overloaded","Network path interruption without TCP RST"],solutions:["The SDK will automatically force-close the socket and reconnect","Check server health and response times","Check for network path issues"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. If media was still flowing, the reconnect is delayed briefly to allow the application to notify the user about a short interruption. Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function ze(t,e){const i=l0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class dn extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,Object.setPrototypeOf(this,dn.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError}}}function Ti(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return ky;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Iy}return xu}function re(t,e,i){const n=a0[t],s=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new dn({code:t,name:n.name,description:n.description,message:i||n.message,causes:[...n.causes],solutions:[...n.solutions],originalError:s})}class c0 extends Error{constructor(e,i,n=""){super(`Signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=i,this.method=n}}class mr extends Error{constructor(e,i,n){super(`Stale request cancelled (id=${e}, gen=${i}, current=${n})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=i,this.currentGeneration=n}}var d0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Vu(t,e){return t(e={exports:{}},e.exports),e.exports}var u0=Vu(function(t){var e,i;e=d0,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(b,_){var C=b[_];if(typeof C.bind=="function")return C.bind(b);try{return Function.prototype.bind.call(C,b)}catch{return function(){return Function.prototype.apply.apply(C,[b,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(b,_){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,_)}this.log=this.debug}function u(b,_,C){return function(){typeof console!==s&&(c.call(this,_,C),this[b].apply(this,arguments))}}function d(b,_,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,_,C){var k,A=this;_=_??"WARN";var x="loglevel";function N(){var E;if(typeof window!==s&&x){try{E=window.localStorage[x]}catch{}if(typeof E===s)try{var p=window.document.cookie,m=p.indexOf(encodeURIComponent(x)+"=");m!==-1&&(E=/^([^;]+)/.exec(p.slice(m))[1])}catch{}return A.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?x+=":"+b:typeof b=="symbol"&&(x=void 0),A.name=b,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return k},A.setLevel=function(E,p){if(typeof E=="string"&&A.levels[E.toUpperCase()]!==void 0&&(E=A.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,p!==!1&&function(m){var f=(r[m]||"silent").toUpperCase();if(typeof window!==s&&x){try{return void(window.localStorage[x]=f)}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+f+";"}catch{}}}(E),c.call(A,E,b),typeof console===s&&E<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(E){_=E,N()||A.setLevel(E,!1)},A.resetLevel=function(){A.setLevel(_,!1),function(){if(typeof window!==s&&x){try{return void window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(E){A.setLevel(A.levels.TRACE,E)},A.disableAll=function(E){A.setLevel(A.levels.SILENT,E)};var T=N();T==null&&(T=_),A.setLevel(T,!1)}var g=new h,y={};g.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var _=y[b];return _||(_=y[b]=new h(b,g.getLevel(),g.methodFactory)),_};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return y},g.default=g,g},t.exports?t.exports=i():e.log=i()});const Uu={debug:0,info:1,warn:2,error:3};class h0{constructor(e={}){var i,n,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(i=e.enabled)!==null&&i!==void 0&&i,level:(n=e.level)!==null&&n!==void 0?n:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,i,n){if(!this.isCapturing||!this.options.enabled||Uu[e]<Uu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:i},n&&Object.keys(n).length>0?{context:n}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let Bu=null;const S=u0.getLogger("telnyx"),os={trace:0,debug:1,info:2,warn:3,error:4};let $u=os.info;function ju(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const f0=S.methodFactory;S.methodFactory=(t,e,i)=>{const n=f0(t,e,i);return function(...s){if(os[t]>=$u){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Bu;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?ju(a[0]):{args:a.map(ju)}),o.addEntry(t,l,c)}}},S.setLevel("debug",!1);const rs=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{S.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Hu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ei=t=>t instanceof Function||typeof t=="function",un=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,p0=/^(ws|wss):\/\//,Gu=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Gu(a,r):{result:s}},Wu=(t,e)=>Math.floor(Math.random()*(e-t+1)+t),as=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),hn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,vr=t=>{var e,i,n,s,o,r;let a="",l="";return!((i=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||i===void 0)&&i.state&&(a=(s=(n=t==null?void 0:t.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function qu({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?g0(n,t):n,i=s}),resolve:e,reject:i}}const g0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},_r="telnyx-voice-sdk-id",ls="telnyx-voice-sdk-session-id",cs="telnyx-voice-sdk-session-id-stored-at",m0=9e4;function zu(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(cs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=m0}function fn(){return sessionStorage.getItem(_r)}function Ku(t,e=Date.now()){sessionStorage.setItem(ls,t),sessionStorage.setItem(cs,String(e))}function Yu(){sessionStorage.removeItem(_r),sessionStorage.removeItem(ls),sessionStorage.removeItem(cs)}var Ne,lt,Q;(function(t){t.Offer="offer",t.Answer="answer"})(Ne||(Ne={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(lt||(lt={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(Q||(Q={}));const it={generic:"event",[Q.Display]:"participantData",[Q.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},v0={invalidCredentialsOptions:"InvalidCredentialsOptions"},_0={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 j,yr,Ke,_t,De,ki;(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"})(j||(j={})),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"}(Ke||(Ke={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(_t||(_t={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(De||(De={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(ki||(ki={}));const Ii="GLOBAL",We={},pn=(t,e)=>`${t}|${e}`,Xu=(t,e=Ii)=>pn(t,e)in We,Vt=(t,e,i=Ii)=>{const n=pn(t,i);n in We||(We[n]=[]),We[n].push(e)},Ju=(t,e,i=Ii)=>{const n=function(s){yt(t,n,i),e(s)};return n.prototype.targetRef=e,Vt(t,n,i)},yt=(t,e,i=Ii)=>{if(!Xu(t,i))return!1;const n=pn(t,i);if(Ei(e))for(let s=We[n].length-1;s>=0;s--){const o=We[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&We[n].splice(s,1)}else We[n]=[];return We[n].length===0&&delete We[n],!0},V=(t,e,i=Ii,n=!0)=>{const s=n&&i!==Ii;if(!Xu(t,i))return s&&V(t,e),!1;const o=pn(t,i),r=We[o].length;if(!r)return s&&V(t,e),!1;for(let a=r-1;a>=0;a--)We[o][a](e);return s&&V(t,e),!0},br=t=>{const e=pn(t,"");Object.keys(We).filter(i=>i.indexOf(e)===0).forEach(i=>delete We[i])};let y0=typeof WebSocket<"u"?WebSocket:null;const b0=0,w0=1,S0=2,Qu=3;class ds{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Ou,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:i,env:n,region:s,useCanaryRtcServer:o}=e.options;n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Ou),i&&(this._host=(r=>`${p0.test(r)?"":"wss://"}${r}`)(i)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===w0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===b0}get closing(){return!!this._wsClient&&this._wsClient.readyState===S0}get closed(){return!!this._wsClient&&this._wsClient.readyState===Qu}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 i=fn();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&e.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),S.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const n=this.socketGeneration;this._wsClient=new y0(e.toString()),this.socketGeneration+=1,S.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:n}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(n){S.error("WebSocket connection failed:",n);const s=re(Dy,n);V(M.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid)}}sendRawText(e){var i;(i=this._wsClient)===null||i===void 0||i.send(e)}send(e,i){var n;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=g=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),u)return;const{result:y,error:v}=Gu(g);return v?c(v):l(y)};Ju(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),i&&i>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),yt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return S.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new mr(s.id,o,this.socketGeneration));c(new c0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return S.debug(`SEND:
111
+ */const gr=je("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),wu=Ln(!1),oy=()=>Ja(wu),xt=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:Rt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Su=({call:t,chatMode:e})=>{const[i,n]=oy(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(xt,{tooltip:i?"Unmute":"Mute",onClick:s,className:Rt(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(X_,{className:"w-5 h-5 text-black dark:text-white"}):D(J_,{className:"w-5 h-5 text-black dark:text-white"})}),D(xt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(Q_,{className:"w-4 h-4 text-black dark:text-white"})})]})},Cu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(wi.div,{layoutId:cn,className:"bg-[#FEFDF5] text-black p-4 rounded-3xl w-[250px] overflow-hidden flex flex-col items-center justify-center dark:bg-black dark:text-white shadow-lg shadow-[#38383878] gap-3",children:[!i&&D(pu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(qd,{stream:t.remoteStream,chatMode:i}),D(Gd,{size:"small"}),D(Su,{call:t,chatMode:i}),D(mu,{debug:n})]});function ry(){const[t,e]=Ae(!1),i=Qt();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(xt,{tooltip:"More",onClick:()=>e(!t),children:D(bu,{className:"text-black dark:text-white"})}),t&&D("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:[D(xt,{tooltip:"More",onClick:()=>e(!t),children:D(bu,{className:"text-black dark:text-white"})}),D("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&D("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",D(ny,{className:"w-4 h-4"})]}),i.report_issue_url&&D("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",D(sy,{className:"w-4 h-4"})]}),i.view_history_url&&D("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",D(K_,{className:"w-4 h-4"})]})]})]})]})}function ay(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ns={exports:{}},ly=ns.exports,Tu;function cy(){return Tu||(Tu=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(ly,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),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===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,w,y){return c(v)||d.apply(this,arguments)}function p(v,w){var y=this,C,I,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function P(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,E=encodeURIComponent(R),x=S.indexOf(E+"=");x!==-1&&(f=/^([^;]+)/.exec(S.slice(x+E.length+1))[1])}catch{}return y.levels[f]===void 0&&(f=void 0),f}}function k(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||h,y.getLevel=function(){return A??I??C},y.setLevel=function(f,S){return A=g(f),S!==!1&&P(A),u.call(y)},y.setDefaultLevel=function(f){I=g(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=g(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(A=g(m)),u.call(y)}r=new p,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 p(w,r.methodFactory)),y};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(ns)),ns.exports}var dy=cy();const uy=ay(dy),hy=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fy="[ai-agent-widget]",oe=uy.getLogger("telnyx-ai-agent-widget"),py=oe.methodFactory;oe.methodFactory=(t,e,i)=>{const n=py(t,e,i);return function(...s){n(hy(),fy,...s)}},oe.setLevel("info");function gy({onCapture:t,onClose:e}){const i=de(null),n=de(null),s=de(null),[o,r]=Ae(null),[a,l]=Ae(!0);xe(()=>((async()=>{try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment",width:{ideal:1920},height:{ideal:1080}}});s.current=h,i.current&&(i.current.srcObject=h,l(!1))}catch(h){oe.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,p=h.getContext("2d");if(!p)return;h.width=d.videoWidth,h.height=d.videoHeight,p.drawImage(d,0,0,h.width,h.height);const _=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(_),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("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:[D("div",{className:"absolute top-2 right-2 z-10",children:D(xt,{tooltip:"Close",onClick:u,children:D(gr,{className:"text-white w-5 h-5"})})}),D("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&D("div",{className:"absolute text-white text-center",children:D("p",{className:"text-sm",children:"Loading camera..."})}),o&&D("div",{className:"text-white text-center max-w-xs",children:[D("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),D("p",{className:"text-xs",children:o}),D("button",{onClick:u,className:"mt-3 px-3 py-1.5 text-xs bg-white text-black rounded-full hover:bg-gray-200 transition-colors",children:"Close"})]}),!o&&D(ht,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:Rt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),D("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&D("div",{className:"p-3 flex justify-center",children:D("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:[D(yu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const mr=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],my=["audio","lang","mark","p","s","sub","w"],ku=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function Iu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function Eu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Ru=mr.filter(t=>!my.includes(t)),vy=Iu(mr,"gi"),Au=Iu(Ru,"gi"),_y=Eu(mr,"i"),yy=Eu(Ru,"i"),by=new RegExp(`${Au.source}|${ku.source}`,"i");function wy(t){const e=by.test(t),i=e?vy:Au,n=e?_y:yy;return t.replace(i,"").replace(n,"").replace(ku,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function Sy({item:t,containerRef:e}){const i=de(null),n=t.role==="assistant"?wy(t.content):t.content;return xe(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:Rt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[D("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&D("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),D("div",{className:Rt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&D("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&D("img",{src:s.url,alt:"Attached image",className:"max-w-32 max-h-32 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"},o))}),n&&D("p",{className:Rt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const Cy=({transcript:t,call:e})=>{const i=de(null),n=de(null),s=de(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=lr();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{if(c.length===0)return;const T=t.filter(k=>k.role==="user"&&!k.id.startsWith("optimistic-"));if(T.length>0){const k=T[T.length-1];u(g=>g.filter(m=>m.timestamp>k.timestamp))}},[t,c]);const h=T=>new Promise((k,g)=>{const m=new FileReader;m.onload=()=>k(m.result),m.onerror=g,m.readAsDataURL(T)}),p=async T=>{if(T.type.startsWith("image/"))try{const k=await h(T),g=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:k,preview:g};r(f=>[...f,m])}catch(k){oe.error("Error processing image:",k)}},_=T=>{r(k=>{const g=k.find(m=>m.id===T);return g&&URL.revokeObjectURL(g.preview),k.filter(m=>m.id!==T)})},v=T=>{const k=T.target,g=k.files;g&&g.length>0&&(Array.from(g).forEach(p),k.value="")},w=T=>{var g;const k=(g=T.clipboardData)==null?void 0:g.items;k&&Array.from(k).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&p(f)}})},y=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},I=T=>{fetch(T).then(k=>k.blob()).then(k=>{const g=new File([k],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});p(g)}).catch(k=>{oe.error("Error processing camera capture:",k)})},A=async()=>{var g;const T=i.current&&i.current.value.trim()!=="",k=o.length>0;if(T||k){const m=((g=i.current)==null?void 0:g.value)||"",f=new Date,S={id:`optimistic-${f.getTime()}`,role:"user",content:m,timestamp:f,attachments:o.map(E=>({type:"image",url:E.base64}))};u(E=>[...E,S]),k&&d("processing_image"),e.sendConversationMessage(m,o.map(E=>E.base64)),i.current&&(i.current.value=""),o.forEach(E=>URL.revokeObjectURL(E.preview)),r([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),A())},P=[...t,...c];return D("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:[D("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:P.map((T,k)=>D(Sy,{item:T,containerRef:s},T.id+k))}),o.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>D("div",{className:"relative",children:[D("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>_(T.id),className:"absolute flex items-center justify-center w-5 h-5 text-xs text-white bg-red-500 rounded-full -top-1 -right-1 hover:bg-red-600",title:"Remove image",children:D(gr,{className:"w-3 h-3"})})]},T.id))}),D("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:[D("input",{ref:i,type:"text",onKeyDown:R,onPaste:w,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),D("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),D(xt,{tooltip:"Attach image",onClick:y,children:D(Z_,{className:"text-[#969696] w-4 h-4"})}),D(xt,{tooltip:"Take photo",onClick:C,children:D(yu,{className:"text-[#969696] w-4 h-4"})}),D(xt,{tooltip:"Send",children:D(ty,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&D(gy,{onCapture:I,onClose:()=>l(!1)})]})};function Ty({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(ry,{}),D(xt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(gr,{className:"text-black dark:text-white"})})]})}const ky=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Ng,{children:D(wi.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:[D("div",{className:"p-4 text-center",children:[D(Ty,{onCollapse:e}),!n&&D(pu,{className:"h-[144px]",stream:t.remoteStream}),D(Gd,{size:"large",className:"mb-4"}),D(Su,{call:t,chatMode:n}),D(mu,{className:"mt-2",debug:s})]}),D(qd,{stream:t.remoteStream,chatMode:n}),D(Cy,{call:t,transcript:i})]})});function xu(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function V(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var Lu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Iy=new Uint8Array(16);function Ey(){if(!Lu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lu(Iy)}for(var Du=[],ss=0;ss<256;++ss)Du[ss]=(ss+256).toString(16).substr(1);function ki(t,e,i){var n=e&&i||0;typeof t=="string"&&(e=t==="binary"?new Array(16):null,t=null);var s=(t=t||{}).random||(t.rng||Ey)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e)for(var o=0;o<16;++o)e[n+o]=s[o];return e||function(r,a){var l=0,c=Du;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 Ry={SDP_CREATE_OFFER_FAILED:40001,SDP_CREATE_ANSWER_FAILED:40002,SDP_SET_LOCAL_DESCRIPTION_FAILED:40003,SDP_SET_REMOTE_DESCRIPTION_FAILED:40004,SDP_SEND_FAILED:40005,MEDIA_MICROPHONE_PERMISSION_DENIED:42001,MEDIA_DEVICE_NOT_FOUND:42002,MEDIA_GET_USER_MEDIA_FAILED:42003,HOLD_FAILED:44001,INVALID_CALL_PARAMETERS:44002,BYE_SEND_FAILED:44003,SUBSCRIBE_FAILED:44004,PEER_CLOSED_DURING_INIT:44005,WEBSOCKET_CONNECTION_FAILED:45001,WEBSOCKET_ERROR:45002,RECONNECTION_EXHAUSTED:45003,GATEWAY_FAILED:45004,LOGIN_FAILED:46001,INVALID_CREDENTIALS:46002,AUTHENTICATION_REQUIRED:46003,ICE_RESTART_FAILED:47001,NETWORK_OFFLINE:48001,SESSION_NOT_REATTACHED:48501,UNEXPECTED_ERROR:49001},Ay={HIGH_RTT:31001,HIGH_JITTER:31002,HIGH_PACKET_LOSS:31003,LOW_MOS:31004,LOW_LOCAL_AUDIO:31005,LOW_INBOUND_AUDIO:31006,LOW_BYTES_RECEIVED:32001,LOW_BYTES_SENT:32002,RECORDING_UNAVAILABLE:32003,RECORDING_BUFFER_OVERFLOW:32004,ICE_CONNECTIVITY_LOST:33001,ICE_GATHERING_TIMEOUT:33002,ICE_GATHERING_EMPTY:33003,PEER_CONNECTION_FAILED:33004,ONLY_HOST_ICE_CANDIDATES:33005,ANSWER_WHILE_PEER_ACTIVE:33006,ICE_CANDIDATE_PAIR_CHANGED:33008,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:33009,MULTIPLE_ACTIVE_CALLS_DETECTED:33010,DUPLICATE_INBOUND_ANSWER:33007,TOKEN_EXPIRING_SOON:34001,UNKNOWN_REATTACHED_SESSION:35002,SIGNALING_RECOVERY_REQUIRED:36003,MEDIA_RECOVERY_REQUIRED:36004,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:36005},{SDP_CREATE_OFFER_FAILED:xy,SDP_CREATE_ANSWER_FAILED:Ly,SDP_SET_LOCAL_DESCRIPTION_FAILED:Dy,SDP_SET_REMOTE_DESCRIPTION_FAILED:Ou,SDP_SEND_FAILED:vr,MEDIA_MICROPHONE_PERMISSION_DENIED:Oy,MEDIA_DEVICE_NOT_FOUND:My,MEDIA_GET_USER_MEDIA_FAILED:Mu,HOLD_FAILED:Py,INVALID_CALL_PARAMETERS:Ny,BYE_SEND_FAILED:Fy,SUBSCRIBE_FAILED:Vy,PEER_CLOSED_DURING_INIT:_r,WEBSOCKET_CONNECTION_FAILED:By,WEBSOCKET_ERROR:Uy,RECONNECTION_EXHAUSTED:yr,GATEWAY_FAILED:$y,LOGIN_FAILED:Pu,INVALID_CREDENTIALS:jy,AUTHENTICATION_REQUIRED:Wy,ICE_RESTART_FAILED:Hy,NETWORK_OFFLINE:Gy,SESSION_NOT_REATTACHED:Nu,UNEXPECTED_ERROR:Fu}=Ry,{HIGH_RTT:qy,HIGH_JITTER:zy,HIGH_PACKET_LOSS:Ky,LOW_MOS:Vu,LOW_LOCAL_AUDIO:os,LOW_INBOUND_AUDIO:Bu,LOW_BYTES_RECEIVED:Uu,LOW_BYTES_SENT:$u,RECORDING_UNAVAILABLE:Yy,RECORDING_BUFFER_OVERFLOW:Xy,ICE_CONNECTIVITY_LOST:Jy,ICE_GATHERING_TIMEOUT:Zy,ICE_GATHERING_EMPTY:Qy,PEER_CONNECTION_FAILED:e0,ONLY_HOST_ICE_CANDIDATES:t0,ANSWER_WHILE_PEER_ACTIVE:i0,ICE_CANDIDATE_PAIR_CHANGED:n0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:s0,MULTIPLE_ACTIVE_CALLS_DETECTED:o0,DUPLICATE_INBOUND_ANSWER:r0,TOKEN_EXPIRING_SOON:a0,UNKNOWN_REATTACHED_SESSION:l0,SIGNALING_RECOVERY_REQUIRED:c0,MEDIA_RECOVERY_REQUIRED:d0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:u0}=Ay,h0=/^a=candidate:.+typ (srflx|prflx|relay)/m,ju="wss://rtc.telnyx.com",Wu={NORMAL_CLOSURE:1e3,GOING_AWAY:1001,PROTOCOL_ERROR:1002,UNSUPPORTED_DATA:1003,NO_STATUS_RECEIVED:1005,ABNORMAL_CLOSURE:1006,INVALID_FRAME_PAYLOAD:1007,POLICY_VIOLATION:1008,MESSAGE_TOO_BIG:1009,INTERNAL_ERROR:1011},Hu={urls:"stun:stun.l.google.com:19302"},f0=[{urls:"stun:stun.telnyx.com:3478"},Hu,{urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}],p0=[{urls:"stun:stundev.telnyx.com:3478"},Hu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"}];var M;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.SocketActivity="telnyx.internal.socketActivity",t.Ready="telnyx.ready",t.Error="telnyx.error",t.Warning="telnyx.warning",t.Notification="telnyx.notification",t.StatsFrame="telnyx.stats.frame",t.StatsReport="telnyx.stats.report",t.Messages="telnyx.messages",t.Calls="telnyx.calls",t.MediaError="telnyx.rtc.mediaError",t.PeerConnectionFailureError="telnyx.rtc.peerConnectionFailureError",t.PeerConnectionSignalingStateClosed="telnyx.rtc.peerConnectionSignalingStateClosed",t.AIConversationMessage="telnyx.ai.conversation"})(M||(M={}));const g0={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],fatal:!0},40002:{name:"SDP_CREATE_ANSWER_FAILED",message:"Failed to answer the call",description:"The browser was unable to generate a local SDP answer. The remote offer may be invalid or the browser state inconsistent.",causes:["Browser WebRTC API error","Invalid remote SDP offer"],solutions:["Retry the call","Check browser WebRTC compatibility"],fatal:!0},40003:{name:"SDP_SET_LOCAL_DESCRIPTION_FAILED",message:"Failed to apply local call settings",description:"setLocalDescription() was rejected by the browser. The generated SDP may be malformed or the browser state may be inconsistent.",causes:["Malformed SDP","Browser state inconsistency"],solutions:["Retry the call"],fatal:!0},40004:{name:"SDP_SET_REMOTE_DESCRIPTION_FAILED",message:"Failed to apply remote call settings",description:"setRemoteDescription() was rejected by the browser. The remote SDP may be malformed or contain unsupported codecs.",causes:["Malformed remote SDP","Browser codec mismatch"],solutions:["Retry the call","Check codec configuration"],fatal:!0},40005:{name:"SDP_SEND_FAILED",message:"Failed to send call data to server",description:"The Invite or Answer message could not be delivered via the signaling WebSocket. The connection may have been lost.",causes:["WebSocket connection lost","Server error"],solutions:["Check network connectivity","Retry the call"],fatal:!0},42001:{name:"MEDIA_MICROPHONE_PERMISSION_DENIED",message:"Microphone access denied",description:"The user or operating system denied microphone permission. The browser permission prompt was dismissed or OS-level access is disabled.",causes:["User denied browser permission prompt","OS-level microphone access disabled"],solutions:["Ask user to grant microphone permission in browser settings"],fatal:!0},42002:{name:"MEDIA_DEVICE_NOT_FOUND",message:"No microphone found",description:"The requested audio input device is not available. No microphone is connected, the device was disconnected, or an invalid deviceId was specified.",causes:["No microphone connected","Device was disconnected","Invalid deviceId"],solutions:["Check that a microphone is connected","Select a valid audio input device"],fatal:!0},42003:{name:"MEDIA_GET_USER_MEDIA_FAILED",message:"Failed to access microphone",description:"getUserMedia() was rejected for an unexpected reason. The device may be in use by another application or the browser encountered an internal error.",causes:["Browser error","Device in use by another application"],solutions:["Close other applications using the microphone","Retry"],fatal:!0},44001:{name:"HOLD_FAILED",message:"Failed to hold the call",description:"The server rejected or did not respond to the hold request. The WebSocket connection may have been lost during the operation.",causes:["Server error","WebSocket connection lost during hold"],solutions:["Retry the hold operation","Check network connectivity"],fatal:!1},44002:{name:"INVALID_CALL_PARAMETERS",message:"Invalid call parameters",description:"The call could not be initiated because required parameters are missing or invalid. For example, no destination number was provided to newCall().",causes:["Missing destinationNumber in call options","Invalid or empty call parameters"],solutions:["Provide a valid destinationNumber when calling newCall()","Check the call options object for required fields"],fatal:!0},44003:{name:"BYE_SEND_FAILED",message:"Failed to hang up cleanly",description:"The hangup signal could not be delivered to the server. The call was terminated locally but the server may not be aware.",causes:["WebSocket connection lost before BYE sent"],solutions:["No action needed — call is terminated locally","Check network connectivity"],fatal:!1},44004:{name:"SUBSCRIBE_FAILED",message:"Failed to subscribe to call events",description:"The Verto subscribe request for the call channel failed. This may prevent receiving call state updates from the server.",causes:["WebSocket connection lost during subscribe","Server rejected the subscription request"],solutions:["Check network connectivity","Retry the call"],fatal:!1},44005:{name:"PEER_CLOSED_DURING_INIT",message:"Call was closed during setup",description:"The PeerConnection was closed (e.g. by hangup()) while peer.init() was still running. This is a race condition: an async operation such as setRemoteDescription, getUserMedia, or the media recovery flow yielded control, and close() ran during that gap. The init() cannot continue because the underlying RTCPeerConnection has been destroyed.",causes:["call.hangup() or call.close() was called while the call was still setting up","A WebSocket Bye message arrived during getUserMedia prompt or SDP negotiation","User clicked hangup/decline before media permissions were granted"],solutions:["This is expected if the user intentionally hung up during setup — no action needed","If this happens frequently without user action, check for automatic hangup triggers that may fire too early"],fatal:!0},45001:{name:"WEBSOCKET_CONNECTION_FAILED",message:"Unable to connect to server",description:"The WebSocket connection to the signaling server could not be established. The server may be unreachable, the URL may be incorrect, or a firewall may be blocking the connection.",causes:["Server unreachable","Incorrect WebSocket URL","Firewall blocking WebSocket connections","Network interruption"],solutions:["Check network connectivity","Verify the signaling server URL","Ensure WebSocket connections are not blocked by a firewall"],fatal:!0},45002:{name:"WEBSOCKET_ERROR",message:"Connection to server lost",description:"An error occurred on the WebSocket connection after it was established. The connection may have been dropped due to network issues or server-side closure.",causes:["Network interruption","Server closed the connection","Idle timeout"],solutions:["Check network connectivity","SDK will attempt automatic reconnection if configured"],fatal:!1},45003:{name:"RECONNECTION_EXHAUSTED",message:"Unable to reconnect to server",description:"All automatic reconnection attempts have been exhausted. The SDK tried to re-establish the WebSocket connection multiple times but failed on every attempt.",causes:["Prolonged network outage","Server unreachable","Firewall or proxy blocking reconnection"],solutions:["Check network connectivity","Call client.disconnect() and client.connect() to manually retry","Notify the user that the connection was lost"],fatal:!0},45004:{name:"GATEWAY_FAILED",message:"Gateway connection failed",description:"The upstream gateway reported a FAILED, FAIL_WAIT, or TIMEOUT state. The signaling server could not establish or maintain a connection to the gateway. When autoReconnect is disabled, this is immediately fatal. When enabled, the SDK will retry until RECONNECTION_EXHAUSTED.",causes:["Gateway down or unreachable","Server-side infrastructure issue","Network partition between signaling server and gateway"],solutions:["Wait for automatic reconnection (if autoReconnect is enabled)","Call client.disconnect() and client.connect() to manually retry","Check Telnyx service status"],fatal:!1},46001:{name:"LOGIN_FAILED",message:"Authentication failed",description:"The login request was rejected by the server. The credentials may be invalid, expired, or the account may be suspended.",causes:["Invalid credentials (username/password or token)","Expired authentication token","Account suspended or disabled"],solutions:["Verify credentials","Generate a new authentication token","Check account status"],fatal:!0},46002:{name:"INVALID_CREDENTIALS",message:"Invalid credential parameters",description:"The SDK rejected the login options before sending any request to the server. This is an internal client-side validation guard — the credentials object is missing required fields or has an invalid structure. No network request was made.",causes:["Missing login and password fields","Missing or malformed authentication token","Invalid combination of credential fields in the options object"],solutions:["Provide valid login/password or a valid authentication token","Check the TelnyxRTC constructor options against the documentation","Ensure the credential object matches one of the supported auth modes (credentials, token, or anonymous)"],fatal:!0},46003:{name:"AUTHENTICATION_REQUIRED",message:"Authentication required",description:"The server rejected a request because the session is not authenticated. This can happen when the client sends a message (e.g. Invite, Subscribe, or Ping) before login completes, after a token expires mid-session, or after the server drops the authenticated state for any reason.",causes:["Message sent before login completed","Authentication token expired during the session","Server-side session was invalidated","WebSocket reconnected but re-authentication did not complete"],solutions:["Ensure the client is fully logged in before sending messages","Re-authenticate using client.login() with fresh credentials","Listen for telnyx.ready before making calls or sending requests"],fatal:!1},47001:{name:"ICE_RESTART_FAILED",message:"ICE restart failed",description:"The ICE restart Modify request could not be sent or the server returned an error. The media path could not be recovered via ICE restart.",causes:["WebSocket connection lost during ICE restart","Server rejected the Modify request","Timeout waiting for server response"],solutions:["The call may recover via WebSocket reconnect + Attach","If the call does not recover, hang up and retry"],fatal:!1},48001:{name:"NETWORK_OFFLINE",message:"Device is offline",description:"The browser reported that the device has lost network connectivity (navigator.onLine === false). All WebSocket and media connections will fail until the network is restored.",causes:["Wi-Fi or ethernet disconnected","Airplane mode enabled","Network interface went down"],solutions:["Check network connectivity","Reconnect to Wi-Fi or ethernet","Disable airplane mode"],fatal:!1},48501:{name:"SESSION_NOT_REATTACHED",message:"Active call lost after reconnect",description:"The WebSocket reconnected successfully but the server did not reattach the active call session. The server no longer knows about the call, so any subsequent call-control operation (hangup, hold, etc.) will fail with CALL_DOES_NOT_EXIST. The call is unrecoverable and must be terminated locally.",causes:["Server-side session expired during the disconnection window","Reconnect token was invalidated","Backend restarted or lost in-memory call state"],solutions:["Terminate the local call and notify the user","Start a new call","Investigate why the session was not preserved on the server"],fatal:!0},49001:{name:"UNEXPECTED_ERROR",message:"An unexpected error occurred",description:"An error was thrown that does not match any known SDK error category. This is a catch-all for unclassified failures.",causes:["Unknown or unhandled error condition"],solutions:["Check the originalError property for the underlying cause","Report the issue if it persists"],fatal:!0}},m0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},31006:{name:"LOW_INBOUND_AUDIO",message:"Low inbound audio detected",description:"Inbound (remote) audio level stayed below the acceptable threshold for multiple consecutive stats intervals while RTP packets continued to flow. This may indicate the remote party is sending silence or comfort-noise (e.g. one-way audio caused by a media bridge issue), as opposed to LOW_BYTES_RECEIVED which fires when no bytes arrive at all.",causes:["Remote party microphone is muted or capturing very low audio","Media bridge or PBX is injecting comfort-noise/silence instead of forwarding real audio","One-way audio where RTP flows but content is silent (server-side media issue)","Remote party is on hold or not speaking"],solutions:["Verify the remote party is not muted and is actively speaking","Check the media bridge / PBX for comfort-noise injection or transcoding issues","Inspect PCAP RTP payload uniqueness to distinguish real audio from comfort-noise","If the issue persists, report the call for server-side media investigation"]},32001:{name:"LOW_BYTES_RECEIVED",message:"No audio data received",description:"No bytes have been received from the remote party for multiple consecutive seconds. This may indicate a network interruption or remote-side issue.",causes:["Network interruption","Remote party microphone issue","Firewall blocking inbound media"],solutions:["Check network connectivity","Ask remote party to check their microphone","Check firewall rules for media ports"]},32002:{name:"LOW_BYTES_SENT",message:"No audio data being sent",description:"No bytes have been sent for multiple consecutive seconds. This may indicate a local microphone issue or network interruption.",causes:["Microphone muted or disconnected","Network interruption","Local media track ended"],solutions:["Check that the microphone is not muted","Verify the microphone is still connected","Check network connectivity"]},32003:{name:"RECORDING_UNAVAILABLE",message:"Call recording is not available in this browser",description:"Call recording was enabled (enableCallRecording is true), but the browser does not support MediaStreamTrackProcessor (required to capture raw audio PCM). Recording is disabled for this call; the call proceeds normally. Currently affects Firefox and older Chromium (< 94).",causes:["Browser does not implement MediaStreamTrackProcessor (Firefox, Safari)","Chromium version older than 94","Recording enabled on an unsupported platform"],solutions:["Use a recent Chromium-based browser (Chrome 94+, Edge 94+) to capture recordings","Disable enableCallRecording if recording is not required for this deployment","See the enableCallRecording JSDoc for platform support details"]},32004:{name:"RECORDING_BUFFER_OVERFLOW",message:"Call recording buffer overflow — oldest packets dropped",description:"The in-memory call recording buffer reached its maxBufferBytes cap before the next scheduled flush. The oldest captured RTP packets were dropped to keep memory bounded. This indicates the flush interval is too long for the call audio rate, or the upload endpoint is slow/unreachable. The recording continues with the remaining (newer) packets.",causes:["Flush interval (callRecordingFlushIntervalMs) is larger than the buffer can hold at the current audio rate","Upload endpoint (/call_recording) is slow or unreachable, so intermediate flushes back up","A very long call with high sample rate filling the buffer between flushes"],solutions:["Reduce callRecordingFlushIntervalMs so flushes happen more frequently","Increase callRecordingMaxBufferBytes if memory headroom allows","Check the /call_recording endpoint health and network path to voice-sdk-proxy"]},33001:{name:"ICE_CONNECTIVITY_LOST",message:"Connection interrupted",description:"The ICE connection transitioned to the disconnected state. The previously selected connection path was lost and renegotiation may be required. The connection may recover automatically.",causes:["Temporary network interruption","Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding"],solutions:["Wait for automatic recovery","Check network connectivity"]},33002:{name:"ICE_GATHERING_TIMEOUT",message:"ICE gathering timed out",description:"ICE candidate gathering did not complete within the safety timeout. This is typically caused by network restrictions blocking STUN/TURN. The call may still succeed if candidates arrive late.",causes:["Firewall blocking STUN/TURN","Network unreachable","STUN/TURN server not responding"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Try forceRelayCandidate option"]},33003:{name:"ICE_GATHERING_EMPTY",message:"No ICE candidates gathered",description:"No ICE candidates were gathered after sending the initial SDP. This may indicate a firewall blocking all STUN/TURN traffic or no available network interface.",causes:["Firewall blocking all STUN/TURN traffic","No network interface available","VPN blocking UDP"],solutions:["Check STUN/TURN server reachability","Ensure UDP traffic is not blocked","Use forceRelayCandidate option"]},33004:{name:"PEER_CONNECTION_FAILED",message:"Connection failed",description:"RTCPeerConnection entered the failed state. This is a recoverable condition — the SDK may attempt ICE restart or the connection may recover. If it does not recover, the call will eventually be terminated.",causes:["ICE failure","DTLS handshake failure","Prolonged network interruption"],solutions:["Wait for automatic recovery","Check network connectivity","Verify TURN server credentials"]},33005:{name:"ONLY_HOST_ICE_CANDIDATES",message:"Only local network candidates available",description:"ICE gathering completed but only host (local network) candidates were collected — no server-reflexive (srflx) or relay (turn) candidates were found. This typically means the STUN/TURN servers are unreachable, which will prevent connections outside the local network.",causes:["STUN/TURN servers unreachable","Firewall blocking UDP traffic to STUN/TURN servers","Incorrect TURN server configuration or credentials","Restrictive corporate network or VPN"],solutions:["Verify STUN/TURN server URLs and credentials","Ensure UDP traffic to STUN/TURN ports is not blocked","Check firewall or VPN settings","Try using TCP-based TURN as a fallback"]},33006:{name:"ANSWER_WHILE_PEER_ACTIVE",message:"Call answer ignored because a peer connection is already active",description:"answer() was called on a call that already has an active or connecting peer connection. Creating a second peer connection for the same call would duplicate media negotiation, confuse the remote party, and break call reporting. This is typically caused by application code invoking answer() multiple times (e.g. from multiple event handlers).",causes:["Application called answer() twice on the same call object","Multiple click handlers or event listeners triggering answer()"],solutions:["Ensure answer() is called only once per call","Disable the answer button after the first click","Check that answer() is not invoked from multiple event handlers"]},33008:{name:"ICE_CANDIDATE_PAIR_CHANGED",message:"ICE candidate pair changed mid-call",description:"The selected ICE candidate pair changed during an active call. This indicates a network path shift — for example, a Wi-Fi to cellular handoff, a NAT rebinding, or a relay fallback. The call may continue normally, but the path change can briefly affect audio quality.",causes:["Network interface change (e.g. Wi-Fi to cellular)","NAT rebinding or IP address change","Previous candidate pair failed and ICE selected an alternative","Network topology change"],solutions:["Monitor for audio quality degradation after the path change","Check network stability if changes are frequent","Verify TURN server configuration for relay fallback"]},33007:{name:"DUPLICATE_INBOUND_ANSWER",message:"Call answer ignored because another inbound call is already being answered",description:"answer() was called on an inbound call while another inbound call is already answering or active in this JavaScript runtime. Answering both legs can trigger SIP 486 USER_BUSY / LOSE_RACE when duplicate WebSocket registrations receive the same incoming call.",causes:["Multiple TelnyxRTC instances in the same page","Application code recreating a client without disconnecting the previous instance","Duplicate inbound call notifications produced by duplicate WebSocket registrations"],solutions:["Keep a single active TelnyxRTC instance for inbound call handling","Call disconnect() before replacing an SDK client instance","Only call answer() for one inbound call notification at a time"]},34001:{name:"TOKEN_EXPIRING_SOON",message:"Authentication token expiring soon",description:"The authentication token is approaching its expiration time. If the token expires the connection will be lost and calls will fail. A new token should be generated before expiration.",causes:["Token was issued with a limited lifetime"],solutions:["Generate a new authentication token","Reconnect with fresh credentials before the token expires"]},36003:{name:"SIGNALING_RECOVERY_REQUIRED",message:"Signaling recovery required",description:"The signaling (WebSocket) path has been detected as unhealthy and the SDK will force-close the socket and reconnect. The source field in the warning payload indicates what triggered the recovery (probe, request, peer_failure, or no_rtp). Active calls will be recovered via reattach after reconnection.",causes:["WebSocket probe timed out with no response","Critical signaling request timed out","Peer/media failure detected while signaling is also unhealthy"],solutions:["The SDK will automatically reconnect and recover the call","Check for network interface changes or interruptions","Verify firewall/NAT timeout settings"]},36004:{name:"MEDIA_RECOVERY_REQUIRED",message:"Media recovery required",description:"The peer connection or media flow has been detected as unhealthy while signaling is healthy. The SDK will attempt ICE restart to recover the media path. No socket reconnection is needed.",causes:["ICE connection state changed to failed","RTCPeerConnection state changed to failed","No RTP packets/bytes received while media should be active"],solutions:["The SDK will automatically attempt ICE restart","Check network connectivity and ICE candidate availability","Verify TURN server configuration"]},36005:{name:"RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT",message:"Reconnection failed — auto-reconnect disabled",description:"The WebSocket was closed and auto-reconnect is disabled, so the SDK will not attempt to reconnect. This typically occurs after the user called disconnect() or after reconnection attempts were exhausted.",causes:["Auto-reconnect was disabled by the application","Reconnection attempts were previously exhausted","The session was intentionally disconnected"],solutions:["Call connect() manually to re-establish the session","Check if disconnect() was called intentionally","Review maxReconnectAttempts configuration"]},33009:{name:"AUDIO_INPUT_DEVICE_CHANGE_SKIPPED",message:"Audio input device change skipped",description:"The SDK could not change the microphone because the active peer connection has no audio RTP sender to replace. The existing local media and mute state were left unchanged.",causes:["The call was created without an audio sender","The peer connection was not ready when setAudioInDevice was called","The call is already ending or the local media sender was removed"],solutions:["Retry after the call is active and local media is attached","Verify the call was started with audio enabled","Inspect call state and peer connection sender availability"]},33010:{name:"MULTIPLE_ACTIVE_CALLS_DETECTED",message:"Multiple active calls detected in one SDK session",description:"A new call was created or received while another call is still active (ringing, answering, active, held, or recovering) in the same SDK session. This may be intentional for some applications (e.g. call waiting, transfer) but is often abnormal and makes call reports and application behavior harder to reason about. The new call proceeds normally — this warning is diagnostic only.",causes:["Application created an outbound call while another call is active","An inbound call arrived while another call is already active","Application did not hang up the previous call before starting a new one","Call waiting or multi-call scenario (may be intentional)"],solutions:["Verify this is the expected behavior for your application","Ensure the previous call is hung up before creating a new one if only one call is expected","Use call.hold() before starting a new call if needed","Check the warning payload for call IDs to correlate which calls are involved"]},35002:{name:"UNKNOWN_REATTACHED_SESSION",message:"Unknown reattach session after reconnect",description:"The WebSocket reconnected successfully and the server sent an Attach message for a session that does not match any active SDK call. The unknown Attach is ACK'd and ignored.",causes:["Server sent an Attach for a call that no longer exists in the SDK","Multiple Attach messages arrived and only the first was recovered","Race condition between reconnection and new inbound call"],solutions:["Check application logic for multiple simultaneous calls","Inspect the Attach callID in the warning payload for details","If a call should be active, start a new call manually"]}};function Be(t,e){const i=m0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Bt extends Error{constructor(e){super(e.message||`[${e.code}] ${e.name}`),this.name=e.name,this.code=e.code,this.description=e.description,this.causes=e.causes,this.solutions=e.solutions,this.originalError=e.originalError,this.fatal=e.fatal,Object.setPrototypeOf(this,Bt.prototype)}toJSON(){return{code:this.code,name:this.name,description:this.description,message:this.message,causes:this.causes,solutions:this.solutions,originalError:this.originalError,fatal:this.fatal}}}function Ii(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return Oy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return My}return Mu}function ne(t,e,i,n){const s=g0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Bt({code:t,name:s.name,description:s.description,message:i||s.message,causes:[...s.causes],solutions:[...s.solutions],originalError:o,fatal:n??s.fatal})}class v0 extends Error{constructor(e,i,n=""){super(`Signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms)`),this.name="RequestTimeoutError",this.requestId=e,this.timeoutMs=i,this.method=n}}class br extends Error{constructor(e,i,n){super(`Stale request cancelled (id=${e}, gen=${i}, current=${n})`),this.name="StaleRequestError",this.requestId=e,this.staleGeneration=i,this.currentGeneration=n}}var _0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gu(t,e){return t(e={exports:{}},e.exports),e.exports}var y0=Gu(function(t){var e,i;e=_0,i=function(){var n=function(){},s="undefined",o=typeof window!==s&&typeof window.navigator!==s&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function a(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 I=r[C];this[I]=C<w?n:this.methodFactory(I,w,y)}this.log=this.debug}function u(w,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[w].apply(this,arguments))}}function d(w,y,C){return function(I){return I==="debug"&&(I="log"),typeof console!==s&&(I==="trace"&&o?l:console[I]!==void 0?a(console,I):console.log!==void 0?a(console,"log"):n)}(w)||u.apply(this,arguments)}function h(w,y,C){var I,A=this;y=y??"WARN";var R="loglevel";function P(){var k;if(typeof window!==s&&R){try{k=window.localStorage[R]}catch{}if(typeof k===s)try{var g=window.document.cookie,m=g.indexOf(encodeURIComponent(R)+"=");m!==-1&&(k=/^([^;]+)/.exec(g.slice(m))[1])}catch{}return A.levels[k]===void 0&&(k=void 0),k}}typeof w=="string"?R+=":"+w:typeof w=="symbol"&&(R=void 0),A.name=w,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return I},A.setLevel=function(k,g){if(typeof k=="string"&&A.levels[k.toUpperCase()]!==void 0&&(k=A.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(I=k,g!==!1&&function(m){var f=(r[m]||"silent").toUpperCase();if(typeof window!==s&&R){try{return void(window.localStorage[R]=f)}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+f+";"}catch{}}}(k),c.call(A,k,w),typeof console===s&&k<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(k){y=k,P()||A.setLevel(k,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(k){A.setLevel(A.levels.TRACE,k)},A.disableAll=function(k){A.setLevel(A.levels.SILENT,k)};var T=P();T==null&&(T=y),A.setLevel(T,!1)}var p=new h,_={};p.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 h(w,p.getLevel(),p.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return _},p.default=p,p},t.exports?t.exports=i():e.log=i()});const qu={debug:0,info:1,warn:2,error:3};class b0{constructor(e={}){var i,n,s;this.buffer=[],this.isCapturing=!1,this.options={enabled:(i=e.enabled)!==null&&i!==void 0&&i,level:(n=e.level)!==null&&n!==void 0?n:"debug",maxEntries:(s=e.maxEntries)!==null&&s!==void 0?s:1e3}}start(){this.options.enabled&&(this.isCapturing=!0,this.buffer=[])}stop(){this.isCapturing=!1}addEntry(e,i,n){if(!this.isCapturing||!this.options.enabled||qu[e]<qu[this.options.level])return;const s=Object.assign({timestamp:new Date().toISOString(),level:e,message:i},n&&Object.keys(n).length>0?{context:n}:{});this.buffer.push(s),this.buffer.length>this.options.maxEntries&&this.buffer.shift()}getLogs(){return[...this.buffer]}getLogCount(){return this.buffer.length}drain(){const e=this.buffer;return this.buffer=[],e}clear(){this.buffer=[]}isActive(){return this.isCapturing}isEnabled(){return this.options.enabled}}let zu=null;const b=y0.getLogger("telnyx"),rs={trace:0,debug:1,info:2,warn:3,error:4};let Ku=rs.info;function Yu(t){if(t==null||typeof t!="object")return t;try{const i=JSON.stringify(t),n=JSON.parse(i);if(typeof n=="object"&&n!==null&&Object.keys(n).length>1)return n}catch{}const e={};for(const i in t)try{const n=t[i];if(typeof n=="function")continue;if(typeof n=="object"&&n!==null)try{e[i]=JSON.parse(JSON.stringify(n))}catch{e[i]=String(n)}else e[i]=n}catch{}return Object.keys(e).length>0?e:{value:String(t)}}const w0=b.methodFactory;b.methodFactory=(t,e,i)=>{const n=w0(t,e,i);return function(...s){if(rs[t]>=Ku){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=zu;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?Yu(a[0]):{args:a.map(Yu)}),o.addEntry(t,l,c)}}},b.setLevel("debug",!1);const as=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{b.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Xu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ei=t=>t instanceof Function||typeof t=="function",hn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,S0=/^(ws|wss):\/\//,Ju=(t,e=null)=>{const{result:i={},error:n}=t;if(n)return{error:n};const{result:s=null}=i;if(s===null)return e!==null&&(i.node_id=e),{result:i};const{code:o=null,node_id:r=null,result:a=null}=s;return o&&o!=="200"?{error:s}:a?Ju(a,r):{result:s}},ls=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),fn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,wr=t=>{var e,i,n,s,o,r;let a="",l="";return!((i=(e=t==null?void 0:t.result)===null||e===void 0?void 0:e.params)===null||i===void 0)&&i.state&&(a=(s=(n=t==null?void 0:t.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state),!((o=t==null?void 0:t.params)===null||o===void 0)&&o.state&&(l=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.state),a||l};function Zu({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?C0(n,t):n,i=s}),resolve:e,reject:i}}const C0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Sr="telnyx-voice-sdk-id",cs="telnyx-voice-sdk-session-id",ds="telnyx-voice-sdk-session-id-stored-at",Cr="telnyx-voice-sdk-active-calls",T0=9e4;function Qu(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(ds));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=T0}function pn(){return sessionStorage.getItem(Sr)}function Tr(t,e=Date.now()){sessionStorage.setItem(cs,t),sessionStorage.setItem(ds,String(e))}function eh(){sessionStorage.removeItem(Sr),sessionStorage.removeItem(cs),sessionStorage.removeItem(ds)}function kr(){(function(t){try{sessionStorage.removeItem(t)}catch(e){b.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Cr)}function k0(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return b.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Cr);if(kr(),!e)return b.debug("Active-calls recovery marker not found in storage — nothing to recover."),null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return b.debug("Active-calls recovery marker payload was malformed — discarded."),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(b.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),null):i.calls.length===0?(b.debug("Active-calls recovery marker had no call records — discarded."),null):i}catch(i){return b.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),null}}function I0(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void kr();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){b.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Cr,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Ne,lt,Z;(function(t){t.Offer="offer",t.Answer="answer"})(Ne||(Ne={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(lt||(lt={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(Z||(Z={}));const it={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},E0={invalidCredentialsOptions:"InvalidCredentialsOptions"},th=24e4,ih=8e6,R0={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 j,Ir,Ke,_t,De,Ri;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(j||(j={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Ir||(Ir={})),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"}(Ke||(Ke={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(_t||(_t={})),function(t){t.REGED="REGED",t.UNREGED="UNREGED",t.NOREG="NOREG",t.FAILED="FAILED",t.FAIL_WAIT="FAIL_WAIT",t.TIMEOUT="TIMEOUT",t.REGISTER="REGISTER",t.TRYING="TRYING",t.EXPIRED="EXPIRED",t.UNREGISTER="UNREGISTER"}(De||(De={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ri||(Ri={}));const Ai="GLOBAL",qe={},gn=(t,e)=>`${t}|${e}`,nh=(t,e=Ai)=>gn(t,e)in qe,Ut=(t,e,i=Ai)=>{const n=gn(t,i);n in qe||(qe[n]=[]),qe[n].push(e)},sh=(t,e,i=Ai)=>{const n=function(s){yt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},yt=(t,e,i=Ai)=>{if(!nh(t,i))return!1;const n=gn(t,i);if(Ei(e))for(let s=qe[n].length-1;s>=0;s--){const o=qe[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&qe[n].splice(s,1)}else qe[n]=[];return qe[n].length===0&&delete qe[n],!0},B=(t,e,i=Ai,n=!0)=>{const s=n&&i!==Ai;if(!nh(t,i))return s&&B(t,e),!1;const o=gn(t,i),r=qe[o].length;if(!r)return s&&B(t,e),!1;for(let a=r-1;a>=0;a--)qe[o][a](e);return s&&B(t,e),!0},Er=t=>{const e=gn(t,"");Object.keys(qe).filter(i=>i.indexOf(e)===0).forEach(i=>delete qe[i])};let A0=typeof WebSocket<"u"?WebSocket:null;const x0=0,L0=1,D0=2,oh=3;class us{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=ju,this._timers={},this._useCanaryRtcServer=!1,this._hasCanaryBeenUsed=!1,this._safetyTimeoutId=null,this._pendingRequestIds=new Set,this._pendingRequestTimers=new Map,this._pendingRequestRejecters=new Map,this.upDur=null,this.downDur=null;const{host:i,env:n,region:s,useCanaryRtcServer:o}=e.options;b.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":ju),i&&(this._host=(r=>`${S0.test(r)?"":"wss://"}${r}`)(i)),s&&(this._host=this._host.replace(/rtc(dev)?/,`${s}.rtc$1`)),o&&(this._useCanaryRtcServer=!0)}get connected(){return!!this._wsClient&&this._wsClient.readyState===L0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===x0}get closing(){return!!this._wsClient&&this._wsClient.readyState===D0}get closed(){return!!this._wsClient&&this._wsClient.readyState===oh}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){b.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=pn();this.session.options.rtcIp&&this.session.options.rtcPort&&(i=null,this._useCanaryRtcServer=!1,e.searchParams.set("rtc_ip",this.session.options.rtcIp),e.searchParams.set("rtc_port",this.session.options.rtcPort.toString())),i&&e.searchParams.set("voice_sdk_id",i),this._useCanaryRtcServer&&(e.searchParams.set("canary","true"),i&&!this._hasCanaryBeenUsed&&(e.searchParams.delete("voice_sdk_id"),b.debug("first canary connection. Refreshing voice_sdk_id")),this._hasCanaryBeenUsed=!0),this.session.callReportVoiceSdkId=e.searchParams.get("voice_sdk_id"),this.session.options.skipLastVoiceSdkId&&e.searchParams.has("voice_sdk_id")&&e.searchParams.set("skip_last_voice_sdk_id","true"),this.session.options.skipTrailing&&e.searchParams.set("skip_trailing","true");try{const n=this.socketGeneration;this._wsClient=new A0(e.toString()),this.socketGeneration+=1,b.debug("WebSocket connection created",{sessionId:this.session.sessionid,voiceSdkId:this.session.callReportVoiceSdkId,socketGeneration:this.socketGeneration,reconnectCount:n}),this.lastInboundAt=0,this._cleanupPendingRequests(),this._registerSocketEvents(this._wsClient)}catch(n){b.error("WebSocket connection failed:",n);const s=ne(By,n);B(M.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),this.session._terminateActiveCallsLocally()}}sendRawText(e){var i;(i=this._wsClient)===null||i===void 0||i.send(e)}send(e,i){var n;const{request:s}=e,o=this.socketGeneration,r=s.method||"",a=new Promise((l,c)=>{if(s.hasOwnProperty("result"))return l();let u=!1,d=null;const h=p=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),u)return;const{result:_,error:v}=Ju(p);return v?c(v):l(_)};sh(s.id,h),this._pendingRequestIds.add(s.id),this._pendingRequestRejecters.set(s.id,{reject:c,generation:o}),i&&i>0&&(d=setTimeout(()=>{if(u=!0,d=null,this._pendingRequestTimers.delete(s.id),this._pendingRequestRejecters.delete(s.id),yt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return b.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new br(s.id,o,this.socketGeneration));c(new v0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return b.debug(`SEND:
112
112
  `,JSON.stringify(s,null,2),`
113
- `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ei(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){e.onopen=i=>V(M.SocketOpen,i,this.session.uuid),e.onclose=i=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),V(M.SocketClose,i,this.session.uuid)),e.onerror=i=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error");const n=re(Py);return V(M.Error,{error:n,sessionId:this.session.sessionid},this.session.uuid),V(M.SocketError,{error:i,sessionId:this.session.sessionid},this.session.uuid)},e.onmessage=i=>{var n,s;this.lastInboundAt=Date.now(),V(M.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const o=Hu(i.data);var r;if(typeof o!="string"){if(o.voice_sdk_id&&(this.session.callReportVoiceSdkId=o.voice_sdk_id,r=o.voice_sdk_id,sessionStorage.setItem(_r,r)),this._unsetTimer(o.id),S.debug(`RECV:
114
- `,JSON.stringify(o,null,2),`
115
- `),De[`${(s=(n=o==null?void 0:o.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.state}`]||!V(o.id,o)){const a=vr(o);V(M.SocketMessage,o,this.session.uuid),a&&(this.previousGatewayState=a)}}else this._handleStringResponse(o)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==Qu?(S.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e||V(M.SocketClose,{code:Nu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1},this.session.uuid)):S.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(S.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(S.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):S.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{yt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new mr(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),V(M.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else S.warn("Unknown message from socket",e)}}ds.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class xi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Ci()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const Zu={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ue extends xi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Cu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in Zu)n&&i.hasOwnProperty(n)&&(i[Zu[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class eh extends Ue{constructor(e){super(),this.method=Q.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class C0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>U(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(vr(i))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const i=new eh(fn());this.pendingRequestId=i.request.id,this.gatewayStateTask=qu({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[De.REGISTER,De.REGED].includes(n)}),this.session=e,this.gatewayStateTask=qu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class wr extends Ue{constructor(e){super(),this.method=Q.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ai{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null}static isCriticalMethod(e){return Ai.CRITICAL_METHODS.has(e)}start(){this._intervalId||(S.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,S.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight||(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),S.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery))return;const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(S.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason,e.source))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?S.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(S.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Ai.isCriticalMethod(n)?(S.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):S.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){S.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){S.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return S.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(S.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new wr(fn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{S.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void S.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(S.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i,s)):o==="unknown"?(S.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(S.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n;let s;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,s=i==="probe"?e0:i==="request"?t0:i0;const o=ze(s);V(M.Warning,{warning:o,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected&&(S.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect())}_triggerIceRestart(e,i,n){S.info(`Signaling health: triggering ICE restart for call ${e}`);const s=this._session.triggerIceRestart(e);if(!s.started)return S.info(`Signaling health: ICE restart not started for call ${e}: ${s.reason}`),void(s.recoverSignaling&&this._triggerSignalingRecovery(`${i}; ICE restart disabled for reattached call, forcing socket reconnect`,n));const o=ze(n0);V(M.Warning,{warning:o,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Ai.CRITICAL_METHODS=new Set([Q.Modify,Q.Bye,Q.Ping]);var th="2.27.2-beta.0",Sr=th;class T0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Sr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class E0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class ih extends Ue{toString(){return Q.Invite}}class nh extends Ue{toString(){return Q.Answer}}class sh extends Ue{toString(){return Q.Attach}}class k0 extends Ue{toString(){return Q.Bye}}class I0 extends Ue{toString(){return Q.Candidate}}class x0 extends Ue{toString(){return Q.EndOfCandidates}}class us extends Ue{toString(){return Q.Modify}}class oh extends Ue{toString(){return Q.Info}}class A0 extends Ue{toString(){return Q.Broadcast}}class R0 extends Ue{toString(){return Q.Subscribe}}class L0 extends Ue{toString(){return Q.Unsubscribe}}class D0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Sr,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 Qt{constructor(e){if(this.options=e,this.uuid=Ci(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Ai(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",$u=(n=os[i])!==null&&n!==void 0?n:os.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new ds(this),this.registerAgent=new C0(this)}get __logger(){return S}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return U(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){return 1e3*Wu(2,6)}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),S.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Ai.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?ds.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>U(this,void 0,void 0,function*(){if(s instanceof mr)throw S.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=re(Ny,s);V(M.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return U(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},Qt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&S.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return as(this.options)||hn(this.options)}broadcast(e){}disconnect(){return U(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),S.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Vt(e,i,this.uuid),this}off(e,i){return yt(e,i,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(S.debug("No existing connection found, creating a new one."),this.connection=new ds(this)),this._attachListeners(),this._autoReconnect||(this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(S.debug("Initiating connection to the server..."),this.connection.connect()),S.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0}_handleLoginError(e){const i=re(Ru,e);V(M.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Yu()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=Qt.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-Qt.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{S.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=ze(Qy);V(M.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return U(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),as(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(hn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";S.error(s);const o=re(Oy,void 0,s);return void V(M.Error,{error:o,type:v0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){return U(this,void 0,void 0,function*(){let s;const o=!!fn(),r=o&&(this.sessionid&&zu()?this.sessionid:function(l=Date.now()){const c=sessionStorage.getItem(ls);return c?zu(l)?c:(sessionStorage.removeItem(ls),sessionStorage.removeItem(cs),null):null}())||"";s=e==="login"?new T0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,r,this.options.userVariables,o):new D0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:r,userVariables:this.options.userVariables,reconnection:o});const a=yield this.execute(s).catch(l=>{this._handleLoginError(l),n&&n(l)});a&&(this.sessionid=a.sessid,this.sessionid&&Ku(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return U(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){S.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(Nu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i;this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),this.relayProtocol&&br(this.relayProtocol);for(const n in this.subscriptions)br(n);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Ku(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const n=(i=this.options.maxReconnectAttempts)!==null&&i!==void 0?i:10;if(this._reconnectAttempts+=1,n>0&&this._reconnectAttempts>n){S.info(`Reconnection exhausted after ${n} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1;const s=re(Au);return void V(M.Error,{error:s,sessionId:this.sessionid},this.uuid)}S.debug(`Reconnect attempt ${this._reconnectAttempts}${n>0?` of ${n}`:""}`),this._reconnectTimeout=setTimeout(()=>{S.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},this.reconnectDelay)}}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],yt(e,null,i)):(delete this.subscriptions[e],br(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ei(i)&&Vt(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),this.on(M.SocketOpen,this._onSocketOpen),this.on(M.SocketClose,this.onNetworkClose),this.on(M.SocketError,this.onNetworkClose),this.on(M.SocketMessage,this._onSocketMessage),this.on(M.SocketActivity,this._onSocketActivity)}_detachListeners(){this.off(M.SocketOpen,this._onSocketOpen),this.off(M.SocketClose,this.onNetworkClose),this.off(M.SocketError,this.onNetworkClose),this.off(M.SocketMessage,this._onSocketMessage),this.off(M.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(S.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new wr(fn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){S.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([j.Early,j.Active,j.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){var i;const n=this.calls,s=n==null?void 0:n[e];if(!s)return S.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};if(!((i=s.options)===null||i===void 0)&&i.attach||s.recoveredCallId)return S.warn(`Signaling health: ICE restart skipped for call ${e}: call was recovered via attach`),{started:!1,reason:"call recovered via attach",recoverSignaling:!0};const o=s.peer;if(!(o!=null&&o.restartIce))return S.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const r=o.restartIce();return r.started||S.debug(`Signaling health: ICE restart skipped for call ${e}: ${r.reason}`),r}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}static on(e,i){Vt(e,i)}static off(e){yt(e)}static uuid(){return Ci()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}Qt.TOKEN_EXPIRY_WARNING_SECONDS=120,Qt.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const hs=t=>navigator.mediaDevices.getUserMedia(t),gn=t=>t&&t instanceof MediaStream,fs=(t,e)=>{const i=un(t);i!==null&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=e)},rh=(t,e)=>{const i=un(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},ah=(t,e)=>U(void 0,void 0,void 0,function*(){const i=un(t);if(i===null)return S.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return S.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),P0=t=>{t&&t.readyState==="live"&&t.stop()},mn=t=>{gn(t)&&t.getTracks().forEach(P0),t=null},ps=t=>U(void 0,void 0,void 0,function*(){S.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield hs(t)}catch(n){if(S.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){S.warn("Device not found or not readable, falling back to default device");try{return yield hs(s)}catch(o){throw S.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),vn=(t=null,e=!1)=>U(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===_t.AudioIn||s===_t.AudioOut,video:!s||s===_t.Video}))(t)).catch(s=>(S.error(s),null));if(n){if(mn(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),lh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],gs=(t,e,i)=>U(void 0,void 0,void 0,function*(){const n=yield vn(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),M0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Cr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,ch=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>Cr(a)):[]},Tr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Er(t);return i.includes(e)||n.includes(e)},Er=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Ri=(t,e=null,i=null)=>{if(!gn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},kr=t=>{Ri(t,"audio",!0)},ms=t=>{Ri(t,"audio",!1)};function O0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!ps}}catch(t){return t.message}}var Ee;function dh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function uh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{S.error("playAudio",e),t._playFulfilled=!0}))}function hh(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Ee||(Ee={}));const fh=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class N0 extends xi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Ci(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class F0 extends xi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ae{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new h0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Bu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,S.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ae.INITIAL_COLLECTION_INTERVAL_MS,initialDuration:ae.INITIAL_COLLECTION_DURATION_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return U(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),S.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s;if(this._flushing||this.statsBuffer.length===0)return null;this._flushing=!0;try{const o=this._segmentIndex++,r=this.statsBuffer;this.statsBuffer=[];const a=(s=(n=this.logCollector)===null||n===void 0?void 0:n.drain())!==null&&s!==void 0?s:[],l=new Date;this._lastIntermediateFlushTime=l;const c=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(l.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:l.toISOString()}),stats:r},a.length>0?{logs:a}:{}),{segment:o}),i?{flushReason:i}:{});return S.info("CallReportCollector: Flushed intermediate segment",{segment:o,intervals:r.length,logEntries:a.length,callId:e.callId,flushReason:i}),c}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return U(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void S.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void S.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s){return U(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1)})}_sendPayload(e,i,n,s,o=!0){var r,a;return U(this,void 0,void 0,function*(){const l=new URL(n),c=`${l.protocol.replace(/^ws/,"http")}//${l.host}/call_report`,u=o?"final report":`intermediate segment ${e.segment}`;S.info(`CallReportCollector: Posting ${u}`,{endpoint:c,intervals:e.stats.length,logEntries:(a=(r=e.logs)===null||r===void 0?void 0:r.length)!==null&&a!==void 0?a:0,callId:e.summary.callId,segment:e.segment});const d={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(d["x-voice-sdk-id"]=s);const h=JSON.stringify(e),g=o&&h.length<=ae.KEEPALIVE_BODY_LIMIT_BYTES;let y;for(let v=0;v<=ae.RETRY_DELAYS_MS.length;v++){try{const _=yield fetch(c,Object.assign({method:"POST",headers:d,body:h},g?{keepalive:!0}:{}));if(_.ok)return void S.info(`CallReportCollector: Successfully posted ${u}`,{attempt:v+1,status:_.status});{const C=yield _.text();y=new Error(`Call report POST failed with status ${_.status}`),S.error(`CallReportCollector: Failed to post ${u}`,{attempt:v+1,status:_.status,error:C})}}catch(_){y=_,S.warn(`CallReportCollector: Network error posting ${u}`,{attempt:v+1,error:_})}const b=ae.RETRY_DELAYS_MS[v];if(b===void 0)break;S.info(`CallReportCollector: Retrying ${u} in ${b}ms`,{attempt:v+2}),yield new Promise(_=>setTimeout(_,b))}throw S.error(`CallReportCollector: Exhausted retries posting ${u}`,{error:y}),y instanceof Error?y:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,g,y,v,b;if(this.statsBuffer.length<2)return!1;const _=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=_.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const A=((i=_.ice)===null||i===void 0?void 0:i.writable)===!1,x=((n=_.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=_.transport)===null||s===void 0?void 0:s.iceState)==="failed",N=this._positiveDelta((o=_.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=_.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=N>0&&T===0,p=this._positiveDelta((u=(c=_.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((y=(g=_.audio)===null||g===void 0?void 0:g.inbound)===null||y===void 0?void 0:y.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return A||x||E||p>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor(this.intervalStartTime);this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(e){const i=this._positiveInterval(this.options.interval,5e3);return e.getTime()-this.callStartTime.getTime()<ae.INITIAL_COLLECTION_DURATION_MS?Math.min(ae.INITIAL_COLLECTION_INTERVAL_MS,i):i}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){return U(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const i=yield this.peerConnection.getStats(),n=new Date;let s,o,r,a,l,c=null,u=null,d=null,h=null;if(i.forEach(v=>{switch(v.type){case"outbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(c=v);break;case"inbound-rtp":v.kind==="audio"&&v.mediaType==="audio"&&(u=v);break;case"candidate-pair":(v.nominated||v.state==="succeeded")&&(d=v);break;case"transport":h=v}}),c){const v=this._getOutboundAudioLevel(i,c);if(v!==null&&this.intervalAudioLevels.outbound.push(v),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const b=(c.bytesSent||0)-this.previousStats.outboundBytes,_=(c.timestamp||n.getTime())-this.previousStats.timestamp;if(_>0){const C=8*b*1e3/_;this.intervalBitrates.outbound.push(C)}}this.previousStats.outboundBytes=c.bytesSent}if(u){const v=this._getInboundAudioLevel(i,u);if(v!==null&&this.intervalAudioLevels.inbound.push(v),u.jitter!==void 0&&this.intervalJitters.push(1e3*u.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const b=(u.bytesReceived||0)-this.previousStats.inboundBytes,_=(u.timestamp||n.getTime())-this.previousStats.timestamp;if(_>0){const C=8*b*1e3/_;this.intervalBitrates.inbound.push(C)}}this.previousStats.inboundBytes=u.bytesReceived}d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(s=this._resolveCandidate(i,d.localCandidateId),o=this._resolveCandidate(i,d.remoteCandidateId)),d&&(r=Object.assign(Object.assign({id:d.id,state:d.state,nominated:d.nominated,writable:d.writable,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},s?{local:s}:{}),o?{remote:o}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(S.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:r}),this._emitWarning(Yy)),this.previousCandidatePairSnapshot=r),c&&(a=this._getLocalAudioTrackSnapshot(),l=this._getOutboundAudioSourceStats(i,c)),this._logLocalAudioTrackSnapshot(a,l),this.previousStats.timestamp=n.getTime();const g=n.getTime()-this.intervalStartTime.getTime(),y=this._collectionIntervalFor(this.intervalStartTime);if(e||g>=y){const v=this._createStatsEntry(this.intervalStartTime,n,c,u,d,s,o,h,a,l);this.statsBuffer.push(v),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),S.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(v,u),this._requestIntermediateFlushIfNeeded(n),this.intervalStartTime=n,this._resetIntervalAccumulators()}}catch(i){S.error("CallReportCollector: Error collecting stats",{error:i})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ae.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;if(!this.onFlushNeeded||this._flushing||this.statsBuffer.length===0)return;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0,r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=ae.STATS_FLUSH_THRESHOLD||o>=ae.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){S.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){S.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,g,y,v,b,_;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(i){const x=(r=i.packetsReceived)!==null&&r!==void 0?r:0,N=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=x-this._prevPacketsReceived,E=N-this._prevPacketsLost,p=T+E;p>0&&(A=E/p*100)}this._prevPacketsReceived=x,this._prevPacketsLost=N}if(this._trackBreach(By,C!==void 0&&C>ae.THRESHOLD_RTT_MS),this._trackBreach($y,k!==void 0&&k>ae.THRESHOLD_JITTER_MS),this._trackBreach(jy,A!==void 0&&A>ae.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),C!==void 0&&k!==void 0&&A!==void 0){const x=93.2-.11*k-2.5*A-.01*(1e3*C),N=Math.max(1,Math.min(4.5,1+.035*x+x*(x-60)*(100-x)*7e-6));this._trackBreach(Du,N<ae.THRESHOLD_MOS)}else this._trackBreach(Du,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const x=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,N=e.audio.inbound.bytesReceived;this._trackBreach(Pu,x!==void 0&&N-x==0)}if(((y=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||y===void 0?void 0:y.bytesSent)!==void 0){const x=(_=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||_===void 0?void 0:_.bytesSent,N=e.audio.outbound.bytesSent;this._trackBreach(Mu,x!==void 0&&N-x==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=ae.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(ss,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ae.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(ss)):this._trackBreach(ss,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(ss,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=ae.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ae.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=ze(e);S.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){S.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u){const d={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};return n&&(d.audio.outbound=Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{})),s&&(d.audio.inbound={packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)}),o&&(d.connection={roundTripTimeAvg:this._average(this.intervalRTTs),packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived},d.ice=Object.assign(Object.assign({id:o.id,state:o.state,nominated:o.nominated,writable:o.writable,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(d.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{})),d}_resolveCandidate(e,i){if(!i)return void S.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void S.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),Object.keys(s).length!==0)return s;S.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void S.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,S.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}ae.INITIAL_COLLECTION_INTERVAL_MS=1e3,ae.INITIAL_COLLECTION_DURATION_MS=1e4,ae.STATS_FLUSH_THRESHOLD=300,ae.LOGS_FLUSH_THRESHOLD=800,ae.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ae.CONSECUTIVE_BREACHES_REQUIRED=3,ae.THRESHOLD_RTT_MS=.4,ae.THRESHOLD_JITTER_MS=30,ae.THRESHOLD_PACKET_LOSS_PCT=1,ae.THRESHOLD_MOS=3.5,ae.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ae.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ae.WARNING_THROTTLE_MS=15e3,ae.RETRY_DELAYS_MS=[500,1e3,2e3],ae.KEEPALIVE_BODY_LIMIT_BYTES=61440;class V0{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return U(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,S.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){S.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return U(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){S.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return U(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&S.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){S.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var vs,ph=Vu(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,m,f,w){var I,L,R;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((L=p._events)?(L.newListener&&(p.emit("newListener",m,f.listener?f.listener:f),L=p._events),R=L[m]):(L=p._events=new n,p._eventsCount=0),R){if(typeof R=="function"?R=L[m]=w?[f,R]:[R,f]:w?R.unshift(f):R.push(f),!R.warned&&(I=o(p))&&0<I&&R.length>I){R.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=p,O.type=m,O.count=R.length,function(P){typeof console.warn=="function"?console.warn(P):console.log(P)}(O)}}else R=L[m]=f,++p._eventsCount;return p}function a(p,m,f){function w(){p.removeListener(m,w),I||(I=!0,f.apply(p,arguments))}var I=!1;return w.listener=f,w}function l(p){var m=this._events;if(m){var f=m[p];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(p,m){for(var f=Array(m);m--;)f[m]=p[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var m,f,w,I,L,R,O,P=p==="error";if(R=this._events)P=P&&R.error==null;else if(!P)return!1;if(O=this.domain,P){if(m=arguments[1],!O){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=O,m.domainThrown=!1,O.emit("error",m),!1}if(!(f=R[p]))return!1;var H=typeof f=="function";switch(w=arguments.length){case 1:(function($,ue,J){if(ue)$.call(J);else for(var G=$.length,le=c($,G),X=0;X<G;++X)le[X].call(J)})(f,H,this);break;case 2:(function($,ue,J,G){if(ue)$.call(J,G);else for(var le=$.length,X=c($,le),ee=0;ee<le;++ee)X[ee].call(J,G)})(f,H,this,arguments[1]);break;case 3:(function($,ue,J,G,le){if(ue)$.call(J,G,le);else for(var X=$.length,ee=c($,X),te=0;te<X;++te)ee[te].call(J,G,le)})(f,H,this,arguments[1],arguments[2]);break;case 4:(function($,ue,J,G,le,X){if(ue)$.call(J,G,le,X);else for(var ee=$.length,te=c($,ee),ie=0;ie<ee;++ie)te[ie].call(J,G,le,X)})(f,H,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(w-1),L=1;L<w;L++)I[L-1]=arguments[L];(function($,ue,J,G){if(ue)$.apply(J,G);else for(var le=$.length,X=c($,le),ee=0;ee<le;++ee)X[ee].apply(J,G)})(f,H,this,I)}return!0},s.prototype.addListener=function(p,m){return r(this,p,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,m){return r(this,p,m,!0)},s.prototype.once=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,m)),this},s.prototype.prependOnceListener=function(p,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,m)),this},s.prototype.removeListener=function(p,m){var f,w,I,L,R;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(w=this._events))return this;if(!(f=w[p]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete w[p],w.removeListener&&this.emit("removeListener",p,f.listener||m));else if(typeof f!="function"){for(I=-1,L=f.length;0<L--;)if(f[L]===m||f[L].listener&&f[L].listener===m){R=f[L].listener,I=L;break}if(0>I)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete w[p]}else(function(O,P){for(var F=P,H=F+1,$=O.length;H<$;F+=1,H+=1)O[F]=O[H];O.pop()})(f,I);w.removeListener&&this.emit("removeListener",p,R||m)}return this},s.prototype.removeAllListeners=function(p){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[p]&&(--this._eventsCount==0?this._events=new n:delete f[p]),this;if(arguments.length===0){for(var w,I=Object.keys(f),L=0;L<I.length;++L)(w=I[L])!=="removeListener"&&this.removeAllListeners(w);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[p])=="function")this.removeListener(p,m);else if(m)do this.removeListener(p,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(p){var m,f,w=this._events;return w?f=(m=w[p])?typeof m=="function"?[m.listener||m]:function(I){for(var L=Array(I.length),R=0;R<L.length;++R)L[R]=I[R].listener||I[R];return L}(m):[]:f=[],f},s.listenerCount=function(p,m){return typeof p.listenerCount=="function"?p.listenerCount(m):l.call(p,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var g=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,y=[],v=0;256>v;++v)y.push((v+256).toString(16).substr(1));function b(p){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(y[p[m+0]]+y[p[m+1]]+y[p[m+2]]+y[p[m+3]]+"-"+y[p[m+4]]+y[p[m+5]]+"-"+y[p[m+6]]+y[p[m+7]]+"-"+y[p[m+8]]+y[p[m+9]]+"-"+y[p[m+10]]+y[p[m+11]]+y[p[m+12]]+y[p[m+13]]+y[p[m+14]]+y[p[m+15]]).toLowerCase();if(!function(w){return typeof w=="string"&&g.test(w)}(f))throw TypeError("Stringified UUID is invalid");return f}function _(p,m,f){var w=(p=p||{}).random||(p.rng||h)();return w[6]=64|15&w[6],w[8]=128|63&w[8],b(w)}function C(p,m){if(!p||!m)return{};const f={...p};if(f.localCandidateId){const w=m.get(f.localCandidateId);f.local={...w}}if(f.remoteCandidateId){const w=m.get(f.remoteCandidateId);f.remote={...w}}return f}function k(p,m,f){return 8*function(w,I,L){const R=w[L],O=I?I[L]:null;return R===null||O===null?null:(R-O)/(w.timestamp-I.timestamp)*1e3}(p,m,f)}function A(p){if(!p.entries)return p;const m={};return p.forEach(function(f,w){m[w]=f}),m}function x(p,m,f={}){if(!p)return null;let w={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(w.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of p.values())switch(I.type){case"outbound-rtp":{const L=I.mediaType||I.kind,R={};let O={};if(!["audio","video"].includes(L))continue;if(I.codecId){const P=p.get(I.codecId);P&&(R.clockRate=P.clockRate,R.mimeType=P.mimeType,R.payloadType=P.payloadType)}O=p.get(I.mediaSourceId)||p.get(I.trackId)||{},w[L].outbound.push({...I,...R,track:{...O}});break}case"inbound-rtp":{let L=I.mediaType||I.kind,R={};const O={};if(!["audio","video"].includes(L))if(I.id.includes("Video"))L="video";else{if(!I.id.includes("Audio"))continue;L="audio"}if(I.codecId){const P=p.get(I.codecId);P&&(O.clockRate=P.clockRate,O.mimeType=P.mimeType,O.payloadType=P.payloadType)}if(!w.connection.id&&I.transportId){const P=p.get(I.transportId);if(P&&P.selectedCandidatePairId){const F=p.get(P.selectedCandidatePairId);w.connection=C(F,p)}}R=p.get(I.mediaSourceId)||p.get(I.trackId)||{},w[L].inbound.push({...I,...O,track:{...R}});break}case"peer-connection":w.connection.dataChannelsClosed=I.dataChannelsClosed,w.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let L=I.mediaType||I.kind;const R={};if(!["audio","video"].includes(L))if(I.id.includes("Video"))L="video";else{if(!I.id.includes("Audio"))continue;L="audio"}if(I.codecId){const O=p.get(I.codecId);O&&(R.clockRate=O.clockRate,R.mimeType=O.mimeType,R.payloadType=O.payloadType)}if(!w.connection.id&&I.transportId){const O=p.get(I.transportId);if(O&&O.selectedCandidatePairId){const P=p.get(O.selectedCandidatePairId);w.connection=C(P,p)}}w.remote[L].inbound.push({...I,...R});break}case"remote-outbound-rtp":{if(!f.remote)break;const L=I.mediaType||I.kind,R={};if(!["audio","video"].includes(L))continue;if(I.codecId){const O=p.get(I.codecId);O&&(R.clockRate=O.clockRate,R.mimeType=O.mimeType,R.payloadType=O.payloadType)}w.remote[L].outbound.push({...I,...R});break}}if(!w.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(w.connection=C(I,p));return w=function(I,L){return L&&(I.audio.inbound.map(R=>{let O=L.audio.inbound.find(P=>P.id===R.id);R.bitrate=k(R,O,"bytesReceived"),R.packetRate=k(R,O,"packetsReceived")}),I.audio.outbound.map(R=>{let O=L.audio.outbound.find(P=>P.id===R.id);R.bitrate=k(R,O,"bytesSent"),R.packetRate=k(R,O,"packetsSent")}),I.video.inbound.map(R=>{let O=L.video.inbound.find(P=>P.id===R.id);R.bitrate=k(R,O,"bytesReceived"),R.packetRate=k(R,O,"packetsReceived")}),I.video.outbound.map(R=>{let O=L.video.outbound.find(P=>P.id===R.id);R.bitrate=k(R,O,"bytesSent"),R.packetRate=k(R,O,"packetsSent")})),I}(w,m),w}let N,T={},E=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:m})}async addConnection(p){const{pc:m,peerId:f}=p;let{connectionId:w,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(w&&w in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${w}.`);for(let R in this.peersToMonitor[f]){const O=this.peersToMonitor[f][R];if(O.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);O.pc.connectionState==="closed"&&this.removeConnection({pc:O.pc})}}const L=m.getConfiguration();return L.iceServers&&L.iceServers.forEach(function(R){delete R.credential}),w||(w=_()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:w,data:{options:p,peerConfiguration:L}}),this.monitorPeer({peerId:f,connectionId:w,pc:m,remote:I}),{connectionId:w}}getTimeline(p){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),p?this.timeline.filter(m=>m.tag===p):this.timeline}get logger(){const p=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(p){let m,{connectionId:f,pc:w}=p;if(!w&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)f in this.peersToMonitor[I]&&(w=this.peersToMonitor[I][f].pc,m=I)}else if(w){if(!(w instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let L in this.peersToMonitor[I])this.peersToMonitor[I][L].pc===w&&(f=L,m=I)}if(!w||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,w),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let m in this.peersToMonitor[p]){let f=this.peersToMonitor[p][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),E.forEach(p=>{this.removeTrackEventListeners(p)}),E=[],this.shouldWrapGetUserMedia&&N&&(navigator.mediaDevices.getUserMedia=N)}monitorPeer(p){let{peerId:m,connectionId:f,pc:w,remote:I}=p;if(!w)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const L={pc:w,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=L}else this.peersToMonitor[m]={[f]:L};this.addPeerConnectionEventListeners(m,f,w),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let m={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);m[p]=this.peersToMonitor[p]}else m=this.peersToMonitor;let f=[];for(const w in m)for(const I in m[w]){const L=m[w][I],R=L.pc;if(R&&!this.checkIfConnectionIsClosed(w,I,R))try{const O=this.getTimestamp(),P=R.getStats(null);if(P){const F=await P,H=this.getTimestamp(),$=A(F),ue={remote:L.options.remote},J=x(F,L.stats.parsed,ue),G={event:"stats",tag:"stats",peerId:w,connectionId:I,timeTaken:H-O,data:J};this.rawStats===!0&&(G.rawStats=F),this.statsObject===!0&&(G.statsObject=$),this.filteredStats===!0&&(G.filteredStats=this.filteroutStats($)),f.push(G),L.stats.parsed=J}else this.logger.error(`PeerConnection from peer ${w} did not return any stats data`)}catch(O){this.logger.error(O)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const m in this.peersToMonitor[p]){const f=this.peersToMonitor[p][m].pc;this.checkIfConnectionIsClosed(p,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,m,f){const w=this.isConnectionClosed(f);if(w){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:m,tag:"connection",data:"closed"})}return w}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),N=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),N.apply(navigator.mediaDevices,arguments).then(m=>(p({stream:m}),m),m=>(p({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const m={...p};for(const w in m){var f=m[w];this.statsToMonitor.includes(f.type)||delete m[w]}return m}get peerConnectionListeners(){return{icecandidate:(p,m,f,w)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",w),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:m,data:w.candidate})},track:(p,m,f,w)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,w);const I=w.track,L=w.streams[0];p in this.peersToMonitor&&m in this.peersToMonitor[p]&&(this.peersToMonitor[p][m].stream=L),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:m,data:{stream:L?this.getStreamDetails(L):null,track:I?this.getMediaTrackDetails(I):null,title:w.track.kind+":"+w.track.id+" "+w.streams.map(function(R){return"stream:"+R.id})}})},signalingstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(p,m,f,w)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:m,error:{errorCode:w.errorCode}})},connectionstatechange:(p,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:m,data:f.connectionState})},negotiationneeded:(p,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:m})},datachannel:(p,m,f,w)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,w),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:m,data:w.channel})}}}addPeerConnectionEventListeners(p,m,f){this.logger.debug(`Adding event listeners for peer ${p} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(w=>{T[m][w]=this.peerConnectionListeners[w].bind(this,p,m,f),f.addEventListener(w,T[m][w],!1)})}parseGetUserMedia(p){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(m.data.details=this.parseStream(p.stream),p.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(m)}catch{}}parseStream(p){const m={audio:[],video:[]};return p.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(p,m){T[p.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(w=>{T[p.id][w]=f[w].bind(this),p.addEventListener(w,T[p.id][w])}),T[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let w=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(w)}},1e3)}removeTrackEventListeners(p){if(p.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{p.removeEventListener(f,T[p.id][f])}),clearInterval(T[p.id].readyState),delete T[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const m={...p,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,m){p in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[p][f],!1)}),delete T[p]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(w){return w},function(w){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,w.name),Promise.reject(w)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(vs=ph)&&vs.__esModule&&Object.prototype.hasOwnProperty.call(vs,"default")&&vs.default;var U0=ph.WebRTCStats;function B0(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function $0(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 j0 extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class H0 extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class G0 extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,debug_report_data:i})}}function W0(t,e){const i=Ci();let n=!1;const s=new U0({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>U(this,void 0,void 0,function*(){r.event==="stats"&&V(M.StatsFrame,function({data:a}){var l,c,u,d,h,g,y,v;const{audio:b,remote:_}=a,{audio:C}=_,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,x=(g=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&g!==void 0?g:-1,N=(v=(y=b.inbound[0])===null||y===void 0?void 0:y.packetsLost)!==null&&v!==void 0?v:-1,T=B0({jitter:1e3*k,rtt:1e3*A,packetsLost:N,packetsReceived:x});return{jitter:k,rtt:A,mos:T,quality:$0(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new G0(i,r))});return{get isRunning(){return n},start:(r,a,l)=>U(this,void 0,void 0,function*(){if(n)S.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new j0(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){S.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>U(this,void 0,void 0,function*(){const a=s.getTimeline();V(M.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new H0(i,e)),s.removeAllPeers(),s.destroy(),n=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const gh=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:it.conferenceUpdate,call:t.calls[s],canvasInfo:q0(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ke.LayerInfo},a);V(M.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ke.LayoutInfo},a);V(M.Notification,l,t.uuid);break}}},q0=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Hu(e)},mh=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],z0={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function oe(t,e){return`telnyx:call:${t}:${e}`}function vh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Ir(t){for(const e of mh)try{performance.clearMarks(oe(t,e))}catch{S.warn("Clearing performance marks is failed")}}class Zt{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>U(this,void 0,void 0,function*(){var r,a;const{connectionState:l}=this.instance;if(S.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return U(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const g=h[0].sender,y=g==null?void 0:g.transport;y&&(d.dtlsState=y.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(y=>{y.type==="candidate-pair"&&y.state==="succeeded"&&(d.candidatePairState=y.state,g.forEach(v=>{v.type==="local-candidate"&&v.id===y.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===y.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),y.type==="transport"&&(d.dtlsCipher=y.dtlsCipher,d.srtpCipher=y.srtpCipher,d.tlsVersion=y.tlsVersion,y.dtlsState&&(d.dtlsState=y.dtlsState))})}catch(g){S.error("Error gathering connection state details:",g)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=ze(Hy);V(M.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=ze(qy);V(M.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(oe(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(oe(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(oe(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;const l=this.instance.iceConnectionState;S.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(oe(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;S.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},S.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.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=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(S.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(S.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},Zt.ICE_RESTART_TIMEOUT_MS),S.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(S.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(S.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Ne.Offer}get isAnswer(){return this.type===Ne.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(oe(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer():this._createAnswer()}startTrickleIceNegotiation(){return U(this,void 0,void 0,function*(){performance.mark(oe(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_logTransceivers(){this.instance?(S.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{S.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),S.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):S.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(S.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":V(M.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(S.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){S.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?S.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()&&!this.isIceRestarting?this.startTrickleIceNegotiation():this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(oe(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&fs(n,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(oe(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=vh(oe(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of mh){if(d==="new-call-start")continue;const h=vh(oe(s,d));h!==void 0&&l.push({label:z0[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void S.info(`${l} No timing data collected`);const c=Math.max(...a.map(y=>y.label.length),4)+2,u=(y,v)=>{for(;y.length<v;)y+=" ";return y},d=(y,v)=>{for(;y.length<v;)y=" "+y;return y},h=u("Step",c)+d("Delta",14)+d("From Start",14);let g="";for(let y=0;y<h.length;y++)g+="-";S.info(`${l} Call establishment timing breakdown:`),S.info(`${l} ${h}`),S.info(`${l} ${g}`),S.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const y of a){const v=y.delta.toFixed(2)+"ms",b=y.fromStart.toFixed(2)+"ms";S.info(`${l} ${u(y.label,c)}${d(v,14)}${d(b,14)}`)}S.info(`${l} ${g}`)})(n),Ir(this.options.id)}createPeerConnection(){return U(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer}),performance.mark(oe(this.options.id,"set-remote-description")),!this.instance))throw re(gr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>U(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),V(M.Error,{error:re(Ti(s),s),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>U(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw re(gr);if(!this.options.localStream&&!i)throw re(n?Ti(n):xu,n??void 0);performance.mark(oe(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&gn(this.options.localStream)&&(S.info("Muting local audio tracks on start"),ms(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(oe(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=ze(Wy);V(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=ze(Gy);V(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},Zt.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return U(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw re(gr);this.isDebugEnabled&&(this.statsReporter=W0(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:i,localStream:n=null,screenShare:s=!1}=this.options;if(gn(n)){const o=n.getAudioTracks();let r=[...o];if(S.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{S.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],S.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{S.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=fh(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&fs(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});S.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=fh(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:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);S.info("Add transceiver",e,i)}}_createOffer(){return U(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,S.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(oe(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(oe(this.options.id,"set-local-description")),performance.mark(oe(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){S.error("Peer _createOffer error:",e);const i=re(Cy,e);V(M.Error,{error:i,sessionId:this._session.sessionid},this.options.id)}}})}_setRemoteDescription(e){return U(this,void 0,void 0,function*(){S.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){S.error("Peer _setRemoteDescription error:",i);const n=re(ku,i);throw V(M.Error,{error:n,sessionId:this._session.sessionid},this.options.id),i}})}_createAnswer(){return U(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return S.debug("Skipping negotiation, state:",this.instance.signalingState),S.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(oe(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(oe(this.options.id,"set-local-description")),performance.mark(oe(this.options.id,"ice-gathering-started")),e}catch(e){S.error("Peer _createAnswer error:",e);const i=re(Ty,e);V(M.Error,{error:i,sessionId:this._session.sessionid},this.options.id)}}})}_setLocalDescription(e){return U(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){S.error("Peer _setLocalDescription error:",i);const n=re(Ey,i);throw V(M.Error,{error:n,sessionId:this._session.sessionid},this.options.id),i}})}_sdpReady(){Ei(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(gn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,U(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield gs(s,a,_t.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield gs(r,l,_t.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return ps(e)})}_isOffer(){return this.type===Ne.Offer}_isAnswer(){return this.type===Ne.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return S.info("RTC config",s),s}restartStatsReporter(){return U(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?S.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(S.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):S.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return U(this,void 0,void 0,function*(){Ir(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}Zt.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,Zt.ICE_RESTART_TIMEOUT_MS=15e3;const _s=Sr;class _h{constructor(e,i){this.session=e,this._callReportCollector=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=j[j.New],this.prevState="",this.channels=[],this.role=yr.Participant,this.extension=null,this._state=j.New,this._prevState=j.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=b=>{const _=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return _&&b>=0&&(this._lastSerno=b),_},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(_=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==_[k])return}C.callback(_)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:g},ringtoneFile:y,ringbackFile:v}=e;this.options=Object.assign({},_0,{audio:h,video:g,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:y,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=dh(this.options.ringtoneFile,"_ringtone"),this._ringback=dh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
- `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return U(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=lt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(oe(this.id,"new-peer")),this.peer=new Zt(Ne.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){S.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof dn?e:re(Lu,e instanceof Error?e:void 0);return V(M.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r;return U(this,void 0,void 0,function*(){if(this._creatingPeer||!((i=this.peer)===null||i===void 0)&&i.instance&&this.peer.instance.signalingState!=="closed"){const a=ze(Ky);return V(M.Warning,{warning:a,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void S.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(o=(s=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||s===void 0?void 0:s.signalingState)!==null&&o!==void 0?o:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(oe(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=lt.Inbound,((r=e==null?void 0:e.customHeaders)===null||r===void 0?void 0:r.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(oe(this.id,"new-peer")),this.peer=new Zt(Ne.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(a){S.error("Peer init failed, aborting call",a),this._creatingPeer=!1;const l=a instanceof dn?a:re(Lu,a instanceof Error?a:void 0);return V(M.Error,{error:l,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){uh(this._ringtone)}stopRingtone(){hh(this._ringtone)}playRingback(){uh(this._ringback)}stopRingback(){hh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return U(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,g=this._captureHangupCallerStack(),y=c.initiator||"app:call.hangup",v=this._state<j.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],S.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:y,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:g}),c.isRecovering)return this._isRecovering=!0,this.setState(j.Recovering),void this._finalize();if(this.setState(j.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new k0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let _;try{yield Promise.race([this._execute(b),new Promise(C=>{_=setTimeout(()=>{S.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){S.error("telnyx_rtc.bye failed!",C);const k=re(Ry,C);V(M.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{_&&clearTimeout(_)}}S.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(j.Destroy)})}hold(){const e=new us({sessid:this.session.sessionid,action:ki.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new us({sessid:this.session.sessionid,action:ki.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new us({sessid:this.session.sessionid,action:ki.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new oh({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new oh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){S.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ms(this.options.localStream)}unmuteAudio(){S.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,kr(this.options.localStream)}_applyDesiredAudioMuteState(){S.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ms(this.options.localStream):kr(this.options.localStream)}toggleAudioMute(){S.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return U(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return S.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void V(M.Warning,{warning:ze(Xy),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;S.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Cr(l.track),localTracks:ch(this.options.localStream)});try{c=yield hs({audio:{deviceId:{exact:e}}})}catch(h){const g=re(Ti(h),h);return void V(M.MediaError,g,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const g=re(Ti(h),h);return V(M.MediaError,g,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(y=>y.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,S.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Cr(l.track),localTracks:ch(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Ri(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Ri(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Ri(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield hs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;fs(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){ms(this.options.remoteStream)}undeaf(){kr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Ri(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void S.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void S.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),S.info("Parameters: ",r),S.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{S.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>S.error(a))}else S.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[j.Hangup,j.Destroy,j.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n;switch(this._prevState=this._state,this._state=e,this.state=j[this._state].toLowerCase(),this.prevState=j[this._prevState].toLowerCase(),S.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:it.callUpdate,call:this}),e){case j.Purge:S.info(`[${this.id}] Entering Purge state.`);break;case j.Active:performance.mark(oe(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,S.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:s,speakerId:o}=this.options;s&&o&&ah(s,o)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._mediaDeviceCollector=new V0,this._mediaDeviceCollector.logDevicesAtStart();break;case j.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Q.Answer:if(performance.mark(oe(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=j.Active)return;this._state>=j.Early&&this.setState(j.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Q.Media:if(performance.mark(oe(this.id,"telnyx-rtc-media")),this._state>=j.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Q.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===lt.Inbound?lt.Outbound:lt.Inbound,c={type:it[i],call:this,displayName:o,displayNumber:r,displayDirection:l};V(M.Notification,c,this.id)||V(M.Notification,c,this.session.uuid);break}case Q.Candidate:this._addIceCandidate(n);break;case Q.Info:case Q.Event:{const o=Object.assign(Object.assign({},n),{type:it.generic,call:this});V(M.Notification,o,this.id)||V(M.Notification,o,this.session.uuid);break}case Q.Ringing:performance.mark(oe(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Q.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return S.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:Ke.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const g=[];for(const y in s)g.push(Object.assign({callId:s[y][0],index:Number(y)},rs(s[y][1])));this._dispatchConferenceUpdate({action:Ke.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ke.Add,callId:o,index:r},rs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ke.Modify,callId:o,index:r},rs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ke.Delete,callId:o,index:r},rs(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ke.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Ke.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{S.error("ConfChat subscription error:",s)});Tr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,gh(this.session,o)):S.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{S.error("ConfInfo subscription error:",s)});Tr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(j.Active):this.setState(j.Held),!0}_handleChangeHoldStateError(e){S.error(`Failed to ${e.action} on call ${this.id}`);const i=re(xy,e);return V(M.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e){const i=new us({sessid:this.session.sessionid,action:ki.UpdateMedia,callID:this.options.id,sdp:e,dialogParams:this.options});S.info("ICE restart: sending Modify with new offer SDP"),this._execute(i).then(n=>U(this,void 0,void 0,function*(){var s;n!=null&&n.sdp?(S.info("ICE restart Modify response received"),(s=this.peer)===null||s===void 0||s.finishIceRestart(),yield this._onRemoteSdp(n.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(n=>{this._onIceRestartFailed("ICE restart Modify failed",n)})}_onIceRestartFailed(e,i){var n;S.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const s=re(Fy,i);V(M.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onRemoteSdp(e){return U(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Ne.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(oe(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(j.Early),this.gotAnswer&&this.setState(j.Active)}).catch(n=>U(this,void 0,void 0,function*(){S.error("Call setRemoteDescription Error: ",n);const s=re(ku,n);V(M.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){S.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){Ei(this.peer.onSdpReadyTwice)?V(M.Error,{error:new Error("SDP without candidates for the second time!"),sessionId:this.session.sessionid},this.session.uuid):(Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation())}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void S.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return S.info(`No candidate - retry
117
- `),void this._requestAnotherLocalDescription();if((n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),!s0.test(o)){const c=ze(zy);S.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),V(M.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(oe(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${_s}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Ne.Offer:this.setState(j.Requesting),a=new ih(l);break;case Ne.Answer:this._isRecovering||this.setState(j.Answering),a=this.options.attach===!0?new sh(l):new nh(l);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(oe(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void S.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Ne.Offer?this.setState(j.Trying):this.setState(j.Active)}).catch(c=>U(this,void 0,void 0,function*(){S.error(`${this.id} - Sending ${r} error:`,c);const u=re(Iu,c);V(M.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){S.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return S.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${_s}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n);else{switch(s){case Ne.Offer:this.setState(j.Requesting),o=new ih(r);break;case Ne.Answer:this._isRecovering||this.setState(j.Answering),o=this.options.attach===!0?new sh(r):new nh(r);break;default:return S.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(oe(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void S.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Ne.Offer?this.setState(j.Trying):this.setState(j.Active)}).catch(a=>U(this,void 0,void 0,function*(){S.error(`${this.id} - Sending ${s} error:`,a);const l=re(Iu,a);V(M.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){S.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(S.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i;e.candidate&&e.candidate.candidate?(S.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const i=new I0({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return S.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{S.debug("Successfully added ICE candidate:",e)}).catch(n=>{S.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new x0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(oe(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(oe(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n,s;if(this.options.trickleIce&&!(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting))this._onTrickleIce(i);else{if(!((s=this.peer)===null||s===void 0)&&s.iceDone)return;this._onIce(i)}},e.onicegatheringstatechange=i=>{S.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(S.debug("Finished gathering candidates"),performance.mark(oe(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(S.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&fs(n,s)})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:it.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),S.error(`Media error (${i}): ${n}`,e),V(M.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:it.peerConnectionFailureError,error:e.error}),S.error("Peer connection failure error"),e.warning&&V(M.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:it.signalingStateClosed},e)),S.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:it.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(V(M.Notification,e,this.id,!1)||V(M.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){if(this.options.attach||this._isRecovering)return!0;for(const e of this._getSessionInboundAnswerCalls()){if(e.id===this.id||!e._isBlockingInboundAnswer())continue;const i=ze(Jy);return V(M.Warning,{warning:i,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),S.warn(`[${this.id}] answer() ignored: inbound call ${e.id} is already answering or active`),!1}return!0}_getSessionInboundAnswerCalls(){return Object.values(this.session.calls).filter(e=>!!e).filter(e=>!e.options.attach&&!e._isRecovering&&e.direction===lt.Inbound)}_isBlockingInboundAnswer(){var e;if([j.Hangup,j.Destroy,j.Purge].includes(this._state))return!1;const i=[j.Answering,j.Early,j.Active,j.Held].includes(this._state);return!(!this._creatingPeer&&!i)&&(!(!this._creatingPeer||!((e=this.peer)===null||e===void 0)&&e.instance)||this._hasUsablePeerConnection())}_hasUsablePeerConnection(){var e;const i=(e=this.peer)===null||e===void 0?void 0:e.instance;return!!i&&i.signalingState!=="closed"&&i.connectionState!=="closed"&&i.iceConnectionState!=="closed"}_init(){var e,i,n;const{id:s,userVariables:o,remoteCallerNumber:r,onNotification:a,recoveredCallId:l}=this.options;var c;this.options.id=s?s.toString():Ci(),this.id=this.options.id,l&&(this.recoveredCallId=l,this._isRecovering=!0),o&&(c=o,Object.keys(c).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),r||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Vt(M.MediaError,this._onMediaError,this.id),Vt(M.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Vt(M.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ei(a)&&Vt(M.Notification,a.bind(this),this.id);const u=this.session.options.enableCallReports!==!1,d=this.session.options.callReportInterval||5e3,h=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,g=this.session.options.debugLogLevel||"debug",y=this.session.options.debugLogMaxEntries||1e3;u&&(this._callReportCollector=new ae({enabled:!0,interval:d,intermediateReportInterval:h},{enabled:!0,level:g,maxEntries:y}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=v=>{var b,_,C,k;V(M.Warning,{warning:v,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),v.code===Pu?(_=(b=this.session).reportNoRtp)===null||_===void 0||_.call(b,this.id,"inbound"):v.code===Mu&&this._hasActiveUnmutedLocalAudioTrack()&&((k=(C=this.session).reportNoRtp)===null||k===void 0||k.call(C,this.id,"outbound"))}),this._isRecovering?this.setState(j.Recovering):this.setState(j.New),S.info(`New Call — region: ${(i=this.session.region)!==null&&i!==void 0?i:"unknown"}, dc: ${(n=this.session.dc)!==null&&n!==void 0?n:"unknown"}`,this.options)}_finalize(){var e,i;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,Ir(this.id),S.debug(`[${this.id}] Closing peer from _finalize`),(i=this.peer)===null||i===void 0||i.close();const{remoteStream:n,localStream:s,remoteElement:o,localElement:r}=this.options;mn(n),mn(s),rh(o,n),rh(r,s),yt(M.MediaError,null,this.id),yt(M.PeerConnectionFailureError,null,this.id),yt(M.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const a=this._postCallReport().catch(l=>{S.error("Unexpected error in _postCallReport",{error:l})});this.session.trackCallReportUpload(a)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void S.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void S.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===lt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:_s},r=this._callReportCollector.flush(o,e);if(!r)return;S.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=this._callReportCollector.sendPayload(r,n,s,a).catch(c=>{S.error("Failed to post intermediate call report segment",{error:c})});this.session.trackCallReportUpload(l)}_postCallReport(){var e,i;return U(this,void 0,void 0,function*(){if(!this._callReportCollector)return void S.warn("Call report collector not initialized");yield this._callReportCollector.stop();const n=this.session.callReportId;if(!n)return S.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const s={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===lt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:_s},o=(e=this.session.connection)===null||e===void 0?void 0:e.host;if(!o)return void S.error("Cannot post call report: connection host not available");const r=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(s,n,o,r)}catch(a){throw S.error("Failed to post call report",{error:a}),a}finally{(i=this._callReportCollector)===null||i===void 0||i.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),S.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),S.debug("Stats stopped")}}_h.setStateTelnyx=t=>{if(t){switch(t._state){case j.Recovering:t.state="recovering";break;case j.Requesting:case j.Trying:case j.Early:t.state="connecting";break;case j.Active:t.state="active";break;case j.Held:t.state="held";break;case j.Hangup:case j.Destroy:t.state="done";break;case j.Answering:t.state="ringing";break;case j.New:t.state="new"}return t}};class ei extends _h{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new N0(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new F0(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return U(this,void 0,void 0,function*(){this.screenShare instanceof ei&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return U(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>U(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new ei(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return U(this,void 0,void 0,function*(){this.screenShare instanceof ei&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&ah(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>U(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
113
+ `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(b.debug("Connection.close() called",{hasWsClient:!!this._wsClient,closing:this.closing,closed:this.closed,socketGeneration:this.socketGeneration,safetyTimeoutId:this._safetyTimeoutId,sessionId:this.session.sessionid}),!this._wsClient||this.closing)return;this._cleanupPendingRequests();const e=this._wsClient;Ei(this._wsClient._beginClose)?this._wsClient._beginClose():this._wsClient.close(),this._safetyTimeoutId||(this._safetyTimeoutId=setTimeout(()=>this._handleCloseTimeout(e),5e3))}_registerSocketEvents(e){const i=this.socketGeneration;e.onopen=n=>(b.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),B(M.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),b.debug("WebSocket onclose",{code:n==null?void 0:n.code,reason:n==null?void 0:n.reason,wasClean:n==null?void 0:n.wasClean,socketGeneration:i,sessionId:this.session.sessionid}),B(M.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),b.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ne(Uy);return B(M.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),B(M.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),B(M.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Xu(n.data);var a;if(typeof r!="string"){if(r.voice_sdk_id&&(this.session.callReportVoiceSdkId=r.voice_sdk_id,a=r.voice_sdk_id,sessionStorage.setItem(Sr,a)),this._unsetTimer(r.id),b.debug(`RECV:
114
+ `,JSON.stringify(r,null,2),`
115
+ `),De[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!B(r.id,r)){const l=wr(r);B(M.SocketMessage,r,this.session.uuid),l&&(this.previousGatewayState=l)}}else this._handleStringResponse(r)}}_deregisterSocketEvents(e){e.onopen=null,e.onclose=null,e.onerror=null,e.onmessage=null}_handleCloseTimeout(e){this._safetyTimeoutId=null,e&&e.readyState!==oh?(b.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?b.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(b.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(M.SocketClose,{code:Wu.ABNORMAL_CLOSURE,reason:"STUCK_WS_TIMEOUT: Socket got stuck in CLOSING state and was forcefully cleaned up by safety timeout",wasClean:!1,socketGeneration:this.socketGeneration},this.session.uuid))):b.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(b.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(b.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):b.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{yt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new br(e,n.generation,this.socketGeneration))),this._pendingRequestRejecters.delete(e)}),this._pendingRequestIds.clear()}_unsetTimer(e){clearTimeout(this._timers[e]),delete this._timers[e]}_handleStringResponse(e){if(/^#SP/.test(e))switch(e[3]){case"U":this.upDur=parseInt(e.substring(4));break;case"D":this.downDur=parseInt(e.substring(4)),B(M.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else b.warn("Unknown message from socket",e)}}us.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class xi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const rh={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ue extends xi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=xu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in rh)n&&i.hasOwnProperty(n)&&(i[rh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class ah extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class O0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(wr(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new ah(pn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Zu({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[De.REGISTER,De.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Zu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Rr extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Li{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null}static isCriticalMethod(e){return Li.CRITICAL_METHODS.has(e)}start(){this._intervalId||(b.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,b.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),b.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void b.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(b.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason,e.source))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?b.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(b.info(`Signaling health: ${e}, sending signaling probe`),this._sendProbe()))}onRequestTimeout(e,i,n=""){var s;!((s=this._session.connection)===null||s===void 0)&&s.connected&&(Li.isCriticalMethod(n)?(b.warn(`Critical signaling request timed out (id=${e}, method=${n}, timeout=${i}ms) — declaring signaling unhealthy`),this._triggerSignalingRecovery(`Critical signaling request timed out (method=${n}, id=${e}, timeout=${i}ms)`,"request")):b.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){b.warn(`Signaling health: peer failure reported (callId=${e}, evidence=${i})`),this._recoverMediaOrSignaling(e,`Peer connection failure (${i})`,`Peer failure detected (${i}) while signaling is unhealthy`,"peer_failure")}onNoRtp(e,i){b.warn(`Signaling health: no RTP detected (callId=${e}, direction=${i})`),this._recoverMediaOrSignaling(e,`No RTP ${i} while media should be active`,`No RTP ${i} while signaling is unhealthy`,"no_rtp")}onIceRestartFailed(e){b.warn(`Signaling health: ICE restart failed (callId=${e}) — triggering socket reconnect`),this._triggerSignalingRecovery(`ICE restart failed for call ${e}`,"peer_failure")}_check(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return;const i=Date.now(),n=i-this._lastInboundAt;if(n<2e4)return;if(!this._probeInFlight)return b.info(`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`),void this._sendProbe();const s=i-this._lastProbeSentAt;s>=5e3&&(b.warn(`Signaling health: probe timed out after ${s}ms with no inbound activity — declaring signaling unhealthy`),this._triggerSignalingRecovery("Signaling health probe timed out: no inbound WS activity after probe","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Rr(pn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{b.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void b.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(b.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i,s)):o==="unknown"?(b.info(`Signaling health: signaling health is unknown, deferring ICE restart decision for call ${e}`),this._pendingMediaRecovery={callId:e,reason:i,source:s},void this._probeIfNeeded(`${s} detected with stale/unknown signaling`)):(b.info("Signaling health: signaling is unhealthy, triggering socket reconnect instead of ICE restart"),void this._triggerSignalingRecovery(n,s))}_getSignalingHealthState(){var e;if(!(!((e=this._session.connection)===null||e===void 0)&&e.connected))return"unhealthy";if(this._probeInFlight)return"unknown";const i=Date.now(),n=this._lastInboundAt||this._session.connection.lastInboundAt||0;return n===0?"unknown":i-n<3e3?"healthy":"unknown"}_triggerSignalingRecovery(e,i="probe"){var n,s,o;this._pendingMediaRecovery=null,this._probeInFlight=!1,this._lastProbeSentAt=0,b.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Be(c0);B(M.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(b.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):b.debug("Signaling health: recovery triggered but connection not connected",{connected:(s=this._session.connection)===null||s===void 0?void 0:s.connected,hasConnection:!!this._session.connection,socketGeneration:(o=this._session.connection)===null||o===void 0?void 0:o.socketGeneration})}_triggerIceRestart(e,i,n){b.info(`Signaling health: triggering ICE restart for call ${e}`);const s=this._session.triggerIceRestart(e);if(!s.started)return void b.info(`Signaling health: ICE restart not started for call ${e}: ${s.reason}`);const o=Be(d0);B(M.Warning,{warning:o,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Li.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var lh="2.27.4-beta.1",Ar=lh;class M0 extends Ue{constructor(e,i,n,s,o={},r){super(),this.method="login";const a={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{},"User-Agent":{sdkVersion:Ar,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class P0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class ch extends Ue{toString(){return Z.Invite}}class dh extends Ue{toString(){return Z.Answer}}class uh extends Ue{toString(){return Z.Attach}}class N0 extends Ue{toString(){return Z.Bye}}class F0 extends Ue{toString(){return Z.Candidate}}class V0 extends Ue{toString(){return Z.EndOfCandidates}}class hs extends Ue{toString(){return Z.Modify}}class hh extends Ue{toString(){return Z.Info}}class B0 extends Ue{toString(){return Z.Broadcast}}class U0 extends Ue{toString(){return Z.Subscribe}}class $0 extends Ue{toString(){return Z.Unsubscribe}}class j0 extends Ue{constructor(e){super(),this.method="anonymous_login";const{target_type:i,target_id:n,target_version_id:s,target_params:o,userVariables:r,sessionId:a,reconnection:l}=e,c={target_type:i,target_id:n,userVariables:r,reconnection:l,"User-Agent":{sdkVersion:Ar,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 ei{constructor(e){if(this.options=e,this.uuid=ki(),this.sessionid="",this.subscriptions={},this.signature=null,this.relayProtocol=null,this.contexts=[],this.timeoutErrorCode=-32e3,this.invalidMethodErrorCode=-32601,this.authenticationRequiredErrorCode=-32e3,this.callReportId=null,this.callReportVoiceSdkId=null,this.dc=null,this.region=null,this.connection=null,this._jwtAuth=!1,this._autoReconnect=!0,this._idle=!1,this._reconnectAttempts=0,this._reconnectCountedGeneration=-1,this._intentionalClose=!1,this._tokenExpiryTimeout=null,this._pendingCallReportUploads=new Set,this._signalingHealthMonitor=new Li(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ku=(n=rs[i])!==null&&n!==void 0?n:rs.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new us(this),this.registerAgent=new O0(this)}get __logger(){return b}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return V(this,void 0,void 0,function*(){return this.registerAgent.getIsRegistered()})}get reconnectDelay(){const e=this._reconnectAttempts,i=Math.min(1e3*Math.pow(2,e-1),3e4),n=Math.floor(.25*i*(2*Math.random()-1)),s=i+n;return b.debug("Reconnect delay computed",{attempt:e,baseDelayMs:1e3,maxDelayMs:3e4,delayMs:i,jitterMs:n,totalDelay:s,sessionId:this.sessionid}),s}execute(e){var i;if(this._idle)return new Promise(s=>this._executeQueue.push({resolve:s,msg:e}));if(!this.connected)return new Promise(s=>{this._executeQueue.push({resolve:s,msg:e}),b.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Li.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?us.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>V(this,void 0,void 0,function*(){if(s instanceof br)throw b.debug(`Stale request settled (id=${s.requestId}, gen=${s.staleGeneration}) — not triggering recovery`),s;if((s==null?void 0:s.name)==="RequestTimeoutError")throw this.onSignalingRequestTimeout(s.requestId,s.timeoutMs,s.method),s;if((s==null?void 0:s.code)===this.authenticationRequiredErrorCode){if(!this._autoReconnect){const o=ne(Wy,s,void 0,!0);B(M.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return V(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},ei.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&b.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ls(this.options)||fn(this.options)}broadcast(e){}disconnect(){return V(this,void 0,void 0,function*(){clearTimeout(this._reconnectTimeout),this._clearTokenExpiryTimeout(),this.subscriptions={},this._autoReconnect=!1,this._intentionalClose=!0,this._reconnectAttempts=0,this.relayProtocol=null,yield this._drainCallReportUploads(),this._closeConnection(),yield sessionStorage.removeItem(this.signature),this._executeQueue=[],this._detachListeners(),b.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Ut(e,i,this.uuid),this}off(e,i){return yt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(b.debug("No existing connection found, creating a new one."),this.connection=new us(this)),this._attachListeners(),this._autoReconnect||(b.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(b.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),b.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Pu,e);B(M.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){eh()}_checkTokenExpiry(){this._clearTokenExpiryTimeout();const e=this.options.login_token;if(e&&typeof e=="string")try{const i=e.split(".");if(i.length!==3)return;const n=JSON.parse(atob(i[1])).exp;if(typeof n!="number")return;const s=n-Math.floor(Date.now()/1e3);if(s<=0)return;if(s<=ei.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ei.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{b.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Be(a0);B(M.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return V(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),ls(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(fn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";b.error(s);const o=ne(jy,void 0,s);return void B(M.Error,{error:o,type:E0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){return V(this,void 0,void 0,function*(){let s;const o=!!pn(),r=o&&(this.sessionid&&Qu()?this.sessionid:function(l=Date.now()){const c=sessionStorage.getItem(cs);return c?Qu(l)?c:(sessionStorage.removeItem(cs),sessionStorage.removeItem(ds),null):null}())||"";s=e==="login"?new M0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,r,this.options.userVariables,o):new j0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:r,userVariables:this.options.userVariables,reconnection:o});const a=yield this.execute(s).catch(l=>{this._handleLoginError(l),n&&n(l)});a&&(this.sessionid=a.sessid,this.sessionid&&Tr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return V(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){b.error("Failed to flush intermediate call report",{callId:n.id,flushReason:e,error:s})}})}_getSocketCloseCodeName(e){if(e===void 0)return;const i=Object.entries(Wu).find(([,n])=>n===e);return i==null?void 0:i[0]}_getSocketCloseError(e){if(e)return e instanceof Error?e.message:String(e)}_createSocketCloseFlushReason(e){return{type:e!=null&&e.error?"socket-error":"socket-close",socketClose:{code:e==null?void 0:e.code,codeName:this._getSocketCloseCodeName(e==null?void 0:e.code),reason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,error:this._getSocketCloseError(e==null?void 0:e.error)}}}onNetworkClose(e){var i,n,s,o;const r=(n=(i=this.connection)===null||i===void 0?void 0:i.socketGeneration)!==null&&n!==void 0?n:0,a=(s=e==null?void 0:e.socketGeneration)!==null&&s!==void 0?s:r;if(a<r)b.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),b.debug("onNetworkClose called",{closeCode:e==null?void 0:e.code,closeReason:e==null?void 0:e.reason,wasClean:e==null?void 0:e.wasClean,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,autoReconnect:this._autoReconnect,reconnectAttempts:this._reconnectAttempts}),this.relayProtocol&&Er(this.relayProtocol);for(const l in this.subscriptions)Er(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Tr(this.sessionid),this.connection&&(this.connection.previousGatewayState=""),this._autoReconnect){const l=(o=this.options.maxReconnectAttempts)!==null&&o!==void 0?o:10;if(this._reconnectCountedGeneration=a,this._reconnectAttempts+=1,l>0&&this._reconnectAttempts>l){b.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(yr);return void B(M.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;b.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{b.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(b.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Be(u0);B(M.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else b.debug(`Skipping duplicate onNetworkClose for socket generation ${a} (already handled, reconnect attempt ${this._reconnectAttempts})`)}_onSocketMessage(e){}_removeSubscription(e,i){this._existsSubscription(e,i)&&(i?(delete this.subscriptions[e][i],yt(e,null,i)):(delete this.subscriptions[e],Er(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ei(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),b.debug("Attaching socket event listeners"),this.on(M.SocketOpen,this._onSocketOpen),this.on(M.SocketClose,this.onNetworkClose),this.on(M.SocketError,this.onNetworkClose),this.on(M.SocketMessage,this._onSocketMessage),this.on(M.SocketActivity,this._onSocketActivity)}_detachListeners(){b.debug("Detaching socket event listeners"),this.off(M.SocketOpen,this._onSocketOpen),this.off(M.SocketClose,this.onNetworkClose),this.off(M.SocketError,this.onNetworkClose),this.off(M.SocketMessage,this._onSocketMessage),this.off(M.SocketActivity,this._onSocketActivity)}_emptyExecuteQueues(){this._executeQueue.forEach(({resolve:e,msg:i})=>{typeof i=="string"?this.executeRaw(i):e(this.execute(i))})}_closeConnection(){var e,i;this._idle=!0,clearTimeout(this._keepAliveTimeout),this.stopSignalingHealthMonitor(),b.debug("_closeConnection called",{connected:(e=this.connection)===null||e===void 0?void 0:e.connected,socketGeneration:(i=this.connection)===null||i===void 0?void 0:i.socketGeneration,voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0}),this.connection&&this.connection.close()}_resetKeepAlive(){this._pong===!1&&(b.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Rr(pn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){b.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([j.Early,j.Active,j.Held]);return Object.values(e).some(n=>n&&n._state!=null&&i.has(n._state))}_terminateActiveCallsLocally(){const e=this.calls;if(!e)return;const i=Object.keys(e);if(i.length!==0){b.debug(`Reconnection exhausted — locally terminating ${i.length} active call(s) (no BYE): ${i.join(", ")}`);for(const n of i){const s=e[n];s==null||s.hangup({},!1)}}}startSignalingHealthMonitor(){this._signalingHealthMonitor.start()}stopSignalingHealthMonitor(){this._signalingHealthMonitor.stop()}triggerIceRestart(e){const i=this.calls,n=i==null?void 0:i[e];if(!n)return b.warn(`Signaling health: cannot trigger ICE restart — call ${e} not found`),{started:!1,reason:"call not found"};const s=n.peer;if(!(s!=null&&s.restartIce))return b.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||b.debug(`Signaling health: ICE restart skipped for call ${e}: ${o.reason}`),o}onSignalingRequestTimeout(e,i,n=""){this._signalingHealthMonitor.onRequestTimeout(e,i,n)}reportPeerFailure(e,i){this._signalingHealthMonitor.onPeerFailure(e,i)}reportNoRtp(e,i){this._signalingHealthMonitor.onNoRtp(e,i)}reportIceRestartFailed(e){this._signalingHealthMonitor.onIceRestartFailed(e)}static on(e,i){Ut(e,i)}static off(e){yt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ei.TOKEN_EXPIRY_WARNING_SECONDS=120,ei.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const fs=t=>navigator.mediaDevices.getUserMedia(t),mn=t=>t&&t instanceof MediaStream,ps=(t,e)=>{const i=hn(t);i!==null&&(i.getAttribute("autoplay")||i.setAttribute("autoplay","autoplay"),i.getAttribute("playsinline")||i.setAttribute("playsinline","playsinline"),i.srcObject=e)},fh=(t,e)=>{const i=hn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},ph=(t,e)=>V(void 0,void 0,void 0,function*(){const i=hn(t);if(i===null)return b.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return b.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),W0=t=>{t&&t.readyState==="live"&&t.stop()},vn=t=>{mn(t)&&t.getTracks().forEach(W0),t=null},gs=t=>V(void 0,void 0,void 0,function*(){b.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield fs(t)}catch(n){if(b.error("getUserMedia error: ",n),(s=>s.name==="NotReadableError"||s.name==="NotFoundError"||s.name==="OverconstrainedError")(n)){const s=(o=>{const{audio:r,video:a}=o;let l=!1,c=r,u=a;if(typeof r=="object"&&r!==null&&"deviceId"in r){l=!0;const d=Object.assign({},r);delete d.deviceId,c=Object.keys(d).length===0||d}if(typeof a=="object"&&a!==null&&"deviceId"in a){l=!0;const d=Object.assign({},a);delete d.deviceId,u=Object.keys(d).length===0||d}return l?{audio:c,video:u}:null})(t);if(s){b.warn("Device not found or not readable, falling back to default device");try{return yield fs(s)}catch(o){throw b.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),_n=(t=null,e=!1)=>V(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===_t.AudioIn||s===_t.AudioOut,video:!s||s===_t.Video}))(t)).catch(s=>(b.error(s),null));if(n){if(vn(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),gh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],ms=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield _n(i,!0);for(let s=0;s<n.length;s++){const{deviceId:o,label:r}=n[s];if(t===o||e===r)return o}return null}),H0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},xr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,mh=t=>{var e,i,n,s,o,r;return t?((i=(e=t.getTracks)===null||e===void 0?void 0:e.call(t))!==null&&i!==void 0?i:[...(s=(n=t.getAudioTracks)===null||n===void 0?void 0:n.call(t))!==null&&s!==void 0?s:[],...(r=(o=t.getVideoTracks)===null||o===void 0?void 0:o.call(t))!==null&&r!==void 0?r:[]]).map(a=>xr(a)):[]},Lr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Dr(t);return i.includes(e)||n.includes(e)},Dr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Di=(t,e=null,i=null)=>{if(!mn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Or=t=>{Di(t,"audio",!0)},vs=t=>{Di(t,"audio",!1)};function G0(){try{const{browserInfo:t,name:e,version:i,supportAudio:n,supportVideo:s}=function(){if(!window||!window.navigator||!window.navigator.userAgent)throw new Error("You should use @telnyx/webrtc in a web browser such as Chrome|Firefox|Safari");if(navigator.userAgent.match(/chrom(e|ium)/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/chrom(e|ium)\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/firefox/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/firefox\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!1}}if(navigator.userAgent.match(/safari/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)&&!navigator.userAgent.match(/edg/gim)){const u=navigator.userAgent.match(/safari/gim)[0],d=navigator.userAgent.match(/version\/[0-9]+\./gim)[0].split("/"),h=parseInt(d[1],10);return{browserInfo:navigator.userAgent,name:u,version:h,supportAudio:!0,supportVideo:!0}}if(navigator.userAgent.match(/edg/gim)&&!navigator.userAgent.match(/OPR\/[0-9]{2}/gi)){const u=navigator.userAgent.match(/edg\/[0-9]+\./gim)[0].split("/"),d=u[0],h=parseInt(u[1],10);return{browserInfo:navigator.userAgent,name:d,version:h,supportAudio:!0,supportVideo:!0}}throw new Error("This browser does not support @telnyx/webrtc. To see browser support list: `TelnyxRTC.webRTCSupportedBrowserList()`")}(),o=window.RTCPeerConnection,r=window.RTCSessionDescription,a=window.RTCIceCandidate,l=window.navigator&&window.navigator.mediaDevices,c=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.msGetUserMedia||navigator.mozGetUserMedia;return{browserInfo:t,browserName:e,browserVersion:i,supportWebRTC:!!(o&&r&&a&&l&&c),supportWebRTCAudio:n,supportWebRTCVideo:s,supportRTCPeerConnection:!!o,supportSessionDescription:!!r,supportIceCandidate:!!a,supportMediaDevices:!!l,supportGetUserMedia:!!gs}}catch(t){return t.message}}var ke;function vh(t,e){const i=document.getElementById(e);if(i)return i;if(t&&e){const n=document.createElement("audio");return n.id=e,n.loop=!0,n.src=t,n.preload="auto",n.load(),document.body.appendChild(n),n}return null}function _h(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{b.error("playAudio",e),t._playFulfilled=!0}))}function yh(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"})(ke||(ke={}));const bh=t=>{const e=[],i=[];return t&&t.length!==0?(t.forEach(n=>{const s=n.mimeType.toLocaleLowerCase();s.startsWith("audio/")?e.push(n):s.startsWith("video/")&&i.push(n)}),{audioCodecs:e,videoCodecs:i}):{audioCodecs:e,videoCodecs:i}};class q0 extends xi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:ki(),type:"message",role:"user",content:[{type:"input_text",text:e},...i==null?void 0:i.map(n=>({type:"image_url",image_url:{url:n}}))]}}})}}class z0 extends xi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ae{constructor(e,i){var n;this.peerConnection=null,this.intervalId=null,this.statsBuffer=[],this.intervalStartTime=null,this.callEndTime=null,this.logCollector=null,this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]},this.previousStats={},this.previousCandidatePairSnapshot=null,this.MAX_BUFFER_SIZE=360,this.onFlushNeeded=null,this.onWarning=null,this._breachCounters={},this._activeWarnings=new Set,this._lastWarningEmitted={},this._prevPacketsReceived=null,this._prevPacketsLost=null,this._previousStatsEntryForWarnings=null,this._lastLocalAudioTrackSnapshotJson=null,this._hasConfirmedLocalAudio=!1,this._confirmedLocalAudioSilenceMs=0,this._segmentIndex=0,this._flushing=!1,this._stopped=!1,this.options=e,this.logCollectorOptions=i||{enabled:!1,level:"debug",maxEntries:1e3},this.callStartTime=new Date,this._lastIntermediateFlushTime=this.callStartTime,this.logCollectorOptions.enabled&&(this.logCollector=function(s){return new b0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,zu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,b.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ae.INITIAL_COLLECTION_INTERVAL_MS,logCollectorActive:(n=(i=this.logCollector)===null||i===void 0?void 0:i.isActive())!==null&&n!==void 0&&n}),this._scheduleNextCollection())}stop(){var e,i;return V(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),b.info("CallReportCollector: Stopped stats collection",{totalIntervals:this.statsBuffer.length,totalLogs:n,duration:this.callEndTime.getTime()-this.callStartTime.getTime()})})}flush(e,i){var n,s,o,r;const a=this.statsBuffer.length,l=(s=(n=this.logCollector)===null||n===void 0?void 0:n.getLogCount())!==null&&s!==void 0?s:0,c=(i==null?void 0:i.type)==="socket-close"||(i==null?void 0:i.type)==="socket-error",u=a>0||l>0||c;if(this._flushing||!u)return b.debug("CallReportCollector: Skipping intermediate flush",{reason:this._flushing?"already-flushing":"no-stats-or-logs",flushReason:i,statsIntervals:a,logEntries:l}),null;this._flushing=!0;try{const d=this._segmentIndex++,h=this.statsBuffer;this.statsBuffer=[];const p=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],_=new Date;this._lastIntermediateFlushTime=_;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(_.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:_.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return b.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:p.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return V(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 b.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void b.info("CallReportCollector: Skipping report — no stats or logs collected");const c=this._segmentIndex>0,u=this._segmentIndex,d=Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:this.callEndTime&&this.callStartTime?(this.callEndTime.getTime()-this.callStartTime.getTime())/1e3:void 0,startTimestamp:this.callStartTime.toISOString(),endTimestamp:(r=this.callEndTime)===null||r===void 0?void 0:r.toISOString()}),stats:this.statsBuffer},a&&a.length>0?{logs:a}:{}),c?{segment:u}:{});yield this._sendPayload(d,i,n,s,!0)})}sendPayload(e,i,n,s,o=!1){return V(this,void 0,void 0,function*(){yield this._sendPayload(e,i,n,s,!1,o)})}_sendPayload(e,i,n,s,o=!0,r=!1){var a,l;return V(this,void 0,void 0,function*(){const c=new URL(n),u=`${c.protocol.replace(/^ws/,"http")}//${c.host}/call_report`,d=o?"final report":`intermediate segment ${e.segment}`;b.info(`CallReportCollector: Posting ${d}`,{endpoint:u,intervals:e.stats.length,logEntries:(l=(a=e.logs)===null||a===void 0?void 0:a.length)!==null&&l!==void 0?l:0,callId:e.summary.callId,segment:e.segment});const h={"Content-Type":"application/json","x-call-report-id":i,"x-call-id":e.summary.callId};s&&(h["x-voice-sdk-id"]=s);const p=JSON.stringify(e),_=(o||r)&&p.length<=ae.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let w=0;w<=ae.RETRY_DELAYS_MS.length;w++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void b.info(`CallReportCollector: Successfully posted ${d}`,{attempt:w+1,status:C.status});{const I=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),b.error(`CallReportCollector: Failed to post ${d}`,{attempt:w+1,status:C.status,error:I})}}catch(C){v=C,b.warn(`CallReportCollector: Network error posting ${d}`,{attempt:w+1,error:C})}const y=ae.RETRY_DELAYS_MS[w];if(y===void 0)break;b.info(`CallReportCollector: Retrying ${d} in ${y}ms`,{attempt:w+2}),yield new Promise(C=>setTimeout(C,y))}throw b.error(`CallReportCollector: Exhausted retries posting ${d}`,{error:v}),v instanceof Error?v:new Error("Call report POST failed after retries")})}getStatsBuffer(){return this.statsBuffer}shouldForceRelayCandidateForRecovery(){var e,i,n,s,o,r,a,l,c,u,d,h,p,_,v,w;if(this.statsBuffer.length<2)return!1;const y=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],I=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((I==null?void 0:I.networkType)==="vpn"&&(I==null?void 0:I.candidateType)!=="relay"))return!1;const A=((i=y.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=y.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",P=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=y.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),k=P>0&&T===0,g=this._positiveDelta((u=(c=y.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),m=this._positiveDelta((_=(p=y.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(w=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||w===void 0?void 0:w.bytesReceived);return A||R||k||g>0&&m===0}getLogs(){var e,i;return(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogs())!==null&&i!==void 0?i:[]}_positiveDelta(e,i){return e===void 0||i===void 0?0:Math.max(0,e-i)}cleanup(){this._lastLocalAudioTrackSnapshotJson=null,this.logCollector&&(this.logCollector.clear(),this.logCollector=null)}_scheduleNextCollection(){if(this._stopped||!this.peerConnection||!this.intervalStartTime||this.intervalId)return;const e=this._collectionIntervalFor();this.intervalId=setTimeout(()=>{this.intervalId=null,this._collectStats().finally(()=>{!this._stopped&&this.peerConnection&&this._scheduleNextCollection()})},e)}_collectionIntervalFor(){const e=this._positiveInterval(this.options.interval,5e3);return Math.min(ae.INITIAL_COLLECTION_INTERVAL_MS,e)}_positiveInterval(e,i){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:i}_collectStats(e=!1){var i,n;return V(this,void 0,void 0,function*(){if(this.peerConnection&&this.intervalStartTime)try{const s=yield this.peerConnection.getStats(),o=new Date;let r=null,a=null,l=null,c=null,u=null,d=null;const h=[];let p=null;s.forEach(g=>{switch(g.type){case"outbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(r=g);break;case"inbound-rtp":g.kind==="audio"&&g.mediaType==="audio"&&(a=g);break;case"media-playout":g.kind==="audio"&&(l=g);break;case"remote-inbound-rtp":g.kind==="audio"&&(c=g);break;case"remote-outbound-rtp":g.kind==="audio"&&(u=g);break;case"candidate-pair":(g.nominated||g.state==="succeeded")&&h.push(g);break;case"transport":p=g}});const _=p==null?void 0:p.selectedCandidatePairId,v=_?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,_):void 0,w=this._getCodec(s,r==null?void 0:r.codecId),y=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:_?h.find(g=>g.id===_)||h[h.length-1]||null:h[h.length-1]||null,r){const g=this._getOutboundAudioLevel(s,r);if(g!==null&&this.intervalAudioLevels.outbound.push(g),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const g=this._getInboundAudioLevel(s,a);if(g!==null&&this.intervalAudioLevels.inbound.push(g),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const m=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*m*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,I,A,R,P;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),I=this._resolveCandidate(s,d.remoteCandidateId)),d&&(A=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),I?{remote:I}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(b.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(n0)),this.previousCandidatePairSnapshot=A),r&&(R=this._getLocalAudioTrackSnapshot(),P=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,P),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),k=this._collectionIntervalFor();if(e||T>=k){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,I,p,R,P,l,c,u,w,y);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),b.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){b.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ae.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS}_requestIntermediateFlushIfNeeded(e){var i,n;const s=this.statsBuffer.length,o=(n=(i=this.logCollector)===null||i===void 0?void 0:i.getLogCount())!==null&&n!==void 0?n:0;if(!this.onFlushNeeded||this._flushing)return;if(s===0&&o===0)return void b.debug("CallReportCollector: Skipping intermediate flush request — no stats or logs buffered");const r=this._getIntermediateReportInterval(),a=e.getTime()-this._lastIntermediateFlushTime.getTime();let l=null;if(s>=ae.STATS_FLUSH_THRESHOLD||o>=ae.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){b.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){b.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,w,y;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,I=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,P=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,k=P-this._prevPacketsLost,g=T+k;g>0&&(A=k/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=P}if(this._trackBreach(qy,C!==void 0&&C>ae.THRESHOLD_RTT_MS),this._trackBreach(zy,I!==void 0&&I>ae.THRESHOLD_JITTER_MS),this._trackBreach(Ky,A!==void 0&&A>ae.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._trackLowInboundAudio(e),C!==void 0&&I!==void 0&&A!==void 0){const R=93.2-.11*I-2.5*A-.01*(1e3*C),P=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Vu,P<ae.THRESHOLD_MOS)}else this._trackBreach(Vu,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const R=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,P=e.audio.inbound.bytesReceived;this._trackBreach(Uu,R!==void 0&&P-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(y=(w=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||w===void 0?void 0:w.outbound)===null||y===void 0?void 0:y.bytesSent,P=e.audio.outbound.bytesSent;this._trackBreach($u,R!==void 0&&P-R==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=ae.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(os,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ae.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(os)):this._trackBreach(os,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(os,!1)}_getStatsIntervalDurationMs(e){const i=new Date(e.intervalStartUtc).getTime(),n=new Date(e.intervalEndUtc).getTime()-i;return Number.isFinite(n)&&n>0?n:this.options.interval}_trackLowInboundAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.inbound,s=n==null?void 0:n.audioLevelAvg;if(s===void 0)return void this._trackBreach(Bu,!1);const o=s<=ae.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(Bu,o)}_trackBreach(e,i){var n,s;if(i){if(this._breachCounters[e]=((n=this._breachCounters[e])!==null&&n!==void 0?n:0)+1,this._breachCounters[e]>=ae.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ae.WARNING_THROTTLE_MS&&(this._lastWarningEmitted[e]=o,this._emitWarning(e))}}else this._breachCounters[e]=0,this._activeWarnings.delete(e),delete this._lastWarningEmitted[e]}_emitWarningOncePerEpisode(e){this._activeWarnings.has(e)||(this._activeWarnings.add(e),this._lastWarningEmitted[e]=Date.now(),this._emitWarning(e))}_emitWarning(e){var i;try{const n=Be(e);b.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){b.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,_,v){const w={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(w.audio.outbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsSent:n.packetsSent,bytesSent:n.bytesSent,audioLevelAvg:this._average(this.intervalAudioLevels.outbound),bitrateAvg:this._average(this.intervalBitrates.outbound)},c?{localTrack:c}:{}),u?{mediaSource:u}:{}),n.retransmittedPacketsSent!==void 0?{retransmittedPacketsSent:n.retransmittedPacketsSent}:{}),n.retransmittedBytesSent!==void 0?{retransmittedBytesSent:n.retransmittedBytesSent}:{}),n.headerBytesSent!==void 0?{headerBytesSent:n.headerBytesSent}:{}),n.nackCount!==void 0?{nackCount:n.nackCount}:{}),n.targetBitrate!==void 0?{targetBitrate:n.targetBitrate}:{}),n.totalPacketSendDelay!==void 0?{totalPacketSendDelay:n.totalPacketSendDelay}:{}),n.active!==void 0?{active:n.active}:{}),_?{codec:this._buildCodecSnapshot(_,n.codecId)}:{})),s&&(w.audio.inbound=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({packetsReceived:s.packetsReceived,bytesReceived:s.bytesReceived,packetsLost:s.packetsLost,packetsDiscarded:s.packetsDiscarded,jitterBufferDelay:s.jitterBufferDelay,jitterBufferEmittedCount:s.jitterBufferEmittedCount,totalSamplesReceived:s.totalSamplesReceived,concealedSamples:s.concealedSamples,concealmentEvents:s.concealmentEvents,audioLevelAvg:this._average(this.intervalAudioLevels.inbound),jitterAvg:this._average(this.intervalJitters),bitrateAvg:this._average(this.intervalBitrates.inbound)},s.nackCount!==void 0?{nackCount:s.nackCount}:{}),s.headerBytesReceived!==void 0?{headerBytesReceived:s.headerBytesReceived}:{}),s.fecPacketsReceived!==void 0?{fecPacketsReceived:s.fecPacketsReceived}:{}),s.fecPacketsDiscarded!==void 0?{fecPacketsDiscarded:s.fecPacketsDiscarded}:{}),s.jitterBufferTargetDelay!==void 0?{jitterBufferTargetDelay:s.jitterBufferTargetDelay}:{}),s.jitterBufferMinimumDelay!==void 0?{jitterBufferMinimumDelay:s.jitterBufferMinimumDelay}:{}),s.totalSamplesDecoded!==void 0?{totalSamplesDecoded:s.totalSamplesDecoded}:{}),s.samplesDecodedWithSilence!==void 0?{samplesDecodedWithSilence:s.samplesDecodedWithSilence}:{}),s.samplesDecodedWithConcealment!==void 0?{samplesDecodedWithConcealment:s.samplesDecodedWithConcealment}:{}),s.totalAudioEnergy!==void 0?{totalAudioEnergy:s.totalAudioEnergy}:{}),s.totalSamplesDuration!==void 0?{totalSamplesDuration:s.totalSamplesDuration}:{}),v?{codec:this._buildCodecSnapshot(v,s.codecId)}:{})),o&&(w.connection=Object.assign(Object.assign({roundTripTimeAvg:this._average(this.intervalRTTs),currentRoundTripTime:o.currentRoundTripTime},o.currentRoundTripTime!==void 0?{roundTripTimeSource:"candidate-pair.currentRoundTripTime"}:{}),{packetsSent:o.packetsSent,packetsReceived:o.packetsReceived,bytesSent:o.bytesSent,bytesReceived:o.bytesReceived}),w.ice=Object.assign(Object.assign({id:o.id,localCandidateId:o.localCandidateId,remoteCandidateId:o.remoteCandidateId,state:o.state,nominated:o.nominated,writable:o.writable,currentRoundTripTime:o.currentRoundTripTime,requestsSent:o.requestsSent,responsesReceived:o.responsesReceived},r?{local:r}:{}),a?{remote:a}:{})),l&&(w.transport=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},l.iceState!==void 0?{iceState:l.iceState}:{}),l.dtlsState!==void 0?{dtlsState:l.dtlsState}:{}),l.srtpCipher!==void 0?{srtpCipher:l.srtpCipher}:{}),l.tlsVersion!==void 0?{tlsVersion:l.tlsVersion}:{}),l.selectedCandidatePairChanges!==void 0?{selectedCandidatePairChanges:l.selectedCandidatePairChanges}:{}),l.selectedCandidatePairId!==void 0?{selectedCandidatePairId:l.selectedCandidatePairId}:{})),d&&(w.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const y={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let I;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(I=h.totalRoundTripTime/h.roundTripTimeMeasurements),y.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:I,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(y.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),w.remoteRtcp=y}return w}_resolveCandidate(e,i){if(!i)return void b.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void b.debug("CallReportCollector: candidate not found in stats report",{candidateId:i});const s={};if(n.id!==void 0&&(s.id=n.id),n.address!==void 0?s.address=n.address:n.ip!==void 0&&(s.address=n.ip),n.port!==void 0&&(s.port=n.port),n.candidateType!==void 0&&(s.candidateType=n.candidateType),n.protocol!==void 0&&(s.protocol=n.protocol),n.networkType!==void 0&&(s.networkType=n.networkType),n.url!==void 0&&(s.url=n.url),n.relayProtocol!==void 0&&(s.relayProtocol=n.relayProtocol),Object.keys(s).length!==0)return s;b.debug("CallReportCollector: candidate report has no usable fields",{candidateId:i})}_getCodec(e,i){if(!i)return;const n=e.get(i);return n&&n.type==="codec"?n:void 0}_buildCodecSnapshot(e,i){const n=this._withoutUndefined(Object.assign({mimeType:e.mimeType,clockRate:e.clockRate,channels:e.channels,payloadType:e.payloadType,sdpFmtpLine:e.sdpFmtpLine},i!==void 0?{codecId:i}:{}));return Object.keys(n).length>0?n:void 0}_getOutboundMediaSource(e,i){let n;return i.mediaSourceId&&(n=e.get(i.mediaSourceId)),n||e.forEach(s=>{n||s.type!=="media-source"||s.kind!=="audio"||(n=s)}),n}_getLocalAudioTrackSnapshot(){var e,i;try{const n=(e=this.peerConnection)===null||e===void 0?void 0:e.getSenders().find(l=>{var c;return((c=l.track)===null||c===void 0?void 0:c.kind)==="audio"}),s=n==null?void 0:n.track;if(!s)return;const o=(i=s.getSettings)===null||i===void 0?void 0:i.call(s),r=this._withoutUndefined({deviceId:o==null?void 0:o.deviceId,groupId:o==null?void 0:o.groupId,channelCount:o==null?void 0:o.channelCount,sampleRate:o==null?void 0:o.sampleRate,sampleSize:o==null?void 0:o.sampleSize,latency:o==null?void 0:o.latency,echoCancellation:o==null?void 0:o.echoCancellation,noiseSuppression:o==null?void 0:o.noiseSuppression,autoGainControl:o==null?void 0:o.autoGainControl}),a=this._withoutUndefined(Object.assign({id:s.id,label:s.label,enabled:s.enabled,muted:s.muted,readyState:s.readyState,contentHint:s.contentHint},Object.keys(r).length>0?{settings:r}:{}));return Object.keys(a).length>0?a:void 0}catch(n){return void b.debug("CallReportCollector: unable to snapshot local audio track",{error:n})}}_getOutboundAudioSourceStats(e,i){const n=this._getOutboundMediaSource(e,i);if(!n)return;const s=this._withoutUndefined({id:n.id,trackIdentifier:n.trackIdentifier,audioLevel:n.audioLevel,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration,echoReturnLoss:n.echoReturnLoss,echoReturnLossEnhancement:n.echoReturnLossEnhancement});return Object.keys(s).length>0?s:void 0}_logLocalAudioTrackSnapshot(e,i){if(!e||Object.keys(e).length===0)return;const n=this._stableStringify(e);n!==this._lastLocalAudioTrackSnapshotJson&&(this._lastLocalAudioTrackSnapshotJson=n,b.debug("CallReportCollector: local audio track snapshot",{localTrack:e,mediaSource:i}))}_withoutUndefined(e){return Object.keys(e).reduce((i,n)=>{const s=e[n];return s!==void 0&&(i[n]=s),i},{})}_stableStringify(e){return JSON.stringify(this._sortObjectKeys(e))}_sortObjectKeys(e){return Array.isArray(e)?e.map(i=>this._sortObjectKeys(i)):e&&typeof e=="object"?Object.keys(e).sort().reduce((i,n)=>(i[n]=this._sortObjectKeys(e[n]),i),{}):e}_getOutboundAudioLevel(e,i){const n=this._getOutboundMediaSource(e,i);if((n==null?void 0:n.audioLevel)!==void 0)return n.audioLevel;if(n){const s=this._computeAudioLevelFromEnergy(n.totalAudioEnergy,n.totalSamplesDuration,"outbound");if(s!==null)return s}return this._getTrackAudioLevel(e,i.trackId)}_getInboundAudioLevel(e,i){if(i.audioLevel!==void 0)return i.audioLevel;const n=this._computeAudioLevelFromEnergy(i.totalAudioEnergy,i.totalSamplesDuration,"inbound");return n!==null?n:this._getTrackAudioLevel(e,i.trackId)}_computeAudioLevelFromEnergy(e,i,n){if(e===void 0||i===void 0)return null;const s=n==="inbound"?"inboundAudioEnergy":"outboundAudioEnergy",o=n==="inbound"?"inboundSamplesDuration":"outboundSamplesDuration",r=this.previousStats[s],a=this.previousStats[o];if(this.previousStats[s]=e,this.previousStats[o]=i,r===void 0||a===void 0)return null;const l=e-r,c=i-a;if(c<=0)return null;const u=Math.sqrt(l/c);return Math.min(1,Math.max(0,u))}_getTrackAudioLevel(e,i){var n;if(!i)return null;const s=e.get(i);return s&&(n=s.audioLevel)!==null&&n!==void 0?n:null}_average(e){if(e.length===0)return;const i=e.reduce((n,s)=>n+s,0);return parseFloat((i/e.length).toFixed(4))}_resetIntervalAccumulators(){this.intervalAudioLevels={outbound:[],inbound:[]},this.intervalJitters=[],this.intervalRTTs=[],this.intervalBitrates={outbound:[],inbound:[]}}}ae.INITIAL_COLLECTION_INTERVAL_MS=1e3,ae.STATS_FLUSH_THRESHOLD=300,ae.LOGS_FLUSH_THRESHOLD=800,ae.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ae.CONSECUTIVE_BREACHES_REQUIRED=3,ae.THRESHOLD_RTT_MS=.4,ae.THRESHOLD_JITTER_MS=30,ae.THRESHOLD_PACKET_LOSS_PCT=1,ae.THRESHOLD_MOS=3.5,ae.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ae.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ae.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,ae.WARNING_THROTTLE_MS=15e3,ae.RETRY_DELAYS_MS=[500,1e3,2e3],ae.KEEPALIVE_BODY_LIMIT_BYTES=61440;class bt{constructor(e,i){this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null},this._processors=[],this._readerCancellers=[],this._flushTimerId=null,this._flushing=!1,this._stopped=!1,this._started=!1,this._startedAt=null,this._endedAt=null,this._overflowWarnedThisWindow=!1,this.onWarning=null,this._host=null,this._callReportId=null,this.options=e,this.callContext=i,this.recordingId=i.recordingId||`${i.callId}-${Date.now().toString(36)}`}start(e,i){if(!this.options.enabled||this._started)return;if(typeof MediaStreamTrackProcessor!="function")return b.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Yy),void(this._started=!0);const n=this.options.tracks||["local","remote"];let s=0;if(n.includes("local")&&e&&(this._attach(e,"local"),s++),n.includes("remote")&&i&&(this._attach(i,"remote"),s++),s===0)return b.info("CallRecorder: no audio tracks available to record — recording idle for this call",{callId:this.callContext.callId}),void(this._started=!0);this._startedAt=new Date,this._started=!0,this._scheduleFlush(),b.info("CallRecorder: started",{callId:this.callContext.callId,tracksAttached:s,flushIntervalMs:this._flushIntervalMs(),maxBufferBytes:this._maxBufferBytes()})}stop(){this._stopped||(this._stopped=!0,this._clearFlushTimer(),this._cancelReaders(),this._endedAt=new Date,b.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return V(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void b.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void b.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"];for(const n of i){const s=this._drain(n);if(s.length===0)continue;const o=this._buildEnvelope(s,n,"final",this._startedAt,this._endedAt||new Date);yield this._postRecording(e,o,!0)}})}cleanup(){this._clearFlushTimer(),this._cancelReaders(),this._buffers={local:[],remote:[]},this._bufferBytes={local:0,remote:0},this._trackStates={local:null,remote:null}}_attach(e,i){this._trackStates[i]={ssrc:Math.floor(4294967295*Math.random())>>>0,seq:0,ts:0};try{const n=new MediaStreamTrackProcessor({track:e});this._processors.push(n);const s=n.readable.getReader();let o=!1;const r=()=>{o=!0,s.cancel().catch(()=>{}).finally(()=>{})};this._readerCancellers.push(r),V(this,void 0,void 0,function*(){try{for(;!o&&!this._stopped;){const{done:a,value:l}=yield s.read();if(a)break;this._onFrame(i,l)}}catch(a){this._stopped||b.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){b.warn("CallRecorder: failed to attach track",{track:i,error:n}),this._trackStates[i]=null}}_onFrame(e,i){var n;const s=this._trackStates[e];if(!s||this._stopped)return;const o=i.numberOfFrames,r=new Float32Array(o);i.copyTo(r,{planeIndex:0}),(n=i.close)===null||n===void 0||n.call(i);const a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);s.seq=s.seq+1&65535;const l=s.ts;s.ts+=o;const c={rtpSeq:s.seq,rtpTs:l,rtpSsrc:s.ssrc,capturedAt:new Date().toISOString(),payloadBytes:a};this._pushPacket(c,e)}_pushPacket(e,i){const n=e.payloadBytes.length+bt.PACKET_OVERHEAD_BYTES,s=this._maxBufferBytes(),o=this._buffers[i];if(o.push(e),this._bufferBytes[i]+=n,this._bufferBytes[i]>s){for(;o.length>1&&this._bufferBytes[i]>s;){const r=o.shift();r&&(this._bufferBytes[i]-=r.payloadBytes.length+bt.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow||(this._overflowWarnedThisWindow=!0,b.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Xy))}}_flushIntervalMs(){var e;return(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:th}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:ih}_sampleRate(){var e;return(e=this.options.sampleRate)!==null&&e!==void 0?e:48e3}_scheduleFlush(){if(this._stopped||this._flushTimerId)return;const e=this._flushIntervalMs();e<=0||(this._flushTimerId=setInterval(()=>{this._periodicFlush().catch(i=>{b.error("CallRecorder: periodic flush error",{error:i})})},e))}_clearFlushTimer(){this._flushTimerId&&(clearInterval(this._flushTimerId),this._flushTimerId=null)}_cancelReaders(){for(const e of this._readerCancellers)try{e()}catch{}this._readerCancellers=[],this._processors=[]}_periodicFlush(){return V(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void b.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;for(const o of i){const r=this._drain(o);if(r.length===0)continue;const a=this._buildEnvelope(r,o,"intermediate",n,s);yield this._postRecording(e,a,!1)}this._overflowWarnedThisWindow=!1}finally{this._flushing=!1}}})}_drain(e){const i=this._buffers[e];return this._buffers[e]=[],this._bufferBytes[e]=0,i}_resolveEndpointFromContext(){const e=this.callContext.host;return e?this._resolveEndpoint(e):this._host?this._resolveEndpoint(this._host):null}_setHost(e){this._host=e}_setCallReportId(e){e&&(this._callReportId=e)}_resolveCallReportId(){return this._callReportId||this.callContext.callReportId}_resolveEndpoint(e){const i=this.options.endpoint||"/call_recording";try{const n=new URL(e);return`${`${n.protocol.replace(/^ws/,"http")}//${n.host}`}${i}`}catch{return/^https?:\/\//.test(e)?`${e}${i}`:`https://${e}${i}`}}_buildEnvelope(e,i,n,s,o){let r=0;const a=e.map(l=>(r+=l.payloadBytes.length,{rtp_seq:l.rtpSeq,rtp_ts:l.rtpTs,rtp_ssrc:l.rtpSsrc,captured_at:l.capturedAt,payload_b64:this._toBase64(l.payloadBytes)}));return Object.assign(Object.assign({call_report_id:this._resolveCallReportId(),call_id:this.callContext.callId},this.callContext.voiceSdkId?{voice_sdk_id:this.callContext.voiceSdkId}:{}),{recording_id:this.recordingId,segment:n,track:i,codec:"pcm-f32-le",sample_rate:this._sampleRate(),channels:1,started_at:s.toISOString(),ended_at:o.toISOString(),packet_count:e.length,byte_count:r,packets:a})}_postRecording(e,i,n){return V(this,void 0,void 0,function*(){const s={"Content-Type":"application/json","x-call-report-id":i.call_report_id,"x-call-id":i.call_id};i.voice_sdk_id&&(s["x-voice-sdk-id"]=i.voice_sdk_id);const o=JSON.stringify(i),r=n&&o.length<=bt.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=bt.RETRY_DELAYS_MS.length;c++){try{const d=yield a(e,Object.assign({method:"POST",headers:s,body:o},r?{keepalive:!0}:{}));if(d.ok)return void b.info("CallRecorder: posted",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,packets:i.packet_count});{const h=yield d.text().catch(()=>"");l=new Error(`Call recording POST failed with status ${d.status}`),b.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,b.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=bt.RETRY_DELAYS_MS[c];if(u===void 0)break;b.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw b.error("CallRecorder: exhausted retries",{track:i.track,segment:i.segment,error:l}),l instanceof Error?l:new Error("Call recording POST failed after retries")})}_emitWarning(e){var i;try{const n=Be(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){b.warn("CallRecorder: failed to emit warning",{code:e,error:n})}}_toBase64(e){let i="";for(let n=0;n<e.length;n+=32768){const s=e.subarray(n,n+32768);i+=String.fromCharCode.apply(null,Array.from(s))}return btoa(i)}}bt.RETRY_DELAYS_MS=[500,1e3,2e3],bt.KEEPALIVE_BODY_LIMIT_BYTES=61440,bt.PACKET_OVERHEAD_BYTES=160;class K0{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return V(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,b.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){b.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return V(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){b.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return V(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&b.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){b.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var _s,wh=Gu(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(g){return g._maxListeners===void 0?s.defaultMaxListeners:g._maxListeners}function r(g,m,f,S){var E,x,L;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((x=g._events)?(x.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),x=g._events),L=x[m]):(x=g._events=new n,g._eventsCount=0),L){if(typeof L=="function"?L=x[m]=S?[f,L]:[L,f]:S?L.unshift(f):L.push(f),!L.warned&&(E=o(g))&&0<E&&L.length>E){L.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+L.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=L.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(N)}}else L=x[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),E||(E=!0,f.apply(g,arguments))}var E=!1;return S.listener=f,S}function l(g){var m=this._events;if(m){var f=m[g];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(g,m){for(var f=Array(m);m--;)f[m]=g[m];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(g){if(typeof g!="number"||0>g||isNaN(g))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=g,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(g){var m,f,S,E,x,L,N,O=g==="error";if(L=this._events)O=O&&L.error==null;else if(!O)return!1;if(N=this.domain,O){if(m=arguments[1],!N){if(m instanceof Error)throw m;var F=new Error('Uncaught, unspecified "error" event. ('+m+")");throw F.context=m,F}return m||(m=new Error('Uncaught, unspecified "error" event')),m.domainEmitter=this,m.domain=N,m.domainThrown=!1,N.emit("error",m),!1}if(!(f=L[g]))return!1;var W=typeof f=="function";switch(S=arguments.length){case 1:(function($,ue,J){if(ue)$.call(J);else for(var H=$.length,le=c($,H),X=0;X<H;++X)le[X].call(J)})(f,W,this);break;case 2:(function($,ue,J,H){if(ue)$.call(J,H);else for(var le=$.length,X=c($,le),ee=0;ee<le;++ee)X[ee].call(J,H)})(f,W,this,arguments[1]);break;case 3:(function($,ue,J,H,le){if(ue)$.call(J,H,le);else for(var X=$.length,ee=c($,X),te=0;te<X;++te)ee[te].call(J,H,le)})(f,W,this,arguments[1],arguments[2]);break;case 4:(function($,ue,J,H,le,X){if(ue)$.call(J,H,le,X);else for(var ee=$.length,te=c($,ee),ie=0;ie<ee;++ie)te[ie].call(J,H,le,X)})(f,W,this,arguments[1],arguments[2],arguments[3]);break;default:for(E=Array(S-1),x=1;x<S;x++)E[x-1]=arguments[x];(function($,ue,J,H){if(ue)$.apply(J,H);else for(var le=$.length,X=c($,le),ee=0;ee<le;++ee)X[ee].apply(J,H)})(f,W,this,E)}return!0},s.prototype.addListener=function(g,m){return r(this,g,m,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(g,m){return r(this,g,m,!0)},s.prototype.once=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.on(g,a(this,g,m)),this},s.prototype.prependOnceListener=function(g,m){if(typeof m!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(g,a(this,g,m)),this},s.prototype.removeListener=function(g,m){var f,S,E,x,L;if(typeof m!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[g]))return this;if(f===m||f.listener&&f.listener===m)--this._eventsCount==0?this._events=new n:(delete S[g],S.removeListener&&this.emit("removeListener",g,f.listener||m));else if(typeof f!="function"){for(E=-1,x=f.length;0<x--;)if(f[x]===m||f[x].listener&&f[x].listener===m){L=f[x].listener,E=x;break}if(0>E)return this;if(f.length===1){if(f[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[g]}else(function(N,O){for(var F=O,W=F+1,$=N.length;W<$;F+=1,W+=1)N[F]=N[W];N.pop()})(f,E);S.removeListener&&this.emit("removeListener",g,L||m)}return this},s.prototype.removeAllListeners=function(g){var m,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[g]&&(--this._eventsCount==0?this._events=new n:delete f[g]),this;if(arguments.length===0){for(var S,E=Object.keys(f),x=0;x<E.length;++x)(S=E[x])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(m=f[g])=="function")this.removeListener(g,m);else if(m)do this.removeListener(g,m[m.length-1]);while(m[0]);return this},s.prototype.listeners=function(g){var m,f,S=this._events;return S?f=(m=S[g])?typeof m=="function"?[m.listener||m]:function(E){for(var x=Array(E.length),L=0;L<x.length;++L)x[L]=E[L].listener||E[L];return x}(m):[]:f=[],f},s.listenerCount=function(g,m){return typeof g.listenerCount=="function"?g.listenerCount(m):l.call(g,m)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var p=/^(?:[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(g){var m=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(_[g[m+0]]+_[g[m+1]]+_[g[m+2]]+_[g[m+3]]+"-"+_[g[m+4]]+_[g[m+5]]+"-"+_[g[m+6]]+_[g[m+7]]+"-"+_[g[m+8]]+_[g[m+9]]+"-"+_[g[m+10]]+_[g[m+11]]+_[g[m+12]]+_[g[m+13]]+_[g[m+14]]+_[g[m+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function y(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],w(S)}function C(g,m){if(!g||!m)return{};const f={...g};if(f.localCandidateId){const S=m.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=m.get(f.remoteCandidateId);f.remote={...S}}return f}function I(g,m,f){return 8*function(S,E,x){const L=S[x],N=E?E[x]:null;return L===null||N===null?null:(L-N)/(S.timestamp-E.timestamp)*1e3}(g,m,f)}function A(g){if(!g.entries)return g;const m={};return g.forEach(function(f,S){m[S]=f}),m}function R(g,m,f={}){if(!g)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};f.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const E of g.values())switch(E.type){case"outbound-rtp":{const x=E.mediaType||E.kind,L={};let N={};if(!["audio","video"].includes(x))continue;if(E.codecId){const O=g.get(E.codecId);O&&(L.clockRate=O.clockRate,L.mimeType=O.mimeType,L.payloadType=O.payloadType)}N=g.get(E.mediaSourceId)||g.get(E.trackId)||{},S[x].outbound.push({...E,...L,track:{...N}});break}case"inbound-rtp":{let x=E.mediaType||E.kind,L={};const N={};if(!["audio","video"].includes(x))if(E.id.includes("Video"))x="video";else{if(!E.id.includes("Audio"))continue;x="audio"}if(E.codecId){const O=g.get(E.codecId);O&&(N.clockRate=O.clockRate,N.mimeType=O.mimeType,N.payloadType=O.payloadType)}if(!S.connection.id&&E.transportId){const O=g.get(E.transportId);if(O&&O.selectedCandidatePairId){const F=g.get(O.selectedCandidatePairId);S.connection=C(F,g)}}L=g.get(E.mediaSourceId)||g.get(E.trackId)||{},S[x].inbound.push({...E,...N,track:{...L}});break}case"peer-connection":S.connection.dataChannelsClosed=E.dataChannelsClosed,S.connection.dataChannelsOpened=E.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let x=E.mediaType||E.kind;const L={};if(!["audio","video"].includes(x))if(E.id.includes("Video"))x="video";else{if(!E.id.includes("Audio"))continue;x="audio"}if(E.codecId){const N=g.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}if(!S.connection.id&&E.transportId){const N=g.get(E.transportId);if(N&&N.selectedCandidatePairId){const O=g.get(N.selectedCandidatePairId);S.connection=C(O,g)}}S.remote[x].inbound.push({...E,...L});break}case"remote-outbound-rtp":{if(!f.remote)break;const x=E.mediaType||E.kind,L={};if(!["audio","video"].includes(x))continue;if(E.codecId){const N=g.get(E.codecId);N&&(L.clockRate=N.clockRate,L.mimeType=N.mimeType,L.payloadType=N.payloadType)}S.remote[x].outbound.push({...E,...L});break}}if(!S.connection.id)for(const E of g.values())E.type==="candidate-pair"&&E.nominated&&E.state==="succeeded"&&(S.connection=C(E,g));return S=function(E,x){return x&&(E.audio.inbound.map(L=>{let N=x.audio.inbound.find(O=>O.id===L.id);L.bitrate=I(L,N,"bytesReceived"),L.packetRate=I(L,N,"packetsReceived")}),E.audio.outbound.map(L=>{let N=x.audio.outbound.find(O=>O.id===L.id);L.bitrate=I(L,N,"bytesSent"),L.packetRate=I(L,N,"packetsSent")}),E.video.inbound.map(L=>{let N=x.video.inbound.find(O=>O.id===L.id);L.bitrate=I(L,N,"bytesReceived"),L.packetRate=I(L,N,"packetsReceived")}),E.video.outbound.map(L=>{let N=x.video.outbound.find(O=>O.id===L.id);L.bitrate=I(L,N,"bytesSent"),L.packetRate=I(L,N,"packetsSent")})),E}(S,m),S}let P,T={},k=[];e.WebRTCStats=class extends s{constructor(g){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const m={...g};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=m.getStatsInterval||1e3,this.rawStats=!!m.rawStats,this.statsObject=!!m.statsObject,this.filteredStats=!!m.filteredStats,this.shouldWrapGetUserMedia=!!m.wrapGetUserMedia,typeof m.remote=="boolean"&&(this.remote=m.remote),this.debug=!!m.debug,this.logLevel=m.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(g,m){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:g,pc:m})}async addConnection(g){const{pc:m,peerId:f}=g;let{connectionId:S,remote:E}=g;if(E=typeof E=="boolean"?E:this.remote,!(m&&m instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!f)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[f]){if(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let L in this.peersToMonitor[f]){const N=this.peersToMonitor[f][L];if(N.pc===m)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const x=m.getConfiguration();return x.iceServers&&x.iceServers.forEach(function(L){delete L.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:x}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:E}),{connectionId:S}}getTimeline(g){return this.timeline=this.timeline.sort((m,f)=>m.timestamp.getTime()-f.timestamp.getTime()),g?this.timeline.filter(m=>m.tag===g):this.timeline}get logger(){const g=m=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(m)>-1};return{error(...m){this.debug&&g("error")&&console.error("[webrtc-stats][error] ",...m)},warn(...m){this.debug&&g("warn")&&console.warn("[webrtc-stats][warn] ",...m)},info(...m){this.debug&&g("info")&&console.log("[webrtc-stats][info] ",...m)},debug(...m){this.debug&&g("debug")&&console.debug("[webrtc-stats][debug] ",...m)}}}removeConnection(g){let m,{connectionId:f,pc:S}=g;if(!S&&!f)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(f){if(typeof f!="string")throw new Error("connectionId must be a string.");for(let E in this.peersToMonitor)f in this.peersToMonitor[E]&&(S=this.peersToMonitor[E][f].pc,m=E)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let E in this.peersToMonitor)for(let x in this.peersToMonitor[E])this.peersToMonitor[E][x].pc===S&&(f=x,m=E)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[m][f],Object.values(this.peersToMonitor[m]).length===0&&delete this.peersToMonitor[m],{connectionId:f}}removeAllPeers(){for(let g in this.peersToMonitor)this.removePeer(g)}removePeer(g){if(this.logger.info(`Removing PeerConnection with id ${g}.`),this.peersToMonitor[g]){for(let m in this.peersToMonitor[g]){let f=this.peersToMonitor[g][m].pc;this.removePeerConnectionEventListeners(m,f)}delete this.peersToMonitor[g]}}destroy(){this.removeAllPeers(),k.forEach(g=>{this.removeTrackEventListeners(g)}),k=[],this.shouldWrapGetUserMedia&&P&&(navigator.mediaDevices.getUserMedia=P)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:E}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const x={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:E}};if(this.peersToMonitor[m]){if(f in this.peersToMonitor[m])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[m][f]=x}else this.peersToMonitor[m]={[f]:x};this.addPeerConnectionEventListeners(m,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(g=>{g.forEach(m=>{this.emitEvent(m)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(g=null){this.logger.info(g?`Getting stats from peer ${g}`:"Getting stats from all peers");let m={};if(g){if(!this.peersToMonitor[g])throw new Error(`Cannot get stats. Peer with id ${g} does not exist`);m[g]=this.peersToMonitor[g]}else m=this.peersToMonitor;let f=[];for(const S in m)for(const E in m[S]){const x=m[S][E],L=x.pc;if(L&&!this.checkIfConnectionIsClosed(S,E,L))try{const N=this.getTimestamp(),O=L.getStats(null);if(O){const F=await O,W=this.getTimestamp(),$=A(F),ue={remote:x.options.remote},J=R(F,x.stats.parsed,ue),H={event:"stats",tag:"stats",peerId:S,connectionId:E,timeTaken:W-N,data:J};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=$),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats($)),f.push(H),x.stats.parsed=J}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const g in this.peersToMonitor)for(const m in this.peersToMonitor[g]){const f=this.peersToMonitor[g][m].pc;this.checkIfConnectionIsClosed(g,m,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(g,m,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let E=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:E,peerId:g,connectionId:m,tag:"connection",data:"closed"})}return S}isConnectionClosed(g){return g.connectionState==="closed"||g.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."),P=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),P.apply(navigator.mediaDevices,arguments).then(m=>(g({stream:m}),m),m=>(g({error:m}),Promise.reject(m)))}).bind(navigator.mediaDevices)}filteroutStats(g={}){const m={...g};for(const S in m){var f=m[S];this.statsToMonitor.includes(f.type)||delete m[S]}return m}get peerConnectionListeners(){return{icecandidate:(g,m,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:g,connectionId:m,data:S.candidate})},track:(g,m,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${g}`,S);const E=S.track,x=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=x),this.addTrackEventListeners(E,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:x?this.getStreamDetails(x):null,track:E?this.getMediaTrackDetails(E):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(L){return"stream:"+L.id})}})},signalingstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${g}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:g,connectionId:m,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${g}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceConnectionState})},icegatheringstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${g}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:g,connectionId:m,data:f.iceGatheringState})},icecandidateerror:(g,m,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${g}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:g,connectionId:m,error:{errorCode:S.errorCode}})},connectionstatechange:(g,m,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${g}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:g,connectionId:m,data:f.connectionState})},negotiationneeded:(g,m,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${g}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:g,connectionId:m})},datachannel:(g,m,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${g}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:g,connectionId:m,data:S.channel})}}}addPeerConnectionEventListeners(g,m,f){this.logger.debug(`Adding event listeners for peer ${g} and connection ${m}.`),T[m]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[m][S]=this.peerConnectionListeners[S].bind(this,g,m,f),f.addEventListener(S,T[m][S],!1)})}parseGetUserMedia(g){try{const m={event:"getUserMedia",tag:"getUserMedia",data:{...g}};g.stream&&(m.data.details=this.parseStream(g.stream),g.stream.getTracks().map(f=>{this.addTrackEventListeners(f),k.push(f)})),this.emitEvent(m)}catch{}}parseStream(g){const m={audio:[],video:[]};return g.getTracks().forEach(f=>{m[f.kind].push(this.getMediaTrackDetails(f))}),m}getMediaTrackDetails(g){return{enabled:g.enabled,id:g.id,contentHint:g.contentHint,kind:g.kind,label:g.label,muted:g.muted,readyState:g.readyState,constructorName:g.constructor.name,capabilities:g.getCapabilities?g.getCapabilities():{},constraints:g.getConstraints?g.getConstraints():{},settings:g.getSettings?g.getSettings():{},_track:g}}getStreamDetails(g){return{active:g.active,id:g.id,_stream:g}}getTrackEventObject(g){return{mute:m=>{this.emitEvent({event:"mute",tag:"track",connectionId:g,data:{event:m}})},unmute:m=>{this.emitEvent({event:"unmute",tag:"track",connectionId:g,data:{event:m}})},overconstrained:m=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:g,data:{event:m}})},ended:m=>{this.emitEvent({event:"ended",tag:"track",connectionId:g,data:{event:m}}),this.removeTrackEventListeners(m.target)}}}addTrackEventListeners(g,m){T[g.id]={};const f=this.getTrackEventObject(m);Object.keys(f).forEach(S=>{T[g.id][S]=f[S].bind(this),g.addEventListener(S,T[g.id][S])}),T[g.id].readyState=setInterval(()=>{if(g.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});g.dispatchEvent(S)}},1e3)}removeTrackEventListeners(g){if(g.id in T){const m=this.getTrackEventObject();Object.keys(m).forEach(f=>{g.removeEventListener(f,T[g.id][f])}),clearInterval(T[g.id].readyState),delete T[g.id]}}addToTimeline(g){this.timeline.push(g),this.emit("timeline",g)}emitEvent(g){const m={...g,timestamp:new Date};this.addToTimeline(m),m.tag&&this.emit(m.tag,m)}set getStatsInterval(g){if(!Number.isInteger(g))throw new Error(`getStatsInterval should be an integer, got: ${g}`);this._getStatsInterval=g,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(g,m){g in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{m.removeEventListener(f,T[g][f],!1)}),delete T[g]),m.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),m.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const g=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const m=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return g.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),m.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return g.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(_s=wh)&&_s.__esModule&&Object.prototype.hasOwnProperty.call(_s,"default")&&_s.default;var Y0=wh.WebRTCStats;function X0(t){const{packetsLost:e,packetsReceived:i,jitter:n,rtt:s}=t,o=function(c){const{jitter:u,rtt:d}=c,h=u+d/2;return .024*h+.11*(h-177.3)*(h>177.3?1:0)}({rtt:s,jitter:n}),r=function(c){const{packetsLost:u,packetsReceived:d}=c,h=u/(d+u)*100;return 20*Math.log(1+h)}({packetsLost:e,packetsReceived:i}),a=93.2-o-r+0,l=1+.035*a+7e-6*a*(a-60)*(100-a);return Math.min(Math.max(l,1),5)}function J0(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 Z0 extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class Q0 extends xi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class eb extends xi{constructor(e,i,n){super(),this.buildRequest({type:"debug_report_data",debug_report_id:e,debug_report_version:1,call_id:i,debug_report_data:n})}}function tb(t,e){const i=ki();let n=!1;const s=new Y0({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>V(this,void 0,void 0,function*(){r.event==="stats"&&B(M.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:w,remote:y}=a,{audio:C}=y,I=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=w.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,P=(v=(_=w.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=X0({jitter:1e3*I,rtt:1e3*A,packetsLost:P,packetsReceived:R});return{jitter:I,rtt:A,mos:T,quality:J0(T),inboundAudio:w.inbound[0],outboundAudio:w.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new eb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)b.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new Z0(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){b.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>V(this,void 0,void 0,function*(){const a=s.getTimeline();B(M.StatsReport,a,t.uuid),r==="file"&&function(l,c){const u=new Blob([JSON.stringify(l)],{type:"application/json"}),d=URL.createObjectURL(u),h=document.createElement("a");h.href=d,h.download=`${c}.json`,h.click(),URL.revokeObjectURL(d)}(a,`webrtc-stats-${i}-${Date.now()}`),yield t.execute(new Q0(i,e)),s.removeAllPeers(),s.destroy(),n=!1}),reportConnectionStateChange:r=>{const a={event:"connectionstatechange-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)},reportIceCandidateError:r=>{const a={event:"icecandidateerror-detailed",tag:"connection",timestamp:new Date().toISOString(),data:r};o(a)}}}const Sh=(t,e)=>{const{contentType:i,canvasType:n,callID:s,canvasInfo:o=null,currentLayerIdx:r=-1}=e;o&&n!=="mcu-personal-canvas"&&delete o.memberID;const a={type:it.conferenceUpdate,call:t.calls[s],canvasInfo:ib(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ke.LayerInfo},a);B(M.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ke.LayoutInfo},a);B(M.Notification,l,t.uuid);break}}},ib=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Xu(e)},Ch=["new-call-start","new-peer","get-user-media","peer-creation-end","start-negotiation","create-offer","create-answer","set-local-description","ice-gathering-started","first-candidate","first-non-host-candidate","send-sdp","ice-gathering-completed","ringing","telnyx-rtc-media","first-remote-media-track","set-remote-description","telnyx-rtc-answer","ice-connected","dtls-connected","call-active","answer-called"],nb={"new-call-start":"Call Start","new-peer":"Peer object created","get-user-media":"Media devices acquired","peer-creation-end":"Peer setup complete","start-negotiation":"SDP negotiation started","create-offer":"SDP offer generated","create-answer":"SDP answer generated","set-local-description":"Local description applied","ice-gathering-started":"ICE candidate gathering started","first-candidate":"First ICE candidate found","first-non-host-candidate":"First server-reflexive/relay candidate found","send-sdp":"SDP sent to server","ice-gathering-completed":"All ICE candidates gathered",ringing:"Remote side ringing","telnyx-rtc-media":"Early media received from server","first-remote-media-track":"First remote audio/video track received","set-remote-description":"Remote description applied","telnyx-rtc-answer":"Call answered by remote side","ice-connected":"ICE connection established","dtls-connected":"Secure media channel established (DTLS)","call-active":"Call is active","answer-called":"Answer delay (invite → call.answer)"};function re(t,e){return`telnyx:call:${t}:${e}`}function Th(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Mr(t){for(const e of Ch)try{performance.clearMarks(re(t,e))}catch{b.warn("Clearing performance marks is failed")}}class ti{constructor(e,i,n,s,o){this.type=e,this.options=i,this.onSdpReadyTwice=null,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>V(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void b.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(b.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return V(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,_=p==null?void 0:p.transport;_&&(d.dtlsState=_.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(_=>{_.type==="candidate-pair"&&_.state==="succeeded"&&(d.candidatePairState=_.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===_.localCandidateId&&(d.localCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.local={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType}),v.type==="remote-candidate"&&v.id===_.remoteCandidateId&&(d.remoteCandidateType=v.candidateType,d.selectedCandidatePair=d.selectedCandidatePair||{local:{},remote:{}},d.selectedCandidatePair.remote={address:v.address,port:v.port,protocol:v.protocol,candidateType:v.candidateType})})),_.type==="transport"&&(d.dtlsCipher=_.dtlsCipher,d.srtpCipher=_.srtpCipher,d.tlsVersion=_.tlsVersion,_.dtlsState&&(d.dtlsState=_.dtlsState))})}catch(p){b.error("Error gathering connection state details:",p)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Be(Jy);B(M.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Be(e0);B(M.PeerConnectionFailureError,{warning:c,error:new Error(`Peer Connection failed. previous state: ${this._prevConnectionState}, current state: ${l}`),sessionId:this._session.sessionid},this.options.id)}this._prevConnectionState=l,l==="connected"&&(performance.mark(re(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(re(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(re(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void b.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;b.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(re(this.options.id,"ice-connected")),l==="failed"&&((a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"ice_failed"))},this._handleIceGatheringStateChange=()=>{const r=this.instance.iceGatheringState;b.debug(`[${new Date().toISOString()}] ICE Gathering State`,r),r==="gathering"?(this._gatheredCandidatesCount=0,this._startIceGatheringSafetyTimeout()):r==="complete"&&this._clearIceGatheringSafetyTimeout()},this._setCodecs=(r,a)=>{if(r.setCodecPreferences)return r.setCodecPreferences(a)},b.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.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=n,this._trickleIceSdpFn=s,this._registerPeerEvents=o}finishIceRestart(){this.isIceRestarting&&(this.isIceRestarting=!1,this._iceRestartTimeoutId&&(clearTimeout(this._iceRestartTimeoutId),this._iceRestartTimeoutId=null))}restartIce(){return this.instance?this.isIceRestarting?(b.debug("ICE restart: already in progress, skipping"),{started:!1,reason:"already in progress"}):this._session.connected?(this.isIceRestarting=!0,this._restartedIceOnConnectionStateFailed=!0,this.instance.restartIce(),this.iceDone=!1,this._iceRestartTimeoutId=setTimeout(()=>{this.isIceRestarting&&(b.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ti.ICE_RESTART_TIMEOUT_MS),b.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(b.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(b.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Ne.Offer}get isAnswer(){return this.type===Ne.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?this._createOffer().catch(e=>this._emitNegotiationError(e)):this._createAnswer().catch(e=>this._emitNegotiationError(e))}startTrickleIceNegotiation(){return V(this,void 0,void 0,function*(){performance.mark(re(this.options.id,"start-negotiation")),this._negotiating=!0,this._isOffer()||this.isIceRestarting?yield this._createOffer().then(this._trickleIceSdpFn.bind(this)):yield this._createAnswer().then(this._trickleIceSdpFn.bind(this))})}_emitNegotiationError(e){e instanceof Bt&&B(M.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(b.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{b.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),b.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):b.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(b.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(M.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(b.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){b.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?b.debug("Skipping negotiation, state:",this.instance.signalingState,"negotiating:",this._negotiating):this._isTrickleIce()?this.startTrickleIceNegotiation().catch(e=>this._emitNegotiationError(e)):this.startNegotiation()}handleTrackEvent(e){this._firstMediaTrackMarked||(performance.mark(re(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&ps(n,this.options.remoteStream)}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(re(this.options.id,"call-active"),"mark").length>0)||this.instance.connectionState!=="connected")return;this._timingsCollected=!0;const e=this._isTrickleIce()?"trickle":"non-trickle",i=this.isOffer?"outbound":"inbound",n=function(s,o,r){const a=Th(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Ch){if(d==="new-call-start")continue;const h=Th(re(s,d));h!==void 0&&l.push({label:nb[d]||d,fromStart:h-a})}l.sort((d,h)=>d.fromStart-h.fromStart);const c=[];let u=0;for(const d of l)c.push({label:d.label,fromStart:d.fromStart,delta:d.fromStart-u}),u=d.fromStart;return{mode:o,direction:r,steps:c}}(this.options.id,e,i);(function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void b.info(`${l} No timing data collected`);const c=Math.max(...a.map(_=>_.label.length),4)+2,u=(_,v)=>{for(;_.length<v;)_+=" ";return _},d=(_,v)=>{for(;_.length<v;)_=" "+_;return _},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let _=0;_<h.length;_++)p+="-";b.info(`${l} Call establishment timing breakdown:`),b.info(`${l} ${h}`),b.info(`${l} ${p}`),b.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",w=_.fromStart.toFixed(2)+"ms";b.info(`${l} ${u(_.label,c)}${d(v,14)}${d(w,14)}`)}b.info(`${l} ${p}`)})(n),Mr(this.options.id)}createPeerConnection(){return V(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(_r);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>V(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),B(M.Error,{error:ne(Ii(s),s,void 0,!1),callId:this.options.id,sessionId:this._session.sessionid,recoverable:!0,retryDeadline:Date.now()+o.timeout,resume:()=>{l()},reject:()=>{c(new Error("Call was rejected during media recovery flow!"))}},this._session.uuid)}).then(()=>V(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ne(_r);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Mu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&mn(this.options.localStream)&&(b.info("Muting local audio tracks on start"),vs(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(re(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Be(Qy);B(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Be(Zy);B(M.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ti.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return V(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ne(_r);this.isDebugEnabled&&(this.statsReporter=tb(this._session,this.options.id),yield(e=this.statsReporter)===null||e===void 0?void 0:e.start(this.instance,this._session.sessionid,this._session.sessionid));const{localElement:i,localStream:n=null,screenShare:s=!1}=this.options;if(mn(n)){const o=n.getAudioTracks();let r=[...o];if(b.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{b.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],b.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{b.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=bh(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&ps(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});b.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=bh(this.options.preferred_codecs);r.length>0&&this._setCodecs(o,r)}this.isOffer?(this.options.negotiateAudio&&this._checkMediaToNegotiate("audio"),this.options.negotiateVideo&&this._checkMediaToNegotiate("video")):this._isTrickleIce()||this.startNegotiation(),this._isTrickleIce()&&this.startTrickleIceNegotiation().catch(o=>this._emitNegotiationError(o)),this._logTransceivers()})}_getSenderByKind(e){return this.instance.getSenders().find(({track:i})=>i&&i.kind===e)}_checkMediaToNegotiate(e){if(!this._getSenderByKind(e)){const i=this.instance.addTransceiver(e);b.info("Add transceiver",e,i)}}_createOffer(){return V(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,b.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(re(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),this._isTrickleIce()||this._sdpReady(),e}catch(e){throw b.error("Peer _createOffer error:",e),e instanceof Bt?e:ne(xy,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){b.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw b.error("Peer _setRemoteDescription error:",i),ne(Ou,i)}})}_createAnswer(){return V(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return b.debug("Skipping negotiation, state:",this.instance.signalingState),b.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(re(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(re(this.options.id,"set-local-description")),performance.mark(re(this.options.id,"ice-gathering-started")),e}catch(e){throw b.error("Peer _createAnswer error:",e),e instanceof Bt?e:ne(Ly,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw b.error("Peer _setLocalDescription error:",i),ne(Dy,i)}})}_sdpReady(){Ei(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(mn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,V(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield ms(s,a,_t.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield ms(r,l,_t.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return gs(e)})}_isOffer(){return this.type===Ne.Offer}_isAnswer(){return this.type===Ne.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?10:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return b.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?b.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(b.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):b.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Mr(this.options.id),this.finishIceRestart(),this._clearIceGatheringSafetyTimeout(),this._sleepWakeupIntervalId!==null&&(clearInterval(this._sleepWakeupIntervalId),this._sleepWakeupIntervalId=null),this.isDebugEnabled&&this.statsReporter&&(yield this.statsReporter.stop(this.debugOutput)),this.instance&&(this.instance.close(),this.instance=null)})}}ti.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ti.ICE_RESTART_TIMEOUT_MS=15e3;const ys=Ar;class kh{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=j[j.New],this.prevState="",this.channels=[],this.role=Ir.Participant,this.extension=null,this._state=j.New,this._prevState=j.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._statsBindings=[],this._statsIntervalId=null,this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._signalingStateClosed=!1,this._creatingPeer=!1,this._desiredAudioMuted=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1,this._isRecovering=!1,this._checkConferenceSerno=w=>{const y=w<0||!this._lastSerno||this._lastSerno&&w===this._lastSerno+1;return y&&w>=0&&(this._lastSerno=w),y},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(w=>{w.forEach(y=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const I in C.constraints)if(C.constraints.hasOwnProperty(I)&&C.constraints[I]!==y[I])return}C.callback(y)}})})})};const{iceServers:n,speaker:s,micId:o,micLabel:r,camId:a,camLabel:l,localElement:c,remoteElement:u,options:d,mediaConstraints:{audio:h,video:p},ringtoneFile:_,ringbackFile:v}=e;this.options=Object.assign({},R0,{audio:h,video:p,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:n,localElement:c,remoteElement:u,micId:o,micLabel:r,camId:a,camLabel:l,speakerId:s,ringtoneFile:_,ringbackFile:v,debug:d.debug,debugOutput:d.debugOutput,trickleIce:d.trickleIce,prefetchIceCandidates:d.prefetchIceCandidates,forceRelayCandidate:d.forceRelayCandidate,keepConnectionAliveOnSocketClose:d.keepConnectionAliveOnSocketClose,mutedMicOnStart:d.mutedMicOnStart},i),this._onMediaError=this._onMediaError.bind(this),this._onPeerConnectionFailureError=this._onPeerConnectionFailureError.bind(this),this._onPeerConnectionSignalingStateClosed=this._onPeerConnectionSignalingStateClosed.bind(this),this._onTrickleIceSdp=this._onTrickleIceSdp.bind(this),this._registerPeerEvents=this._registerPeerEvents.bind(this),this._desiredAudioMuted=!!this.options.mutedMicOnStart,this.options.applyDesiredAudioMuteState=this._applyDesiredAudioMuteState.bind(this),this._init(),this.options&&(this._ringtone=vh(this.options.ringtoneFile,"_ringtone"),this._ringback=vh(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
116
+ `).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!this.options.forceRelayCandidate&&!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return V(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=lt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ti(Ne.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){b.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Bt?e:ne(Fu,e instanceof Error?e:void 0);return B(M.Error,{error:i,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void this.hangup({initiator:"sdk:peer-init-failed"},!1)}this._creatingPeer=!1})}answer(e={}){var i,n,s,o,r,a,l,c;return V(this,void 0,void 0,function*(){const u=((s=(n=(i=this.session).getActiveCalls)===null||n===void 0?void 0:n.call(i))!==null&&s!==void 0?s:[]).filter(d=>d.id!==this.id);if(u.length>0&&b.debug(`[${this.id}] answer(): answering inbound call while ${u.length} other active call(s) exist in session ${this.session.sessionid}`),this._creatingPeer||((o=this.peer)===null||o===void 0?void 0:o.instance)&&this.peer.instance.signalingState!=="closed"){const d=Be(i0);return B(M.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void b.warn(`[${this.id}] answer() ignored: peer connection already exists or is being created (signalingState: ${(l=(a=(r=this.peer)===null||r===void 0?void 0:r.instance)===null||a===void 0?void 0:a.signalingState)!==null&&l!==void 0?l:"creating"})`)}if(this._registerInboundAnswerAttempt()){performance.mark(re(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=lt.Inbound,((c=e==null?void 0:e.customHeaders)===null||c===void 0?void 0:c.length)>0&&(this.options=Object.assign(Object.assign({},this.options),{customHeaders:e.customHeaders})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ti(Ne.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){b.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Bt?d:ne(Fu,d instanceof Error?d:void 0);return B(M.Error,{error:h,callId:this.id,sessionId:this.session.sessionid,recoverable:!1},this.session.uuid),void(yield this.hangup({initiator:"sdk:peer-init-failed"},!0))}this._creatingPeer=!1}})}playRingtone(){_h(this._ringtone)}stopRingtone(){yh(this._ringtone)}playRingback(){_h(this._ringback)}stopRingback(){yh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return V(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),_=c.initiator||"app:call.hangup",v=this._state<j.Active?{cause:"USER_BUSY",causeCode:17}:{cause:"NORMAL_CLEARING",causeCode:16};if(this.cause=c.cause||v.cause,this.causeCode=c.causeCode||v.causeCode,this.sipCode=c.sipCode||null,this.sipReason=c.sipReason||null,this.sipCallId=c.sip_call_id||null,this.options.customHeaders=[...(n=this.options.customHeaders)!==null&&n!==void 0?n:[],...(o=(s=c==null?void 0:c.dialogParams)===null||s===void 0?void 0:s.customHeaders)!==null&&o!==void 0?o:[]],b.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:_,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:p}),c.isRecovering)return this._isRecovering=!0,this.setState(j.Recovering),void this._finalize();if(this.setState(j.Hangup),this.stopRingtone(),this.stopRingback(),u){const w=new N0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let y;try{yield Promise.race([this._execute(w),new Promise(C=>{y=setTimeout(()=>{b.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){b.error("telnyx_rtc.bye failed!",C);const I=ne(Fy,C);B(M.Error,{error:I,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{y&&clearTimeout(y)}}b.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(j.Destroy)})}hold(){const e=new hs({sessid:this.session.sessionid,action:Ri.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new hs({sessid:this.session.sessionid,action:Ri.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new hs({sessid:this.session.sessionid,action:Ri.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new hh({sessid:this.session.sessionid,dtmf:e,dialogParams:this.options});this._execute(i)}message(e,i){const n={from:this.session.options.login,to:e,body:i},s=new hh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){b.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,vs(this.options.localStream)}unmuteAudio(){b.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Or(this.options.localStream)}_applyDesiredAudioMuteState(){b.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?vs(this.options.localStream):Or(this.options.localStream)}toggleAudioMute(){b.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return V(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return b.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void B(M.Warning,{warning:Be(s0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;b.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:xr(l.track),localTracks:mh(this.options.localStream)});try{c=yield fs({audio:{deviceId:{exact:e}}})}catch(h){const p=ne(Ii(h),h);return void B(M.MediaError,p,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const p=ne(Ii(h),h);return B(M.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(_=>_.stop())}this._desiredAudioMuted=r,this.options.micId=e;const{localStream:d}=this.options;d.getAudioTracks().forEach(h=>h.stop()),d.getVideoTracks().forEach(h=>c.addTrack(h)),this.options.localStream=c,b.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:xr(l.track),localTracks:mh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Di(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Di(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Di(e,"video",null)}setVideoDevice(e){return V(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield fs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ps(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){vs(this.options.remoteStream)}undeaf(){Or(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Di(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void b.error("Could not set bandwidth (reason: no peer connection). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const{instance:n}=this.peer,s=n.getSenders();if(!s)return void b.error("Could not set bandwidth (reason: no senders). Dynamic bandwidth can only be set when there is a call running - is there any call running?)");const o=s.find(({track:{kind:r}})=>r===i);if(o){const r=o.getParameters();r.encodings||(r.encodings=[{rid:"h"}]),b.info("Parameters: ",r),b.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{b.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>b.error(a))}else b.error("Could not set bandwidth (reason: no "+i+" sender). Dynamic bandwidth can only be set when there is a call running - is there any call running?)")})}setAudioBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"audio")}setVideoBandwidthEncodingsMaxBps(e){this.setBandwidthEncodingsMaxBps(e,"video")}_isTerminatingOrTerminated(){return[j.Hangup,j.Destroy,j.Purge].includes(this._state)}getStats(e,i){if(!e)return;const n={callback:e,constraints:i};this._statsBindings.push(n),!this._statsIntervalId&&this._startStats(2e3)}setState(e){var i,n,s,o,r;switch(this._prevState=this._state,this._state=e,this.state=j[this._state].toLowerCase(),this.prevState=j[this._prevState].toLowerCase(),b.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:it.callUpdate,call:this}),e){case j.Purge:b.info(`[${this.id}] Entering Purge state.`);break;case j.Active:if(performance.mark(re(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,b.debug(`[${this.id}] Recovery complete, call is active`)),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:a,speakerId:l}=this.options;a&&l&&ph(a,l)},0),this._callReportCollector&&!((n=this.peer)===null||n===void 0)&&n.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const a=(s=this.session.connection)===null||s===void 0?void 0:s.host;a&&this._callRecorder._setHost(a),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const l=(o=this.options.localStream)===null||o===void 0?void 0:o.getAudioTracks()[0],c=(r=this.options.remoteStream)===null||r===void 0?void 0:r.getAudioTracks()[0];this._callRecorder.start(l,c)}this._mediaDeviceCollector=new K0,this._mediaDeviceCollector.logDevicesAtStart();break;case j.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case Z.Answer:if(performance.mark(re(this.id,"telnyx-rtc-answer")),this.gotAnswer=!0,n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id),this._state>=j.Active)return;this._state>=j.Early&&this.setState(j.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case Z.Media:if(performance.mark(re(this.id,"telnyx-rtc-media")),this._state>=j.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case Z.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===lt.Inbound?lt.Outbound:lt.Inbound,c={type:it[i],call:this,displayName:o,displayNumber:r,displayDirection:l};B(M.Notification,c,this.id)||B(M.Notification,c,this.session.uuid);break}case Z.Candidate:this._addIceCandidate(n);break;case Z.Info:case Z.Event:{const o=Object.assign(Object.assign({},n),{type:it.generic,call:this});B(M.Notification,o,this.id)||B(M.Notification,o,this.session.uuid);break}case Z.Ringing:performance.mark(re(this.id,"ringing")),this.playRingback(),n.telnyx_call_control_id&&(this.options.telnyxCallControlId=n.telnyx_call_control_id),n.telnyx_session_id&&(this.options.telnyxSessionId=n.telnyx_session_id),n.telnyx_leg_id&&(this.options.telnyxLegId=n.telnyx_leg_id);break;case Z.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return V(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return b.error("ConferenceUpdate invalid wireSerno or packet name:",e),"INVALID_PACKET";const{action:n,data:s,hashKey:o=String(this._lastSerno),arrIndex:r}=e;switch(n){case"bootObj":{this._lastSerno=0;const{chatChannel:a,infoChannel:l,modChannel:c,laName:u,conferenceMemberID:d,role:h}=i;this._dispatchConferenceUpdate({action:Ke.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const _ in s)p.push(Object.assign({callId:s[_][0],index:Number(_)},as(s[_][1])));this._dispatchConferenceUpdate({action:Ke.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ke.Add,callId:o,index:r},as(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ke.Modify,callId:o,index:r},as(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ke.Delete,callId:o,index:r},as(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ke.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:Ke.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{b.error("ConfChat subscription error:",s)});Lr(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return V(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,Sh(this.session,o)):b.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{b.error("ConfInfo subscription error:",s)});Lr(n,e)&&this._addChannel(e)})}_confControl(e,i={}){const n=Object.assign({application:"conf-control",callID:this.id,value:null},i);this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:n})}_handleChangeHoldStateSuccess(e){return e.holdState==="active"?this.setState(j.Active):this.setState(j.Held),!0}_handleChangeHoldStateError(e){b.error(`Failed to ${e.action} on call ${this.id}`);const i=ne(Py,e);return B(M.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new hs(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ri.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));b.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>V(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(b.info("ICE restart Modify response received"),(o=this.peer)===null||o===void 0||o.finishIceRestart(),yield this._onRemoteSdp(s.sdp)):this._onIceRestartFailed("ICE restart Modify response missing SDP")})).catch(s=>{this._onIceRestartFailed("ICE restart Modify failed",s)})}_onIceRestartFailed(e,i){var n,s,o;b.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ne(Hy,i);B(M.Error,{error:r,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),(o=(s=this.session).reportIceRestartFailed)===null||o===void 0||o.call(s,this.id)}_onRemoteSdp(e){return V(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Ne.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(re(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(j.Early),this.gotAnswer&&this.setState(j.Active)}).catch(n=>V(this,void 0,void 0,function*(){b.error("Call setRemoteDescription Error: ",n);const s=ne(Ou,n);B(M.Error,{error:s,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:set-remote-description-failure"},!0)}catch(o){b.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ei(this.peer.onSdpReadyTwice)){const e=ne(vr,new Error("SDP without candidates for the second time!"));B(M.Error,{error:e,sessionId:this.session.sessionid},this.session.uuid)}else Object.defineProperty(this.peer,"onSdpReadyTwice",{value:this._onIceSdp.bind(this)}),this.peer.iceDone=!1,this.peer.startNegotiation()}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this.peer&&(this.peer.iceDone=!0),!e)return void b.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return b.info(`No candidate - retry
117
+ `),void this._requestAnotherLocalDescription();if((n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),!h0.test(o)){const c=Be(t0);b.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),B(M.Warning,{warning:c,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}performance.mark(re(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${ys}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Ne.Offer:this.setState(j.Requesting),a=new ch(l);break;case Ne.Answer:this._isRecovering||this.setState(j.Answering),a=this.options.attach===!0?new uh(l):new dh(l);break;default:return b.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void b.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Ne.Offer?this.setState(j.Trying):this.setState(j.Active)}).catch(c=>V(this,void 0,void 0,function*(){b.error(`${this.id} - Sending ${r} error:`,c);const u=ne(vr,c);B(M.Error,{error:u,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(d){b.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return b.error("No SDP data provided"),void this.hangup({initiator:"sdk:missing-local-sdp"},!1);const{sdp:n,type:s}=e;let o=null;const r={sessid:this.session.sessionid,sdp:n,dialogParams:this.options,trickle:!0,"User-Agent":`Web-${ys}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Ne.Offer:this.setState(j.Requesting),o=new ch(r);break;case Ne.Answer:this._isRecovering||this.setState(j.Answering),o=this.options.attach===!0?new uh(r):new dh(r);break;default:return b.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(re(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void b.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Ne.Offer?this.setState(j.Trying):this.setState(j.Active)}).catch(a=>V(this,void 0,void 0,function*(){b.error(`${this.id} - Sending ${s} error:`,a);const l=ne(vr,a);B(M.Error,{error:l,callId:this.id,sessionId:this.session.sessionid},this.session.uuid);try{yield this.hangup({cause:"USER_BUSY",causeCode:17,initiator:"sdk:sdp-send-failure"},!0)}catch(c){b.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;const{instance:n}=this.peer;if(this._iceTimeout===null){const s=this.options.attach?5e3:1e3;this._iceTimeout=setTimeout(()=>this._onIceSdp(n.localDescription),s)}e.candidate?(b.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate)):this._onIceSdp(n.localDescription)}_onTrickleIce(e){var i;e.candidate&&e.candidate.candidate?(b.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):this._sendEndOfCandidates()}_sendIceCandidate(e){const i=new F0({sessid:this.session.sessionid,candidate:e.candidate,sdpMLineIndex:e.sdpMLineIndex,sdpMid:e.sdpMid,dialogParams:this.options});this._execute(i)}_addIceCandidate(e){if(!this._isRemoteDescriptionSet)return b.debug("Remote description not set. Queued ICE candidate.",e),void this._pendingIceCandidates.push(e);this._addIceCandidateToPeer(e)}_addIceCandidateToPeer(e){const i=this.peer.instance.addIceCandidate(e);Promise.resolve(i).then(()=>{b.debug("Successfully added ICE candidate:",e)}).catch(n=>{b.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new V0({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(re(this.id,"first-candidate")),this._firstCandidateSent=!0),!this._firstNonHostCandidateSent){const n=(i=e.candidate.match(/typ (\w+)/))===null||i===void 0?void 0:i[1];n&&n!=="host"&&(performance.mark(re(this.id,"first-non-host-candidate")),this._firstNonHostCandidateSent=!0)}}_resetTrickleIceCandidateState(){this._pendingIceCandidates=[],this._isRemoteDescriptionSet=!1,this._firstCandidateSent=!1,this._firstNonHostCandidateSent=!1}_flushPendingTrickleIceCandidates(){if(!this._pendingIceCandidates.length)return;const e=[...this._pendingIceCandidates];this._pendingIceCandidates=[],e.forEach(i=>{this._addIceCandidateToPeer(i)})}_registerPeerEvents(e){e.onicecandidate=i=>{var n;this.options.trickleIce?this._onTrickleIce(i):!((n=this.peer)===null||n===void 0)&&n.iceDone||this._onIce(i)},e.onicegatheringstatechange=i=>{b.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(b.debug("Finished gathering candidates"),performance.mark(re(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(b.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&ps(n,s)})}_onMediaError(e){const i=(e==null?void 0:e.name)||"UnknownError",n=(e==null?void 0:e.message)||"Unknown media error",s=(e==null?void 0:e.originalError)||e;this._dispatchNotification({type:it.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),b.error(`Media error (${i}): ${n}`,e),B(M.Error,{error:e,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),this.hangup({initiator:"sdk:media-error"},!1)}_onPeerConnectionFailureError(e){this._dispatchNotification({type:it.peerConnectionFailureError,error:e.error}),b.error("Peer connection failure error"),e.warning&&B(M.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:it.signalingStateClosed},e)),b.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:it.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(M.Notification,e,this.id,!1)||B(M.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){if(this.options.attach||this._isRecovering)return!0;for(const e of this._getSessionInboundAnswerCalls()){if(e.id===this.id||!e._isBlockingInboundAnswer())continue;const i=Be(r0);return B(M.Warning,{warning:i,callId:this.id,activeCallId:e.id,sessionId:this.session.sessionid,activeSessionId:e.session.sessionid},this.session.uuid),b.warn(`[${this.id}] answer() ignored: inbound call ${e.id} is already answering or active`),!1}return!0}_getSessionInboundAnswerCalls(){return Object.values(this.session.calls).filter(e=>!!e).filter(e=>!e.options.attach&&!e._isRecovering&&e.direction===lt.Inbound)}_isBlockingInboundAnswer(){var e;if([j.Hangup,j.Destroy,j.Purge].includes(this._state))return!1;const i=[j.Answering,j.Early,j.Active,j.Held].includes(this._state);return!(!this._creatingPeer&&!i)&&(!(!this._creatingPeer||!((e=this.peer)===null||e===void 0)&&e.instance)||this._hasUsablePeerConnection())}_hasUsablePeerConnection(){var e;const i=(e=this.peer)===null||e===void 0?void 0:e.instance;return!!i&&i.signalingState!=="closed"&&i.connectionState!=="closed"&&i.iceConnectionState!=="closed"}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v}=this.options;var w;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0),h&&(w=h,Object.keys(w).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Ut(M.MediaError,this._onMediaError,this.id),Ut(M.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(M.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ei(_)&&Ut(M.Notification,_.bind(this),this.id);const y=this.session.options.enableCallReports!==!1,C=this.session.options.callReportInterval||5e3,I=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,A=this.session.options.debugLogLevel||"debug",R=this.session.options.debugLogMaxEntries||1e3;if(y&&(this._callReportCollector=new ae({enabled:!0,interval:C,intermediateReportInterval:I},{enabled:!0,level:A,maxEntries:R}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=P=>{var T,k,g,m;B(M.Warning,{warning:P,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),P.code===Uu?(k=(T=this.session).reportNoRtp)===null||k===void 0||k.call(T,this.id,"inbound"):P.code===$u&&this._hasActiveUnmutedLocalAudioTrack()&&((m=(g=this.session).reportNoRtp)===null||m===void 0||m.call(g,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const P={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:th,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:ih,sampleRate:(s=this.session.options.callRecordingSampleRate)!==null&&s!==void 0?s:48e3,tracks:(o=this.session.options.callRecordingTracks)!==null&&o!==void 0?o:["local","remote"],endpoint:(r=this.session.options.callRecordingEndpoint)!==null&&r!==void 0?r:"/call_recording"},T={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new bt(P,T);const k=(l=this.session.connection)===null||l===void 0?void 0:l.host;k&&this._callRecorder._setHost(k),this._callRecorder.onWarning=g=>{B(M.Warning,{warning:g,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(j.Recovering):this.setState(j.New),b.info(`New Call — region: ${(c=this.session.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=this.session.dc)!==null&&u!==void 0?u:"unknown"}`,this.options)}_finalize(){var e,i,n;this._stopStats(),(e=this._mediaDeviceCollector)===null||e===void 0||e.stop(),this._mediaDeviceCollector=null,(i=this._callRecorder)===null||i===void 0||i.stop(),Mr(this.id),b.debug(`[${this.id}] Closing peer from _finalize`),(n=this.peer)===null||n===void 0||n.close();const{remoteStream:s,localStream:o,remoteElement:r,localElement:a}=this.options;vn(s),vn(o),fh(r,s),fh(a,o),yt(M.MediaError,null,this.id),yt(M.PeerConnectionFailureError,null,this.id),yt(M.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{b.error("Unexpected error in _postCallReport",{error:c})});this.session.trackCallReportUpload(l)}_getCallReportVoiceSdkId(){return this.session.callReportVoiceSdkId||void 0}_getClientSummary(){var e,i,n,s,o,r,a,l,c,u,d,h;const p=this.session.options,_=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},_?{anonymousLogin:{targetType:_.target_type,targetId:_.target_id,targetVersionId:_.target_version_id,targetParams:this._sanitizeClientOption(_.target_params)}}:{}),connection:{env:p.env,host:p.host,project:p.project,region:(e=this.session.region)!==null&&e!==void 0?e:p.region,dc:this.session.dc,rtcIp:p.rtcIp,rtcPort:p.rtcPort,autoReconnect:(i=p.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=p.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=p.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:p.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=p.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=p.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=p.skipTrailing)!==null&&a!==void 0&&a},media:{audio:this._sanitizeClientOption(this.options.audio),video:this._sanitizeClientOption(this.options.video),mutedMicOnStart:(l=this.options.mutedMicOnStart)!==null&&l!==void 0&&l,prefetchIceCandidates:(c=this.options.prefetchIceCandidates)===null||c===void 0||c,forceRelayCandidate:(u=this.options.forceRelayCandidate)!==null&&u!==void 0&&u,trickleIce:(d=this.options.trickleIce)!==null&&d!==void 0&&d,iceServers:this._sanitizeIceServers(this.options.iceServers)},callReports:{enabled:p.enableCallReports!==!1,intervalMs:p.callReportInterval||5e3,flushIntervalMs:(h=p.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:p.debugLogLevel||"debug",debugLogMaxEntries:p.debugLogMaxEntries||1e3}}}_getAuthenticationType(){const e=this.session.options;return e.anonymous_login?"anonymous_login":e.login_token?"login_token":e.login&&(e.password||e.passwd)?"login_password":e.token?"token":"unknown"}_sanitizeIceServers(e){if(e&&e.length!==0)return e.map(({urls:i,username:n,credential:s})=>({urls:i,hasUsername:!!n,hasCredential:!!s}))}_sanitizeClientOption(e,i=0){if(e!==void 0){if(e===null)return null;if(typeof e=="string")return e;if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="boolean")return e;if(typeof e!="function"){if(i>=4)return"[truncated]";if(Array.isArray(e))return e.map(n=>this._sanitizeClientOption(n,i+1)).filter(n=>n!==void 0);if(typeof e=="object"){const n=Object.entries(e).filter(([s])=>!this._isSensitiveClientOptionKey(s)).map(([s,o])=>[s,this._sanitizeClientOption(o,i+1)]).filter(s=>s[1]!==void 0);return Object.fromEntries(n)}}}}_isSensitiveClientOptionKey(e){return/(password|passwd|credential|secret|token|authorization|auth|api[_-]?key)/i.test(e)}flushIntermediateCallReport(e={type:"manual"}){this._flushIntermediateReport(e)}_flushIntermediateReport(e={type:"buffer-limit"}){var i;if(!this._callReportCollector)return;const n=this.session.callReportId;if(!n)return void b.debug("Cannot flush intermediate report: call_report_id not available");const s=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!s)return void b.debug("Cannot flush intermediate report: connection host not available");const o={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===lt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ys,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;b.info("Flushing intermediate call report",{callId:this.id,flushReason:e,segment:r.segment});const a=this._getCallReportVoiceSdkId(),l=e.type==="page-unload",c=this._callReportCollector.sendPayload(r,n,s,a,l).catch(u=>{b.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return V(this,void 0,void 0,function*(){if(!this._callReportCollector)return void b.warn("Call report collector not initialized");if(yield this._callReportCollector.stop(),this._callRecorder){this._callRecorder.stop();const c=(e=this.session.connection)===null||e===void 0?void 0:e.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=this._callRecorder.postFinalReport().catch(d=>{b.error("Failed to post final call recording",{error:d})}).finally(()=>{var d;(d=this._callRecorder)===null||d===void 0||d.cleanup()});this.session.trackCallReportUpload(u)}const o=this.session.callReportId;if(!o)return b.debug("Cannot post call report: call_report_id not available"),void this._callReportCollector.cleanup();const r={callId:this.id,destinationNumber:this.options.destinationNumber,callerNumber:this.options.callerNumber,direction:this.direction===lt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ys,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void b.error("Cannot post call report: connection host not available");const l=this._getCallReportVoiceSdkId();try{yield this._callReportCollector.postReport(r,o,a,l)}catch(c){throw b.error("Failed to post call report",{error:c}),c}finally{(n=this._callReportCollector)===null||n===void 0||n.cleanup(),(s=this._callRecorder)===null||s===void 0||s.cleanup()}})}_startStats(e){this._statsIntervalId=setInterval(this._doStats,e),b.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),b.debug("Stats stopped")}}kh.setStateTelnyx=t=>{if(t){switch(t._state){case j.Recovering:t.state="recovering";break;case j.Requesting:case j.Trying:case j.Early:t.state="connecting";break;case j.Active:t.state="active";break;case j.Held:t.state="held";break;case j.Hangup:case j.Destroy:t.state="done";break;case j.Answering:t.state="ringing";break;case j.New:t.state="new"}return t}};class ii extends kh{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new q0(e,i)),this.sendAIConversationMessage=e=>{if(!this.session.connected)throw new Error("Cannot send AI conversation message: session is not connected. sendAIConversationMessage requires an active WebSocket connection.");const i=new z0(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return V(this,void 0,void 0,function*(){this.screenShare instanceof ii&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return V(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>V(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new ii(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof ii&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return V(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&ph(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>V(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
118
118
  ${r.type}
119
119
  `,Object.keys(r).forEach(a=>{o.includes(a)||(n+=` ${a}: ${r[a]}
120
- `)}))}),S.info(n)}),2e3)}}class K0 extends Qt{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._remoteElement=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._onlineHandler=null,this._offlineHandler=null,this._wasOffline=!1,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile,this._setupNetworkListeners()}get reconnectDelay(){return 1e3}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return U(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return U(this,void 0,void 0,function*(){e.connect.call(this)})}checkPermissions(e=!0,i=!0){return U(this,void 0,void 0,function*(){try{const n=yield ps({audio:e,video:i});return mn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){S.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(j.Purge),S.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){S.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(j.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(Ju(M.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return vn().catch(e=>{const i=re(Ti(e),e);return V(M.MediaError,i,this.uuid),[]})}getVideoDevices(){return vn(_t.Video).catch(e=>(V(M.MediaError,e,this.uuid),[]))}getAudioInDevices(){return vn(_t.AudioIn).catch(e=>{const i=re(Ti(e),e);return V(M.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return vn(_t.AudioOut).catch(e=>(S.error("getAudioOutDevices",e),V(M.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return gs(e,i,n)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(i=>U(void 0,void 0,void 0,function*(){const n=[],s=yield ps({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<lh.length;r++){const[a,l]=lh[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return mn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=Cu(e,["micId","micLabel"]);return M0(s),this._audioConstraints=yield((o,r,a,l)=>U(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield gs(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const i=this.options.env==="development";this._iceServers=i?r0:o0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=un(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=un(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new A0({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new R0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Er(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new L0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Er(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}_setupNetworkListeners(){typeof window<"u"&&(this._onlineHandler=()=>{this._wasOffline&&(S.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,S.debug(`Network connectivity lost for session ${this.sessionid}`);const e=re(Vy);V(M.Error,{error:e,sessionId:this.sessionid},this.uuid)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return ei.setStateTelnyx(e)}}class yh{constructor(e,i){this.code=i,this.message=e}}class Y0{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new E0(e,i);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*Wu(2,6)}handleMessage(e){var i,n,s,o,r,a,l,c,u,d,h;const{session:g}=this;g.setPingReceived();const{id:y,method:v,params:b={},voice_sdk_id:_}=e,C=b==null?void 0:b.callID,k=b==null?void 0:b.eventChannel,A=b==null?void 0:b.eventType,x=g.calls[C],N=(i=x==null?void 0:x.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),T=new Set(Object.keys(g.calls));if(Array.isArray(b==null?void 0:b.reattached_sessions)&&T.size){S.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=b.reattached_sessions.length===0,w=b.reattached_sessions.some(I=>T.has(I));if(f||!w)for(const I of Object.keys(g.calls)){const L=g.calls[I];S.debug(`Session not reattached — terminating active call ${I} `);const R=re(Uy);V(M.Error,{error:R,callId:I,sessionId:g.sessionid},g.uuid),L.hangup({},!1)}}if(A==="channelPvtData")return this._handlePvtEvent(b.pvtData);const E=({recoveredCallId:f,forceRelayCandidateForRecovery:w,mutedMicOnStart:I}={})=>{var L,R,O,P,F;const H={audio:!0,video:g.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Q.Attach,mediaSettings:b.mediaSettings,debug:(L=g.options.debug)!==null&&L!==void 0&&L,debugOutput:(R=g.options.debugOutput)!==null&&R!==void 0?R:"socket",trickleIce:(O=g.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(P=g.options.prefetchIceCandidates)===null||P===void 0||P,forceRelayCandidate:w||g.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(F=g.options.keepConnectionAliveOnSocketClose)!==null&&F!==void 0&&F,mutedMicOnStart:I??g.options.mutedMicOnStart};C&&(H.id=C),b.telnyx_call_control_id&&(H.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(H.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(H.telnyxLegId=b.telnyx_leg_id),b.client_state&&(H.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(H.customHeaders=b.dialogParams.custom_headers),f&&(H.recoveredCallId=f),performance.mark(oe(H.id,"new-call-start"));const $=new ei(g,H);return $.nodeId=this.nodeId,$},p=new eh(_),m=new wr(_);switch(v){case Q.Answer:case Q.Display:case Q.Candidate:case Q.Ringing:case Q.Bye:case Q.Media:if(!C||!x)return void S.error(`Received ${v} for non existing call:`,b);x.handleMessage(e),this._ack(y,v);break;case Q.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Q.Punt:g.options.keepConnectionAliveOnSocketClose&&N?(S.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),g.socketDisconnect(),this._ack(y,v)):(S.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),g.serverDisconnect());break;case Q.Invite:{const I=E();I.direction=lt.Inbound,I.playRingtone(),I.setState(j.Ringing),this._ack(y,v);break}case Q.Attach:{const I=x||null;if(Object.keys(g.calls).length===0){S.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`),E({recoveredCallId:C}).answer(),this._ack(y,v);break}if(I){const L=I.id,R=(s=(n=I.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(I))!==null&&s!==void 0&&s;R&&S.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),S.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${L}.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1),E({recoveredCallId:L,forceRelayCandidateForRecovery:R,mutedMicOnStart:I.isAudioMuted}).answer(),this._ack(y,v);break}S.warn(`Attach: callID ${C} does not match any active calls. `),V(M.Warning,{warning:ze(Zy),callId:C,params:b,sessionId:g.sessionid},g.uuid),this._ack(y,v);break}case Q.Event:case"webrtc.event":if(!k)return void S.error("Verto received an unknown event:",b);const f=g.relayProtocol,w=k.split(".")[0];g._existsSubscription(f,k)?V(f,b,k):k===g.sessionid?this._handleSessionEvent(b.eventData):g._existsSubscription(f,w)?V(f,b,w):g.calls.hasOwnProperty(k)?g.calls[k].handleMessage(e):V(M.Notification,b,g.uuid);break;case Q.Info:b.type=it.generic,V(M.Notification,b,g.uuid);break;case Q.ClientReady:this.session.execute(p);break;case"ai_conversation":V(M.AIConversationMessage,{method:"ai_conversation",params:b,voice_sdk_id:_},g.uuid);break;default:{const I=vr(e);if(I){switch(I){case De.REGISTER:case De.REGED:if(!this.isDuplicateGatewayState(I,[De.REGED,De.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,I===De.REGED&&this.session.resetReconnectAttempts();const L=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.call_report_id;L&&(g.callReportId=L,S.debug("Captured call_report_id from REGED:",L));const R=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;R&&(g.dc=R);const O=(u=(c=e==null?void 0:e.result)===null||c===void 0?void 0:c.params)===null||u===void 0?void 0:u.region;O&&(g.region=O),S.info(`Connected to Telnyx — region: ${(d=g.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=g.dc)!==null&&h!==void 0?h:"unknown"}`),b.type=it.vertoClientReady,V(M.Ready,b,g.uuid)}break;case De.UNREGED:case De.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const L=new yh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),R=re(Ru,L);V(M.Error,{error:R,sessionId:g.sessionid},g.uuid);break}setTimeout(()=>{this.session.execute(p)},this.reconnectDelay());break;case De.FAILED:case De.FAIL_WAIT:case De.TIMEOUT:if(!this.isDuplicateGatewayState(I,[De.FAILED,De.FAIL_WAIT,De.TIMEOUT])){const L=re(My,new Error(`Gateway state: ${I}`));if(V(M.Error,{error:L,sessionId:g.sessionid},g.uuid),g.options.skipLastVoiceSdkId=!0,S.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${g.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const R=new yh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT"),O=re(Au,R);V(M.Error,{error:O,sessionId:g.sessionid},g.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0;const R=re(45003,new Error("Connection Retry Failed"));V(M.Error,{error:R,sessionId:g.sessionid},g.uuid);break}setTimeout(()=>{if(S.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(g.calls).some(R=>{var O;return((O=R.peer)===null||O===void 0?void 0:O.instance)&&!R.signalingStateClosed}))return S.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();S.debug("keepConnectionAliveOnSocketClose is set but all peer connections have signalingState closed, doing full reconnect")}this.session.disconnect().then(()=>{this.session.clearConnection(),this.session.connect()})},this.reconnectDelay())}break;default:S.warn("GatewayState message unknown method:",e)}break}S.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&S.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const g=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},y={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const _=h||this._retrieveCallId(b,o);if(_&&i.calls.hasOwnProperty(_)){const C=i.calls[_];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&g()})}}},v=yield i.vertoSubscribe(y).catch(b=>{S.error("liveArray subscription error:",b);const _=re(Ly,b);V(M.Error,{error:_,sessionId:i.sessionid},i.uuid)});Tr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(g=i.calls[v]||null,v!==null){const b={type:it.conferenceUpdate,action:Ke.Leave,conferenceName:r,participantId:Number(u),role:d};V(M.Notification,b,v,!1)||V(M.Notification,b,i.uuid),g===null&&yt(M.Notification,null,v)}}const y=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:y}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(b=>!v.includes(b)))}).catch(v=>{S.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":gh(this.session,e);break;case"logo-info":{const i={type:it.conferenceUpdate,action:Ke.LogoInfo,logo:e.logoURL};V(M.Notification,i,this.session.uuid);break}}}}class X0 extends K0{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new Y0(this),e.hangupOnBeforeUnload!==!1&&window.addEventListener("beforeunload",i=>{Yu(),this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(S.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))})})}validateOptions(){return as(this.options)||hn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw re(Ay,void 0,"Error: destinationNumber is required");const i=new ei(this,e);return performance.mark(oe(i.id,"new-call-start")),i.invite(),i}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!hn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return U(this,void 0,void 0,function*(){return yield e._onSocketOpen.call(this),as(this.options)?this.handleLoginOnSocketOpen():hn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class J0 extends X0{constructor(e){super(e),S.info(`SDK version: ${th}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return O0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ee.not_supported},{browserName:"Firefox",supported:Ee.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",supported:Ee.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",features:["video","audio"],supported:Ee.full},{browserName:"Edge",features:["audio"],supported:Ee.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ee.full},{browserName:"Firefox",features:["audio"],supported:Ee.partial},{browserName:"Safari",supported:Ee.not_supported},{browserName:"Edge",features:["audio"],supported:Ee.partial}]}]}}function Q0(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const i=e;return i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"&&typeof i.arguments=="string"}function bh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var wh={exports:{}},Sh;function Z0(){return Sh||(Sh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,h),y=i?i+c:c;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],g]:l._events[y].push(g):(l._events[y]=g,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,g=new Array(h);d<h;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,g){var y=i?i+l:l;if(!this._events[y])return!1;var v=this._events[y],b=arguments.length,_,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,g),!0}for(C=1,_=new Array(b-1);C<b;C++)_[C-1]=arguments[C];v.fn.apply(v.context,_)}else{var k=v.length,A;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!_)for(A=1,_=new Array(b-1);A<b;A++)_[A-1]=arguments[A];v[C].fn.apply(v[C].context,_)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var g=this._events[h];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&r(this,h);else{for(var y=0,v=[],b=g.length;y<b;y++)(g[y].fn!==c||d&&!g[y].once||u&&g[y].context!==u)&&v.push(g[y]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=i?i+l:l,this._events[c]&&r(this,c)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(wh)),wh.exports}var eb=Z0();const xr=bh(eb),ys=new xr;var Ar={exports:{}},tb=Ar.exports,Ch;function ib(){return Ch||(Ch=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(tb,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,b){var _=v[b];if(typeof _.bind=="function")return _.bind(v);try{return Function.prototype.bind.call(_,v)}catch{return function(){return Function.prototype.apply.apply(_,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var _=s[b];this[_]=b<v?e:this.methodFactory(_,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,_){return c(v)||d.apply(this,arguments)}function g(v,b){var _=this,C,k,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(f){var w=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=w;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+w+";"}catch{}}}function T(){var f;if(!(typeof window===i||!x)){try{f=window.localStorage[x]}catch{}if(typeof f===i)try{var w=window.document.cookie,I=encodeURIComponent(x),L=w.indexOf(I+"=");L!==-1&&(f=/^([^;]+)/.exec(w.slice(L+I.length+1))[1])}catch{}return _.levels[f]===void 0&&(f=void 0),f}}function E(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function p(f){var w=f;if(typeof w=="string"&&_.levels[w.toUpperCase()]!==void 0&&(w=_.levels[w.toUpperCase()]),typeof w=="number"&&w>=0&&w<=_.levels.SILENT)return w;throw new TypeError("log.setLevel() called with invalid level: "+f)}_.name=v,_.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},_.methodFactory=b||h,_.getLevel=function(){return A??k??C},_.setLevel=function(f,w){return A=p(f),w!==!1&&N(A),u.call(_)},_.setDefaultLevel=function(f){k=p(f),T()||_.setLevel(f,!1)},_.resetLevel=function(){A=null,E(),u.call(_)},_.enableAll=function(f){_.setLevel(_.levels.TRACE,f)},_.disableAll=function(f){_.setLevel(_.levels.SILENT,f)},_.rebuild=function(){if(r!==_&&(C=p(r.getLevel())),u.call(_),r===_)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var m=T();m!=null&&(A=p(m)),u.call(_)}r=new g,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new g(v,r.methodFactory)),b};var y=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=y),r},r.getLoggers=function(){return o},r.default=r,r})}(Ar)),Ar.exports}var nb=ib();const sb=bh(nb),ob=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ge=sb.getLogger("telnyx-ai-agent"),rb=ge.methodFactory;ge.methodFactory=(t,e,i)=>{const n=rb(t,e,i);return function(...s){n(ob(),"-",...s)}},ge.setLevel("info");function ab(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const lb=10,cb=500,db=100,Th=20;class ub{constructor(e){W(this,"remoteIntervalId",null);W(this,"localIntervalId",null);W(this,"remoteStream",null);W(this,"localStream",null);W(this,"remoteAudioContext",null);W(this,"remoteSource",null);W(this,"remoteAnalyser",null);W(this,"localAudioContext",null);W(this,"localSource",null);W(this,"localAnalyser",null);W(this,"thinkingStartTime",null);W(this,"lastState",null);W(this,"userIsSpeaking",!1);W(this,"lastUserAudioTime",null);W(this,"userSpeechStartTime",null);W(this,"userSilenceStartTime",null);W(this,"isFirstAgentSpeech",!0);W(this,"monitorStartTime",null);W(this,"volumeThreshold");W(this,"silenceDurationMs");W(this,"minSpeechDurationMs");W(this,"maxLatencyMs");W(this,"updateAgentState",ab(e=>{ge.debug("AudioStreamMonitor updateAgentState",e),ge.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ys.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??lb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??cb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??db,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,i;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(i=this.remoteAudioContext)==null||i.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,i;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(i=this.localAudioContext)==null||i.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){ge.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,ge.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(ge.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;ge.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let n=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(i);const o=i.reduce((l,c)=>l+c,0)/i.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&ge.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(n)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});n=r};this.remoteIntervalId=window.setInterval(s,Th)}startLocalMonitor(){if(!this.localStream){ge.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,ge.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(ge.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),i=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const n=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&ge.debug("Local audio volume:",n),n>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(i,Th)}destroy(){this.stopAudioStreamMonitor()}}function hb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function fb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function pb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function gb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function mb(t){if(!gb(t))return null;const e=t.params;return Q0(e)?e.item:null}function vb(t){var i;if(!t||typeof t!="object")return!1;const e=t;return((i=e.params)==null?void 0:i.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const _b=3e4;function yb(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function Rr(t){return JSON.stringify({error:t})}class bb{constructor(e){W(this,"registry",new Map);W(this,"inFlight",new Set);W(this,"completed",new Set);W(this,"generation",0);W(this,"getActiveCall");W(this,"timeoutMs");W(this,"events");W(this,"handleEvent",e=>{const i=mb(e);i&&this.execute(i)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:_b,this.events=e.events}register(e,i){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,i)}registerAll(e){for(const[i,n]of Object.entries(e))this.register(i,n)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}reset(){this.generation+=1,this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,i){this.generation===i&&this.completed.add(e)}async execute(e){const{call_id:i,name:n}=e;if(this.inFlight.has(i)||this.completed.has(i)){ge.debug(`[client-tools] duplicate function_call ignored (call_id=${i})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(n);if(!r){ge.warn(`[client-tools] no handler registered for tool "${n}"`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"unknown_tool"}),this.sendOutput(i,n,Rr("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{ge.warn(`[client-tools] invalid JSON arguments for tool "${n}" (call_id=${i})`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"invalid_arguments"}),this.sendOutput(i,n,Rr("invalid_arguments"),!0,s,o);return}this.inFlight.add(i),this.events.onInvoked({callId:i,toolName:n});const l={callId:i,toolName:n,rawArguments:e.arguments};try{const c=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n);this.sendOutput(i,n,yb(c),!1,s,o)}catch(c){const u=c instanceof Eh?"timeout":"handler_error";ge.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${u})`),this.events.onError({callId:i,toolName:n,reason:u}),this.sendOutput(i,n,Rr(u),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n){return new Promise((s,o)=>{const r=setTimeout(()=>{o(new Eh(n,i,this.timeoutMs))},this.timeoutMs);e.then(a=>{clearTimeout(r),s(a)},a=>{clearTimeout(r),o(a)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){ge.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){ge.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}if(!r||a!==r){ge.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:n}),this.events.onCompleted({callId:e,toolName:i,isError:s})}catch(l){ge.warn(`[client-tools] failed to send output for "${i}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:i,reason:"shutdown"})}}}class Eh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}function wb(t){return fb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Sb(t){if(!pb(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",i=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((n,s)=>(s.type==="text"&&(n+=s.text),n),""),i=t.params.item.content.reduce((n,s)=>(s.type==="image_url"&&s.image_url.url&&n.push({type:"image",url:s.image_url.url}),n),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:i}}class Cb extends xr{constructor(i){super();W(this,"telnyxRTC");W(this,"transcript",[]);W(this,"onSocketMessage",i=>{if(hb(i))switch(i.params.type){case"response.text.delta":{const n=wb(i);n&&(this.transcript.push(n),this.emit("transcript.item",n),ys.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(vb(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=Sb(i);if(n){const s=this.transcript.findIndex(o=>o.id===n.id);s!==-1?this.transcript[s]=n:this.transcript.push(n),this.emit("transcript.item",n)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage)}}const Rt=t=>typeof t=="object"&&t!==null,kh=t=>{const e=Rt(t)&&Rt(t.result)?t.result:t;if(!(!Rt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Tb=t=>Rt(t)&&Rt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Eb=(t,e)=>{if(!e||!Rt(t)||!Rt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Rt(i.params))return;const n=i.params;Rt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class kb extends xr{constructor(i){super();W(this,"telnyxRTC");W(this,"transcription");W(this,"removeLoginSuccessHook",null);W(this,"authenticated",!1);W(this,"authenticating",!1);W(this,"agentId");W(this,"versionId");W(this,"widgetVersion");W(this,"conversationId");W(this,"debug");W(this,"audioStreamMonitor");W(this,"clientTools");W(this,"activeCall");W(this,"chatMode");W(this,"dc",null);W(this,"region",null);W(this,"callReportId",null);W(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});W(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});W(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset()});W(this,"onSocketMessage",i=>{const n=kh(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});W(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});W(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});W(this,"onAgentStateChange",i=>{this.emit("conversation.agent.state",i)});this.agentId=i.agentId,this.versionId=i.versionId||"main",this.widgetVersion=i.widgetVersion,this.conversationId=i.conversationId,this.debug=i.debug||!1,this.chatMode=i.chatMode||!1,this.activeCall=null,ge.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId};i.conversationId&&(n.target_params={conversation_id:i.conversationId}),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new J0({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(M.Ready,this.onClientReady),this.telnyxRTC.on(M.Error,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketClose,this.onSocketClose),this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(M.Notification,this.onNotification),this.transcription=new Cb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ys.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new ub(i.vad),this.clientTools=new bb({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:s=>this.emit("client.tool.invoked",s),onCompleted:s=>this.emit("client.tool.completed",s),onError:s=>this.emit("client.tool.error",s)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(M.AIConversationMessage,this.clientTools.handleEvent)}registerClientTool(i,n){this.clientTools.register(i,n)}unregisterClientTool(i){return this.clientTools.unregister(i)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var i;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(M.AIConversationMessage,this.clientTools.handleEvent),this.clientTools.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(M.Ready,this.onClientReady),this.telnyxRTC.off(M.Error,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketClose,this.onSocketClose),this.telnyxRTC.off(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(M.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ys.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){ge.error("No active call to send message.");return}this.activeCall.sendConversationMessage(i,n)}get transcript(){return this.transcription.transcript}async startConversation(i){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw ge.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw ge.warn(d.message),this.emit("agent.error",d),d}const n=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=i||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[n],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var i;return(i=this.activeCall)==null?void 0:i.hangup()}setRemoteStream(i){this.audioStreamMonitor.setRemoteStream(i)}installLoginSuccessHook(){const i=this.telnyxRTC,n=i.execute,s=i.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=g=>{c===g&&(this.authenticating=!1)},d=function(g){const y=Tb(g),v=c;return y&&Eb(g,a),n.call(this,g).then(b=>{const _=y?kh(b):void 0;return l&&_!==void 0&&(u(v),r({sessionId:_})),b})},h=function(g){const y=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,g).finally(()=>{l&&i.login===h&&u(y)})};return i.execute=d,i.login=h,()=>{l=!1,i.execute===d&&(i.execute=n),i.login===h&&(i.login=s)}}emitLoginStarted(i){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",i)}emitLoginSuccess(i){const n=this.telnyxRTC,s=n.sessionid||null;i.sessionId&&(n.sessionid=i.sessionId);const o=i.sessionId||n.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}var Ih={exports:{}},_n={},xh;function Ib(){if(xh)return _n;xh=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(n,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:n,key:r,ref:s!==void 0?s:null,props:o}}return _n.Fragment=e,_n.jsx=i,_n.jsxs=i,_n}var Ah;function xb(){return Ah||(Ah=1,Ih.exports=Ib()),Ih.exports}xb(),Tt(void 0),Tt(null);const Ab=(t,e,i,n,s,o,r,a,l,c)=>new kb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),bs=10,Rh=5e3,Rb=[46001,46003],Lb=["login incorrect","authentication required","authentication failed"];function Lh(t){var n;const e=t.code;if(e&&Rb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Lb.some(s=>i.includes(s))}const Db=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[g,y]=Ae(!1),[v,b]=Ae(null),[_,C]=Ae(!1),k=de(0),A=de(null),x=de(null),N=de(!1),T=de(!1),E=de(0),p=de(0),m=He(()=>{A.current&&(clearTimeout(A.current),A.current=null)},[]),f=He(()=>{m(),k.current=0,T.current=!0,C(!1),b(null)},[m]),w=He(()=>{m(),C(!1)},[m]),I=He(L=>{if(m(),k.current>=bs){se.error(`Max login retry attempts (${bs}) exceeded`),C(!1);return}k.current+=1;const R=E.current,O=p.current;se.info(`Scheduling login retry attempt ${k.current}/${bs} in ${Rh}ms due to: ${L}`),C(!0),A.current=window.setTimeout(()=>{var H;A.current=null;const P=x.current,F=P==null?void 0:P.telnyxRTC;if(E.current!==R||p.current!==O||P!=null&&P.isAuthenticating){se.info("Skipping login retry because a newer socket/login is already in progress"),w();return}if(N.current||T.current||P!=null&&P.isAuthenticated){se.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}x.current&&(se.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(H=F==null?void 0:F.socketDisconnect)==null||H.call(F))},Rh)},[m,w,f]);return Re(()=>{if(!t)return;const L=Ab(t,e,i,n,s,o,r,a,l,u);N.current=!1,T.current=!1,y(!1),b(null),C(!1),x.current=L;const R=()=>{se.info("Agent connected successfully"),N.current=!0,y(!0),f()},O=()=>{se.info("Agent disconnected"),N.current=!1,T.current=!1,y(!1)},P=G=>{if(se.error("AI Agent error:",G),Lh(G)){if(N.current||T.current){se.debug("Ignoring retryable error — login already succeeded");return}k.current<bs?(b(null),I(G.message)):(b(G),C(!1))}else b(G),C(!1)},F=L.telnyxRTC??null,H=()=>{p.current+=1,T.current=!1},$=()=>{se.info("Login succeeded; clearing pending login retry flow"),f()},ue=()=>{E.current+=1,T.current=!1},J=()=>{T.current=!1};return L.on("agent.connected",R),L.on("agent.disconnected",O),L.on("agent.error",P),L.on("agent.login.started",H),L.on("agent.login.success",$),F&&typeof F=="object"&&(F.on(M.SocketOpen,ue),F.on(M.SocketClose,J)),L.connect(),h(L),()=>{m(),L.off("agent.connected",R),L.off("agent.disconnected",O),L.off("agent.error",P),L.off("agent.login.started",H),L.off("agent.login.success",$),F&&typeof F=="object"&&(F.off(M.SocketOpen,ue),F.off(M.SocketClose,J)),L.disconnect(),N.current=!1,x.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:g,error:v,isReconnecting:_}},Pb="telnyx-ai-agent",nt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error"};function Dh(){const t=document.querySelector(Pb);return t instanceof HTMLElement?t:null}function Lt(t,e,i){const n=i||Dh();if(!n){se.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),se.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const Mb=(t,e)=>{const{onReady:i,onConversationUpdate:n,onError:s,onConfigMessage:o}=e,r=de(null),a=Dn(lu);Re(()=>{r.current=Dh()},[]),Re(()=>{if(!t)return;const l=r.current,c=()=>{i();const x=t.telnyxRTC,N={dc:(x==null?void 0:x.dc)??null,region:(x==null?void 0:x.region)??null,callReportId:(x==null?void 0:x.callReportId)??null};a(N),Lt(nt.AGENT_CONNECTED,N,l)},u=()=>{a(null),Lt(nt.AGENT_DISCONNECTED,void 0,l)},d=A=>{const x={message:A.message,name:A.name};if(Lh(A)){se.debug("Ignoring retryable agent.error in widget event layer"),Lt(nt.AGENT_ERROR,x,l);return}s(A),Lt(nt.AGENT_ERROR,x,l)},h=A=>{var x;n(A),Lt(nt.CONVERSATION_UPDATE,{type:A.type,callState:(x=A.call)==null?void 0:x.state},l)},g=A=>{Lt(nt.TRANSCRIPT_ITEM,A,l)},y=A=>{Lt(nt.CONVERSATION_AGENT_STATE,A,l)},v=A=>{Lt(nt.AGENT_AUDIO_MUTE,{muted:A},l)},_=t.telnyxRTC,C=A=>{o(A)},k=A=>{const x=A,N={code:x==null?void 0:x.code,reason:x==null?void 0:x.reason,wasClean:x==null?void 0:x.wasClean,timestamp:new Date().toISOString()};se.info("[socket.close]",N),Lt(nt.SOCKET_CLOSE,N,l)};return _&&typeof _=="object"&&(_.on(M.SocketMessage,C),_.on(M.SocketClose,k)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",h),t.on("transcript.item",g),t.on("conversation.agent.state",y),t.on("agent.audio.mute",v),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",h),t.off("transcript.item",g),t.off("conversation.agent.state",y),t.off("agent.audio.mute",v),_&&typeof _=="object"&&(_.off(M.SocketMessage,C),_.off(M.SocketClose,k))}},[t,i,n,s,o,a])},Ob=2e3;async function Nb(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Ph(t){const e=t.split("-"),i=e[e.length-1];return i&&i.length===13&&/^\d+$/.test(i)?e.slice(0,-1).join("-"):t}const Fb=(t,e)=>{const[i,n]=Ae([]),[,s]=rr(),o=de(e);Re(()=>{o.current=e},[e]);const r=de(void 0),a=de(void 0);return Re(()=>{if(!t)return;const c=h=>{n(g=>{const y=g[g.length-1];if(h.role==="assistant"&&y&&Ph(y.id)===Ph(h.id)&&y.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&y.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&y.greetingLatencyMs===void 0,_={...y,content:y.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...g.slice(0,-1),_]}if(h.role==="assistant"){s(_=>_==="thinking"||_==="processing_image"?"speaking":_);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const _={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,_]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=g.findIndex(_=>_.id===h.id);if(v!==-1){const _=[...g];return _[v]={...g[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},_}if(y&&y.role==="user"&&h.timestamp.getTime()-y.timestamp.getTime()<Ob){const C={...y,id:h.id,content:y.content+" "+h.content,timestamp:h.timestamp,attachments:[...y.attachments||[],...h.attachments||[]]};return[...g.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,h]})},u=({state:h,userPerceivedLatencyMs:g,greetingLatencyMs:y,thinkingStartedAt:v})=>{(g!==void 0||y!==void 0)&&se.info(`[AgentState] state=${h} userPerceivedLatencyMs=${g} greetingLatencyMs=${y} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),y!==void 0&&(a.current=y)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var y;const g=(y=h.call)==null?void 0:y.state;(g==="destroy"||g==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const g=await Nb(h);d.push(g)}catch(g){throw se.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},Li={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class Vb{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,i){var n;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,i),se.debug(`[client-tools] registered handler "${e}"`),(n=this.agent)==null||n.registerClientTool(e,i)}unregister(e){var n;const i=this.handlers.delete(e);return i&&(se.debug(`[client-tools] unregistered handler "${e}"`),(n=this.agent)==null||n.unregisterClientTool(e)),i}list(){return Array.from(this.handlers.keys())}attach(e,i){this.detach(),this.agent=e,this.listeners=i;for(const[n,s]of this.handlers)e.registerClientTool(n,s);this.boundInvoked=n=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(n)},this.boundCompleted=n=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(n)},this.boundError=n=>{var s;return(s=this.listeners)==null?void 0:s.onError(n)},e.on(Li.INVOKED,this.boundInvoked),e.on(Li.COMPLETED,this.boundCompleted),e.on(Li.ERROR,this.boundError),this.handlers.size>0&&se.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Li.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Li.COMPLETED,this.boundCompleted),this.boundError&&e.off(Li.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function Lr(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const Ub=(t,e)=>{const i=de(null);i.current===null&&(i.current=new Vb),Ms(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){se.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=i.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),Re(()=>{const n=i.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return n.attach(t,{onInvoked:o=>{Lr(s(),nt.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{Lr(s(),nt.CLIENT_TOOL_COMPLETED,o)},onError:o=>{Lr(s(),nt.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},Bb=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=Jt(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=Fb(e,i),d=de(!1);switch(Re(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(g=>{g.enabled=!1,se.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[n,t]),r){case"collapsed":return D(mu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(_y,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(mu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Dr=()=>D(yi.div,{layoutId:an,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:D("div",{className:"rounded-full animate-spin",children:D(j_,{})})}),$b=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(Dr,{});case"done":case"purged":case"destroy":return null;case"active":return D(Bb,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(Dr,{})}},jb=({className:t})=>D("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:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Mh(){const t=Jt();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(jb,{className:"w-8 h-8 mr-2"})}const Hb=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Jt(),o=de(!1),r=He(async()=>{if(!t){se.error("Client is not initialized.");return}if(!n){se.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){se.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return Re(()=>{i&&t&&n&&!o.current&&(o.current=!0,se.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(yi.div,{layoutId:an,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:[D(Mh,{}),"Connecting..."]}):D(yi.button,{layoutId:an,onClick:r,disabled:!n,"aria-busy":!n,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D(Mh,{}),s.start_call_text]})},Gb='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',Wb=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),qb={duration:.1,ease:"circOut"},zb=({children:t,position:e="fixed",rootRef:i})=>{const n=Jt(),o=(e??n.position??"fixed")==="fixed"?D(Wb,{children:t}):t;return D("div",{ref:i,className:It(n.theme==="dark"&&"dark"),children:D(Pg,{transition:qb,children:[D("style",{children:Gb}),o]})})},Kb=t=>D(yi.div,{layoutId:an,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:[D(B_,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("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"," ",D(Y_,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(z_,{className:"w-4 h-4"}),"Retry"]})]});function Di(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Yb({"agent-id":t,debug:e,"trickle-ice":i,"call-destination-number":n,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":h,region:g,"skip-last-voice-sdk-id":y,environment:v,position:b="fixed","version-id":_}){const C=Di(e),k=Di(i),A=Di(h),x=y===void 0?!0:Di(y),N=Je(()=>{if(l)try{return JSON.parse(l)}catch(he){se.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Je(()=>({showUserPerceivedLatency:Di(c),showGreetingLatency:Di(u)}),[c,u]),{client:E,error:p,isConnected:m,isReconnecting:f}=Db(t,v,_,C,k,N,d,A,g,x),[w,I]=Ae(null),[L,R]=Ae(!1),[O,P]=Ae(!1),[F,H]=Ae(!1),[$,ue]=Ae(!1),J=Dn(pu),G=f_(),le={};if(n&&(le.destinationNumber=n),s&&(le.callerNumber=s),o&&(le.callerName=o),r)try{le.customHeaders=JSON.parse(r)}catch(he){se.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{le.audio=JSON.parse(a);const he=le.audio;if(typeof he=="object"){const ne=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(pe=>{ne[pe]||se.warn(`Audio constraint not supported by browser: ${pe}`)})}}catch(he){se.error("Invalid JSON for call-audio attribute:",a,he)}const X=He(()=>{R(!1)},[]),ee=He(he=>{var ne;if(((ne=he.call)==null?void 0:ne.state)==="destroy")return J(!1),ue(!0),I(null);I(he)},[J]),te=He(()=>{R(!1),f||P(!0)},[f]),ie=He(()=>{se.info("User triggered retry"),P(!1),R(!0),E&&E.connect()},[E]),me=He(he=>{if(h_(he)){const ne=he.params.widget_settings;ne&&Object.keys(ne).length>0&&(G(ne),H(!0))}},[G]);Mb(E,{onReady:X,onConversationUpdate:ee,onError:te,onConfigMessage:me});const Pe=de(null);return Ub(E,Pe),D(zb,{position:b,rootRef:Pe,children:t?O||p?D(Kb,{agentId:t,onRetry:ie}):L||f?D(Dr,{message:f?"Retrying...":void 0}):w!=null&&w.call?D($b,{call:w.call,client:E,latencySettings:T,chatMode:A,debug:C}):F?D(Hb,{client:E,callProps:le,chatMode:A&&!$,isReady:m&&!!E}):null:D("div",{children:"Please provide an assistant ID."})})}Jh(Yb,"telnyx-ai-agent",d_,{shadow:!0})})();
120
+ `)}))}),b.info(n)}),2e3)}}class bs extends ei{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()}getActiveCalls(){return Object.values(this.calls).filter(e=>bs.ACTIVE_CALL_STATE_NAMES.has(e.state))}_extractSafeCallIdentifiers(e){var i,n;const s={callId:e.id,state:e.state,direction:e.direction};!((i=e.options)===null||i===void 0)&&i.telnyxSessionId&&(s.telnyxSessionId=e.options.telnyxSessionId),!((n=e.options)===null||n===void 0)&&n.telnyxLegId&&(s.telnyxLegId=e.options.telnyxLegId);const o=e.sipCallId;return typeof o=="string"&&o&&(s.sipCallId=o),s}emitMultipleActiveCallsWarning(e){const i=this.getActiveCalls().filter(r=>r.id!==e);if(i.length===0)return;const n=Be(o0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};B(M.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),b.warn(`MULTIPLE_ACTIVE_CALLS_DETECTED: new call ${e} created while ${i.length} other call(s) are active in session ${this.sessionid}`)}getIsRegistered(){const e=Object.create(null,{getIsRegistered:{get:()=>super.getIsRegistered}});return V(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return V(this,void 0,void 0,function*(){b.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return V(this,void 0,void 0,function*(){try{const n=yield gs({audio:e,video:i});return vn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){b.info("[disconnect] Client-initiated disconnect — setting Purge with BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(j.Purge),b.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){b.info("[serverDisconnect] Server-initiated disconnect — setting Purge without BYE on all active calls.");for(const i in this.calls){const n=this.calls[i];n.setState(j.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},this._cleanupNetworkListeners(),yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(sh(M.SpeedTest,r=>{const{upDur:a,downDur:l}=r,c=l?8*e/(l/1e3)/1024:0;i({upDur:a,downDur:l,upKps:(a?8*e/(a/1e3)/1024:0).toFixed(0),downKps:c.toFixed(0)})},this.uuid),!(e=Number(e)))return n(`Invalid parameter 'bytes': ${e}`);this.executeRaw(`#SPU ${e}`);let s=e/1024;e%1024&&s++;const o=".".repeat(1024);for(let r=0;r<s;r++)this.executeRaw(`#SPB ${o}`);this.executeRaw("#SPE")})}getDevices(){return _n().catch(e=>{const i=ne(Ii(e),e);return B(M.MediaError,i,this.uuid),[]})}getVideoDevices(){return _n(_t.Video).catch(e=>(B(M.MediaError,e,this.uuid),[]))}getAudioInDevices(){return _n(_t.AudioIn).catch(e=>{const i=ne(Ii(e),e);return B(M.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return _n(_t.AudioOut).catch(e=>(b.error("getAudioOutDevices",e),B(M.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return ms(e,i,n)}getDeviceResolutions(e){return V(this,void 0,void 0,function*(){try{return yield(i=>V(void 0,void 0,void 0,function*(){const n=[],s=yield gs({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<gh.length;r++){const[a,l]=gh[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return vn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return V(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=xu(e,["micId","micLabel"]);return H0(s),this._audioConstraints=yield((o,r,a,l)=>V(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield ms(o,r,a).catch(()=>null);u&&(l.deviceId={exact:u})}return l}))(i,n,"audioinput",s),this.micId=i,this.micLabel=n,this._audioConstraints})}disableMicrophone(){this._previousAudioConstraints=this._audioConstraints,this._audioConstraints=!1}enableMicrophone(){this._audioConstraints=this._previousAudioConstraints||!0}set iceServers(e){if(e&&Array.isArray(e))this._iceServers=e;else{const i=this.options.env==="development";this._iceServers=i?p0:f0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElement=hn(e)}get localElement(){return this._localElement}set remoteElement(e){this._remoteElement=hn(e)}get remoteElement(){return this._remoteElement}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new B0({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return V(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new U0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Dr(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return V(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new $0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Dr(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&&(b.debug(`Network connectivity restored for session ${this.sessionid}. Reconnecting...`),this._wasOffline=!1,this._autoReconnect=!0,this.socketDisconnect())},this._offlineHandler=()=>{this._wasOffline=!0,b.debug(`Network connectivity lost for session ${this.sessionid}`);const e=ne(Gy);B(M.Error,{error:e,sessionId:this.sessionid},this.uuid)},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupNetworkListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null)}static telnyxStateCall(e){return ii.setStateTelnyx(e)}}bs.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class Ih{constructor(e,i){this.code=i,this.message=e}}class sb{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new P0(e,i);this.nodeId&&(n.targetNodeId=this.nodeId),this.session.execute(n)}reconnectDelay(){return 1e3*(e=2,i=6,Math.floor(Math.random()*(i-e+1)+e));var e,i}handleMessage(e){var i,n,s,o,r,a,l,c,u,d,h;const{session:p}=this;p.setPingReceived();const{id:_,method:v,params:w={},voice_sdk_id:y}=e,C=w==null?void 0:w.callID,I=w==null?void 0:w.eventChannel,A=w==null?void 0:w.eventType,R=p.calls[C],P=(i=R==null?void 0:R.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),T=new Set(Object.keys(p.calls));if(Array.isArray(w==null?void 0:w.reattached_sessions)&&T.size){b.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=w.reattached_sessions.length===0,S=w.reattached_sessions.some(E=>T.has(E));if(f||!S)for(const E of Object.keys(p.calls)){const x=p.calls[E];b.debug(`Session not reattached — terminating active call ${E} `);const L=ne(Nu);B(M.Error,{error:L,callId:E,sessionId:p.sessionid},p.uuid),x.hangup({},!1)}}if(Array.isArray(w==null?void 0:w.reattached_sessions)&&p.sessionid){const f=k0();if(f&&f.calls.length>0)if(f.sessionId!==p.sessionid)b.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${p.sessionid}) — ignoring all.`);else{const S=new Set(w.reattached_sessions);for(const E of f.calls)try{if(S.has(E.id)){b.debug(`Recovery marker for call ${E.id} was reattached — no notification.`);continue}b.info(`Recovery marker for call ${E.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const x=ne(Nu);B(M.Error,{error:x,callId:E.id,sessionId:p.sessionid,customHeaders:E.customHeaders},p.uuid)}catch(x){b.debug(`Recovery marker for a saved call failed to process (callId=${E==null?void 0:E.id}) — skipping: ${x instanceof Error?x.message:String(x)}`)}}}if(A==="channelPvtData")return this._handlePvtEvent(w.pvtData);const k=({recoveredCallId:f,forceRelayCandidateForRecovery:S,mutedMicOnStart:E}={})=>{var x,L,N,O,F;const W={audio:!0,video:p.options.video,remoteSdp:w.sdp,destinationNumber:w.callee_id_number,remoteCallerName:w.caller_id_name,remoteCallerNumber:w.caller_id_number,callerName:w.callee_id_name,callerNumber:w.callee_id_number,attach:v===Z.Attach,mediaSettings:w.mediaSettings,debug:(x=p.options.debug)!==null&&x!==void 0&&x,debugOutput:(L=p.options.debugOutput)!==null&&L!==void 0?L:"socket",trickleIce:(N=p.options.trickleIce)!==null&&N!==void 0&&N,prefetchIceCandidates:(O=p.options.prefetchIceCandidates)===null||O===void 0||O,forceRelayCandidate:S||p.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(F=p.options.keepConnectionAliveOnSocketClose)!==null&&F!==void 0&&F,mutedMicOnStart:E??p.options.mutedMicOnStart};C&&(W.id=C),w.telnyx_call_control_id&&(W.telnyxCallControlId=w.telnyx_call_control_id),w.telnyx_session_id&&(W.telnyxSessionId=w.telnyx_session_id),w.telnyx_leg_id&&(W.telnyxLegId=w.telnyx_leg_id),w.client_state&&(W.clientState=w.client_state),w.dialogParams&&w.dialogParams.custom_headers&&w.dialogParams.custom_headers.length&&(W.customHeaders=w.dialogParams.custom_headers),f&&(W.recoveredCallId=f),performance.mark(re(W.id,"new-call-start"));const $=new ii(p,W);return $.nodeId=this.nodeId,$},g=new ah(y),m=new Rr(y);switch(v){case Z.Answer:case Z.Display:case Z.Candidate:case Z.Ringing:case Z.Bye:case Z.Media:if(!C||!R)return void b.error(`Received ${v} for non existing call:`,w);R.handleMessage(e),this._ack(_,v);break;case Z.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Z.Punt:p.options.keepConnectionAliveOnSocketClose&&P?(b.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(_,v)):(b.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Z.Invite:{const E=k();E.direction=lt.Inbound,E.playRingtone(),E.setState(j.Ringing),this.session.emitMultipleActiveCallsWarning(E.id),this._ack(_,v);break}case Z.Attach:{const E=R||null;if(Object.keys(p.calls).length===0){b.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`);const x=k({recoveredCallId:C});x.answer(),this.session.emitMultipleActiveCallsWarning(x.id),this._ack(_,v);break}if(E){const x=E.id,L=(s=(n=E.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(E))!==null&&s!==void 0&&s;L&&b.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),b.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${x}.`),E.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const N=k({recoveredCallId:x,forceRelayCandidateForRecovery:L,mutedMicOnStart:E.isAudioMuted});N.answer(),this.session.emitMultipleActiveCallsWarning(N.id),this._ack(_,v);break}b.warn(`Attach: callID ${C} does not match any active calls. `),B(M.Warning,{warning:Be(l0),callId:C,params:w,sessionId:p.sessionid},p.uuid),this._ack(_,v);break}case Z.Event:case"webrtc.event":if(!I)return void b.error("Verto received an unknown event:",w);const f=p.relayProtocol,S=I.split(".")[0];p._existsSubscription(f,I)?B(f,w,I):I===p.sessionid?this._handleSessionEvent(w.eventData):p._existsSubscription(f,S)?B(f,w,S):p.calls.hasOwnProperty(I)?p.calls[I].handleMessage(e):B(M.Notification,w,p.uuid);break;case Z.Info:w.type=it.generic,B(M.Notification,w,p.uuid);break;case Z.ClientReady:this.session.execute(g);break;case"ai_conversation":B(M.AIConversationMessage,{method:"ai_conversation",params:w,voice_sdk_id:y},p.uuid);break;default:{const E=wr(e);if(E){switch(E){case De.REGISTER:case De.REGED:if(!this.isDuplicateGatewayState(E,[De.REGED,De.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,E===De.REGED&&this.session.resetReconnectAttempts();const x=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.call_report_id;x&&(p.callReportId=x,b.debug("Captured call_report_id from REGED:",x));const L=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;L&&(p.dc=L);const N=(u=(c=e==null?void 0:e.result)===null||c===void 0?void 0:c.params)===null||u===void 0?void 0:u.region;N&&(p.region=N),b.info(`Connected to Telnyx — region: ${(d=p.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),w.type=it.vertoClientReady,B(M.Ready,w,p.uuid)}break;case De.UNREGED:case De.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const x=new Ih("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),L=ne(Pu,x);B(M.Error,{error:L,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{this.session.execute(g)},this.reconnectDelay());break;case De.FAILED:case De.FAIL_WAIT:case De.TIMEOUT:if(!this.isDuplicateGatewayState(E,[De.FAILED,De.FAIL_WAIT,De.TIMEOUT])){const x=ne($y,new Error(`Gateway state: ${E}`));if(B(M.Error,{error:x,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,b.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${p.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const L=new Ih("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const N=ne(yr,L);B(M.Error,{error:N,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const L=ne(yr,new Error("Connection Retry Failed"));B(M.Error,{error:L,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{if(b.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some(L=>{var N;return((N=L.peer)===null||N===void 0?void 0:N.instance)&&!L.signalingStateClosed}))return b.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();b.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:b.warn("GatewayState message unknown method:",e)}break}b.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&b.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return V(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},_={nodeId:this.nodeId,channels:[o],handler:({data:w})=>{const y=h||this._retrieveCallId(w,o);if(y&&i.calls.hasOwnProperty(y)){const C=i.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(w,e).then(I=>{I==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(_).catch(w=>{b.error("liveArray subscription error:",w);const y=ne(Vy,w);B(M.Error,{error:y,sessionId:i.sessionid},i.uuid)});Lr(v,o)&&p();break}case"conference-liveArray-part":{let p=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(p=i.calls[v]||null,v!==null){const w={type:it.conferenceUpdate,action:Ke.Leave,conferenceName:r,participantId:Number(u),role:d};B(M.Notification,w,v,!1)||B(M.Notification,w,i.uuid),p===null&&yt(M.Notification,null,v)}}const _=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(w=>!v.includes(w)))}).catch(v=>{b.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Sh(this.session,e);break;case"logo-info":{const i={type:it.conferenceUpdate,action:Ke.LogoInfo,logo:e.logoURL};B(M.Notification,i,this.session.uuid);break}}}}class ob extends bs{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>V(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new sb(this),window.addEventListener("beforeunload",i=>{if(b.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return eh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(b.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));this.calls&&Object.keys(this.calls).forEach(n=>{const s=this.calls[n];s!=null&&s.flushIntermediateCallReport&&(b.debug(`beforeunload: flushing call report for ${n}.`),s.flushIntermediateCallReport({type:"page-unload"}))});try{const n=(this.calls?Object.keys(this.calls):[]).filter(s=>!!this.calls[s]).map(s=>this.calls[s]).map(s=>({id:s.id,customHeaders:s.options.customHeaders}));if(!this.sessionid||n.length===0)return b.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void kr();b.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),I0(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];b.debug(`Failed to save active-calls recovery marker before unload (active call ids: [${s.join(", ")}]): ${n instanceof Error?n.message:String(n)}`)}}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e.hangupOnBeforeUnload===!1&&this.sessionid&&this.hasActiveCall()&&(b.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Tr(this.sessionid))})}validateOptions(){return ls(this.options)||fn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ne(Ny,void 0,"Error: destinationNumber is required");const i=new ii(this,e);return e.id||b.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(re(i.id,"new-call-start")),i.invite(),i}broadcast(e){return this.vertoBroadcast(e)}subscribe(e){return this.vertoSubscribe(e)}unsubscribe(e){return this.vertoUnsubscribe(e)}validateCallOptions(e){return!!fn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return V(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),ls(this.options)?this.handleLoginOnSocketOpen():fn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class rb extends ob{constructor(e){super(e),b.info(`SDK version: ${lh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return G0()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:ke.not_supported},{browserName:"Firefox",supported:ke.not_supported},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",supported:ke.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",features:["video","audio"],supported:ke.full},{browserName:"Edge",features:["audio"],supported:ke.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:ke.full},{browserName:"Firefox",features:["audio"],supported:ke.partial},{browserName:"Safari",supported:ke.not_supported},{browserName:"Edge",features:["audio"],supported:ke.partial}]}]}}function ab(t){if(!t||typeof t!="object"||t.type!=="conversation.item.created")return!1;const e=t.item;if(typeof e!="object"||e===null)return!1;const i=e;return i.type==="function_call"&&typeof i.call_id=="string"&&typeof i.name=="string"&&typeof i.arguments=="string"}function Eh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Rh={exports:{}},Ah;function lb(){return Ah||(Ah=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var p=new s(u,d||l,h),_=i?i+c:c;return l._events[_]?l._events[_].fn?l._events[_]=[l._events[_],p]:l._events[_].push(p):(l._events[_]=p,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,p=new Array(h);d<h;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,p){var _=i?i+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,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,p),!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 I=v.length,A;for(C=0;C<I;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,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!y)for(A=1,y=new Array(w-1);A<w;A++)y[A-1]=arguments[A];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var _=0,v=[],w=p.length;_<w;_++)(p[_].fn!==c||d&&!p[_].once||u&&p[_].context!==u)&&v.push(p[_]);v.length?this._events[h]=v.length===1?v[0]:v:r(this,h)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=i?i+l:l,this._events[c]&&r(this,c)):(this._events=new n,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Rh)),Rh.exports}var cb=lb();const Pr=Eh(cb),ws=new Pr;var Nr={exports:{}},db=Nr.exports,xh;function ub(){return xh||(xh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(db,function(){var e=function(){},i="undefined",n=typeof window!==i&&typeof window.navigator!==i&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],o={},r=null;function a(v,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===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),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===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,w,y){return c(v)||d.apply(this,arguments)}function p(v,w){var y=this,C,I,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function P(f){var S=(s[f]||"silent").toUpperCase();if(!(typeof window===i||!R)){try{window.localStorage[R]=S;return}catch{}try{window.document.cookie=encodeURIComponent(R)+"="+S+";"}catch{}}}function T(){var f;if(!(typeof window===i||!R)){try{f=window.localStorage[R]}catch{}if(typeof f===i)try{var S=window.document.cookie,E=encodeURIComponent(R),x=S.indexOf(E+"=");x!==-1&&(f=/^([^;]+)/.exec(S.slice(x+E.length+1))[1])}catch{}return y.levels[f]===void 0&&(f=void 0),f}}function k(){if(!(typeof window===i||!R)){try{window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function g(f){var S=f;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=w||h,y.getLevel=function(){return A??I??C},y.setLevel=function(f,S){return A=g(f),S!==!1&&P(A),u.call(y)},y.setDefaultLevel=function(f){I=g(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=g(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(A=g(m)),u.call(y)}r=new p,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 p(v,r.methodFactory)),w};var _=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=_),r},r.getLoggers=function(){return o},r.default=r,r})}(Nr)),Nr.exports}var hb=ub();const fb=Eh(hb),pb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),ge=fb.getLogger("telnyx-ai-agent"),gb=ge.methodFactory;ge.methodFactory=(t,e,i)=>{const n=gb(t,e,i);return function(...s){n(pb(),"-",...s)}},ge.setLevel("info");function mb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const vb=10,_b=500,yb=100,Lh=20;class bb{constructor(e){G(this,"remoteIntervalId",null);G(this,"localIntervalId",null);G(this,"remoteStream",null);G(this,"localStream",null);G(this,"remoteAudioContext",null);G(this,"remoteSource",null);G(this,"remoteAnalyser",null);G(this,"localAudioContext",null);G(this,"localSource",null);G(this,"localAnalyser",null);G(this,"thinkingStartTime",null);G(this,"lastState",null);G(this,"userIsSpeaking",!1);G(this,"lastUserAudioTime",null);G(this,"userSpeechStartTime",null);G(this,"userSilenceStartTime",null);G(this,"isFirstAgentSpeech",!0);G(this,"monitorStartTime",null);G(this,"volumeThreshold");G(this,"silenceDurationMs");G(this,"minSpeechDurationMs");G(this,"maxLatencyMs");G(this,"updateAgentState",mb(e=>{ge.debug("AudioStreamMonitor updateAgentState",e),ge.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,ws.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??vb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??_b,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??yb,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,i;this.remoteIntervalId&&(clearInterval(this.remoteIntervalId),this.remoteIntervalId=null),(e=this.remoteSource)==null||e.disconnect(),(i=this.remoteAudioContext)==null||i.close(),this.remoteAudioContext=null,this.remoteSource=null,this.remoteAnalyser=null}stopLocalMonitor(){var e,i;this.localIntervalId&&(clearInterval(this.localIntervalId),this.localIntervalId=null),(e=this.localSource)==null||e.disconnect(),(i=this.localAudioContext)==null||i.close(),this.localAudioContext=null,this.localSource=null,this.localAnalyser=null}resetLatencyState(){this.thinkingStartTime=null,this.lastState=null,this.userIsSpeaking=!1,this.lastUserAudioTime=null,this.userSpeechStartTime=null,this.userSilenceStartTime=null,this.isFirstAgentSpeech=!0,this.monitorStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){ge.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,ge.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(ge.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;ge.debug("AudioContext resumed, state:",(o=this.remoteAudioContext)==null?void 0:o.state)})),this.remoteSource=this.remoteAudioContext.createMediaStreamSource(this.remoteStream),this.remoteAnalyser=this.remoteAudioContext.createAnalyser(),this.remoteSource.connect(this.remoteAnalyser);const e=this.remoteAudioContext.createGain();e.gain.value=0,this.remoteAnalyser.connect(e),e.connect(this.remoteAudioContext.destination),this.remoteAnalyser.fftSize=512;const i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);let n=!1;const s=()=>{var a;(a=this.remoteAnalyser)==null||a.getByteFrequencyData(i);const o=i.reduce((l,c)=>l+c,0)/i.length,r=o>=this.volumeThreshold;if(Math.random()<.01&&ge.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(n)this.updateAgentState({state:"speaking"});else if(this.isFirstAgentSpeech&&this.monitorStartTime!==null){const l=Math.round(performance.now()-this.monitorStartTime);this.isFirstAgentSpeech=!1,this.thinkingStartTime=null,this.userSilenceStartTime=null,this.userSpeechStartTime=null,this.updateAgentState({state:"speaking",greetingLatencyMs:l})}else if(this.userSilenceStartTime!==null){const l=Math.round(performance.now()-this.userSilenceStartTime);this.thinkingStartTime=null,this.userSilenceStartTime=null,this.maxLatencyMs===void 0||l<this.maxLatencyMs?this.updateAgentState({state:"speaking",userPerceivedLatencyMs:l}):this.updateAgentState({state:"speaking"})}else this.updateAgentState({state:"speaking"});else this.thinkingStartTime===null&&this.updateAgentState({state:"listening"});n=r};this.remoteIntervalId=window.setInterval(s,Lh)}startLocalMonitor(){if(!this.localStream){ge.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,ge.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(ge.debug("Resuming suspended local AudioContext..."),this.localAudioContext.resume()),this.localSource=this.localAudioContext.createMediaStreamSource(this.localStream),this.localAnalyser=this.localAudioContext.createAnalyser(),this.localSource.connect(this.localAnalyser),this.localAnalyser.fftSize=512;const e=new Uint8Array(this.localAnalyser.frequencyBinCount),i=()=>{var s;(s=this.localAnalyser)==null||s.getByteFrequencyData(e);const n=e.reduce((o,r)=>o+r,0)/e.length;if(Math.random()<.02&&ge.debug("Local audio volume:",n),n>=this.volumeThreshold)this.userIsSpeaking||(this.userIsSpeaking=!0,this.userSpeechStartTime=performance.now(),this.userSilenceStartTime=null),this.lastUserAudioTime=performance.now();else if(this.userIsSpeaking&&this.lastUserAudioTime!==null&&(this.lastUserAudioTime-(this.userSpeechStartTime||this.lastUserAudioTime)>=this.minSpeechDurationMs&&this.userSilenceStartTime===null&&(this.userSilenceStartTime=this.lastUserAudioTime),performance.now()-this.lastUserAudioTime>this.silenceDurationMs)){this.userIsSpeaking=!1,this.userSpeechStartTime=null,this.thinkingStartTime=performance.now();const o=new Date().toISOString();this.updateAgentState({state:"thinking",thinkingStartedAt:o})}};this.localIntervalId=window.setInterval(i,Lh)}destroy(){this.stopAudioStreamMonitor()}}function wb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Sb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Cb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Tb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function kb(t){if(!Tb(t))return null;const e=t.params;return ab(e)?e.item:null}function Ib(t){var i;if(!t||typeof t!="object")return!1;const e=t;return((i=e.params)==null?void 0:i.type)!=="conversation.item.deleted"?!1:!!e.params.item_id}const Eb=3e4;function Rb(t){if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return JSON.stringify({error:"unserializable_tool_result"})}}function Fr(t){return JSON.stringify({error:t})}class Ab{constructor(e){G(this,"registry",new Map);G(this,"inFlight",new Set);G(this,"completed",new Set);G(this,"generation",0);G(this,"getActiveCall");G(this,"timeoutMs");G(this,"events");G(this,"handleEvent",e=>{const i=kb(e);i&&this.execute(i)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Eb,this.events=e.events}register(e,i){if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.registry.set(e,i)}registerAll(e){for(const[i,n]of Object.entries(e))this.register(i,n)}unregister(e){return this.registry.delete(e)}has(e){return this.registry.has(e)}list(){return Array.from(this.registry.keys())}reset(){this.generation+=1,this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.inFlight.clear(),this.completed.clear()}markCompleted(e,i){this.generation===i&&this.completed.add(e)}async execute(e){const{call_id:i,name:n}=e;if(this.inFlight.has(i)||this.completed.has(i)){ge.debug(`[client-tools] duplicate function_call ignored (call_id=${i})`);return}const s=this.generation,o=this.getActiveCall(),r=this.registry.get(n);if(!r){ge.warn(`[client-tools] no handler registered for tool "${n}"`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"unknown_tool"}),this.sendOutput(i,n,Fr("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{ge.warn(`[client-tools] invalid JSON arguments for tool "${n}" (call_id=${i})`),this.markCompleted(i,s),this.events.onError({callId:i,toolName:n,reason:"invalid_arguments"}),this.sendOutput(i,n,Fr("invalid_arguments"),!0,s,o);return}this.inFlight.add(i),this.events.onInvoked({callId:i,toolName:n});const l={callId:i,toolName:n,rawArguments:e.arguments};try{const c=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n);this.sendOutput(i,n,Rb(c),!1,s,o)}catch(c){const u=c instanceof Dh?"timeout":"handler_error";ge.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${u})`),this.events.onError({callId:i,toolName:n,reason:u}),this.sendOutput(i,n,Fr(u),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n){return new Promise((s,o)=>{const r=setTimeout(()=>{o(new Dh(n,i,this.timeoutMs))},this.timeoutMs);e.then(a=>{clearTimeout(r),s(a)},a=>{clearTimeout(r),o(a)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){ge.warn(`[client-tools] dropping stale output after reset (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}const a=this.getActiveCall();if(!a){ge.warn(`[client-tools] no active call to send output (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}if(!r||a!==r){ge.warn(`[client-tools] dropping stale output after call change (call_id=${e})`),this.events.onError({callId:e,toolName:i,reason:"shutdown"});return}try{a.sendAIConversationMessage({type:"function_call_output",call_id:e,output:n}),this.events.onCompleted({callId:e,toolName:i,isError:s})}catch(l){ge.warn(`[client-tools] failed to send output for "${i}" (call_id=${e}): ${l instanceof Error?l.message:"unknown error"}`),this.events.onError({callId:e,toolName:i,reason:"shutdown"})}}}class Dh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}function xb(t){return Sb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Lb(t){if(!Cb(t)||t.params.item.role!=="user"||t.params.item.status!=="completed")return null;let e="",i=[];return Array.isArray(t.params.item.content)?(e=t.params.item.content.reduce((n,s)=>(s.type==="text"&&(n+=s.text),n),""),i=t.params.item.content.reduce((n,s)=>(s.type==="image_url"&&s.image_url.url&&n.push({type:"image",url:s.image_url.url}),n),[])):e=t.params.item.content,{id:t.params.item.id,role:t.params.item.role,timestamp:new Date,content:e,attachments:i}}class Db extends Pr{constructor(i){super();G(this,"telnyxRTC");G(this,"transcript",[]);G(this,"onSocketMessage",i=>{if(wb(i))switch(i.params.type){case"response.text.delta":{const n=xb(i);n&&(this.transcript.push(n),this.emit("transcript.item",n),ws.emit("conversation.agent.state",{state:"listening"}));return}case"conversation.item.deleted":{if(Ib(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&this.transcript.splice(s,1)}return}case"conversation.item.created":{const n=Lb(i);if(n){const s=this.transcript.findIndex(o=>o.id===n.id);s!==-1?this.transcript[s]=n:this.transcript.push(n),this.emit("transcript.item",n)}return}}});this.telnyxRTC=i,this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage)}}const Lt=t=>typeof t=="object"&&t!==null,Oh=t=>{const e=Lt(t)&&Lt(t.result)?t.result:t;if(!(!Lt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Ob=t=>Lt(t)&&Lt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Mb=(t,e)=>{if(!e||!Lt(t)||!Lt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Lt(i.params))return;const n=i.params;Lt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class Pb extends Pr{constructor(i){super();G(this,"telnyxRTC");G(this,"transcription");G(this,"removeLoginSuccessHook",null);G(this,"authenticated",!1);G(this,"authenticating",!1);G(this,"agentId");G(this,"versionId");G(this,"widgetVersion");G(this,"conversationId");G(this,"debug");G(this,"audioStreamMonitor");G(this,"clientTools");G(this,"activeCall");G(this,"chatMode");G(this,"dc",null);G(this,"region",null);G(this,"callReportId",null);G(this,"onClientReady",()=>{this.dc=this.telnyxRTC.dc??null,this.region=this.telnyxRTC.region??null,this.callReportId=this.telnyxRTC.callReportId??null;const i={dc:this.dc,region:this.region,callReportId:this.callReportId};this.emit("agent.connected",i)});G(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});G(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset()});G(this,"onSocketMessage",i=>{const n=Oh(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});G(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.audioStreamMonitor.stopAudioStreamMonitor()))});G(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});G(this,"onAgentStateChange",i=>{this.emit("conversation.agent.state",i)});this.agentId=i.agentId,this.versionId=i.versionId||"main",this.widgetVersion=i.widgetVersion,this.conversationId=i.conversationId,this.debug=i.debug||!1,this.chatMode=i.chatMode||!1,this.activeCall=null,ge.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId};i.conversationId&&(n.target_params={conversation_id:i.conversationId}),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new rb({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(M.Ready,this.onClientReady),this.telnyxRTC.on(M.Error,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(M.SocketClose,this.onSocketClose),this.telnyxRTC.on(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(M.Notification,this.onNotification),this.transcription=new Db(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),ws.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new bb(i.vad),this.clientTools=new Ab({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:s=>this.emit("client.tool.invoked",s),onCompleted:s=>this.emit("client.tool.completed",s),onError:s=>this.emit("client.tool.error",s)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(M.AIConversationMessage,this.clientTools.handleEvent)}registerClientTool(i,n){this.clientTools.register(i,n)}unregisterClientTool(i){return this.clientTools.unregister(i)}getClientTools(){return this.clientTools.list()}async connect(){return this.telnyxRTC.connect()}get isAuthenticated(){return this.authenticated}get isAuthenticating(){return this.authenticating}get sessionId(){return this.telnyxRTC.sessionid||null}clearReconnectToken(){this.telnyxRTC.clearReconnectToken()}async disconnect(){var i;this.audioStreamMonitor.destroy(),this.telnyxRTC.off(M.AIConversationMessage,this.clientTools.handleEvent),this.clientTools.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(M.Ready,this.onClientReady),this.telnyxRTC.off(M.Error,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(M.SocketClose,this.onSocketClose),this.telnyxRTC.off(M.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(M.Notification,this.onNotification),this.dc=null,this.region=null,this.callReportId=null,this.authenticated=!1,this.authenticating=!1,this.emit("agent.disconnected"),this.transcription.removeAllListeners(),ws.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){ge.error("No active call to send message.");return}this.activeCall.sendConversationMessage(i,n)}get transcript(){return this.transcription.transcript}async startConversation(i){var c,u;if(!this.telnyxRTC){const d=new Error("Client is not initialized.");throw ge.error(d.message),this.emit("agent.error",d),d}if(!this.authenticated||!this.sessionId){const d=new Error("Cannot start AI agent conversation before login is complete.");throw ge.warn(d.message),this.emit("agent.error",d),d}const n=(u=(c=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:c.codecs)==null?void 0:u.find(d=>d.mimeType.toLowerCase().includes("opus")),{customHeaders:s,audio:o,...r}=i||{},a=s?[...s]:[];this.versionId&&a.push({name:"X-AI-Assistant-Version-ID",value:this.versionId}),this.conversationId&&a.push({name:"X-AI-Assistant-Conversation-ID",value:this.conversationId});const l=this.telnyxRTC.newCall({destinationNumber:"xxx",...r,audio:this.chatMode?!1:o??!0,...this.chatMode?{receiveOnlyAudio:!0}:{},preferred_codecs:[n],customHeaders:a.length>0?a:void 0});this.emit("conversation.update",{call:l,type:"callUpdate"})}endConversation(){var i;return(i=this.activeCall)==null?void 0:i.hangup()}setRemoteStream(i){this.audioStreamMonitor.setRemoteStream(i)}installLoginSuccessHook(){const i=this.telnyxRTC,n=i.execute,s=i.login,o=this.emitLoginStarted.bind(this),r=this.emitLoginSuccess.bind(this),a=this.widgetVersion;let l=!0,c=0;const u=p=>{c===p&&(this.authenticating=!1)},d=function(p){const _=Ob(p),v=c;return _&&Mb(p,a),n.call(this,p).then(w=>{const y=_?Oh(w):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),w})},h=function(p){const _=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&i.login===h&&u(_)})};return i.execute=d,i.login=h,()=>{l=!1,i.execute===d&&(i.execute=n),i.login===h&&(i.login=s)}}emitLoginStarted(i){this.authenticating=!0,this.authenticated=!1,this.emit("agent.login.started",i)}emitLoginSuccess(i){const n=this.telnyxRTC,s=n.sessionid||null;i.sessionId&&(n.sessionid=i.sessionId);const o=i.sessionId||n.sessionid||null;this.authenticated&&o===s||(this.authenticated=!0,this.authenticating=!1,this.emit("agent.login.success",{sessionId:o}))}}var Mh={exports:{}},yn={},Ph;function Nb(){if(Ph)return yn;Ph=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function i(n,s,o){var r=null;if(o!==void 0&&(r=""+o),s.key!==void 0&&(r=""+s.key),"key"in s){o={};for(var a in s)a!=="key"&&(o[a]=s[a])}else o=s;return s=o.ref,{$$typeof:t,type:n,key:r,ref:s!==void 0?s:null,props:o}}return yn.Fragment=e,yn.jsx=i,yn.jsxs=i,yn}var Nh;function Fb(){return Nh||(Nh=1,Mh.exports=Nb()),Mh.exports}Fb(),kt(void 0),kt(null);const Vb=(t,e,i,n,s,o,r,a,l,c)=>new Pb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Ss=10,Fh=5e3,Bb=[46001,46003],Ub=["login incorrect","authentication required","authentication failed"];function Vh(t){var n;const e=t.code;if(e&&Bb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Ub.some(s=>i.includes(s))}const $b=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[p,_]=Ae(!1),[v,w]=Ae(null),[y,C]=Ae(!1),I=de(0),A=de(null),R=de(null),P=de(!1),T=de(!1),k=de(0),g=de(0),m=He(()=>{A.current&&(clearTimeout(A.current),A.current=null)},[]),f=He(()=>{m(),I.current=0,T.current=!0,C(!1),w(null)},[m]),S=He(()=>{m(),C(!1)},[m]),E=He(x=>{if(m(),I.current>=Ss){oe.error(`Max login retry attempts (${Ss}) exceeded`),C(!1);return}I.current+=1;const L=k.current,N=g.current;oe.info(`Scheduling login retry attempt ${I.current}/${Ss} in ${Fh}ms due to: ${x}`),C(!0),A.current=window.setTimeout(()=>{var W;A.current=null;const O=R.current,F=O==null?void 0:O.telnyxRTC;if(k.current!==L||g.current!==N||O!=null&&O.isAuthenticating){oe.info("Skipping login retry because a newer socket/login is already in progress"),S();return}if(P.current||T.current||O!=null&&O.isAuthenticated){oe.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(oe.info(`Executing reconnect attempt ${I.current} (socket disconnect)`),(W=F==null?void 0:F.socketDisconnect)==null||W.call(F))},Fh)},[m,S,f]);return xe(()=>{if(!t)return;const x=Vb(t,e,i,n,s,o,r,a,l,u);P.current=!1,T.current=!1,_(!1),w(null),C(!1),R.current=x;const L=()=>{oe.info("Agent connected successfully"),P.current=!0,_(!0),f()},N=()=>{oe.info("Agent disconnected"),P.current=!1,T.current=!1,_(!1)},O=H=>{if(oe.error("AI Agent error:",H),Vh(H)){if(P.current||T.current){oe.debug("Ignoring retryable error — login already succeeded");return}I.current<Ss?(w(null),E(H.message)):(w(H),C(!1))}else w(H),C(!1)},F=x.telnyxRTC??null,W=()=>{g.current+=1,T.current=!1},$=()=>{oe.info("Login succeeded; clearing pending login retry flow"),f()},ue=()=>{k.current+=1,T.current=!1},J=()=>{T.current=!1};return x.on("agent.connected",L),x.on("agent.disconnected",N),x.on("agent.error",O),x.on("agent.login.started",W),x.on("agent.login.success",$),F&&typeof F=="object"&&(F.on(M.SocketOpen,ue),F.on(M.SocketClose,J)),x.connect(),h(x),()=>{m(),x.off("agent.connected",L),x.off("agent.disconnected",N),x.off("agent.error",O),x.off("agent.login.started",W),x.off("agent.login.success",$),F&&typeof F=="object"&&(F.off(M.SocketOpen,ue),F.off(M.SocketClose,J)),x.disconnect(),P.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,E]),{client:d,isConnected:p,error:v,isReconnecting:y}},jb="telnyx-ai-agent",nt={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",CONVERSATION_UPDATE:"conversation.update",CONVERSATION_AGENT_STATE:"conversation.agent.state",AGENT_AUDIO_MUTE:"agent.audio.mute",CLIENT_TOOL_INVOKED:"client.tool.invoked",CLIENT_TOOL_COMPLETED:"client.tool.completed",CLIENT_TOOL_ERROR:"client.tool.error"};function Bh(){const t=document.querySelector(jb);return t instanceof HTMLElement?t:null}function Dt(t,e,i){const n=i||Bh();if(!n){oe.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),oe.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const Wb=(t,e)=>{const{onReady:i,onConversationUpdate:n,onError:s,onConfigMessage:o}=e,r=de(null),a=On(gu);xe(()=>{r.current=Bh()},[]),xe(()=>{if(!t)return;const l=r.current,c=()=>{i();const R=t.telnyxRTC,P={dc:(R==null?void 0:R.dc)??null,region:(R==null?void 0:R.region)??null,callReportId:(R==null?void 0:R.callReportId)??null};a(P),Dt(nt.AGENT_CONNECTED,P,l)},u=()=>{a(null),Dt(nt.AGENT_DISCONNECTED,void 0,l)},d=A=>{const R={message:A.message,name:A.name};if(Vh(A)){oe.debug("Ignoring retryable agent.error in widget event layer"),Dt(nt.AGENT_ERROR,R,l);return}s(A),Dt(nt.AGENT_ERROR,R,l)},h=A=>{var R;n(A),Dt(nt.CONVERSATION_UPDATE,{type:A.type,callState:(R=A.call)==null?void 0:R.state},l)},p=A=>{Dt(nt.TRANSCRIPT_ITEM,A,l)},_=A=>{Dt(nt.CONVERSATION_AGENT_STATE,A,l)},v=A=>{Dt(nt.AGENT_AUDIO_MUTE,{muted:A},l)},y=t.telnyxRTC,C=A=>{o(A)},I=A=>{const R=A,P={code:R==null?void 0:R.code,reason:R==null?void 0:R.reason,wasClean:R==null?void 0:R.wasClean,timestamp:new Date().toISOString()};oe.info("[socket.close]",P),Dt(nt.SOCKET_CLOSE,P,l)};return y&&typeof y=="object"&&(y.on(M.SocketMessage,C),y.on(M.SocketClose,I)),t.on("agent.connected",c),t.on("agent.disconnected",u),t.on("agent.error",d),t.on("conversation.update",h),t.on("transcript.item",p),t.on("conversation.agent.state",_),t.on("agent.audio.mute",v),()=>{t.off("agent.connected",c),t.off("agent.disconnected",u),t.off("agent.error",d),t.off("conversation.update",h),t.off("transcript.item",p),t.off("conversation.agent.state",_),t.off("agent.audio.mute",v),y&&typeof y=="object"&&(y.off(M.SocketMessage,C),y.off(M.SocketClose,I))}},[t,i,n,s,o,a])},Hb=2e3;async function Gb(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Uh(t){const e=t.split("-"),i=e[e.length-1];return i&&i.length===13&&/^\d+$/.test(i)?e.slice(0,-1).join("-"):t}const qb=(t,e)=>{const[i,n]=Ae([]),[,s]=lr(),o=de(e);xe(()=>{o.current=e},[e]);const r=de(void 0),a=de(void 0);return xe(()=>{if(!t)return;const c=h=>{n(p=>{const _=p[p.length-1];if(h.role==="assistant"&&_&&Uh(_.id)===Uh(h.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+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),w&&(a.current=void 0),[...p.slice(0,-1),y]}if(h.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,w=o.current.showGreetingLatency&&a.current!==void 0;if(v||w){const y={...h,...v&&{userPerceivedLatencyMs:r.current},...w&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...p];return y[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(_&&_.role==="user"&&h.timestamp.getTime()-_.timestamp.getTime()<Hb){const C={..._,id:h.id,content:_.content+" "+h.content,timestamp:h.timestamp,attachments:[..._.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const w=h.attachments&&h.attachments.length>0;s(w?"processing_image":"thinking")}return[...p,h]})},u=({state:h,userPerceivedLatencyMs:p,greetingLatencyMs:_,thinkingStartedAt:v})=>{(p!==void 0||_!==void 0)&&oe.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${_} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),_!==void 0&&(a.current=_)):h==="listening"&&s(w=>w==="processing_image"||w==="thinking"?w:"listening")},d=h=>{var _;const p=(_=h.call)==null?void 0:_.state;(p==="destroy"||p==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const p=await Gb(h);d.push(p)}catch(p){throw oe.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Oi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class zb{constructor(){this.handlers=new Map,this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}register(e,i){var n;if(!e||typeof e!="string")throw new Error("registerClientTool: tool name must be a non-empty string");if(typeof i!="function")throw new Error(`registerClientTool: handler for "${e}" must be a function`);this.handlers.set(e,i),oe.debug(`[client-tools] registered handler "${e}"`),(n=this.agent)==null||n.registerClientTool(e,i)}unregister(e){var n;const i=this.handlers.delete(e);return i&&(oe.debug(`[client-tools] unregistered handler "${e}"`),(n=this.agent)==null||n.unregisterClientTool(e)),i}list(){return Array.from(this.handlers.keys())}attach(e,i){this.detach(),this.agent=e,this.listeners=i;for(const[n,s]of this.handlers)e.registerClientTool(n,s);this.boundInvoked=n=>{var s;return(s=this.listeners)==null?void 0:s.onInvoked(n)},this.boundCompleted=n=>{var s;return(s=this.listeners)==null?void 0:s.onCompleted(n)},this.boundError=n=>{var s;return(s=this.listeners)==null?void 0:s.onError(n)},e.on(Oi.INVOKED,this.boundInvoked),e.on(Oi.COMPLETED,this.boundCompleted),e.on(Oi.ERROR,this.boundError),this.handlers.size>0&&oe.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Oi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Oi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Oi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function Vr(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const Kb=(t,e)=>{const i=de(null);i.current===null&&(i.current=new zb),Ns(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){oe.warn("[client-tools] could not resolve widget host element; imperative tool API unavailable");return}const r=i.current;return o.registerClientTool=(a,l)=>{r.register(a,l)},o.unregisterClientTool=a=>r.unregister(a),o.getClientTools=()=>r.list(),()=>{delete o.registerClientTool,delete o.unregisterClientTool,delete o.getClientTools}},[e]),xe(()=>{const n=i.current;if(!t)return;const s=()=>{const o=e.current,r=o==null?void 0:o.getRootNode();return r instanceof ShadowRoot?r.host:null};return n.attach(t,{onInvoked:o=>{Vr(s(),nt.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{Vr(s(),nt.CLIENT_TOOL_COMPLETED,o)},onError:o=>{Vr(s(),nt.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},Yb=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=Qt(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=qb(e,i),d=de(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,oe.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[n,t]),r){case"collapsed":return D(Cu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(ky,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(Cu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Br=()=>D(wi.div,{layoutId:cn,className:"bg-[#FEFDF5] text-black dark:bg-black gap-3 dark:text-white w-[240px] max-w-full rounded-4xl p-4 text-center flex items-center justify-center flex-col shadow-lg shadow-[#38383878]",children:D("div",{className:"rounded-full animate-spin",children:D(Y_,{})})}),Xb=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{switch(t==null?void 0:t.state){case"new":case"trying":case"requesting":return D(Br,{});case"done":case"purged":case"destroy":return null;case"active":return D(Yb,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(Br,{})}},Jb=({className:t})=>D("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:[D("g",{clipPath:"url(#:R5lfm:)",children:[D("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"}),D("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"}),D("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"}),D("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"}),D("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"})]}),D("defs",{children:D("clipPath",{id:":R5lfm:",children:D("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function $h(){const t=Qt();return t.logo_icon_url?D("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:D("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):D(Jb,{className:"w-8 h-8 mr-2"})}const Zb=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=de(!1),r=He(async()=>{if(!t){oe.error("Client is not initialized.");return}if(!n){oe.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){oe.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,oe.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(wi.div,{layoutId:cn,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg dark:bg-black dark:text-white",children:[D($h,{}),"Connecting..."]}):D(wi.button,{layoutId:cn,onClick:r,disabled:!n,"aria-busy":!n,className:"bg-[#FEFDF5] text-black flex items-center px-4 py-2 text-xl font-medium rounded-full shadow-lg cursor-pointer disabled:cursor-not-allowed disabled:opacity-60 dark:bg-black dark:text-white ",children:[D($h,{}),s.start_call_text]})},Qb='@layer components;/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-font-weight:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-green-400:oklch(79.2% .209 151.711);--color-green-500:oklch(72.3% .219 149.579);--color-green-600:oklch(62.7% .194 149.214);--color-gray-200:oklch(92.8% .006 264.531);--color-black:#000;--color-white:#fff;--spacing:.25rem;--container-xs:20rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-xl:1.25rem;--text-xl--line-height:calc(1.75/1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--font-weight-medium:500;--font-weight-semibold:600;--radius-md:.375rem;--radius-lg:.5rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--radius-4xl:2rem;--animate-spin:spin 1s linear infinite;--blur-xs:4px;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;-moz-tab-size:4;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){-webkit-appearance:button;-moz-appearance:button;appearance:button}::file-selector-button{-webkit-appearance:button;-moz-appearance:button;appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer utilities{.pointer-events-auto{pointer-events:auto}.pointer-events-none{pointer-events:none}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.inset-0{inset:calc(var(--spacing)*0)}.-top-1{top:calc(var(--spacing)*-1)}.top-0{top:calc(var(--spacing)*0)}.top-2{top:calc(var(--spacing)*2)}.-right-1{right:calc(var(--spacing)*-1)}.right-0{right:calc(var(--spacing)*0)}.right-2{right:calc(var(--spacing)*2)}.bottom-0{bottom:calc(var(--spacing)*0)}.bottom-12{bottom:calc(var(--spacing)*12)}.left-0{left:calc(var(--spacing)*0)}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\\[9999\\]{z-index:9999}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-2{margin-right:calc(var(--spacing)*2)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.ml-2{margin-left:calc(var(--spacing)*2)}.ml-4{margin-left:calc(var(--spacing)*4)}.ml-auto{margin-left:auto}.contents{display:contents}.flex{display:flex}.hidden{display:none}.inline{display:inline}.inline-flex{display:inline-flex}.h-3{height:calc(var(--spacing)*3)}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-8{height:calc(var(--spacing)*8)}.h-16{height:calc(var(--spacing)*16)}.h-\\[72px\\]{height:72px}.h-\\[144px\\]{height:144px}.h-\\[300px\\]{height:300px}.h-full{height:100%}.max-h-32{max-height:calc(var(--spacing)*32)}.min-h-\\[180px\\]{min-height:180px}.w-3{width:calc(var(--spacing)*3)}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-8{width:calc(var(--spacing)*8)}.w-16{width:calc(var(--spacing)*16)}.w-\\[200px\\]{width:200px}.w-\\[240px\\]{width:240px}.w-\\[250px\\]{width:250px}.w-\\[344px\\]{width:344px}.w-full{width:100%}.max-w-32{max-width:calc(var(--spacing)*32)}.max-w-full{max-width:100%}.max-w-xs{max-width:var(--container-xs)}.flex-1{flex:1}.animate-spin{animation:var(--animate-spin)}.cursor-pointer{cursor:pointer}.list-disc{list-style-type:disc}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px*var(--tw-divide-y-reverse));border-bottom-width:calc(1px*calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-\\[\\#3D3D46\\]>:not(:last-child)){border-color:#3d3d46}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-4xl{border-radius:var(--radius-4xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-md{border-radius:var(--radius-md)}.rounded-t-3xl{border-top-left-radius:var(--radius-3xl);border-top-right-radius:var(--radius-3xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-solid{--tw-border-style:solid;border-style:solid}.border-\\[\\#969696\\]{border-color:#969696}.bg-\\[\\#E6E3D3\\]{background-color:#e6e3d3}.bg-\\[\\#F36666\\]{background-color:#f36666}.bg-\\[\\#FEFDF5\\]{background-color:#fefdf5}.bg-\\[\\#FEFDF599\\]{background-color:#fefdf599}.bg-black{background-color:var(--color-black)}.bg-green-500{background-color:var(--color-green-500)}.bg-red-500{background-color:var(--color-red-500)}.bg-transparent{background-color:#0000}.bg-white{background-color:var(--color-white)}.object-cover{object-fit:cover}.object-center{object-position:center}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.px-2\\.5{padding-inline:calc(var(--spacing)*2.5)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.py-1\\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-3{padding-block:calc(var(--spacing)*3)}.text-center{text-align:center}.text-left{text-align:left}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.text-\\[\\#969696\\]{color:#969696}.text-black{color:var(--color-black)}.text-green-400{color:var(--color-green-400)}.text-red-400{color:var(--color-red-400)}.text-white{color:var(--color-white)}.underline{text-decoration-line:underline}.opacity-0{opacity:0}.opacity-60{opacity:.6}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a),0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[\\#38383878\\]{--tw-shadow-color:#38383878}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383878\\]{--tw-shadow-color:color-mix(in oklab,#38383878 var(--tw-shadow-alpha),transparent)}}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.backdrop-blur-xs{--tw-backdrop-blur:blur(var(--blur-xs));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.outline-none{--tw-outline-style:none;outline-style:none}@media (hover:hover){.hover\\:bg-\\[\\#E6E3D3\\]:hover{background-color:#e6e3d3}.hover\\:bg-gray-200:hover{background-color:var(--color-gray-200)}.hover\\:bg-green-600:hover{background-color:var(--color-green-600)}.hover\\:bg-red-600:hover{background-color:var(--color-red-600)}}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:opacity-60:disabled{opacity:.6}@media (min-width:40rem){.sm\\:h-\\[386px\\]{height:386px}.sm\\:w-\\[400px\\]{width:400px}.sm\\:rounded-3xl{border-radius:var(--radius-3xl)}}@media (min-width:48rem){.md\\:right-10{right:calc(var(--spacing)*10)}.md\\:bottom-10{bottom:calc(var(--spacing)*10)}}.dark\\:border-\\[\\#3D3D46\\]:where(.dark,.dark *){border-color:#3d3d46}.dark\\:bg-\\[\\#3C3C3C\\]:where(.dark,.dark *){background-color:#3c3c3c}.dark\\:bg-\\[\\#38383C96\\]:where(.dark,.dark *){background-color:#38383c96}.dark\\:bg-\\[\\#38383C\\]:where(.dark,.dark *){background-color:#38383c}.dark\\:bg-\\[\\#222227\\]:where(.dark,.dark *){background-color:#222227}.dark\\:bg-\\[\\#750000\\]:where(.dark,.dark *){background-color:#750000}.dark\\:bg-black:where(.dark,.dark *){background-color:var(--color-black)}.dark\\:text-black:where(.dark,.dark *){color:var(--color-black)}.dark\\:text-white:where(.dark,.dark *){color:var(--color-white)}@media (hover:hover){.dark\\:hover\\:bg-\\[\\#2A2A2E\\]:where(.dark,.dark *):hover{background-color:#2a2a2e}}}::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-track{background:0 0}::-webkit-scrollbar-thumb{background-color:#888;background-clip:content-box;border:2px solid #0000;border-radius:4px}::-webkit-scrollbar-thumb:hover{background-color:#555}html{scrollbar-width:thin;scrollbar-color:#888 transparent}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@keyframes spin{to{transform:rotate(360deg)}}',ew=({children:t})=>D("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:D("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),tw={duration:.1,ease:"circOut"},iw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?D(ew,{children:t}):t;return D("div",{ref:i,className:Rt(n.theme==="dark"&&"dark"),children:D(Ug,{transition:tw,children:[D("style",{children:Qb}),o]})})},nw=t=>D(wi.div,{layoutId:cn,className:"bg-[#FEFDF5] text-black dark:bg-black rounded-2xl p-4 flex flex-col items-center justify-center dark:text-white w-[344px] max-w-full",children:[D(z_,{className:"w-8 h-8 text-red-400"}),D("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),D("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[D("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),D("li",{children:["Make sure that the"," ",D("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"," ",D(iy,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&D("button",{onClick:t.onRetry,className:"flex items-center gap-2 px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded-lg font-medium transition-colors",children:[D(ey,{className:"w-4 h-4"}),"Retry"]})]});function Mi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function sw({"agent-id":t,debug:e,"trickle-ice":i,"call-destination-number":n,"call-caller-number":s,"call-caller-name":o,"call-custom-headers":r,"call-audio":a,vad:l,"show-user-perceived-latency":c,"show-greeting-latency":u,"conversation-id":d,"chat-mode":h,region:p,"skip-last-voice-sdk-id":_,environment:v,position:w="fixed","version-id":y}){const C=Mi(e),I=Mi(i),A=Mi(h),R=_===void 0?!0:Mi(_),P=Je(()=>{if(l)try{return JSON.parse(l)}catch(he){oe.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Je(()=>({showUserPerceivedLatency:Mi(c),showGreetingLatency:Mi(u)}),[c,u]),{client:k,error:g,isConnected:m,isReconnecting:f}=$b(t,v,y,C,I,P,d,A,p,R),[S,E]=Ae(null),[x,L]=Ae(!1),[N,O]=Ae(!1),[F,W]=Ae(!1),[$,ue]=Ae(!1),J=On(wu),H=b_(),le={};if(n&&(le.destinationNumber=n),s&&(le.callerNumber=s),o&&(le.callerName=o),r)try{le.customHeaders=JSON.parse(r)}catch(he){oe.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{le.audio=JSON.parse(a);const he=le.audio;if(typeof he=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(pe=>{se[pe]||oe.warn(`Audio constraint not supported by browser: ${pe}`)})}}catch(he){oe.error("Invalid JSON for call-audio attribute:",a,he)}const X=He(()=>{L(!1)},[]),ee=He(he=>{var se;if(((se=he.call)==null?void 0:se.state)==="destroy")return J(!1),ue(!0),E(null);E(he)},[J]),te=He(()=>{L(!1),f||O(!0)},[f]),ie=He(()=>{oe.info("User triggered retry"),O(!1),L(!0),k&&k.connect()},[k]),me=He(he=>{if(y_(he)){const se=he.params.widget_settings;se&&Object.keys(se).length>0&&(H(se),W(!0))}},[H]);Wb(k,{onReady:X,onConversationUpdate:ee,onError:te,onConfigMessage:me});const Oe=de(null);return Kb(k,Oe),D(iw,{position:w,rootRef:Oe,children:t?N||g?D(nw,{agentId:t,onRetry:ie}):x||f?D(Br,{message:f?"Retrying...":void 0}):S!=null&&S.call?D(Xb,{call:S.call,client:k,latencySettings:T,chatMode:A,debug:C}):F?D(Zb,{client:k,callProps:le,chatMode:A&&!$,isReady:m&&!!k}):null:D("div",{children:"Please provide an assistant ID."})})}of(sw,"telnyx-ai-agent",v_,{shadow:!0})})();