@telnyx/ai-agent-widget 0.33.9-beta.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Sw=Object.defineProperty;var Cw=(rt,K,Gt)=>K in rt?Sw(rt,K,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):rt[K]=Gt;var j=(rt,K,Gt)=>Cw(rt,typeof K!="symbol"?K+"":K,Gt);(function(){"use strict";var rt,K,Gt,qt,Jr,Zr,Qr,ea,Is,Rs,As,ta,Bi={},ia=[],Yh=/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 xs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ze(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?rt.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 Ui(t,r,n,s,null)}function Ui(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&&K.vnode!=null&&K.vnode(o),o}function ht(t){return t.children}function at(t,e){this.props=t,this.context=e}function di(t,e){if(e==null)return t.__?di(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"?di(t):null}function na(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 na(t)}}function Ls(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!En.__r++||Jr!=K.debounceRendering)&&((Jr=K.debounceRendering)||Zr)(En)}function En(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(Qr),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,K.vnode&&K.vnode(i),Ds(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??di(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,la(o,i,r),i.__e!=s&&na(i)));En.__r=0}function sa(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,_,v,b,w=n&&n.__k||ia,C=e.length;for(l=Xh(i,e,w,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Bi:w[p.__i]||Bi,p.__i=d,b=Ds(t,p,h,s,o,r,a,l,c,u),_=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Os(h.ref,null,p),u.push(p.ref,p.__c||_,p)),v==null&&_!=null&&(v=_),4&p.__u||h.__k===p.__k?l=oa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:_&&(l=_.nextSibling),p.__u&=-7);return i.__e=v,l}function Xh(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?Ui(null,r,null,null,null):Vi(r)?Ui(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Ui(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=di(a)),da(a,a));return n}function oa(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=oa(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=di(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 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 ra(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Yh.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||ra(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||ra(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(ea,"$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?As:Rs,o)):t.removeEventListener(e,o?As:Rs,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 aa(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(K.event?K.event(e):e)}}}function Ds(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,_,v,b,w,C,k,L,R,O,T,E,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=K.__b)&&u(e);e:if(typeof f=="function")try{if(w=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],L=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(w,L):(e.__c=d=new at(w,L),d.constructor=f,d.render=Qh),k&&k.sub(d),d.props=w,d.state||(d.state={}),d.context=L,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(w,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&&w!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,L),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,L)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=w,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(w,d.__s,L),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,_,v)})}if(d.context=L,d.props=w,d.__P=t,d.__e=!1,O=K.__r,T=0,C){for(d.state=d.__s,d.__d=!1,O&&O(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,O&&O(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=ca(u.props.children)),a=sa(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),b&&(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--;)xs(o[m]);else e.__e=i.__e,e.__k=i.__k;K.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Zh(i.__e,e,i,n,s,o,r,l,c);return(u=K.diffed)&&u(e),128&e.__u?void 0:a}function la(t,e,i){for(var n=0;n<i.length;n++)Os(i[n],i[++n],i[++n]);K.__c&&K.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){K.__e(o,s.__v)}})}function ca(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Vi(t)?t.map(ca):ut({},t)}function Zh(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,_,v,b=i.props,w=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(w);t=document.createElementNS(s,C,w.is&&w),a&&(K.__m&&K.__m(e,o),a=!1),o=null}if(C==null)b===w||a&&t.data==w||(t.data=w);else{if(o=o&&rt.call(t.childNodes),b=i.props||Bi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in w)){if(c=="value"&&"defaultValue"in w||c=="checked"&&"defaultChecked"in w)continue;kn(t,c,null,p,s)}}for(c in w)p=w[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?_=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||kn(t,c,p,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=""),sa(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&&di(i,0),a,l),o!=null)for(c=o.length;c--;)xs(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=b[c])&&kn(t,c,_,b[c],s),c="checked",v!=null&&v!=t[c]&&kn(t,c,v,b[c],s))}return t}function Os(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){K.__e(s,i)}}function da(t,e,i){var n,s;if(K.unmount&&K.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Os(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){K.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&da(n[s],e,i||typeof t.type!="function");i||xs(t.__e),t.__c=t.__=t.__e=void 0}function Qh(t,e,i){return this.constructor(t,i)}function In(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),K.__&&K.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ds(e,t=(!n&&i||e).__k=Ze(ht,null,[t]),s||Bi,Bi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?rt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),la(o,t,r)}function ua(t,e){In(t,e,ua)}function Ms(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?rt.call(arguments,2):i),Ui(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,Ls(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"+ta++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}rt=ia.slice,K={__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,at.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),Ls(this))},at.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Ls(this))},at.prototype.render=ht,qt=[],Zr=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Qr=function(t,e){return t.__v.__b-e.__v.__b},En.__r=0,ea=/(PointerCapture)$|Capture$/i,Is=0,Rs=aa(!1),As=aa(!0),ta=0;var ef=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:--ef,__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 K.vnode&&K.vnode(c),c}function Ps(){return(Ps=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 tf=["context","children"];function nf(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,tf);return Ms(e,i)}function sf(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ze(nf,Ps({},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[ha(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Ze(fa,{name:u},c):s[r]=c}var d=n?Ze(fa,null,s):s;return Ze(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?ua:In)(this._vdom,this._root)}function ha(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function of(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[ha(t)]=i,this._vdom=Ms(this._vdom,n),In(this._vdom,this._root)}}function rf(){In(this._vdom=null,this._root)}function fa(t,e){var i=this;return Ze("slot",Ps({},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 af(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=sf,s.prototype.attributeChangedCallback=of,s.prototype.disconnectedCallback=rf,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,Ns,pa,$i=0,ga=[],Se=K,ma=Se.__b,va=Se.__r,_a=Se.diffed,ya=Se.__c,ba=Se.unmount,wa=Se.__;function ui(t,e){Se.__h&&Se.__h(_e,t,$i||e),$i=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return $i=1,Sa(Ta,t)}function Sa(t,e,i){var n=ui(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):Ta(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=ui(Mt++,3);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Fs(t,e){var i=ui(Mt++,4);!Se.__s&&Us(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function ue(t){return $i=5,Qe(function(){return{current:t}},[])}function Qe(t,e){var i=ui(Mt++,7);return Us(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ge(t,e){return $i=8,Qe(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=ui(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function lf(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Bs(){var t=ui(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 cf(){for(var t;t=ga.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Rn),t.__H.__h.forEach(Vs),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,ma&&ma(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),wa&&wa(t,e)},Se.__r=function(t){va&&va(t),Mt=0;var e=(_e=t.__c).__H;e&&(Ns===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Rn),e.__h.forEach(Vs),e.__h=[],Mt=0)),Ns=_e},Se.diffed=function(t){_a&&_a(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ga.push(e)!==1&&pa===Se.requestAnimationFrame||((pa=Se.requestAnimationFrame)||df)(cf)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Ns=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Rn),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)}}),ya&&ya(t,e)},Se.unmount=function(t){ba&&ba(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Rn(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var Ca=typeof requestAnimationFrame=="function";function df(t){var e,i=function(){clearTimeout(n),Ca&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Ca&&(e=requestAnimationFrame(i))}function Rn(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 Us(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ta(t,e){return typeof e=="function"?e(t):e}const ji={},Ea=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,ka=t=>"init"in t,$s=t=>!!t.write,Ia=t=>"v"in t||"e"in t,An=t=>{if("e"in t)throw t.e;if((ji?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},xn=new WeakMap,Ra=t=>{var e;return Ln(t)&&!!((e=xn.get(t))!=null&&e[0])},uf=t=>{const e=xn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},Aa=(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)},Ln=t=>typeof(t==null?void 0:t.then)=="function",xa=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},js=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Ln(e))for(const r of n.d.keys())xa(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Ln(o)&&uf(o))},La=(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},hf=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Hs=()=>{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},ff=t=>(t.c||(t.c=Hs()),t.m||(t.m=Hs()),t.u||(t.u=Hs()),t.f||(t.f=hf()),t),pf=Symbol(),Da=(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((ji?"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,O)),E}),p=d[1]||(()=>{const T=[],E=g=>{try{g()}catch(m){T.push(m)}};do{r.f&&E(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(E),n.size&&_()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),_=d[2]||(()=>{const T=[],E=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(E.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if((ji?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");g.add(f),m.pop();continue}E.add(f);for(const I of La(f,S,e))E.has(I)||m.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let A=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){A=!0;break}A&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const g=h(T);if(Ia(g)&&(e.has(T)&&i.get(T)!==g.n||Array.from(g.d).every(([M,F])=>v(M).n===F)))return g;g.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),_(),p())},S=M=>{var F;if(Ea(T,M)){const U=h(M);if(!Ia(U))if(ka(M))js(M,M.init,h);else throw new Error("no atom init");return An(U)}const G=v(M);try{return An(G)}finally{g.d.set(M,G.n),Ra(g.v)&&xa(T,g.v,G),(F=e.get(M))==null||F.t.add(T),m||f()}};let I,A;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(ji?"production":void 0)!=="production"&&!$s(T)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&$s(T)&&(A=(...M)=>{if((ji?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return w(T,...M)}finally{_(),p()}}),A}},N=g.n;try{const M=a(T,S,x);return js(T,M,h),Ln(M)&&(Aa(M,()=>I==null?void 0:I.abort()),M.then(f,f)),g}catch(M){return delete g.v,g.e=M,++g.n,g}finally{m=!1,N!==g.n&&i.get(T)===N&&(i.set(T,g.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const g=E.pop(),m=h(g);for(const f of La(g,m,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),w=d[5]||((T,...E)=>{let g=!0;const m=S=>An(v(S)),f=(S,...I)=>{var A;const x=h(S);try{if(Ea(T,S)){if(!ka(S))throw new Error("atom not writable");const N=x.n,M=I[0];js(S,M,h),C(S),N!==x.n&&(n.add(S),(A=r.c)==null||A.call(r,S),b(S));return}else return w(S,...I)}finally{g||(_(),p())}};try{return l(T,m,f,...E)}finally{g=!1}}),C=d[6]||(T=>{var E;const g=h(T),m=e.get(T);if(m&&!Ra(g.v)){for(const[f,S]of g.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(T),m.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of m.d||[])if(!g.d.has(f)){m.d.delete(f);const S=L(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const g=h(T);let m=e.get(T);if(!m){v(T);for(const f of g.d.keys())k(f).t.add(T);if(m={l:new Set,d:new Set(g.d.keys()),t:new Set},e.set(T,m),(E=r.m)==null||E.call(r,T),$s(T)){const f=()=>{let S=!0;const I=(...A)=>{try{return w(T,...A)}finally{S||(_(),p())}};try{const A=u(T,I);A&&(m.u=()=>{S=!0;try{A()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return m}),L=d[8]||(T=>{var E;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),(E=r.u)==null||E.call(r,T);for(const f of g.d.keys()){const S=L(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,b,w,C,k,L],O={get:T=>An(v(T)),set:(T,...E)=>{try{return w(T,...E)}finally{_(),p()}},sub:(T,E)=>{const m=k(T).l;return m.add(E),p(),()=>{m.delete(E),L(T),p()}}};return Object.defineProperty(O,pf,{value:R}),O},gf=ff,Oa=Aa,Ws={};let mf=0;function Dn(t,e){const i=`atom${++mf}`,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=vf,n.write=_f),n}function vf(t){return t(this)}function _f(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const yf=()=>{let t=0;const e=gf({}),i=new WeakMap,n=new WeakMap,s=Da(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 bf(){return(Ws?"production":void 0)!=="production"?yf():Da()}let Hi;function wf(){return Hi||(Hi=bf(),(Ws?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Hi),globalThis.__JOTAI_DEFAULT_STORE__!==Hi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Hi}function Ma(t,e){for(var i in e)t[i]=e[i];return t}function Pa(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 Na=Fs;function Fa(t,e){this.props=t,this.context=e}(Fa.prototype=new at).isPureReactComponent=!0,Fa.prototype.shouldComponentUpdate=function(t,e){return Pa(this.props,t)||Pa(this.state,e)};var Ba=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ba&&Ba(t)};var Sf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Cf(t){function e(i){var n=Ma({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=Sf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var Va=function(t,e){return t==null?null:ft(ft(t).map(e))},Tf={map:Va,forEach:Va,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},Ef=K.__e;K.__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)}Ef(t,e,i,n)};var Ua=K.unmount;function $a(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=Ma({},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 $a(n,e,i)})),t}function ja(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return ja(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 Gs(){this.__u=0,this.o=null,this.__b=null}function Ha(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function On(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),Ua&&Ua(t)},(Gs.prototype=new at).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Ha(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]=ja(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)},Gs.prototype.componentWillUnmount=function(){this.o=[]},Gs.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]=$a(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Ze(ht,null,t.fallback);return s&&(s.__u&=-33),[Ze(ht,null,e.__a?null:t.children),s]};var Wa=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]}};(On.prototype=new at).__a=function(t){var e=this,i=Ha(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Wa(e,t,n)):s()};i?i(o):o()}},On.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},On.prototype.componentDidUpdate=On.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Wa(t,i,e)})};var Ga=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,kf=/^(?: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]/,If=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Rf=/[A-Z0-9]/g,Af=typeof document<"u",xf=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};at.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(at.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var qa=K.event;function Lf(){}function Df(){return this.cancelBubble}function Of(){return this.defaultPrevented}K.event=function(t){return qa&&(t=qa(t)),t.persist=Lf,t.isPropagationStopped=Df,t.isDefaultPrevented=Of,t.nativeEvent=t};var Mf={enumerable:!1,configurable:!0,get:function(){return this.class}},za=K.vnode;K.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||Af&&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"||xf(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":If.test(r)&&(r=l):l=r="oninput":o&&kf.test(r)?r=r.replace(Rf,"-$&").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",Mf)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=Ga,za&&za(t)};var Ka=K.__r;K.__r=function(t){Ka&&Ka(t),t.__c};var Ya=K.diffed;K.diffed=function(t){Ya&&Ya(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 Xa(t){return!!t&&t.$$typeof===Ga}function Pf(t){return Xa(t)?Ms.apply(null,arguments):t}var Ja={};const Nf={},Ff=kt(void 0);function Za(t){return De(Ff)||wf()}const qs=t=>typeof(t==null?void 0:t.then)=="function",zs=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Bf=Ja.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(zs(t),t)}),Ks=new WeakMap,Qa=(t,e)=>{let i=Ks.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();qs(c)?(Ks.set(c,i),o=c,c.then(r(c),a(c)),Oa(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),Oa(t,l)}),Ks.set(t,i)),i};function Ys(t,e){const{delay:i,unstable_promiseStatus:n=!Ja.use}={},s=Za(),[[o,r,a],l]=Sa(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);qs(d)&&zs(Qa(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),lf(c),qs(c)){const u=Qa(c,()=>s.get(t));return n&&zs(u),Bf(u)}return c}function Mn(t,e){const i=Za();return Ge((...s)=>{if((Nf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function el(t,e){return[Ys(t),Mn(t)]}const Xs=kt({});function Pn(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const Js=typeof window<"u",tl=Js?Fs:xe,Nn=kt(null);function Zs(t,e){t.indexOf(e)===-1&&t.push(e)}function Qs(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 eo=()=>{};const Rt={},il=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function nl(t){return typeof t=="object"&&t!==null}const sl=t=>/^0[^.\s]+$/u.test(t);function to(t){let e;return()=>(e===void 0&&(e=t()),e)}const et=t=>t,Vf=(t,e)=>i=>e(t(i)),Wi=(...t)=>t.reduce(Vf),Gi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class io{constructor(){this.subscriptions=[]}add(e){return Zs(this.subscriptions,e),()=>Qs(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 ol(t,e){return e?t*(1e3/e):0}const rl=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Uf=1e-7,$f=12;function jf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=rl(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Uf&&++a<$f);return r}function qi(t,e,i,n){if(t===e&&i===n)return et;const s=o=>jf(o,0,1,t,i);return o=>o===0||o===1?o:rl(s(o),e,n)}const al=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,ll=t=>e=>1-t(1-e),cl=qi(.33,1.53,.69,.99),no=ll(cl),dl=al(no),ul=t=>(t*=2)<1?.5*no(t):.5*(2-Math.pow(2,-10*(t-1))),so=t=>1-Math.sin(Math.acos(t)),hl=ll(so),fl=al(so),Hf=qi(.42,0,1,1),Wf=qi(0,0,.58,1),pl=qi(.42,0,.58,1),Gf=t=>Array.isArray(t)&&typeof t[0]!="number",gl=t=>Array.isArray(t)&&typeof t[0]=="number",qf={linear:et,easeIn:Hf,easeInOut:pl,easeOut:Wf,circIn:so,circInOut:fl,circOut:hl,backIn:no,backInOut:dl,backOut:cl,anticipate:ul},zf=t=>typeof t=="string",ml=t=>{if(gl(t)){eo(t.length===4);const[e,i,n,s]=t;return qi(e,i,n,s)}else if(zf(t))return qf[t];return t},Fn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],vl={value:null};function Kf(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&&vl.value&&vl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Yf=40;function _l(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Fn.reduce((k,L)=>(k[L]=Kf(o,e?L:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:_}=r,v=()=>{const k=Rt.useManualTiming?s.timestamp:performance.now();i=!1,Rt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Yf),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),p.process(s),_.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:Fn.reduce((k,L)=>{const R=r[L];return k[L]=(O,T=!1,E=!1)=>(i||b(),R.schedule(O,T,E)),k},{}),cancel:k=>{for(let L=0;L<Fn.length;L++)r[Fn[L]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:oo}=_l(typeof requestAnimationFrame<"u"?requestAnimationFrame:et,!0);let Bn;function Xf(){Bn=void 0}const qe={now:()=>(Bn===void 0&&qe.set(Pe.isProcessing||Rt.useManualTiming?Pe.timestamp:performance.now()),Bn),set:t=>{Bn=t,queueMicrotask(Xf)}},yl=t=>e=>typeof e=="string"&&e.startsWith(t),ro=yl("--"),Jf=yl("var(--"),ao=t=>Jf(t)?Zf.test(t.split("/*")[0].trim()):!1,Zf=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,hi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},zi={...hi,transform:t=>It(0,1,t)},Vn={...hi,default:1},Ki=t=>Math.round(t*1e5)/1e5,lo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Qf(t){return t==null}const ep=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,co=(t,e)=>i=>!!(typeof i=="string"&&ep.test(i)&&i.startsWith(t)||e&&!Qf(i)&&Object.prototype.hasOwnProperty.call(i,e)),bl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(lo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},tp=t=>It(0,255,t),uo={...hi,transform:t=>Math.round(tp(t))},zt={test:co("rgb","red"),parse:bl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+uo.transform(t)+", "+uo.transform(e)+", "+uo.transform(i)+", "+Ki(zi.transform(n))+")"};function ip(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 ho={test:co("#"),parse:ip,transform:zt.transform},Yi=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Yi("deg"),mt=Yi("%"),Y=Yi("px"),np=Yi("vh"),sp=Yi("vw"),wl={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},fi={test:co("hsl","hue"),parse:bl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(Ki(e))+", "+mt.transform(Ki(i))+", "+Ki(zi.transform(n))+")"},Ie={test:t=>zt.test(t)||ho.test(t)||fi.test(t),parse:t=>zt.test(t)?zt.parse(t):fi.test(t)?fi.parse(t):ho.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):fi.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},op=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function rp(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(lo))==null?void 0:e.length)||0)+(((i=t.match(op))==null?void 0:i.length)||0)>0}const Sl="number",Cl="color",ap="var",lp="var(",Tl="${}",cp=/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 Xi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(cp,l=>(Ie.test(l)?(n.color.push(o),s.push(Cl),i.push(Ie.parse(l))):l.startsWith(lp)?(n.var.push(o),s.push(ap),i.push(l)):(n.number.push(o),s.push(Sl),i.push(parseFloat(l))),++o,Tl)).split(Tl);return{values:i,split:a,indexes:n,types:s}}function El(t){return Xi(t).values}function kl(t){const{split:e,types:i}=Xi(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===Sl?o+=Ki(s[r]):a===Cl?o+=Ie.transform(s[r]):o+=s[r]}return o}}const dp=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function up(t){const e=El(t);return kl(t)(e.map(dp))}const Ft={test:rp,parse:El,createTransformer:kl,getAnimatableNone:up};function fo(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 hp({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=fo(l,a,t+1/3),o=fo(l,a,t),r=fo(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Un(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,po=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},fp=[ho,zt,fi],pp=t=>fp.find(e=>e.test(t));function Il(t){const e=pp(t);if(!e)return!1;let i=e.parse(t);return e===fi&&(i=hp(i)),i}const Rl=(t,e)=>{const i=Il(t),n=Il(e);if(!i||!n)return Un(t,e);const s={...i};return o=>(s.red=po(i.red,n.red,o),s.green=po(i.green,n.green,o),s.blue=po(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},go=new Set(["none","hidden"]);function gp(t,e){return go.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function mp(t,e){return i=>Ce(t,e,i)}function mo(t){return typeof t=="number"?mp:typeof t=="string"?ao(t)?Un:Ie.test(t)?Rl:yp:Array.isArray(t)?Al:typeof t=="object"?Ie.test(t)?Rl:vp:Un}function Al(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>mo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function vp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=mo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function _p(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 yp=(t,e)=>{const i=Ft.createTransformer(e),n=Xi(t),s=Xi(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?go.has(t)&&!s.values.length||go.has(e)&&!n.values.length?gp(t,e):Wi(Al(_p(n,s),s.values),i):Un(t,e)};function xl(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):mo(t)(t,e)}const bp=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:qe.now()}},Ll=(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)})`},$n=2e4;function vo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<$n;)e+=i,n=t.next(e);return e>=$n?1/0:e}function wp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(vo(n),$n);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const Sp=5;function Dl(t,e,i){const n=Math.max(e-Sp,0);return ol(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},_o=.001;function Cp({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=yo(c,r),_=Math.exp(-d);return _o-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=yo(Math.pow(c,2),r);return(-s(c)+_o>0?-1:1)*((h-p)*_)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-_o+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Ep(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 Tp=12;function Ep(t,e,i){let n=i;for(let s=1;s<Tp;s++)n=n-t(n)/e(n);return n}function yo(t,e){return t*Math.sqrt(1-e*e)}const kp=["duration","bounce"],Ip=["stiffness","damping","mass"];function Ol(t,e){return e.some(i=>t[i]!==void 0)}function Rp(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!Ol(t,Ip)&&Ol(t,kp))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=Cp(t);e={...e,...i,mass:Te.mass},e.isResolvedFromDuration=!0}return e}function jn(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}=Rp({...i,velocity:-gt(i.velocity||0)}),_=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,w=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 R=yo(w,v);k=O=>{const T=Math.exp(-v*w*O);return r-T*((_+v*w*b)/R*Math.sin(R*O)+b*Math.cos(R*O))}}else if(v===1)k=R=>r-Math.exp(-w*R)*(b+(_+w*b)*R);else{const R=w*Math.sqrt(v*v-1);k=O=>{const T=Math.exp(-v*w*O),E=Math.min(R*O,300);return r-T*((_+v*w*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const L={calculatedDuration:p&&d||null,next:R=>{const O=k(R);if(p)a.done=R>=d;else{let T=R===0?_:0;v<1&&(T=R===0?pt(_):Dl(k,R,O));const E=Math.abs(T)<=n,g=Math.abs(r-O)<=s;a.done=E&&g}return a.value=a.done?r:O,a},toString:()=>{const R=Math.min(vo(L),$n),O=Ll(T=>L.next(R*T).value,R,30);return R+"ms "+O},toTransition:()=>{}};return L}jn.applyToOptions=t=>{const e=wp(t,100,jn);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function bo({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=E=>a!==void 0&&E<a||l!==void 0&&E>l,_=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,w=r===void 0?b:r(b);w!==b&&(v=w-d);const C=E=>-v*Math.exp(-E/n),k=E=>w+C(E),L=E=>{const g=C(E),m=k(E);h.done=Math.abs(g)<=c,h.value=h.done?w:m};let R,O;const T=E=>{p(h.value)&&(R=E,O=jn({keyframes:[h.value,_(h.value)],velocity:Dl(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let g=!1;return!O&&R===void 0&&(g=!0,L(E),T(E)),R!==void 0&&E>=R?O.next(E-R):(!g&&L(E),h)}}}function Ap(t,e,i){const n=[],s=i||Rt.mix||xl,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]||et:e;a=Wi(l,a)}n.push(a)}return n}function xp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(eo(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=Ap(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=Gi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Lp(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Gi(0,e,n);t.push(Ce(i,1,s))}}function Dp(t){const e=[0];return Lp(e,t.length-1),e}function Op(t,e){return t.map(i=>i*e)}function Mp(t,e){return t.map(()=>e||pl).splice(0,t.length-1)}function Ji({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Gf(n)?n.map(ml):ml(n),o={done:!1,value:e[0]},r=Op(i&&i.length===e.length?i:Dp(e),t),a=xp(r,e,{ease:Array.isArray(s)?s:Mp(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Pp=t=>t!==null;function wo(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Pp),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Np={decay:bo,inertia:bo,tween:Ji,keyframes:Ji,spring:jn};function Ml(t){typeof t.type=="string"&&(t.type=Np[t.type])}class So{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 Fp=t=>t/100;class Co extends So{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!==qe.now()&&this.tick(qe.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;Ml(e);const{type:i=Ji,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Ji;l!==Ji&&typeof a[0]!="number"&&(this.mixKeyframes=Wi(Fp,xl(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=vo(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: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 w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,L=n;if(d){const E=Math.min(this.currentTime,s)/a;let g=Math.floor(E),m=E%1;!m&&E>=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"&&(L=r)),k=It(0,1,m)*a}const R=C?{done:!1,value:u[0]}:L.next(k);o&&(R.value=o(R.value));let{done:O}=R;!C&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return T&&_!==bo&&(R.value=wo(u,this.options,b,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(qe.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=bp,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(qe.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 Bp(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,To=t=>{const e=Kt(Math.atan2(t[1],t[0]));return Eo(e)},Vp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:To,rotateZ:To,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},Eo=t=>(t=t%360,t<0&&(t+=360),t),Pl=To,Nl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Fl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Up={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Nl,scaleY:Fl,scale:t=>(Nl(t)+Fl(t))/2,rotateX:t=>Eo(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>Eo(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Pl,rotate:Pl,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=Up,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Vp,s=a}if(!s)return ko(e);const o=n[e],r=s[1].split(",").map(jp);return typeof o=="function"?o(r):r[o]}const $p=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Io(i,e)};function jp(t){return parseFloat(t.trim())}const pi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],gi=new Set(pi),Bl=t=>t===hi||t===Y,Hp=new Set(["x","y","z"]),Wp=pi.filter(t=>!Hp.has(t));function Gp(t){const e=[];return Wp.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 Ro=!1,Ao=!1,xo=!1;function Vl(){if(Ao){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=Gp(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)})}Ao=!1,Ro=!1,Xt.forEach(t=>t.complete(xo)),Xt.clear()}function Ul(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ao=!0)})}function qp(){xo=!0,Ul(),Vl(),xo=!1}class Lo{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),Ro||(Ro=!0,we.read(Ul),we.resolveKeyframes(Vl))):(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])}Bp(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 zp=t=>t.startsWith("--");function Kp(t,e,i){zp(e)?t.style.setProperty(e,i):t.style[e]=i}const Yp=to(()=>window.ScrollTimeline!==void 0),Xp={};function Jp(t,e){const i=to(t);return()=>Xp[e]??i()}const $l=Jp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zi=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,jl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zi([0,.65,.55,1]),circOut:Zi([.55,0,1,.45]),backIn:Zi([.31,.01,.66,-.59]),backOut:Zi([.33,1.53,.69,.99])};function Hl(t,e){if(t)return typeof t=="function"?$l()?Ll(t,e):"ease-out":gl(t)?Zi(t):Array.isArray(t)?t.map(i=>Hl(i,e)||jl.easeOut):jl[t]}function Zp(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=Hl(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 Wl(t){return typeof t=="function"&&"applyToOptions"in t}function Qp({type:t,...e}){return Wl(t)&&$l()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class eg extends So{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,eo(typeof e.type!="string");const c=Qp(e);this.animation=Zp(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=wo(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Kp(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&&Yp()?(this.animation.timeline=e,et):i(this)}}const Gl={anticipate:ul,backInOut:dl,circInOut:fl};function tg(t){return t in Gl}function ig(t){typeof t.ease=="string"&&tg(t.ease)&&(t.ease=Gl[t.ease])}const ql=10;class ng extends eg{constructor(e){ig(e),Ml(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 Co({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-ql).value,a.sample(l).value,ql),a.stop()}}const zl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function sg(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 og(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=zl(s,e),a=zl(o,e);return!r||!a?!1:sg(t)||(i==="spring"||Wl(i))&&n}function Do(t){return nl(t)&&"offsetHeight"in t}const rg=new Set(["opacity","clipPath","filter","transform"]),ag=to(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function lg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Do((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return ag()&&i&&rg.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const cg=40;class dg extends So{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,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=qe.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)||Lo;this.keyframeResolver=new p(a,(v,b,w)=>this.onKeyframesResolved(v,b,h,!w),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=qe.now(),og(e,o,r,a)||((Rt.instantAnimations||!l)&&(u==null||u(wo(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>cg?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&lg(h)?new ng({...h,element:h.motionValue.owner.current}):new Co(h);p.finished.then(()=>this.notifyFinished()).catch(et),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(),qp()),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 ug=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function hg(t){const e=ug.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Kl(t,e,i=1){const[n,s]=hg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return il(r)?parseFloat(r):r}return ao(s)?Kl(s,e,i+1):s}function Oo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Yl=new Set(["width","height","top","left","right","bottom",...pi]),fg={test:t=>t==="auto",parse:t=>t},Xl=t=>e=>e.test(t),Jl=[hi,Y,mt,Nt,sp,np,fg],Zl=t=>Jl.find(Xl(t));function pg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||sl(t):!0}const gg=new Set(["brightness","contrast","saturate","opacity"]);function mg(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(lo)||[];if(!n)return t;const s=i.replace(n,"");let o=gg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const vg=/\b([a-z-]*)\(.*?\)/gu,Mo={...Ft,getAnimatableNone:t=>{const e=t.match(vg);return e?e.map(mg).join(" "):t}},Ql={...hi,transform:Math.round},Po={borderWidth:Y,borderTopWidth:Y,borderRightWidth:Y,borderBottomWidth:Y,borderLeftWidth:Y,borderRadius:Y,radius:Y,borderTopLeftRadius:Y,borderTopRightRadius:Y,borderBottomRightRadius:Y,borderBottomLeftRadius:Y,width:Y,maxWidth:Y,height:Y,maxHeight:Y,top:Y,right:Y,bottom:Y,left:Y,padding:Y,paddingTop:Y,paddingRight:Y,paddingBottom:Y,paddingLeft:Y,margin:Y,marginTop:Y,marginRight:Y,marginBottom:Y,marginLeft:Y,backgroundPositionX:Y,backgroundPositionY:Y,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Vn,scaleX:Vn,scaleY:Vn,scaleZ:Vn,skew:Nt,skewX:Nt,skewY:Nt,distance:Y,translateX:Y,translateY:Y,translateZ:Y,x:Y,y:Y,z:Y,perspective:Y,transformPerspective:Y,opacity:zi,originX:wl,originY:wl,originZ:Y},zIndex:Ql,fillOpacity:zi,strokeOpacity:zi,numOctaves:Ql},_g={...Po,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:Mo,WebkitFilter:Mo},ec=t=>_g[t];function tc(t,e){let i=ec(t);return i!==Mo&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const yg=new Set(["auto","none","0"]);function bg(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!yg.has(o)&&Xi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=tc(i,s)}class wg extends Lo{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(),ao(c))){const u=Kl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Yl.has(n)||e.length!==2)return;const[s,o]=e,r=Zl(s),a=Zl(o);if(r!==a)if(Bl(r)&&Bl(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||pg(e[s]))&&n.push(s);n.length&&bg(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 Sg(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 ic=(t,e)=>e&&typeof t=="number"?e.transform(t):t,nc=30,Cg=t=>!isNaN(parseFloat(t));class Tg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=qe.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=qe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Cg(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,i){this.events[e]||(this.events[e]=new io);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=qe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>nc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,nc);return ol(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 mi(t,e){return new Tg(t,e)}const{schedule:No}=_l(queueMicrotask,!1),lt={x:!1,y:!1};function sc(){return lt.x||lt.y}function Eg(t){return t==="x"||t==="y"?lt[t]?null:(lt[t]=!0,()=>{lt[t]=!1}):lt.x||lt.y?null:(lt.x=lt.y=!0,()=>{lt.x=lt.y=!1})}function oc(t,e){const i=Sg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function rc(t){return!(t.pointerType==="touch"||sc())}function kg(t,e,i={}){const[n,s,o]=oc(t,i),r=a=>{if(!rc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{rc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const ac=(t,e)=>e?t===e?!0:ac(t,e.parentElement):!1,Fo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ig=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Rg(t){return Ig.has(t.tagName)||t.tabIndex!==-1}const Hn=new WeakSet;function lc(t){return e=>{e.key==="Enter"&&t(e)}}function Bo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Ag=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=lc(()=>{if(Hn.has(i))return;Bo(i,"down");const s=lc(()=>{Bo(i,"up")}),o=()=>Bo(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 cc(t){return Fo(t)&&!sc()}function xg(t,e,i={}){const[n,s,o]=oc(t,i),r=a=>{const l=a.currentTarget;if(!cc(a))return;Hn.add(l);const c=e(l,a),u=(p,_)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Hn.has(l)&&Hn.delete(l),cc(p)&&typeof c=="function"&&c(p,{success:_})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||ac(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),Do(a)&&(a.addEventListener("focus",c=>Ag(c,s)),!Rg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function dc(t){return nl(t)&&"ownerSVGElement"in t}function Lg(t){return dc(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),Dg=[...Jl,Ie,Ft],Og=t=>Dg.find(Xl(t)),Qi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Mg extends at{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Do(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 Pg({children:t,isPresent:e,anchorX:i,root:n}){const s=Bs(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(Qi);return Na(()=>{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(`
1
+ var Tw=Object.defineProperty;var Ew=(rt,K,Gt)=>K in rt?Tw(rt,K,{enumerable:!0,configurable:!0,writable:!0,value:Gt}):rt[K]=Gt;var $=(rt,K,Gt)=>Ew(rt,typeof K!="symbol"?K+"":K,Gt);(function(){"use strict";var rt,K,Gt,qt,Qr,ea,ta,ia,As,xs,Ls,na,Bi={},sa=[],Jh=/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 Ds(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Ze(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?rt.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 Ui(t,r,n,s,null)}function Ui(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&&K.vnode!=null&&K.vnode(o),o}function ht(t){return t.children}function at(t,e){this.props=t,this.context=e}function di(t,e){if(e==null)return t.__?di(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"?di(t):null}function oa(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 oa(t)}}function Os(t){(!t.__d&&(t.__d=!0)&&qt.push(t)&&!En.__r++||Qr!=K.debounceRendering)&&((Qr=K.debounceRendering)||ea)(En)}function En(){for(var t,e,i,n,s,o,r,a=1;qt.length;)qt.length>a&&qt.sort(ta),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,K.vnode&&K.vnode(i),Ms(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??di(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,da(o,i,r),i.__e!=s&&oa(i)));En.__r=0}function ra(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,_,v,b,w=n&&n.__k||sa,C=e.length;for(l=Zh(i,e,w,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Bi:w[p.__i]||Bi,p.__i=d,b=Ms(t,p,h,s,o,r,a,l,c,u),_=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&Ps(h.ref,null,p),u.push(p.ref,p.__c||_,p)),v==null&&_!=null&&(v=_),4&p.__u||h.__k===p.__k?l=aa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:_&&(l=_.nextSibling),p.__u&=-7);return i.__e=v,l}function Zh(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?Ui(null,r,null,null,null):Vi(r)?Ui(ht,{children:r},null,null,null):r.constructor==null&&r.__b>0?Ui(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=Qh(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=di(a)),ha(a,a));return n}function aa(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=aa(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=di(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 Qh(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 la(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||Jh.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||la(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||la(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(ia,"$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=As,t.addEventListener(e,o?Ls:xs,o)):t.removeEventListener(e,o?Ls:xs,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 ca(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=As++;else if(e.t<i.u)return;return i(K.event?K.event(e):e)}}}function Ms(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,_,v,b,w,C,k,L,R,O,T,E,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=K.__b)&&u(e);e:if(typeof f=="function")try{if(w=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],L=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(w,L):(e.__c=d=new at(w,L),d.constructor=f,d.render=tf),k&&k.sub(d),d.props=w,d.state||(d.state={}),d.context=L,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(w,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&&w!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(w,L),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(w,d.__s,L)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=w,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(w,d.__s,L),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,_,v)})}if(d.context=L,d.props=w,d.__P=t,d.__e=!1,O=K.__r,T=0,C){for(d.state=d.__s,d.__d=!1,O&&O(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,O&&O(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=ua(u.props.children)),a=ra(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),b&&(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--;)Ds(o[m]);else e.__e=i.__e,e.__k=i.__k;K.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=ef(i.__e,e,i,n,s,o,r,l,c);return(u=K.diffed)&&u(e),128&e.__u?void 0:a}function da(t,e,i){for(var n=0;n<i.length;n++)Ps(i[n],i[++n],i[++n]);K.__c&&K.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){K.__e(o,s.__v)}})}function ua(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Vi(t)?t.map(ua):ut({},t)}function ef(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,_,v,b=i.props,w=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(w);t=document.createElementNS(s,C,w.is&&w),a&&(K.__m&&K.__m(e,o),a=!1),o=null}if(C==null)b===w||a&&t.data==w||(t.data=w);else{if(o=o&&rt.call(t.childNodes),b=i.props||Bi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=p;else if(!(c in w)){if(c=="value"&&"defaultValue"in w||c=="checked"&&"defaultChecked"in w)continue;kn(t,c,null,p,s)}}for(c in w)p=w[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?_=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||kn(t,c,p,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=""),ra(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&&di(i,0),a,l),o!=null)for(c=o.length;c--;)Ds(o[c]);a||(c="value",C=="progress"&&_==null?t.removeAttribute("value"):_!=null&&(_!==t[c]||C=="progress"&&!_||C=="option"&&_!=b[c])&&kn(t,c,_,b[c],s),c="checked",v!=null&&v!=t[c]&&kn(t,c,v,b[c],s))}return t}function Ps(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){K.__e(s,i)}}function ha(t,e,i){var n,s;if(K.unmount&&K.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||Ps(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){K.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&ha(n[s],e,i||typeof t.type!="function");i||Ds(t.__e),t.__c=t.__=t.__e=void 0}function tf(t,e,i){return this.constructor(t,i)}function In(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),K.__&&K.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],Ms(e,t=(!n&&i||e).__k=Ze(ht,null,[t]),s||Bi,Bi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?rt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),da(o,t,r)}function fa(t,e){In(t,e,fa)}function Ns(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?rt.call(arguments,2):i),Ui(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,Os(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"+na++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}rt=sa.slice,K={__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,at.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),Os(this))},at.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Os(this))},at.prototype.render=ht,qt=[],ea=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ta=function(t,e){return t.__v.__b-e.__v.__b},En.__r=0,ia=/(PointerCapture)$|Capture$/i,As=0,xs=ca(!1),Ls=ca(!0),na=0;var nf=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:--nf,__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 K.vnode&&K.vnode(c),c}function Fs(){return(Fs=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 sf=["context","children"];function of(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,sf);return Ns(e,i)}function rf(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=Ze(of,Fs({},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[pa(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=Ze(ga,{name:u},c):s[r]=c}var d=n?Ze(ga,null,s):s;return Ze(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?fa:In)(this._vdom,this._root)}function pa(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function af(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[pa(t)]=i,this._vdom=Ns(this._vdom,n),In(this._vdom,this._root)}}function lf(){In(this._vdom=null,this._root)}function ga(t,e){var i=this;return Ze("slot",Fs({},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 cf(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=rf,s.prototype.attributeChangedCallback=af,s.prototype.disconnectedCallback=lf,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,Bs,ma,ji=0,va=[],Se=K,_a=Se.__b,ya=Se.__r,ba=Se.diffed,wa=Se.__c,Sa=Se.unmount,Ca=Se.__;function ui(t,e){Se.__h&&Se.__h(_e,t,ji||e),ji=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return ji=1,Ta(ka,t)}function Ta(t,e,i){var n=ui(Mt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):ka(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=ui(Mt++,3);!Se.__s&&$s(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Vs(t,e){var i=ui(Mt++,4);!Se.__s&&$s(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function ue(t){return ji=5,Qe(function(){return{current:t}},[])}function Qe(t,e){var i=ui(Mt++,7);return $s(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ge(t,e){return ji=8,Qe(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=ui(Mt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function df(t,e){Se.useDebugValue&&Se.useDebugValue(e?e(t):t)}function Us(){var t=ui(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 uf(){for(var t;t=va.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Rn),t.__H.__h.forEach(js),t.__H.__h=[]}catch(e){t.__H.__h=[],Se.__e(e,t.__v)}}Se.__b=function(t){_e=null,_a&&_a(t)},Se.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ca&&Ca(t,e)},Se.__r=function(t){ya&&ya(t),Mt=0;var e=(_e=t.__c).__H;e&&(Bs===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Rn),e.__h.forEach(js),e.__h=[],Mt=0)),Bs=_e},Se.diffed=function(t){ba&&ba(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(va.push(e)!==1&&ma===Se.requestAnimationFrame||((ma=Se.requestAnimationFrame)||hf)(uf)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Bs=_e=null},Se.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Rn),i.__h=i.__h.filter(function(n){return!n.__||js(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Se.__e(n,i.__v)}}),wa&&wa(t,e)},Se.unmount=function(t){Sa&&Sa(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Rn(n)}catch(s){e=s}}),i.__H=void 0,e&&Se.__e(e,i.__v))};var Ea=typeof requestAnimationFrame=="function";function hf(t){var e,i=function(){clearTimeout(n),Ea&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Ea&&(e=requestAnimationFrame(i))}function Rn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function js(t){var e=_e;t.__c=t.__(),_e=e}function $s(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function ka(t,e){return typeof e=="function"?e(t):e}const $i={},Ia=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Ra=t=>"init"in t,Hs=t=>!!t.write,Aa=t=>"v"in t||"e"in t,An=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},xn=new WeakMap,xa=t=>{var e;return Ln(t)&&!!((e=xn.get(t))!=null&&e[0])},ff=t=>{const e=xn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},La=(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)},Ln=t=>typeof(t==null?void 0:t.then)=="function",Da=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},Ws=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Ln(e))for(const r of n.d.keys())Da(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Ln(o)&&ff(o))},Oa=(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},pf=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},Gs=()=>{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},gf=t=>(t.c||(t.c=Gs()),t.m||(t.m=Gs()),t.u||(t.u=Gs()),t.f||(t.f=pf()),t),mf=Symbol(),Ma=(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 E=t.get(T);return E||(E={d:new Map,p:new Set,n:0},t.set(T,E),c==null||c(T,O)),E}),p=d[1]||(()=>{const T=[],E=g=>{try{g()}catch(m){T.push(m)}};do{r.f&&E(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(E),n.size&&_()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),_=d[2]||(()=>{const T=[],E=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(E.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}E.add(f);for(const I of Oa(f,S,e))E.has(I)||m.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let A=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){A=!0;break}A&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const g=h(T);if(Aa(g)&&(e.has(T)&&i.get(T)!==g.n||Array.from(g.d).every(([M,F])=>v(M).n===F)))return g;g.d.clear();let m=!0;const f=()=>{e.has(T)&&(C(T),_(),p())},S=M=>{var F;if(Ia(T,M)){const U=h(M);if(!Aa(U))if(Ra(M))Ws(M,M.init,h);else throw new Error("no atom init");return An(U)}const G=v(M);try{return An(G)}finally{g.d.set(M,G.n),xa(g.v)&&Da(T,g.v,G),(F=e.get(M))==null||F.t.add(T),m||f()}};let I,A;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return($i?"production":void 0)!=="production"&&!Hs(T)&&console.warn("setSelf function cannot be used with read-only atom"),!A&&Hs(T)&&(A=(...M)=>{if(($i?"production":void 0)!=="production"&&m&&console.warn("setSelf function cannot be called in sync"),!m)try{return w(T,...M)}finally{_(),p()}}),A}},N=g.n;try{const M=a(T,S,x);return Ws(T,M,h),Ln(M)&&(La(M,()=>I==null?void 0:I.abort()),M.then(f,f)),g}catch(M){return delete g.v,g.e=M,++g.n,g}finally{m=!1,N!==g.n&&i.get(T)===N&&(i.set(T,g.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const g=E.pop(),m=h(g);for(const f of Oa(g,m,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),w=d[5]||((T,...E)=>{let g=!0;const m=S=>An(v(S)),f=(S,...I)=>{var A;const x=h(S);try{if(Ia(T,S)){if(!Ra(S))throw new Error("atom not writable");const N=x.n,M=I[0];Ws(S,M,h),C(S),N!==x.n&&(n.add(S),(A=r.c)==null||A.call(r,S),b(S));return}else return w(S,...I)}finally{g||(_(),p())}};try{return l(T,m,f,...E)}finally{g=!1}}),C=d[6]||(T=>{var E;const g=h(T),m=e.get(T);if(m&&!xa(g.v)){for(const[f,S]of g.d)if(!m.d.has(f)){const I=h(f);k(f).t.add(T),m.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of m.d||[])if(!g.d.has(f)){m.d.delete(f);const S=L(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const g=h(T);let m=e.get(T);if(!m){v(T);for(const f of g.d.keys())k(f).t.add(T);if(m={l:new Set,d:new Set(g.d.keys()),t:new Set},e.set(T,m),(E=r.m)==null||E.call(r,T),Hs(T)){const f=()=>{let S=!0;const I=(...A)=>{try{return w(T,...A)}finally{S||(_(),p())}};try{const A=u(T,I);A&&(m.u=()=>{S=!0;try{A()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return m}),L=d[8]||(T=>{var E;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),(E=r.u)==null||E.call(r,T);for(const f of g.d.keys()){const S=L(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,b,w,C,k,L],O={get:T=>An(v(T)),set:(T,...E)=>{try{return w(T,...E)}finally{_(),p()}},sub:(T,E)=>{const m=k(T).l;return m.add(E),p(),()=>{m.delete(E),L(T),p()}}};return Object.defineProperty(O,mf,{value:R}),O},vf=gf,Pa=La,qs={};let _f=0;function Dn(t,e){const i=`atom${++_f}`,n={toString(){return(qs?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=yf,n.write=bf),n}function yf(t){return t(this)}function bf(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const wf=()=>{let t=0;const e=vf({}),i=new WeakMap,n=new WeakMap,s=Ma(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 Sf(){return(qs?"production":void 0)!=="production"?wf():Ma()}let Hi;function Cf(){return Hi||(Hi=Sf(),(qs?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Hi),globalThis.__JOTAI_DEFAULT_STORE__!==Hi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Hi}function Na(t,e){for(var i in e)t[i]=e[i];return t}function Fa(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 Ba=Vs;function Va(t,e){this.props=t,this.context=e}(Va.prototype=new at).isPureReactComponent=!0,Va.prototype.shouldComponentUpdate=function(t,e){return Fa(this.props,t)||Fa(this.state,e)};var Ua=K.__b;K.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),Ua&&Ua(t)};var Tf=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Ef(t){function e(i){var n=Na({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=Tf,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var ja=function(t,e){return t==null?null:ft(ft(t).map(e))},kf={map:ja,forEach:ja,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},If=K.__e;K.__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)}If(t,e,i,n)};var $a=K.unmount;function Ha(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=Na({},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 Ha(n,e,i)})),t}function Wa(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return Wa(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 zs(){this.__u=0,this.o=null,this.__b=null}function Ga(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function On(){this.i=null,this.l=null}K.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),$a&&$a(t)},(zs.prototype=new at).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=Ga(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]=Wa(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)},zs.prototype.componentWillUnmount=function(){this.o=[]},zs.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]=Ha(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&Ze(ht,null,t.fallback);return s&&(s.__u&=-33),[Ze(ht,null,e.__a?null:t.children),s]};var qa=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]}};(On.prototype=new at).__a=function(t){var e=this,i=Ga(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),qa(e,t,n)):s()};i?i(o):o()}},On.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},On.prototype.componentDidUpdate=On.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){qa(t,i,e)})};var za=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Rf=/^(?: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]/,Af=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,xf=/[A-Z0-9]/g,Lf=typeof document<"u",Df=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};at.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(at.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Ka=K.event;function Of(){}function Mf(){return this.cancelBubble}function Pf(){return this.defaultPrevented}K.event=function(t){return Ka&&(t=Ka(t)),t.persist=Of,t.isPropagationStopped=Mf,t.isDefaultPrevented=Pf,t.nativeEvent=t};var Nf={enumerable:!1,configurable:!0,get:function(){return this.class}},Ya=K.vnode;K.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||Lf&&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"||Df(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Af.test(r)&&(r=l):l=r="oninput":o&&Rf.test(r)?r=r.replace(xf,"-$&").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",Nf)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=za,Ya&&Ya(t)};var Xa=K.__r;K.__r=function(t){Xa&&Xa(t),t.__c};var Ja=K.diffed;K.diffed=function(t){Ja&&Ja(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===za}function Ff(t){return Za(t)?Ns.apply(null,arguments):t}var Qa={};const Bf={},Vf=kt(void 0);function el(t){return De(Vf)||Cf()}const Ks=t=>typeof(t==null?void 0:t.then)=="function",Ys=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Uf=Qa.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(Ys(t),t)}),Xs=new WeakMap,tl=(t,e)=>{let i=Xs.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();Ks(c)?(Xs.set(c,i),o=c,c.then(r(c),a(c)),Pa(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),Pa(t,l)}),Xs.set(t,i)),i};function Js(t,e){const{delay:i,unstable_promiseStatus:n=!Qa.use}={},s=el(),[[o,r,a],l]=Ta(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);Ks(d)&&Ys(tl(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),df(c),Ks(c)){const u=tl(c,()=>s.get(t));return n&&Ys(u),Uf(u)}return c}function Mn(t,e){const i=el();return Ge((...s)=>{if((Bf?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function il(t,e){return[Js(t),Mn(t)]}const Zs=kt({});function Pn(t){const e=ue(null);return e.current===null&&(e.current=t()),e.current}const Qs=typeof window<"u",nl=Qs?Vs:xe,Nn=kt(null);function eo(t,e){t.indexOf(e)===-1&&t.push(e)}function to(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 io=()=>{};const Rt={},sl=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function ol(t){return typeof t=="object"&&t!==null}const rl=t=>/^0[^.\s]+$/u.test(t);function no(t){let e;return()=>(e===void 0&&(e=t()),e)}const et=t=>t,jf=(t,e)=>i=>e(t(i)),Wi=(...t)=>t.reduce(jf),Gi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class so{constructor(){this.subscriptions=[]}add(e){return eo(this.subscriptions,e),()=>to(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 al(t,e){return e?t*(1e3/e):0}const ll=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,$f=1e-7,Hf=12;function Wf(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=ll(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>$f&&++a<Hf);return r}function qi(t,e,i,n){if(t===e&&i===n)return et;const s=o=>Wf(o,0,1,t,i);return o=>o===0||o===1?o:ll(s(o),e,n)}const cl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,dl=t=>e=>1-t(1-e),ul=qi(.33,1.53,.69,.99),oo=dl(ul),hl=cl(oo),fl=t=>(t*=2)<1?.5*oo(t):.5*(2-Math.pow(2,-10*(t-1))),ro=t=>1-Math.sin(Math.acos(t)),pl=dl(ro),gl=cl(ro),Gf=qi(.42,0,1,1),qf=qi(0,0,.58,1),ml=qi(.42,0,.58,1),zf=t=>Array.isArray(t)&&typeof t[0]!="number",vl=t=>Array.isArray(t)&&typeof t[0]=="number",Kf={linear:et,easeIn:Gf,easeInOut:ml,easeOut:qf,circIn:ro,circInOut:gl,circOut:pl,backIn:oo,backInOut:hl,backOut:ul,anticipate:fl},Yf=t=>typeof t=="string",_l=t=>{if(vl(t)){io(t.length===4);const[e,i,n,s]=t;return qi(e,i,n,s)}else if(Yf(t))return Kf[t];return t},Fn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],yl={value:null};function Xf(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&&yl.value&&yl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Jf=40;function bl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=Fn.reduce((k,L)=>(k[L]=Xf(o,e?L:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:_}=r,v=()=>{const k=Rt.useManualTiming?s.timestamp:performance.now();i=!1,Rt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Jf),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),p.process(s),_.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:Fn.reduce((k,L)=>{const R=r[L];return k[L]=(O,T=!1,E=!1)=>(i||b(),R.schedule(O,T,E)),k},{}),cancel:k=>{for(let L=0;L<Fn.length;L++)r[Fn[L]].cancel(k)},state:s,steps:r}}const{schedule:we,cancel:Pt,state:Pe,steps:ao}=bl(typeof requestAnimationFrame<"u"?requestAnimationFrame:et,!0);let Bn;function Zf(){Bn=void 0}const qe={now:()=>(Bn===void 0&&qe.set(Pe.isProcessing||Rt.useManualTiming?Pe.timestamp:performance.now()),Bn),set:t=>{Bn=t,queueMicrotask(Zf)}},wl=t=>e=>typeof e=="string"&&e.startsWith(t),lo=wl("--"),Qf=wl("var(--"),co=t=>Qf(t)?ep.test(t.split("/*")[0].trim()):!1,ep=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,hi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},zi={...hi,transform:t=>It(0,1,t)},Vn={...hi,default:1},Ki=t=>Math.round(t*1e5)/1e5,uo=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function tp(t){return t==null}const ip=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,ho=(t,e)=>i=>!!(typeof i=="string"&&ip.test(i)&&i.startsWith(t)||e&&!tp(i)&&Object.prototype.hasOwnProperty.call(i,e)),Sl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(uo);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},np=t=>It(0,255,t),fo={...hi,transform:t=>Math.round(np(t))},zt={test:ho("rgb","red"),parse:Sl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+fo.transform(t)+", "+fo.transform(e)+", "+fo.transform(i)+", "+Ki(zi.transform(n))+")"};function sp(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 po={test:ho("#"),parse:sp,transform:zt.transform},Yi=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Nt=Yi("deg"),mt=Yi("%"),Y=Yi("px"),op=Yi("vh"),rp=Yi("vw"),Cl={...mt,parse:t=>mt.parse(t)/100,transform:t=>mt.transform(t*100)},fi={test:ho("hsl","hue"),parse:Sl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+mt.transform(Ki(e))+", "+mt.transform(Ki(i))+", "+Ki(zi.transform(n))+")"},Ie={test:t=>zt.test(t)||po.test(t)||fi.test(t),parse:t=>zt.test(t)?zt.parse(t):fi.test(t)?fi.parse(t):po.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?zt.transform(t):fi.transform(t),getAnimatableNone:t=>{const e=Ie.parse(t);return e.alpha=0,Ie.transform(e)}},ap=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function lp(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(uo))==null?void 0:e.length)||0)+(((i=t.match(ap))==null?void 0:i.length)||0)>0}const Tl="number",El="color",cp="var",dp="var(",kl="${}",up=/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 Xi(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(up,l=>(Ie.test(l)?(n.color.push(o),s.push(El),i.push(Ie.parse(l))):l.startsWith(dp)?(n.var.push(o),s.push(cp),i.push(l)):(n.number.push(o),s.push(Tl),i.push(parseFloat(l))),++o,kl)).split(kl);return{values:i,split:a,indexes:n,types:s}}function Il(t){return Xi(t).values}function Rl(t){const{split:e,types:i}=Xi(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===Tl?o+=Ki(s[r]):a===El?o+=Ie.transform(s[r]):o+=s[r]}return o}}const hp=t=>typeof t=="number"?0:Ie.test(t)?Ie.getAnimatableNone(t):t;function fp(t){const e=Il(t);return Rl(t)(e.map(hp))}const Ft={test:lp,parse:Il,createTransformer:Rl,getAnimatableNone:fp};function go(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 pp({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=go(l,a,t+1/3),o=go(l,a,t),r=go(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Un(t,e){return i=>i>0?e:t}const Ce=(t,e,i)=>t+(e-t)*i,mo=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},gp=[po,zt,fi],mp=t=>gp.find(e=>e.test(t));function Al(t){const e=mp(t);if(!e)return!1;let i=e.parse(t);return e===fi&&(i=pp(i)),i}const xl=(t,e)=>{const i=Al(t),n=Al(e);if(!i||!n)return Un(t,e);const s={...i};return o=>(s.red=mo(i.red,n.red,o),s.green=mo(i.green,n.green,o),s.blue=mo(i.blue,n.blue,o),s.alpha=Ce(i.alpha,n.alpha,o),zt.transform(s))},vo=new Set(["none","hidden"]);function vp(t,e){return vo.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function _p(t,e){return i=>Ce(t,e,i)}function _o(t){return typeof t=="number"?_p:typeof t=="string"?co(t)?Un:Ie.test(t)?xl:wp:Array.isArray(t)?Ll:typeof t=="object"?Ie.test(t)?xl:yp:Un}function Ll(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>_o(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function yp(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=_o(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function bp(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 wp=(t,e)=>{const i=Ft.createTransformer(e),n=Xi(t),s=Xi(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?vo.has(t)&&!s.values.length||vo.has(e)&&!n.values.length?vp(t,e):Wi(Ll(bp(n,s),s.values),i):Un(t,e)};function Dl(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Ce(t,e,i):_o(t)(t,e)}const Sp=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>we.update(e,i),stop:()=>Pt(e),now:()=>Pe.isProcessing?Pe.timestamp:qe.now()}},Ol=(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)})`},jn=2e4;function yo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<jn;)e+=i,n=t.next(e);return e>=jn?1/0:e}function Cp(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(yo(n),jn);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:gt(s)}}const Tp=5;function Ml(t,e,i){const n=Math.max(e-Tp,0);return al(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},bo=.001;function Ep({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=wo(c,r),_=Math.exp(-d);return bo-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=wo(Math.pow(c,2),r);return(-s(c)+bo>0?-1:1)*((h-p)*_)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-bo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Ip(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 kp=12;function Ip(t,e,i){let n=i;for(let s=1;s<kp;s++)n=n-t(n)/e(n);return n}function wo(t,e){return t*Math.sqrt(1-e*e)}const Rp=["duration","bounce"],Ap=["stiffness","damping","mass"];function Pl(t,e){return e.some(i=>t[i]!==void 0)}function xp(t){let e={velocity:Te.velocity,stiffness:Te.stiffness,damping:Te.damping,mass:Te.mass,isResolvedFromDuration:!1,...t};if(!Pl(t,Ap)&&Pl(t,Rp))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=Ep(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}=xp({...i,velocity:-gt(i.velocity||0)}),_=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,w=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 R=wo(w,v);k=O=>{const T=Math.exp(-v*w*O);return r-T*((_+v*w*b)/R*Math.sin(R*O)+b*Math.cos(R*O))}}else if(v===1)k=R=>r-Math.exp(-w*R)*(b+(_+w*b)*R);else{const R=w*Math.sqrt(v*v-1);k=O=>{const T=Math.exp(-v*w*O),E=Math.min(R*O,300);return r-T*((_+v*w*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const L={calculatedDuration:p&&d||null,next:R=>{const O=k(R);if(p)a.done=R>=d;else{let T=R===0?_:0;v<1&&(T=R===0?pt(_):Ml(k,R,O));const E=Math.abs(T)<=n,g=Math.abs(r-O)<=s;a.done=E&&g}return a.value=a.done?r:O,a},toString:()=>{const R=Math.min(yo(L),jn),O=Ol(T=>L.next(R*T).value,R,30);return R+"ms "+O},toTransition:()=>{}};return L}$n.applyToOptions=t=>{const e=Cp(t,100,$n);return t.ease=e.ease,t.duration=pt(e.duration),t.type="keyframes",t};function So({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=E=>a!==void 0&&E<a||l!==void 0&&E>l,_=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,w=r===void 0?b:r(b);w!==b&&(v=w-d);const C=E=>-v*Math.exp(-E/n),k=E=>w+C(E),L=E=>{const g=C(E),m=k(E);h.done=Math.abs(g)<=c,h.value=h.done?w:m};let R,O;const T=E=>{p(h.value)&&(R=E,O=$n({keyframes:[h.value,_(h.value)],velocity:Ml(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let g=!1;return!O&&R===void 0&&(g=!0,L(E),T(E)),R!==void 0&&E>=R?O.next(E-R):(!g&&L(E),h)}}}function Lp(t,e,i){const n=[],s=i||Rt.mix||Dl,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]||et:e;a=Wi(l,a)}n.push(a)}return n}function Dp(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(io(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=Lp(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=Gi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(It(t[0],t[o-1],u)):c}function Op(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Gi(0,e,n);t.push(Ce(i,1,s))}}function Mp(t){const e=[0];return Op(e,t.length-1),e}function Pp(t,e){return t.map(i=>i*e)}function Np(t,e){return t.map(()=>e||ml).splice(0,t.length-1)}function Ji({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=zf(n)?n.map(_l):_l(n),o={done:!1,value:e[0]},r=Pp(i&&i.length===e.length?i:Mp(e),t),a=Dp(r,e,{ease:Array.isArray(s)?s:Np(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Fp=t=>t!==null;function Co(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Fp),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Bp={decay:So,inertia:So,tween:Ji,keyframes:Ji,spring:$n};function Nl(t){typeof t.type=="string"&&(t.type=Bp[t.type])}class To{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 Vp=t=>t/100;class Eo extends To{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!==qe.now()&&this.tick(qe.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;Nl(e);const{type:i=Ji,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||Ji;l!==Ji&&typeof a[0]!="number"&&(this.mixKeyframes=Wi(Vp,Dl(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=yo(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: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 w=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?w<0:w>s;this.currentTime=Math.max(w,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,L=n;if(d){const E=Math.min(this.currentTime,s)/a;let g=Math.floor(E),m=E%1;!m&&E>=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"&&(L=r)),k=It(0,1,m)*a}const R=C?{done:!1,value:u[0]}:L.next(k);o&&(R.value=o(R.value));let{done:O}=R;!C&&l!==null&&(O=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return T&&_!==So&&(R.value=Co(u,this.options,b,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(qe.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=Sp,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(qe.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 Up(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Kt=t=>t*180/Math.PI,ko=t=>{const e=Kt(Math.atan2(t[1],t[0]));return Io(e)},jp={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:ko,rotateZ:ko,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},Io=t=>(t=t%360,t<0&&(t+=360),t),Fl=ko,Bl=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),Vl=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),$p={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:Bl,scaleY:Vl,scale:t=>(Bl(t)+Vl(t))/2,rotateX:t=>Io(Kt(Math.atan2(t[6],t[5]))),rotateY:t=>Io(Kt(Math.atan2(-t[2],t[0]))),rotateZ:Fl,rotate:Fl,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 Ro(t){return t.includes("scale")?1:0}function Ao(t,e){if(!t||t==="none")return Ro(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=$p,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=jp,s=a}if(!s)return Ro(e);const o=n[e],r=s[1].split(",").map(Wp);return typeof o=="function"?o(r):r[o]}const Hp=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Ao(i,e)};function Wp(t){return parseFloat(t.trim())}const pi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],gi=new Set(pi),Ul=t=>t===hi||t===Y,Gp=new Set(["x","y","z"]),qp=pi.filter(t=>!Gp.has(t));function zp(t){const e=[];return qp.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})=>Ao(e,"x"),y:(t,{transform:e})=>Ao(e,"y")};Yt.translateX=Yt.x,Yt.translateY=Yt.y;const Xt=new Set;let xo=!1,Lo=!1,Do=!1;function jl(){if(Lo){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=zp(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)})}Lo=!1,xo=!1,Xt.forEach(t=>t.complete(Do)),Xt.clear()}function $l(){Xt.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Lo=!0)})}function Kp(){Do=!0,$l(),jl(),Do=!1}class Oo{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),xo||(xo=!0,we.read($l),we.resolveKeyframes(jl))):(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])}Up(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 Yp=t=>t.startsWith("--");function Xp(t,e,i){Yp(e)?t.style.setProperty(e,i):t.style[e]=i}const Jp=no(()=>window.ScrollTimeline!==void 0),Zp={};function Qp(t,e){const i=no(t);return()=>Zp[e]??i()}const Hl=Qp(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Zi=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,Wl={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Zi([0,.65,.55,1]),circOut:Zi([.55,0,1,.45]),backIn:Zi([.31,.01,.66,-.59]),backOut:Zi([.33,1.53,.69,.99])};function Gl(t,e){if(t)return typeof t=="function"?Hl()?Ol(t,e):"ease-out":vl(t)?Zi(t):Array.isArray(t)?t.map(i=>Gl(i,e)||Wl.easeOut):Wl[t]}function eg(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=Gl(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 ql(t){return typeof t=="function"&&"applyToOptions"in t}function tg({type:t,...e}){return ql(t)&&Hl()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class ig extends To{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,io(typeof e.type!="string");const c=tg(e);this.animation=eg(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Co(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Xp(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&&Jp()?(this.animation.timeline=e,et):i(this)}}const zl={anticipate:fl,backInOut:hl,circInOut:gl};function ng(t){return t in zl}function sg(t){typeof t.ease=="string"&&ng(t.ease)&&(t.ease=zl[t.ease])}const Kl=10;class og extends ig{constructor(e){sg(e),Nl(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 Eo({...r,autoplay:!1}),l=pt(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Kl).value,a.sample(l).value,Kl),a.stop()}}const Yl=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Ft.test(t)||t==="0")&&!t.startsWith("url("));function rg(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 ag(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=Yl(s,e),a=Yl(o,e);return!r||!a?!1:rg(t)||(i==="spring"||ql(i))&&n}function Mo(t){return ol(t)&&"offsetHeight"in t}const lg=new Set(["opacity","clipPath","filter","transform"]),cg=no(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function dg(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!Mo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return cg()&&i&&lg.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const ug=40;class hg extends To{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,b;this._animation&&(this._animation.stop(),(v=this.stopTimeline)==null||v.call(this)),(b=this.keyframeResolver)==null||b.cancel()},this.createdAt=qe.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)||Oo;this.keyframeResolver=new p(a,(v,b,w)=>this.onKeyframesResolved(v,b,h,!w),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=qe.now(),ag(e,o,r,a)||((Rt.instantAnimations||!l)&&(u==null||u(Co(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>ug?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&dg(h)?new og({...h,element:h.motionValue.owner.current}):new Eo(h);p.finished.then(()=>this.notifyFinished()).catch(et),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(),Kp()),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 fg=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pg(t){const e=fg.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Xl(t,e,i=1){const[n,s]=pg(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return sl(r)?parseFloat(r):r}return co(s)?Xl(s,e,i+1):s}function Po(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Jl=new Set(["width","height","top","left","right","bottom",...pi]),gg={test:t=>t==="auto",parse:t=>t},Zl=t=>e=>e.test(t),Ql=[hi,Y,mt,Nt,rp,op,gg],ec=t=>Ql.find(Zl(t));function mg(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||rl(t):!0}const vg=new Set(["brightness","contrast","saturate","opacity"]);function _g(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(uo)||[];if(!n)return t;const s=i.replace(n,"");let o=vg.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const yg=/\b([a-z-]*)\(.*?\)/gu,No={...Ft,getAnimatableNone:t=>{const e=t.match(yg);return e?e.map(_g).join(" "):t}},tc={...hi,transform:Math.round},Fo={borderWidth:Y,borderTopWidth:Y,borderRightWidth:Y,borderBottomWidth:Y,borderLeftWidth:Y,borderRadius:Y,radius:Y,borderTopLeftRadius:Y,borderTopRightRadius:Y,borderBottomRightRadius:Y,borderBottomLeftRadius:Y,width:Y,maxWidth:Y,height:Y,maxHeight:Y,top:Y,right:Y,bottom:Y,left:Y,padding:Y,paddingTop:Y,paddingRight:Y,paddingBottom:Y,paddingLeft:Y,margin:Y,marginTop:Y,marginRight:Y,marginBottom:Y,marginLeft:Y,backgroundPositionX:Y,backgroundPositionY:Y,...{rotate:Nt,rotateX:Nt,rotateY:Nt,rotateZ:Nt,scale:Vn,scaleX:Vn,scaleY:Vn,scaleZ:Vn,skew:Nt,skewX:Nt,skewY:Nt,distance:Y,translateX:Y,translateY:Y,translateZ:Y,x:Y,y:Y,z:Y,perspective:Y,transformPerspective:Y,opacity:zi,originX:Cl,originY:Cl,originZ:Y},zIndex:tc,fillOpacity:zi,strokeOpacity:zi,numOctaves:tc},bg={...Fo,color:Ie,backgroundColor:Ie,outlineColor:Ie,fill:Ie,stroke:Ie,borderColor:Ie,borderTopColor:Ie,borderRightColor:Ie,borderBottomColor:Ie,borderLeftColor:Ie,filter:No,WebkitFilter:No},ic=t=>bg[t];function nc(t,e){let i=ic(t);return i!==No&&(i=Ft),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const wg=new Set(["auto","none","0"]);function Sg(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!wg.has(o)&&Xi(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=nc(i,s)}class Cg extends Oo{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(),co(c))){const u=Xl(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Jl.has(n)||e.length!==2)return;const[s,o]=e,r=ec(s),a=ec(o);if(r!==a)if(Ul(r)&&Ul(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||mg(e[s]))&&n.push(s);n.length&&Sg(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 Tg(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 sc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,oc=30,Eg=t=>!isNaN(parseFloat(t));class kg{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=qe.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=qe.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Eg(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 so);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=qe.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>oc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,oc);return al(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 mi(t,e){return new kg(t,e)}const{schedule:Bo}=bl(queueMicrotask,!1),lt={x:!1,y:!1};function rc(){return lt.x||lt.y}function Ig(t){return t==="x"||t==="y"?lt[t]?null:(lt[t]=!0,()=>{lt[t]=!1}):lt.x||lt.y?null:(lt.x=lt.y=!0,()=>{lt.x=lt.y=!1})}function ac(t,e){const i=Tg(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function lc(t){return!(t.pointerType==="touch"||rc())}function Rg(t,e,i={}){const[n,s,o]=ac(t,i),r=a=>{if(!lc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{lc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const cc=(t,e)=>e?t===e?!0:cc(t,e.parentElement):!1,Vo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Ag=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function xg(t){return Ag.has(t.tagName)||t.tabIndex!==-1}const Hn=new WeakSet;function dc(t){return e=>{e.key==="Enter"&&t(e)}}function Uo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Lg=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=dc(()=>{if(Hn.has(i))return;Uo(i,"down");const s=dc(()=>{Uo(i,"up")}),o=()=>Uo(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 uc(t){return Vo(t)&&!rc()}function Dg(t,e,i={}){const[n,s,o]=ac(t,i),r=a=>{const l=a.currentTarget;if(!uc(a))return;Hn.add(l);const c=e(l,a),u=(p,_)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Hn.has(l)&&Hn.delete(l),uc(p)&&typeof c=="function"&&c(p,{success:_})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||cc(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),Mo(a)&&(a.addEventListener("focus",c=>Lg(c,s)),!xg(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function hc(t){return ol(t)&&"ownerSVGElement"in t}function Og(t){return hc(t)&&t.tagName==="svg"}const Ve=t=>!!(t&&t.getVelocity),Mg=[...Ql,Ie,Ft],Pg=t=>Mg.find(Zl(t)),Qi=kt({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class Ng extends at{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=Mo(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 Fg({children:t,isPresent:e,anchorX:i,root:n}){const s=Us(),o=ue(null),r=ue({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(Qi);return Ba(()=>{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;
@@ -6,115 +6,115 @@ var Sw=Object.defineProperty;var Cw=(rt,K,Gt)=>K in rt?Sw(rt,K,{enumerable:!0,co
6
6
  ${p}px !important;
7
7
  top: ${u}px !important;
8
8
  }
9
- `),()=>{v.removeChild(_),v.contains(_)&&v.removeChild(_)}},[e]),D(Mg,{isPresent:e,childRef:o,sizeRef:r,children:Pf(t,{ref:o})})}const Ng=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Pn(Fg),u=Bs();let d=!0,h=Qe(()=>(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}),Qe(()=>{c.forEach((p,_)=>c.set(_,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Pg,{isPresent:i,anchorX:a,root:l,children:t})),D(Nn.Provider,{value:h,children:t})};function Fg(){return new Map}function uc(t=!0){const e=De(Nn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Bs();xe(()=>{if(t)return s(o)},[t]);const r=Ge(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Wn=t=>t.key||"";function hc(t){const e=[];return Tf.forEach(t,i=>{Xa(i)&&e.push(i)}),e}const Bg=({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]=uc(r),d=Qe(()=>hc(t),[t]),h=r&&!c?[]:d.map(Wn),p=ue(!0),_=ue(d),v=Pn(()=>new Map),[b,w]=Ae(d),[C,k]=Ae(d);tl(()=>{p.current=!1,_.current=d;for(let O=0;O<C.length;O++){const T=Wn(C[O]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const L=[];if(d!==b){let O=[...d];for(let T=0;T<C.length;T++){const E=C[T],g=Wn(E);h.includes(g)||(O.splice(T,0,E),L.push(E))}return o==="wait"&&L.length&&(O=L),k(hc(O)),w(d),null}const{forceRender:R}=De(Xs);return D(ht,{children:C.map(O=>{const T=Wn(O),E=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(),k(_.current),r&&(u==null||u()),n&&n())};return D(Ng,{isPresent:E,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:g,anchorX:a,children:O},T)})})},fc=kt({strict:!1}),pc={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"]},vi={};for(const t in pc)vi[t]={isEnabled:e=>pc[t].some(i=>!!e[i])};function Vg(t){for(const e in t)vi[e]={...vi[e],...t[e]}}const Ug=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 Gn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Ug.has(t)}let gc=t=>!Gn(t);function mc(t){typeof t=="function"&&(gc=e=>e.startsWith("on")?!Gn(e):t(e))}try{mc(require("@emotion/is-prop-valid").default)}catch{}function $g(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(gc(s)||i===!0&&Gn(s)||!e&&!Gn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function jg({children:t,isValidProp:e,...i}){e&&mc(e),i={...De(Qi),...i},i.isStatic=Pn(()=>i.isStatic);const n=Qe(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Qi.Provider,{value:n,children:t})}function Hg(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 qn=kt({});function zn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function en(t){return typeof t=="string"||Array.isArray(t)}const Vo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Uo=["initial",...Vo];function Kn(t){return zn(t.animate)||Uo.some(e=>en(t[e]))}function vc(t){return!!(Kn(t)||t.variants)}function Wg(t,e){if(Kn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||en(i)?i:void 0,animate:en(n)?n:void 0}}return t.inherit!==!1?e:{}}function Gg(t){const{initial:e,animate:i}=Wg(t,De(qn));return Qe(()=>({initial:e,animate:i}),[_c(e),_c(i)])}function _c(t){return Array.isArray(t)?t.join(" "):t}const qg=Symbol.for("motionComponentSymbol");function _i(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function zg(t,e,i){return Ge(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):_i(i)&&(i.current=n))},[e])}const $o=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),yc="data-"+$o("framerAppearId"),bc=kt({});function Kg(t,e,i,n,s){var v,b;const{visualElement:o}=De(qn),r=De(fc),a=De(Nn),l=De(Qi).reducedMotion,c=ue(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=De(bc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Yg(c.current,i,s,d);const h=ue(!1);Na(()=>{u&&h.current&&u.update(i,a)});const p=i[yc],_=ue(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return tl(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),No.render(u.render),_.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!_.current&&u.animationState&&u.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),_.current=!1))}),u}function Yg(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:wc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&_i(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function wc(t){if(t)return t.options.allowProjection!==!1?t.projection:wc(t.parent)}function Xg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Vg(t);function o(a,l){let c;const u={...De(Qi),...a,layoutId:Jg(a)},{isStatic:d}=u,h=Gg(a),p=n(a,d);if(!d&&Js){Zg();const _=Qg(u);c=_.MeasureLayout,h.visualElement=Kg(s,p,u,e,_.ProjectionNode)}return D(qn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,zg(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Cf(o);return r[qg]=s,r}function Jg({layoutId:t}){const e=De(Xs).id;return e&&t!==void 0?e+"-"+t:t}function Zg(t,e){De(fc).strict}function Qg(t){const{drag:e,layout:i}=vi;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 tn={};function em(t){for(const e in t)tn[e]=t[e],ro(e)&&(tn[e].isCSSVariable=!0)}function Sc(t,{layout:e,layoutId:i}){return gi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!tn[t]||t==="opacity")}const tm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},im=pi.length;function nm(t,e,i){let n="",s=!0;for(let o=0;o<im;o++){const r=pi[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=ic(a,Po[r]);if(!l){s=!1;const u=tm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function jo(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(gi.has(l)){r=!0;continue}else if(ro(l)){s[l]=c;continue}else{const u=ic(c,Po[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=nm(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 Ho=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Cc(t,e,i){for(const n in e)!Ve(e[n])&&!Sc(n,i)&&(t[n]=e[n])}function sm({transformTemplate:t},e){return Qe(()=>{const i=Ho();return jo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function om(t,e){const i=t.style||{},n={};return Cc(n,i,t),Object.assign(n,sm(t,e)),n}function rm(t,e){const i={},n=om(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 am={offset:"stroke-dashoffset",array:"stroke-dasharray"},lm={offset:"strokeDashoffset",array:"strokeDasharray"};function cm(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?am:lm;t[o.offset]=Y.transform(-n);const r=Y.transform(e),a=Y.transform(i);t[o.array]=`${r} ${a}`}function Tc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(jo(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&&cm(d,s,o,r,!1)}const Ec=()=>({...Ho(),attrs:{}}),kc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function dm(t,e,i,n){const s=Qe(()=>{const o=Ec();return Tc(o,e,kc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Cc(o,t.style,t),s.style={...o,...s.style}}return s}const um=["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:!!(um.indexOf(t)>-1||/[A-Z]/u.test(t))}function hm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(Wo(i)?dm:rm)(n,o,r,i),c=$g(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Qe(()=>Ve(d)?d.get():d,[d]);return Ze(i,{...u,children:h})}}function Ic(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function Go(t,e,i,n){if(typeof e=="function"){const[s,o]=Ic(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]=Ic(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Yn(t){return Ve(t)?t.get():t}function fm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:pm(i,n,s,t),renderState:e()}}const Rc=t=>(e,i)=>{const n=De(qn),s=De(Nn),o=()=>fm(t,e,n,s);return i?o():Pn(o)};function pm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Yn(o[h]);let{initial:r,animate:a}=t;const l=Kn(t),c=vc(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"&&!zn(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const _=Go(t,h[p]);if(_){const{transitionEnd:v,transition:b,...w}=_;for(const C in w){let k=w[C];if(Array.isArray(k)){const L=u?k.length-1:0;k=k[L]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function qo(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||Sc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const gm={useVisualState:Rc({scrapeMotionValuesFromProps:qo,createRenderState:Ho})};function Ac(t,e,i){const n=qo(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=pi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const mm={useVisualState:Rc({scrapeMotionValuesFromProps:Ac,createRenderState:Ec})};function vm(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...Wo(n)?mm:gm,preloadedFeatures:t,useRender:hm(s),createVisualElement:e,Component:n};return Xg(r)}}function nn(t,e,i){const n=t.getProps();return Go(n,e,i!==void 0?i:n.custom,t)}const zo=t=>Array.isArray(t);function _m(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,mi(i))}function ym(t){return zo(t)?t[t.length-1]||0:t}function bm(t,e){const i=nn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=ym(o[r]);_m(t,r,a)}}function wm(t){return!!(Ve(t)&&t.add)}function Ko(t,e){const i=t.getValue("willChange");if(wm(i))return i.add(e);if(!i&&Rt.WillChange){const n=new Rt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function xc(t){return t.props[yc]}const Sm=t=>t!==null;function Cm(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Sm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Tm={type:"spring",stiffness:500,damping:25,restSpeed:10},Em=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),km={type:"keyframes",duration:.8},Im={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Rm=(t,{keyframes:e})=>e.length>2?km:gi.has(t)?t.startsWith("scale")?Em(e[1]):Tm:Im;function Am({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 Yo=(t,e,i,n={},s,o)=>r=>{const a=Oo(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};Am(a)||Object.assign(u,Rm(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)),(Rt.instantAnimations||Rt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=Cm(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Co(u):new dg(u)};function xm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Lc(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&&xm(c,u))continue;const p={delay:i,...Oo(o||{},u)},_=d.get();if(_!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===_&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=xc(t);if(w){const C=window.MotionHandoffAnimation(w,u,we);C!==null&&(p.startTime=C,v=!0)}}Ko(t,u),d.start(Yo(u,d,h,t.shouldReduceMotion&&Yl.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&bm(t,r)})}),l}function Xo(t,e,i={}){var l;const n=nn(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(Lc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Lm(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 Lm(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(Dm).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(Xo(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Dm(t,e){return t.sortNodePosition(e)}function Om(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>Xo(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=Xo(t,e,i);else{const s=typeof e=="function"?nn(t,e,i.custom):e;n=Promise.all(Lc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Dc(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 Mm=Uo.length;function Oc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?Oc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Mm;i++){const n=Uo[i],s=t.props[n];(en(s)||s===!1)&&(e[n]=s)}return e}const Pm=[...Vo].reverse(),Nm=Vo.length;function Fm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Om(t,i,n)))}function Bm(t){let e=Fm(t),i=Mc(),n=!0;const s=l=>(c,u)=>{var h;const d=nn(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=Oc(t.parent)||{},d=[],h=new Set;let p={},_=1/0;for(let b=0;b<Nm;b++){const w=Pm[b],C=i[w],k=c[w]!==void 0?c[w]:u[w],L=en(k),R=w===l?C.isActive:null;R===!1&&(_=b);let O=k===u[w]&&k!==c[w]&&L;if(O&&n&&t.manuallyAnimateOnMount&&(O=!1),C.protectedKeys={...p},!C.isActive&&R===null||!k&&!C.prevProp||zn(k)||typeof k=="boolean")continue;const T=Vm(C.prevProp,k);let E=T||w===l&&C.isActive&&!O&&L||b>_&&L,g=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(w),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},A=M=>{E=!0,h.has(M)&&(g=!0,h.delete(M)),C.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in I){const F=f[M],G=S[M];if(p.hasOwnProperty(M))continue;let U=!1;zo(F)&&zo(G)?U=!Dc(F,G):U=F!==G,U?F!=null?A(M):h.add(M):F!==void 0&&h.has(M)?A(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(p={...p,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(O&&T)||g)&&d.push(...m.map(M=>({animation:M,options:{type:w}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const w=nn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(b.transition=w.transition)}h.forEach(w=>{const C=t.getBaseTarget(w),k=t.getValue(w);k&&(k.liveStyle=!0),b[w]=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 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=Mc(),n=!0}}}function Vm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Dc(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Mc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Bt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Um extends Bt{constructor(e){super(e),e.animationState||(e.animationState=Bm(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();zn(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 $m=0;class jm extends Bt{constructor(){super(...arguments),this.id=$m++}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 Hm={animation:{Feature:Um},exit:{Feature:jm}};function sn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function on(t){return{point:{x:t.pageX,y:t.pageY}}}const Wm=t=>e=>Fo(e)&&t(e,on(e));function rn(t,e,i,n){return sn(t,e,Wm(i),n)}function Pc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Gm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function qm(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 Nc=1e-4,zm=1-Nc,Km=1+Nc,Fc=.01,Ym=0-Fc,Xm=0+Fc;function je(t){return t.max-t.min}function Jm(t,e,i){return Math.abs(t-e)<=i}function Bc(t,e,i,n=.5){t.origin=n,t.originPoint=Ce(e.min,e.max,t.origin),t.scale=je(i)/je(e),t.translate=Ce(i.min,i.max,t.origin)-t.originPoint,(t.scale>=zm&&t.scale<=Km||isNaN(t.scale))&&(t.scale=1),(t.translate>=Ym&&t.translate<=Xm||isNaN(t.translate))&&(t.translate=0)}function an(t,e,i,n){Bc(t.x,e.x,i.x,n?n.originX:void 0),Bc(t.y,e.y,i.y,n?n.originY:void 0)}function Vc(t,e,i){t.min=i.min+e.min,t.max=t.min+je(e)}function Zm(t,e,i){Vc(t.x,e.x,i.x),Vc(t.y,e.y,i.y)}function Uc(t,e,i){t.min=e.min-i.min,t.max=t.min+je(e)}function ln(t,e,i){Uc(t.x,e.x,i.x),Uc(t.y,e.y,i.y)}const $c=()=>({translate:0,scale:1,origin:0,originPoint:0}),yi=()=>({x:$c(),y:$c()}),jc=()=>({min:0,max:0}),ke=()=>({x:jc(),y:jc()});function tt(t){return[t("x"),t("y")]}function Jo(t){return t===void 0||t===1}function Zo({scale:t,scaleX:e,scaleY:i}){return!Jo(t)||!Jo(e)||!Jo(i)}function Zt(t){return Zo(t)||Hc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Hc(t){return Wc(t.x)||Wc(t.y)}function Wc(t){return t&&t!=="0%"}function Xn(t,e,i){const n=t-i,s=e*n;return i+s}function Gc(t,e,i,n,s){return s!==void 0&&(t=Xn(t,s,n)),Xn(t,i,n)+e}function Qo(t,e=0,i=1,n,s){t.min=Gc(t.min,e,i,n,s),t.max=Gc(t.max,e,i,n,s)}function qc(t,{x:e,y:i}){Qo(t.x,e.translate,e.scale,e.originPoint),Qo(t.y,i.translate,i.scale,i.originPoint)}const zc=.999999999999,Kc=1.0000000000001;function Qm(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&&wi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,qc(t,r)),n&&Zt(o.latestValues)&&wi(t,o.latestValues))}e.x<Kc&&e.x>zc&&(e.x=1),e.y<Kc&&e.y>zc&&(e.y=1)}function bi(t,e){t.min=t.min+e,t.max=t.max+e}function Yc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);Qo(t,e,i,o,n)}function wi(t,e){Yc(t.x,e.x,e.scaleX,e.scale,e.originX),Yc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Xc(t,e){return Pc(qm(t.getBoundingClientRect(),e))}function ev(t,e,i){const n=Xc(t,i),{scroll:s}=e;return s&&(bi(n.x,s.offset.x),bi(n.y,s.offset.y)),n}const Jc=({current:t})=>t?t.ownerDocument.defaultView:null,Zc=(t,e)=>Math.abs(t-e);function tv(t,e){const i=Zc(t.x,e.x),n=Zc(t.y,e.y);return Math.sqrt(i**2+n**2)}class Qc{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=tr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,_=tv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!_)return;const{point:v}=h,{timestamp:b}=Pe;this.history.push({...v,timestamp:b});const{onStart:w,onMove:C}=this.handlers;p||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=er(p,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=tr(h.type==="pointercancel"?this.lastMoveEventInfo:er(p,this.transformPagePoint),this.history);this.startEvent&&_&&_(h,w),v&&v(h,w)},!Fo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=on(e),l=er(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,tr(l,this.history)),this.removeListeners=Wi(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function er(t,e){return e?{point:e(t.point)}:t}function ed(t,e){return{x:t.x-e.x,y:t.y-e.y}}function tr({point:t},e){return{point:t,delta:ed(t,td(e)),offset:ed(t,iv(e)),velocity:nv(e,.1)}}function iv(t){return t[0]}function td(t){return t[t.length-1]}function nv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=td(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 sv(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 id(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 ov(t,{top:e,left:i,bottom:n,right:s}){return{x:id(t.x,i,s),y:id(t.y,e,n)}}function nd(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 rv(t,e){return{x:nd(t.x,e.x),y:nd(t.y,e.y)}}function av(t,e){let i=.5;const n=je(t),s=je(e);return s>n?i=Gi(e.min,e.max-n,t.min):n>s&&(i=Gi(t.min,t.max-s,e.min)),It(0,1,i)}function lv(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 ir=.35;function cv(t=ir){return t===!1?t=0:t===!0&&(t=ir),{x:sd(t,"left","right"),y:sd(t,"top","bottom")}}function sd(t,e,i){return{min:od(t,e),max:od(t,i)}}function od(t,e){return typeof t=="number"?t:t[e]||0}const dv=new WeakMap;class uv{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(on(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:_,onDragStart:v}=this.getProps();if(p&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Eg(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),tt(w=>{let C=this.getAxisMotionValue(w).get()||0;if(mt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const L=k.layout.layoutBox[w];L&&(C=je(L)*(parseFloat(C)/100))}}this.originPoint[w]=C}),v&&we.postRender(()=>v(d,h)),Ko(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:_,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=h;if(_&&this.currentDirection===null){this.currentDirection=hv(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),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=()=>tt(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 Qc(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Jc(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||!Jn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=sv(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&&_i(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=ov(n.layoutBox,e):this.constraints=!1,this.elastic=cv(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&tt(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=lv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!_i(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=ev(n,s.root,this.visualElement.getTransformPagePoint());let r=rv(s.layout.layoutBox,o);if(i){const a=i(Gm(r));this.hasMutatedConstraints=!!a,a&&(r=Pc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=tt(u=>{if(!Jn(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 Ko(this.visualElement,e),n.start(Yo(e,n,0,i,this.visualElement,!1))}stopAnimation(){tt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){tt(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){tt(i=>{const{drag:n}=this.getProps();if(!Jn(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(!_i(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};tt(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=av({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(),tt(r=>{if(!Jn(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;dv.set(this.visualElement,this);const e=this.visualElement.current,i=rn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();_i(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=sn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(tt(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=ir,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Jn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function hv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class fv extends Bt{constructor(e){super(e),this.removeGroupControls=et,this.removeListeners=et,this.controls=new uv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||et}unmount(){this.removeGroupControls(),this.removeListeners()}}const rd=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class pv extends Bt{constructor(){super(...arguments),this.removePointerDownListener=et}onPointerDown(e){this.session=new Qc(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Jc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:rd(e),onStart:rd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=rn(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 Zn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function ad(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const cn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(Y.test(t))t=parseFloat(t);else return t;const i=ad(t,e.target.x),n=ad(t,e.target.y);return`${i}% ${n}%`}},gv={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 ld=!1;class mv extends at{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;em(vv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),ld&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Zn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,ld=!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(),No.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 cd(t){const[e,i]=uc(),n=De(Xs);return D(mv,{...t,layoutGroup:n,switchLayoutGroup:De(bc),isPresent:e,safeToRemove:i})}const vv={borderRadius:{...cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:cn,borderTopRightRadius:cn,borderBottomLeftRadius:cn,borderBottomRightRadius:cn,boxShadow:gv};function _v(t,e,i){const n=Ve(t)?t:mi(t);return n.start(Yo("",n,e,i)),n.animation}const yv=(t,e)=>t.depth-e.depth;class bv{constructor(){this.children=[],this.isDirty=!1}add(e){Zs(this.children,e),this.isDirty=!0}remove(e){Qs(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(yv),this.isDirty=!1,this.children.forEach(e)}}function wv(t,e){const i=qe.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const dd=["TopLeft","TopRight","BottomLeft","BottomRight"],Sv=dd.length,ud=t=>typeof t=="string"?parseFloat(t):t,hd=t=>typeof t=="number"||Y.test(t);function Cv(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,Tv(n)),t.opacityExit=Ce(e.opacity??1,0,Ev(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<Sv;r++){const a=`border${dd[r]}Radius`;let l=fd(e,a),c=fd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||hd(l)===hd(c)?(t[a]=Math.max(Ce(ud(l),ud(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 fd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const Tv=pd(0,.5,hl),Ev=pd(.5,.95,et);function pd(t,e,i){return n=>n<t?0:n>e?1:i(Gi(t,e,n))}function gd(t,e){t.min=e.min,t.max=e.max}function it(t,e){gd(t.x,e.x),gd(t.y,e.y)}function md(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function vd(t,e,i,n,s){return t-=e,t=Xn(t,1/i,n),s!==void 0&&(t=Xn(t,1/s,n)),t}function kv(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=vd(t.min,e,i,a,s),t.max=vd(t.max,e,i,a,s)}function _d(t,e,[i,n,s],o,r){kv(t,e[i],e[n],e[s],e.scale,o,r)}const Iv=["x","scaleX","originX"],Rv=["y","scaleY","originY"];function yd(t,e,i,n){_d(t.x,e,Iv,i?i.x:void 0,n?n.x:void 0),_d(t.y,e,Rv,i?i.y:void 0,n?n.y:void 0)}function bd(t){return t.translate===0&&t.scale===1}function wd(t){return bd(t.x)&&bd(t.y)}function Sd(t,e){return t.min===e.min&&t.max===e.max}function Av(t,e){return Sd(t.x,e.x)&&Sd(t.y,e.y)}function Cd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Td(t,e){return Cd(t.x,e.x)&&Cd(t.y,e.y)}function Ed(t){return je(t.x)/je(t.y)}function kd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class xv{constructor(){this.members=[]}add(e){Zs(this.members,e),e.scheduleRender()}remove(e){if(Qs(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 Lv(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 nr=["","X","Y","Z"],Dv=1e3;let Ov=0;function sr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Id(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=xc(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&&Id(n)}function Rd({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Ov++,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(Nv),this.nodes.forEach(Uv),this.nodes.forEach($v),this.nodes.forEach(Fv)},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 bv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new io),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=dc(r)&&!Lg(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=wv(h,250),Zn.hasAnimatedSinceResize&&(Zn.hasAnimatedSinceResize=!1,this.nodes.forEach(Ld)))})}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()||qv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),w=!this.targetLayout||!Td(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Oo(_,"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||Ld(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(jv),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&&Id(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(Ad);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(xd);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(Vv),this.nodes.forEach(Mv),this.nodes.forEach(Pv)):this.nodes.forEach(xd),this.clearAllSnapshots();const a=qe.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,oo.update.process(Pe),oo.preRender.process(Pe),oo.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,No.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Bv),this.sharedNodes.forEach(Hv)}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&&!je(this.snapshot.measuredBox.x)&&!je(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&&!wd(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)),zv(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(Kv))){const{scroll:u}=this.root;u&&(bi(a.x,u.offset.x),bi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(it(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&&it(a,r),bi(a.x,d.offset.x),bi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();it(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&&wi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&wi(l,u.latestValues)}return Zt(this.latestValues)&&wi(l,this.latestValues),l}removeTransform(r){const a=ke();it(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;Zo(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();it(u,d),yd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&yd(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=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),it(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(),Zm(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):it(this.target,this.layout.layoutBox),qc(this.target,this.targetDelta)):it(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=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.target,p.target),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||Zo(this.parent.latestValues)||Hc(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;it(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Qm(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:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(md(this.prevProjectionDelta.x,this.projectionDelta.x),md(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!kd(this.projectionDelta.x,this.prevProjectionDelta.x)||!kd(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=yi(),this.projectionDelta=yi(),this.projectionDeltaWithTransform=yi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),p=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=p!==_,b=this.getStack(),w=!b||b.members.length<=1,C=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(Gv));this.animationProgress=0;let k;this.mixTargetDelta=L=>{const R=L/1e3;Dd(d.x,r.x,R),Dd(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ln(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),Wv(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&Av(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),it(k,this.relativeTarget)),v&&(this.animationValues=u,Cv(u,c,this.latestValues,R,C,w)),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(()=>{Zn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=mi(0)),this.currentAnimation=_v(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(Dv),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&&Fd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();const d=je(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=je(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}it(a,l),wi(a,u),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new xv),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&&sr("z",r,c,this.animationValues);for(let u=0;u<nr.length;u++)sr(`rotate${nr[u]}`,r,c,this.animationValues),sr(`skew${nr[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=Yn(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=Yn(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=Lv(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 tn){if(u[_]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:w}=tn[_],C=d==="none"?u[_]:v(u[_],c);if(b){const k=b.length;for(let L=0;L<k;L++)r[b[L]]=C}else w?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Yn(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(Ad),this.root.sharedNodes.clear()}}}function Mv(t){t.updateLayout()}function Pv(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"?tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=je(h);h.min=n[d].min,h.max=h.min+p}):Fd(o,e.layoutBox,n)&&tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=je(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=yi();an(a,n,e.layoutBox);const l=yi();r?an(l,t.applyTransform(s,!0),e.measuredBox):an(l,n,e.layoutBox);const c=!wd(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 _=ke();ln(_,e.layoutBox,h.layoutBox);const v=ke();ln(v,n,p.layoutBox),Td(_,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 Nv(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 Fv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Bv(t){t.clearSnapshot()}function Ad(t){t.clearMeasurements()}function xd(t){t.isLayoutDirty=!1}function Vv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Ld(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function Uv(t){t.resolveTargetDelta()}function $v(t){t.calcProjection()}function jv(t){t.resetSkewAndRotation()}function Hv(t){t.removeLeadSnapshot()}function Dd(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 Od(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function Wv(t,e,i,n){Od(t.x,e.x,i.x,n),Od(t.y,e.y,i.y,n)}function Gv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const qv={duration:.45,ease:[.4,0,.1,1]},Md=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Pd=Md("applewebkit/")&&!Md("chrome/")?Math.round:et;function Nd(t){t.min=Pd(t.min),t.max=Pd(t.max)}function zv(t){Nd(t.x),Nd(t.y)}function Fd(t,e,i){return t==="position"||t==="preserve-aspect"&&!Jm(Ed(e),Ed(i),.2)}function Kv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Yv=Rd({attachResizeListener:(t,e)=>sn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),or={current:void 0},Bd=Rd({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!or.current){const t=new Yv({});t.mount(window),t.setOptions({layoutScroll:!0}),or.current=t}return or.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Xv={pan:{Feature:pv},drag:{Feature:fv,ProjectionNode:Bd,MeasureLayout:cd}};function Vd(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,on(e)))}class Jv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=kg(e,(i,n)=>(Vd(this.node,n,"Start"),s=>Vd(this.node,s,"End"))))}unmount(){}}class Zv extends Bt{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(sn(this.node.current,"focus",()=>this.onFocus()),sn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ud(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,on(e)))}class Qv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=xg(e,(i,n)=>(Ud(this.node,n,"Start"),(s,{success:o})=>Ud(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const rr=new WeakMap,ar=new WeakMap,e_=t=>{const e=rr.get(t.target);e&&e(t)},t_=t=>{t.forEach(e_)};function i_({root:t,...e}){const i=t||document;ar.has(i)||ar.set(i,{});const n=ar.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(t_,{root:t,...e})),n[s]}function n_(t,e,i){const n=i_(e);return rr.set(t,i),n.observe(t),()=>{rr.delete(t),n.unobserve(t)}}const s_={some:0,all:1};class o_ extends Bt{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:s_[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 n_(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(r_(e,i))&&this.startObserver()}unmount(){}}function r_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const a_={inView:{Feature:o_},tap:{Feature:Qv},focus:{Feature:Zv},hover:{Feature:Jv}},l_={layout:{ProjectionNode:Bd,MeasureLayout:cd}},lr={current:null},$d={current:!1};function c_(){if($d.current=!0,!!Js)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>lr.current=t.matches;t.addEventListener("change",e),e()}else lr.current=!1}const d_=new WeakMap;function u_(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,mi(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,mi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const jd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class h_{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=Lo,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=qe.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=Kn(i),this.isVariantNode=vc(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,d_.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)),$d.current||c_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:lr.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=gi.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 vi){const i=vi[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<jd.length;n++){const s=jd[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=u_(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=mi(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"&&(il(n)||sl(n))?n=parseFloat(n):!Og(n)&&Ft.test(i)&&(n=tc(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=Go(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 io),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Hd extends h_{constructor(){super(...arguments),this.KeyframeResolver=wg}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 Wd(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 f_(t){return window.getComputedStyle(t)}class p_ extends Hd{constructor(){super(...arguments),this.type="html",this.renderInstance=Wd}readValueFromInstance(e,i){var n;if(gi.has(i))return(n=this.projection)!=null&&n.isProjecting?ko(i):$p(e,i);{const s=f_(e),o=(ro(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Xc(e,i)}build(e,i,n){jo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return qo(e,i,n)}}const Gd=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 g_(t,e,i,n){Wd(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(Gd.has(s)?s:$o(s),e.attrs[s])}class m_ extends Hd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(gi.has(i)){const n=ec(i);return n&&n.default||0}return i=Gd.has(i)?i:$o(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return Ac(e,i,n)}build(e,i,n){Tc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){g_(e,i,n,s)}mount(e){this.isSVGTag=kc(e.tagName),super.mount(e)}}const v_=(t,e)=>Wo(t)?new m_(e):new p_(e,{allowProjection:t!==ht}),__=vm({...Hm,...a_,...Xv,...l_},v_),Si=Hg(__),y_=["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"],dn="widget-layout-id";function qd(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=qd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function At(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=qd(t))&&(n&&(n+=" "),n+=e);return n}const b_=Dn("listening"),cr=()=>el(b_);function w_(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 Qn={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},zd=Dn(Qn),S_=()=>{const t=Mn(zd);return Ge(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Qn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Qn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Qn.speak_to_interrupt_text),i}),[t])},Qt=()=>Ys(zd),Kd=({size:t="large",className:e})=>{const i=Qt(),[n]=cr();return D("h1",{className:At({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Yd=({stream:t,chatMode:e})=>{const i=ue(null);return xe(()=>{!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(Ng,{isPresent:e,childRef:o,sizeRef:r,children:Ff(t,{ref:o})})}const Bg=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Pn(Vg),u=Us();let d=!0,h=Qe(()=>(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}),Qe(()=>{c.forEach((p,_)=>c.set(_,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Fg,{isPresent:i,anchorX:a,root:l,children:t})),D(Nn.Provider,{value:h,children:t})};function Vg(){return new Map}function fc(t=!0){const e=De(Nn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Us();xe(()=>{if(t)return s(o)},[t]);const r=Ge(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Wn=t=>t.key||"";function pc(t){const e=[];return kf.forEach(t,i=>{Za(i)&&e.push(i)}),e}const Ug=({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]=fc(r),d=Qe(()=>pc(t),[t]),h=r&&!c?[]:d.map(Wn),p=ue(!0),_=ue(d),v=Pn(()=>new Map),[b,w]=Ae(d),[C,k]=Ae(d);nl(()=>{p.current=!1,_.current=d;for(let O=0;O<C.length;O++){const T=Wn(C[O]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const L=[];if(d!==b){let O=[...d];for(let T=0;T<C.length;T++){const E=C[T],g=Wn(E);h.includes(g)||(O.splice(T,0,E),L.push(E))}return o==="wait"&&L.length&&(O=L),k(pc(O)),w(d),null}const{forceRender:R}=De(Zs);return D(ht,{children:C.map(O=>{const T=Wn(O),E=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(),k(_.current),r&&(u==null||u()),n&&n())};return D(Bg,{isPresent:E,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:g,anchorX:a,children:O},T)})})},gc=kt({strict:!1}),mc={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"]},vi={};for(const t in mc)vi[t]={isEnabled:e=>mc[t].some(i=>!!e[i])};function jg(t){for(const e in t)vi[e]={...vi[e],...t[e]}}const $g=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 Gn(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||$g.has(t)}let vc=t=>!Gn(t);function _c(t){typeof t=="function"&&(vc=e=>e.startsWith("on")?!Gn(e):t(e))}try{_c(require("@emotion/is-prop-valid").default)}catch{}function Hg(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(vc(s)||i===!0&&Gn(s)||!e&&!Gn(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Wg({children:t,isValidProp:e,...i}){e&&_c(e),i={...De(Qi),...i},i.isStatic=Pn(()=>i.isStatic);const n=Qe(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(Qi.Provider,{value:n,children:t})}function Gg(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 qn=kt({});function zn(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function en(t){return typeof t=="string"||Array.isArray(t)}const jo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],$o=["initial",...jo];function Kn(t){return zn(t.animate)||$o.some(e=>en(t[e]))}function yc(t){return!!(Kn(t)||t.variants)}function qg(t,e){if(Kn(t)){const{initial:i,animate:n}=t;return{initial:i===!1||en(i)?i:void 0,animate:en(n)?n:void 0}}return t.inherit!==!1?e:{}}function zg(t){const{initial:e,animate:i}=qg(t,De(qn));return Qe(()=>({initial:e,animate:i}),[bc(e),bc(i)])}function bc(t){return Array.isArray(t)?t.join(" "):t}const Kg=Symbol.for("motionComponentSymbol");function _i(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Yg(t,e,i){return Ge(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):_i(i)&&(i.current=n))},[e])}const Ho=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),wc="data-"+Ho("framerAppearId"),Sc=kt({});function Xg(t,e,i,n,s){var v,b;const{visualElement:o}=De(qn),r=De(gc),a=De(Nn),l=De(Qi).reducedMotion,c=ue(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=De(Sc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Jg(c.current,i,s,d);const h=ue(!1);Ba(()=>{u&&h.current&&u.update(i,a)});const p=i[wc],_=ue(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return nl(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Bo.render(u.render),_.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!_.current&&u.animationState&&u.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var w;(w=window.MotionHandoffMarkAsComplete)==null||w.call(window,p)}),_.current=!1))}),u}function Jg(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:Cc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&_i(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function Cc(t){if(t)return t.options.allowProjection!==!1?t.projection:Cc(t.parent)}function Zg({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&jg(t);function o(a,l){let c;const u={...De(Qi),...a,layoutId:Qg(a)},{isStatic:d}=u,h=zg(a),p=n(a,d);if(!d&&Qs){em();const _=tm(u);c=_.MeasureLayout,h.visualElement=Xg(s,p,u,e,_.ProjectionNode)}return D(qn.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,Yg(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Ef(o);return r[Kg]=s,r}function Qg({layoutId:t}){const e=De(Zs).id;return e&&t!==void 0?e+"-"+t:t}function em(t,e){De(gc).strict}function tm(t){const{drag:e,layout:i}=vi;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 tn={};function im(t){for(const e in t)tn[e]=t[e],lo(e)&&(tn[e].isCSSVariable=!0)}function Tc(t,{layout:e,layoutId:i}){return gi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!tn[t]||t==="opacity")}const nm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},sm=pi.length;function om(t,e,i){let n="",s=!0;for(let o=0;o<sm;o++){const r=pi[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=sc(a,Fo[r]);if(!l){s=!1;const u=nm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function Wo(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(gi.has(l)){r=!0;continue}else if(lo(l)){s[l]=c;continue}else{const u=sc(c,Fo[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=om(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 Go=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Ec(t,e,i){for(const n in e)!Ve(e[n])&&!Tc(n,i)&&(t[n]=e[n])}function rm({transformTemplate:t},e){return Qe(()=>{const i=Go();return Wo(i,e,t),Object.assign({},i.vars,i.style)},[e])}function am(t,e){const i=t.style||{},n={};return Ec(n,i,t),Object.assign(n,rm(t,e)),n}function lm(t,e){const i={},n=am(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 cm={offset:"stroke-dashoffset",array:"stroke-dasharray"},dm={offset:"strokeDashoffset",array:"strokeDasharray"};function um(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?cm:dm;t[o.offset]=Y.transform(-n);const r=Y.transform(e),a=Y.transform(i);t[o.array]=`${r} ${a}`}function kc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(Wo(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&&um(d,s,o,r,!1)}const Ic=()=>({...Go(),attrs:{}}),Rc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function hm(t,e,i,n){const s=Qe(()=>{const o=Ic();return kc(o,e,Rc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Ec(o,t.style,t),s.style={...o,...s.style}}return s}const fm=["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 qo(t){return typeof t!="string"||t.includes("-")?!1:!!(fm.indexOf(t)>-1||/[A-Z]/u.test(t))}function pm(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(qo(i)?hm:lm)(n,o,r,i),c=Hg(n,typeof i=="string",t),u=i!==ht?{...c,...l,ref:s}:{},{children:d}=n,h=Qe(()=>Ve(d)?d.get():d,[d]);return Ze(i,{...u,children:h})}}function Ac(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function zo(t,e,i,n){if(typeof e=="function"){const[s,o]=Ac(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]=Ac(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function Yn(t){return Ve(t)?t.get():t}function gm({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:mm(i,n,s,t),renderState:e()}}const xc=t=>(e,i)=>{const n=De(qn),s=De(Nn),o=()=>gm(t,e,n,s);return i?o():Pn(o)};function mm(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=Yn(o[h]);let{initial:r,animate:a}=t;const l=Kn(t),c=yc(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"&&!zn(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const _=zo(t,h[p]);if(_){const{transitionEnd:v,transition:b,...w}=_;for(const C in w){let k=w[C];if(Array.isArray(k)){const L=u?k.length-1:0;k=k[L]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function Ko(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ve(n[r])||e.style&&Ve(e.style[r])||Tc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const vm={useVisualState:xc({scrapeMotionValuesFromProps:Ko,createRenderState:Go})};function Lc(t,e,i){const n=Ko(t,e,i);for(const s in t)if(Ve(t[s])||Ve(e[s])){const o=pi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const _m={useVisualState:xc({scrapeMotionValuesFromProps:Lc,createRenderState:Ic})};function ym(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...qo(n)?_m:vm,preloadedFeatures:t,useRender:pm(s),createVisualElement:e,Component:n};return Zg(r)}}function nn(t,e,i){const n=t.getProps();return zo(n,e,i!==void 0?i:n.custom,t)}const Yo=t=>Array.isArray(t);function bm(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,mi(i))}function wm(t){return Yo(t)?t[t.length-1]||0:t}function Sm(t,e){const i=nn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=wm(o[r]);bm(t,r,a)}}function Cm(t){return!!(Ve(t)&&t.add)}function Xo(t,e){const i=t.getValue("willChange");if(Cm(i))return i.add(e);if(!i&&Rt.WillChange){const n=new Rt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function Dc(t){return t.props[wc]}const Tm=t=>t!==null;function Em(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Tm),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const km={type:"spring",stiffness:500,damping:25,restSpeed:10},Im=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Rm={type:"keyframes",duration:.8},Am={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},xm=(t,{keyframes:e})=>e.length>2?Rm:gi.has(t)?t.startsWith("scale")?Im(e[1]):km:Am;function Lm({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 Jo=(t,e,i,n={},s,o)=>r=>{const a=Po(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};Lm(a)||Object.assign(u,xm(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)),(Rt.instantAnimations||Rt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=Em(u.keyframes,a);if(h!==void 0){we.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Eo(u):new hg(u)};function Dm({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function Oc(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&&Dm(c,u))continue;const p={delay:i,...Po(o||{},u)},_=d.get();if(_!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===_&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const w=Dc(t);if(w){const C=window.MotionHandoffAnimation(w,u,we);C!==null&&(p.startTime=C,v=!0)}}Xo(t,u),d.start(Jo(u,d,h,t.shouldReduceMotion&&Jl.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{we.update(()=>{r&&Sm(t,r)})}),l}function Zo(t,e,i={}){var l;const n=nn(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(Oc(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Om(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 Om(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(Mm).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(Zo(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Mm(t,e){return t.sortNodePosition(e)}function Pm(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"?nn(t,e,i.custom):e;n=Promise.all(Oc(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function Mc(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 Nm=$o.length;function Pc(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?Pc(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<Nm;i++){const n=$o[i],s=t.props[n];(en(s)||s===!1)&&(e[n]=s)}return e}const Fm=[...jo].reverse(),Bm=jo.length;function Vm(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Pm(t,i,n)))}function Um(t){let e=Vm(t),i=Nc(),n=!0;const s=l=>(c,u)=>{var h;const d=nn(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=Pc(t.parent)||{},d=[],h=new Set;let p={},_=1/0;for(let b=0;b<Bm;b++){const w=Fm[b],C=i[w],k=c[w]!==void 0?c[w]:u[w],L=en(k),R=w===l?C.isActive:null;R===!1&&(_=b);let O=k===u[w]&&k!==c[w]&&L;if(O&&n&&t.manuallyAnimateOnMount&&(O=!1),C.protectedKeys={...p},!C.isActive&&R===null||!k&&!C.prevProp||zn(k)||typeof k=="boolean")continue;const T=jm(C.prevProp,k);let E=T||w===l&&C.isActive&&!O&&L||b>_&&L,g=!1;const m=Array.isArray(k)?k:[k];let f=m.reduce(s(w),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},A=M=>{E=!0,h.has(M)&&(g=!0,h.delete(M)),C.needsAnimating[M]=!0;const F=t.getValue(M);F&&(F.liveStyle=!1)};for(const M in I){const F=f[M],G=S[M];if(p.hasOwnProperty(M))continue;let U=!1;Yo(F)&&Yo(G)?U=!Mc(F,G):U=F!==G,U?F!=null?A(M):h.add(M):F!==void 0&&h.has(M)?A(M):C.protectedKeys[M]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(p={...p,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(O&&T)||g)&&d.push(...m.map(M=>({animation:M,options:{type:w}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const w=nn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);w&&w.transition&&(b.transition=w.transition)}h.forEach(w=>{const C=t.getBaseTarget(w),k=t.getValue(w);k&&(k.liveStyle=!0),b[w]=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 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=Nc(),n=!0}}}function jm(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!Mc(e,t):!1}function Jt(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Nc(){return{animate:Jt(!0),whileInView:Jt(),whileHover:Jt(),whileTap:Jt(),whileDrag:Jt(),whileFocus:Jt(),exit:Jt()}}class Bt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class $m extends Bt{constructor(e){super(e),e.animationState||(e.animationState=Um(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();zn(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 Hm=0;class Wm extends Bt{constructor(){super(...arguments),this.id=Hm++}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 Gm={animation:{Feature:$m},exit:{Feature:Wm}};function sn(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function on(t){return{point:{x:t.pageX,y:t.pageY}}}const qm=t=>e=>Vo(e)&&t(e,on(e));function rn(t,e,i,n){return sn(t,e,qm(i),n)}function Fc({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function zm({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Km(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 Bc=1e-4,Ym=1-Bc,Xm=1+Bc,Vc=.01,Jm=0-Vc,Zm=0+Vc;function $e(t){return t.max-t.min}function Qm(t,e,i){return Math.abs(t-e)<=i}function Uc(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>=Ym&&t.scale<=Xm||isNaN(t.scale))&&(t.scale=1),(t.translate>=Jm&&t.translate<=Zm||isNaN(t.translate))&&(t.translate=0)}function an(t,e,i,n){Uc(t.x,e.x,i.x,n?n.originX:void 0),Uc(t.y,e.y,i.y,n?n.originY:void 0)}function jc(t,e,i){t.min=i.min+e.min,t.max=t.min+$e(e)}function ev(t,e,i){jc(t.x,e.x,i.x),jc(t.y,e.y,i.y)}function $c(t,e,i){t.min=e.min-i.min,t.max=t.min+$e(e)}function ln(t,e,i){$c(t.x,e.x,i.x),$c(t.y,e.y,i.y)}const Hc=()=>({translate:0,scale:1,origin:0,originPoint:0}),yi=()=>({x:Hc(),y:Hc()}),Wc=()=>({min:0,max:0}),ke=()=>({x:Wc(),y:Wc()});function tt(t){return[t("x"),t("y")]}function Qo(t){return t===void 0||t===1}function er({scale:t,scaleX:e,scaleY:i}){return!Qo(t)||!Qo(e)||!Qo(i)}function Zt(t){return er(t)||Gc(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Gc(t){return qc(t.x)||qc(t.y)}function qc(t){return t&&t!=="0%"}function Xn(t,e,i){const n=t-i,s=e*n;return i+s}function zc(t,e,i,n,s){return s!==void 0&&(t=Xn(t,s,n)),Xn(t,i,n)+e}function tr(t,e=0,i=1,n,s){t.min=zc(t.min,e,i,n,s),t.max=zc(t.max,e,i,n,s)}function Kc(t,{x:e,y:i}){tr(t.x,e.translate,e.scale,e.originPoint),tr(t.y,i.translate,i.scale,i.originPoint)}const Yc=.999999999999,Xc=1.0000000000001;function tv(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&&wi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,Kc(t,r)),n&&Zt(o.latestValues)&&wi(t,o.latestValues))}e.x<Xc&&e.x>Yc&&(e.x=1),e.y<Xc&&e.y>Yc&&(e.y=1)}function bi(t,e){t.min=t.min+e,t.max=t.max+e}function Jc(t,e,i,n,s=.5){const o=Ce(t.min,t.max,s);tr(t,e,i,o,n)}function wi(t,e){Jc(t.x,e.x,e.scaleX,e.scale,e.originX),Jc(t.y,e.y,e.scaleY,e.scale,e.originY)}function Zc(t,e){return Fc(Km(t.getBoundingClientRect(),e))}function iv(t,e,i){const n=Zc(t,i),{scroll:s}=e;return s&&(bi(n.x,s.offset.x),bi(n.y,s.offset.y)),n}const Qc=({current:t})=>t?t.ownerDocument.defaultView:null,ed=(t,e)=>Math.abs(t-e);function nv(t,e){const i=ed(t.x,e.x),n=ed(t.y,e.y);return Math.sqrt(i**2+n**2)}class td{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=nr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,_=nv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!_)return;const{point:v}=h,{timestamp:b}=Pe;this.history.push({...v,timestamp:b});const{onStart:w,onMove:C}=this.handlers;p||(w&&w(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=ir(p,this.transformPagePoint),we.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=nr(h.type==="pointercancel"?this.lastMoveEventInfo:ir(p,this.transformPagePoint),this.history);this.startEvent&&_&&_(h,w),v&&v(h,w)},!Vo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=on(e),l=ir(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Pe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,nr(l,this.history)),this.removeListeners=Wi(rn(this.contextWindow,"pointermove",this.handlePointerMove),rn(this.contextWindow,"pointerup",this.handlePointerUp),rn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Pt(this.updatePoint)}}function ir(t,e){return e?{point:e(t.point)}:t}function id(t,e){return{x:t.x-e.x,y:t.y-e.y}}function nr({point:t},e){return{point:t,delta:id(t,nd(e)),offset:id(t,sv(e)),velocity:ov(e,.1)}}function sv(t){return t[0]}function nd(t){return t[t.length-1]}function ov(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=nd(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 rv(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 sd(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 av(t,{top:e,left:i,bottom:n,right:s}){return{x:sd(t.x,i,s),y:sd(t.y,e,n)}}function od(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 lv(t,e){return{x:od(t.x,e.x),y:od(t.y,e.y)}}function cv(t,e){let i=.5;const n=$e(t),s=$e(e);return s>n?i=Gi(e.min,e.max-n,t.min):n>s&&(i=Gi(t.min,t.max-s,e.min)),It(0,1,i)}function dv(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 sr=.35;function uv(t=sr){return t===!1?t=0:t===!0&&(t=sr),{x:rd(t,"left","right"),y:rd(t,"top","bottom")}}function rd(t,e,i){return{min:ad(t,e),max:ad(t,i)}}function ad(t,e){return typeof t=="number"?t:t[e]||0}const hv=new WeakMap;class fv{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(on(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:_,onDragStart:v}=this.getProps();if(p&&!_&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Ig(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),tt(w=>{let C=this.getAxisMotionValue(w).get()||0;if(mt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const L=k.layout.layoutBox[w];L&&(C=$e(L)*(parseFloat(C)/100))}}this.originPoint[w]=C}),v&&we.postRender(()=>v(d,h)),Xo(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:p,dragDirectionLock:_,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:w}=h;if(_&&this.currentDirection===null){this.currentDirection=pv(w),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,w),this.updateAxis("y",h.point,w),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=()=>tt(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 td(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Qc(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||!Jn(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=rv(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&&_i(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=av(n.layoutBox,e):this.constraints=!1,this.elastic=uv(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&tt(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=dv(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!_i(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=iv(n,s.root,this.visualElement.getTransformPagePoint());let r=lv(s.layout.layoutBox,o);if(i){const a=i(zm(r));this.hasMutatedConstraints=!!a,a&&(r=Fc(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=tt(u=>{if(!Jn(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 Xo(this.visualElement,e),n.start(Jo(e,n,0,i,this.visualElement,!1))}stopAnimation(){tt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){tt(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){tt(i=>{const{drag:n}=this.getProps();if(!Jn(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(!_i(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};tt(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=cv({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(),tt(r=>{if(!Jn(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;hv.set(this.visualElement,this);const e=this.visualElement.current,i=rn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();_i(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=sn(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(tt(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=sr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function Jn(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function pv(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class gv extends Bt{constructor(e){super(e),this.removeGroupControls=et,this.removeListeners=et,this.controls=new fv(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||et}unmount(){this.removeGroupControls(),this.removeListeners()}}const ld=t=>(e,i)=>{t&&we.postRender(()=>t(e,i))};class mv extends Bt{constructor(){super(...arguments),this.removePointerDownListener=et}onPointerDown(e){this.session=new td(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Qc(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:ld(e),onStart:ld(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&we.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=rn(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 Zn={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function cd(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const cn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(Y.test(t))t=parseFloat(t);else return t;const i=cd(t,e.target.x),n=cd(t,e.target.y);return`${i}% ${n}%`}},vv={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 dd=!1;class _v extends at{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;im(yv),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),dd&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),Zn.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,dd=!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(),Bo.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 ud(t){const[e,i]=fc(),n=De(Zs);return D(_v,{...t,layoutGroup:n,switchLayoutGroup:De(Sc),isPresent:e,safeToRemove:i})}const yv={borderRadius:{...cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:cn,borderTopRightRadius:cn,borderBottomLeftRadius:cn,borderBottomRightRadius:cn,boxShadow:vv};function bv(t,e,i){const n=Ve(t)?t:mi(t);return n.start(Jo("",n,e,i)),n.animation}const wv=(t,e)=>t.depth-e.depth;class Sv{constructor(){this.children=[],this.isDirty=!1}add(e){eo(this.children,e),this.isDirty=!0}remove(e){to(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(wv),this.isDirty=!1,this.children.forEach(e)}}function Cv(t,e){const i=qe.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Pt(n),t(o-e))};return we.setup(n,!0),()=>Pt(n)}const hd=["TopLeft","TopRight","BottomLeft","BottomRight"],Tv=hd.length,fd=t=>typeof t=="string"?parseFloat(t):t,pd=t=>typeof t=="number"||Y.test(t);function Ev(t,e,i,n,s,o){s?(t.opacity=Ce(0,i.opacity??1,kv(n)),t.opacityExit=Ce(e.opacity??1,0,Iv(n))):o&&(t.opacity=Ce(e.opacity??1,i.opacity??1,n));for(let r=0;r<Tv;r++){const a=`border${hd[r]}Radius`;let l=gd(e,a),c=gd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||pd(l)===pd(c)?(t[a]=Math.max(Ce(fd(l),fd(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 gd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const kv=md(0,.5,pl),Iv=md(.5,.95,et);function md(t,e,i){return n=>n<t?0:n>e?1:i(Gi(t,e,n))}function vd(t,e){t.min=e.min,t.max=e.max}function it(t,e){vd(t.x,e.x),vd(t.y,e.y)}function _d(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function yd(t,e,i,n,s){return t-=e,t=Xn(t,1/i,n),s!==void 0&&(t=Xn(t,1/s,n)),t}function Rv(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=yd(t.min,e,i,a,s),t.max=yd(t.max,e,i,a,s)}function bd(t,e,[i,n,s],o,r){Rv(t,e[i],e[n],e[s],e.scale,o,r)}const Av=["x","scaleX","originX"],xv=["y","scaleY","originY"];function wd(t,e,i,n){bd(t.x,e,Av,i?i.x:void 0,n?n.x:void 0),bd(t.y,e,xv,i?i.y:void 0,n?n.y:void 0)}function Sd(t){return t.translate===0&&t.scale===1}function Cd(t){return Sd(t.x)&&Sd(t.y)}function Td(t,e){return t.min===e.min&&t.max===e.max}function Lv(t,e){return Td(t.x,e.x)&&Td(t.y,e.y)}function Ed(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function kd(t,e){return Ed(t.x,e.x)&&Ed(t.y,e.y)}function Id(t){return $e(t.x)/$e(t.y)}function Rd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class Dv{constructor(){this.members=[]}add(e){eo(this.members,e),e.scheduleRender()}remove(e){if(to(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 Ov(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 or=["","X","Y","Z"],Mv=1e3;let Pv=0;function rr(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function Ad(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=Dc(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&&Ad(n)}function xd({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=Pv++,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(Bv),this.nodes.forEach($v),this.nodes.forEach(Hv),this.nodes.forEach(Vv)},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 Sv)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new so),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=hc(r)&&!Og(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=Cv(h,250),Zn.hasAnimatedSinceResize&&(Zn.hasAnimatedSinceResize=!1,this.nodes.forEach(Od)))})}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()||Kv,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),w=!this.targetLayout||!kd(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(w||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...Po(_,"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||Od(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(Wv),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&&Ad(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(Ld);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(Dd);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(jv),this.nodes.forEach(Nv),this.nodes.forEach(Fv)):this.nodes.forEach(Dd),this.clearAllSnapshots();const a=qe.now();Pe.delta=It(0,1e3/60,a-Pe.timestamp),Pe.timestamp=a,Pe.isProcessing=!0,ao.update.process(Pe),ao.preRender.process(Pe),ao.render.process(Pe),Pe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Bo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(Uv),this.sharedNodes.forEach(Gv)}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=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&&!Cd(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)),Yv(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(Xv))){const{scroll:u}=this.root;u&&(bi(a.x,u.offset.x),bi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(it(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&&it(a,r),bi(a.x,d.offset.x),bi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();it(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&&wi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),Zt(u.latestValues)&&wi(l,u.latestValues)}return Zt(this.latestValues)&&wi(l,this.latestValues),l}removeTransform(r){const a=ke();it(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!Zt(c.latestValues))continue;er(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();it(u,d),wd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return Zt(this.latestValues)&&wd(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=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),it(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(),ev(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):it(this.target,this.layout.layoutBox),Kc(this.target,this.targetDelta)):it(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=ke(),this.relativeTargetOrigin=ke(),ln(this.relativeTargetOrigin,this.target,p.target),it(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||er(this.parent.latestValues)||Gc(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;it(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;tv(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:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(_d(this.prevProjectionDelta.x,this.projectionDelta.x),_d(this.prevProjectionDelta.y,this.projectionDelta.y)),an(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Rd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Rd(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=yi(),this.projectionDelta=yi(),this.projectionDeltaWithTransform=yi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=yi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),p=l?l.source:void 0,_=this.layout?this.layout.source:void 0,v=p!==_,b=this.getStack(),w=!b||b.members.length<=1,C=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(zv));this.animationProgress=0;let k;this.mixTargetDelta=L=>{const R=L/1e3;Md(d.x,r.x,R),Md(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ln(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),qv(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&Lv(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),it(k,this.relativeTarget)),v&&(this.animationValues=u,Ev(u,c,this.latestValues,R,C,w)),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(()=>{Zn.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=mi(0)),this.currentAnimation=bv(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(Mv),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&&Vd(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ke();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}it(a,l),wi(a,u),an(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new Dv),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&&rr("z",r,c,this.animationValues);for(let u=0;u<or.length;u++)rr(`rotate${or[u]}`,r,c,this.animationValues),rr(`skew${or[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=Yn(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=Yn(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=Ov(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 tn){if(u[_]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:w}=tn[_],C=d==="none"?u[_]:v(u[_],c);if(b){const k=b.length;for(let L=0;L<k;L++)r[b[L]]=C}else w?this.options.visualElement.renderState.vars[_]=C:r[_]=C}this.options.layoutId&&(r.pointerEvents=c===this?Yn(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(Ld),this.root.sharedNodes.clear()}}}function Nv(t){t.updateLayout()}function Fv(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"?tt(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=$e(h);h.min=n[d].min,h.max=h.min+p}):Vd(o,e.layoutBox,n)&&tt(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=yi();an(a,n,e.layoutBox);const l=yi();r?an(l,t.applyTransform(s,!0),e.measuredBox):an(l,n,e.layoutBox);const c=!Cd(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 _=ke();ln(_,e.layoutBox,h.layoutBox);const v=ke();ln(v,n,p.layoutBox),kd(_,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 Bv(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 Vv(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function Uv(t){t.clearSnapshot()}function Ld(t){t.clearMeasurements()}function Dd(t){t.isLayoutDirty=!1}function jv(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function Od(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function $v(t){t.resolveTargetDelta()}function Hv(t){t.calcProjection()}function Wv(t){t.resetSkewAndRotation()}function Gv(t){t.removeLeadSnapshot()}function Md(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 Pd(t,e,i,n){t.min=Ce(e.min,i.min,n),t.max=Ce(e.max,i.max,n)}function qv(t,e,i,n){Pd(t.x,e.x,i.x,n),Pd(t.y,e.y,i.y,n)}function zv(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Kv={duration:.45,ease:[.4,0,.1,1]},Nd=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),Fd=Nd("applewebkit/")&&!Nd("chrome/")?Math.round:et;function Bd(t){t.min=Fd(t.min),t.max=Fd(t.max)}function Yv(t){Bd(t.x),Bd(t.y)}function Vd(t,e,i){return t==="position"||t==="preserve-aspect"&&!Qm(Id(e),Id(i),.2)}function Xv(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const Jv=xd({attachResizeListener:(t,e)=>sn(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),ar={current:void 0},Ud=xd({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!ar.current){const t=new Jv({});t.mount(window),t.setOptions({layoutScroll:!0}),ar.current=t}return ar.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),Zv={pan:{Feature:mv},drag:{Feature:gv,ProjectionNode:Ud,MeasureLayout:ud}};function jd(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,on(e)))}class Qv extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=Rg(e,(i,n)=>(jd(this.node,n,"Start"),s=>jd(this.node,s,"End"))))}unmount(){}}class e_ extends Bt{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(sn(this.node.current,"focus",()=>this.onFocus()),sn(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function $d(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,on(e)))}class t_ extends Bt{mount(){const{current:e}=this.node;e&&(this.unmount=Dg(e,(i,n)=>($d(this.node,n,"Start"),(s,{success:o})=>$d(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const lr=new WeakMap,cr=new WeakMap,i_=t=>{const e=lr.get(t.target);e&&e(t)},n_=t=>{t.forEach(i_)};function s_({root:t,...e}){const i=t||document;cr.has(i)||cr.set(i,{});const n=cr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(n_,{root:t,...e})),n[s]}function o_(t,e,i){const n=s_(e);return lr.set(t,i),n.observe(t),()=>{lr.delete(t),n.unobserve(t)}}const r_={some:0,all:1};class a_ extends Bt{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:r_[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 o_(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(l_(e,i))&&this.startObserver()}unmount(){}}function l_({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const c_={inView:{Feature:a_},tap:{Feature:t_},focus:{Feature:e_},hover:{Feature:Qv}},d_={layout:{ProjectionNode:Ud,MeasureLayout:ud}},dr={current:null},Hd={current:!1};function u_(){if(Hd.current=!0,!!Qs)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>dr.current=t.matches;t.addEventListener("change",e),e()}else dr.current=!1}const h_=new WeakMap;function f_(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,mi(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,mi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const Wd=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class p_{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=Oo,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=qe.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=Kn(i),this.isVariantNode=yc(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,h_.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)),Hd.current||u_(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:dr.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=gi.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 vi){const i=vi[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<Wd.length;n++){const s=Wd[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=f_(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=mi(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"&&(sl(n)||rl(n))?n=parseFloat(n):!Pg(n)&&Ft.test(i)&&(n=nc(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=zo(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 so),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Gd extends p_{constructor(){super(...arguments),this.KeyframeResolver=Cg}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 qd(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 g_(t){return window.getComputedStyle(t)}class m_ extends Gd{constructor(){super(...arguments),this.type="html",this.renderInstance=qd}readValueFromInstance(e,i){var n;if(gi.has(i))return(n=this.projection)!=null&&n.isProjecting?Ro(i):Hp(e,i);{const s=g_(e),o=(lo(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){Wo(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return Ko(e,i,n)}}const zd=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 v_(t,e,i,n){qd(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(zd.has(s)?s:Ho(s),e.attrs[s])}class __ extends Gd{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(gi.has(i)){const n=ic(i);return n&&n.default||0}return i=zd.has(i)?i:Ho(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return Lc(e,i,n)}build(e,i,n){kc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){v_(e,i,n,s)}mount(e){this.isSVGTag=Rc(e.tagName),super.mount(e)}}const y_=(t,e)=>qo(t)?new __(e):new m_(e,{allowProjection:t!==ht}),b_=ym({...Gm,...c_,...Zv,...d_},y_),Si=Gg(b_),w_=["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"],dn="widget-layout-id";function Kd(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=Kd(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function At(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=Kd(t))&&(n&&(n+=" "),n+=e);return n}const S_=Dn("listening"),ur=()=>il(S_);function C_(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 Qn={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},Yd=Dn(Qn),T_=()=>{const t=Mn(Yd);return Ge(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=Qn.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=Qn.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=Qn.speak_to_interrupt_text),i}),[t])},Qt=()=>Js(Yd),Xd=({size:t="large",className:e})=>{const i=Qt(),[n]=ur();return D("h1",{className:At({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Jd=({stream:t,chatMode:e})=>{const i=ue(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 C_="4.5.1",dr=Math.PI,Ci=2*dr,ur=dr/2,Xd=8.17579892,Jd="dual-combined",es="dual-horizontal",xt="single",vt="dual-vertical",Zd="bar-index",Qd="bar-level",ts="gradient",eu=60,tu="click",T_="fullscreenchange",iu="resize",E_="#111",nu="",su="A",ou="B",ru="C",au="D",lu="468",is="sans-serif",k_="#0f0",I_="#7f7f7f22",Ti=10,cu="create",du="fschange",R_="lores",A_=iu,hr="user",x_="#000c",uu="#fff",L_="#4f4",hu="#888",D_="#555",fr="bark",un="linear",Ei="log",pr="mel",fu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],pu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:fu}],["rainbow",{dir:"h",colorStops:["#817",...fu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],hn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:ts,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ei,gradient:pu[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:nu,width:void 0},O_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],M_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],P_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],gr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],N_=["ERR_INVALID_MODE","Invalid mode"],F_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],B_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],V_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],U_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],$_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class nt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const gu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),mu=t=>{for(const e in t)return!1;return!0},ns=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],j_=(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 H_{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||(mu(i)&&!mu(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 pu)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 nt(O_)}}if(!s.createGain)throw new nt(M_);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(A_),this._fsTimeout=0)},eu))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(iu,l,{signal:c}),n.addEventListener(T_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(du),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},eu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(tu,u))};window.addEventListener(tu,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(cu)}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=ns(e,[xt,es,vt,Jd]),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=ns(e,[ts,Zd,Qd])}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=ns(e,[Ei,fr,pr,un]),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||hn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(hr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(R_)}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 nt(gr);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 nt(gr);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 nt(N_,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||hn.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 nt(F_);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=-ur),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return gu("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){gu("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=ns(e,[nu,su,ou,ru,au,lu],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(hr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return C_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new nt(B_);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(hn))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 nt(V_);if(typeof i!="object")throw new nt(U_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new nt($_);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||E_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(hr)}setFreqRange(e,i){if(e<1||i<1)throw new nt(gr);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,b=o==es,w=c%10!=0,C=w&&this._frequencyScale==Ei,k=this._showLeds&&w&&!u,L=this._lumiBars&&w&&!u,R=this._alphaBars&&!L&&c!=Ti,O=this._outlineBars&&w&&!L&&!k,T=this._roundBars&&w&&!L&&!k,E=o!=vt||h>0&&!L,g=s.height-(v&&!k?.5:0)>>v,m=g*(L||u?1:1-h)|0,f=s.width-p*(b||l!=0),S=v?s.height-g*2:0,I=p*(l==-1&&!b&&!u);let A=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,x=Math.min(p,_);d&&o!=vt&&([A,x]=[x,A]);const N=J=>e.push({...J,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=J=>{const ee=this._freqToBin(J,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),me=Math.log2(J/te)/Math.log2(ie/te);return[ee,me]};let F,G,U;if(C){const J=(se,ge,pe)=>+se.toPrecision(pe?Math.max(ge,1+Math.log10(se)|0):ge),ee=se=>{const ge=[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],pe=Math.log10(se)|0,St=se/10**pe;let ct=1;for(;ct<ge.length&&St>ge[ct];)ct++;return St-ge[ct-1]<ge[ct]-St&&ct--,(ge[ct]*10**(pe+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 Le=i?7.94328235/(te%2?1:me):Xd;do{let se=Le;const ge=J(se/me,4,!0),pe=J(se*me,4,!0),[St,ct]=M(ge),[wn,Ct]=M(pe);i?se=te<4?ee(se):J(se,se.toString()[0]<5?3:2):se=J(se,4,!0),se>=a&&N({posX:0,freq:se,freqLo:ge,freqHi:pe,binLo:St,binHi:wn,ratioLo:ct,ratioHi:Ct}),Le*=ie}while(Le<=r);F=f/e.length,e.forEach((se,ge)=>se.posX=I+ge*F);const ye=e[0],he=e[e.length-1];G=this._freqScaling(ye.freqLo),U=f/(this._freqScaling(he.freqHi)-G),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=M(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=M(r))}else if(w){const J=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case fr:return 1960/(26.81/(te+.53)-1);case pr:return 700*(2**te-1);case un:return te}};F=f/J,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);for(let te=0,ie=0;te<J;te++,ie+=F){const me=ee(G+ie/U),Le=ee(G+(ie+F/2)/U),ye=ee(G+(ie+F)/U),[he,se]=M(me),[ge,pe]=M(ye);N({posX:I+ie,freq:Le,freqLo:me,freqHi:ye,binLo:he,binHi:ge,ratioLo:se,ratioHi:pe})}}else{F=1,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);const J=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=J;ie<=ee;ie++){const me=this._binToFreq(ie),Le=I+Math.round(U*(this._freqScaling(me)-G));if(Le>te)N({posX:Le,freq:me,freqLo:me,freqHi:me,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Le;else if(e.length){const ye=e[e.length-1];ye.binHi=ie,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let ae=0,q=0;if(k){const J=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,Le]=te||ee[c];let ye,he=m;if(te){const se=2*J;let ge;ye=ie+1;do ye--,ge=he/ye/(1+me),q=ge*me;while((ge<se||q<se)&&ye>1)}else{const se=540/me;q=Math.min(me*J,Math.max(2,he/se+.1|0))}E&&(he+=q),te||(ye=Math.min(ie,he/(q*2)|0)),ae=Le>=1?Le:F*Le,this._leds=[ye,ae,q,he/ye-q]}const H=Math.min(F-1,n*(n>0&&n<1?F:1));w&&(F-=Math.max(k?ae:0,H)),e.forEach((J,ee)=>{let te=J.posX,ie=F;w&&(n==0&&!k?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(k?ae:0,H)/2,J.posX=te),J.barCenter=te+(F==1?0:ie/2),J.width=ie});const ce=[];for(const J of[0,1]){const ee=o==vt?(g+S)*J:0,te=ee+g,ie=ee+m-(!k||E?0:q);ce.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:p,centerY:_,channelCoords:ce,channelHeight:g,channelGap:S,initialX:I,innerRadius:A,outerRadius:x,scaleMin:G,unitWidth:U},this._flg={isAlpha:R,isBands:w,isLeds:k,isLumi:L,isOctaves:C,isOutline:O,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,p=d.canvas,_=h.canvas,v=[],b=this._chLayout==es,w=this._chLayout==vt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],L=C/34|0,R=p.height>>1,O=L>>1,T=R*(c?.7:1.5),E=O*(c?1:2),g=2**(1/12);if(!c&&(this._ansiBands||a!=Ei))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==un?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=Xd;for(let N=-1;N<11;N++)for(let M=0;M<12;M++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[M],G=F=="C";(F&&c&&!l&&!b||G)&&v.push(c?[x,F+(G?N:"")]:x)}x*=g}}_.width=_.height=Math.max(C*.15,(n<<1)+w*L);const m=_.width>>1,f=m-L*.7,S=(x,N)=>{const M=Ci*(x/r.width),F=M-ur,G=f*Math.cos(F),U=f*Math.sin(F);h.save(),h.translate(m+G,m+U),h.rotate(M),h.fillText(N,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=x_,d.fillRect(0,0,p.width,p.height),h.arc(m,m,m-L/2,0,Ci),h.lineWidth=L,h.stroke(),d.fillStyle=h.fillStyle=uu,d.font=`${R}px ${is}`,h.font=`${O}px ${is}`,d.textAlign=h.textAlign="center";let I=-T/4,A=-E;for(const x of v){const[N,M]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(N)-s),G=p.height*.75,U=M[0]=="C",ae=R*(c&&!l&&!b?U?1.2:.6:3);if(d.fillStyle=h.fillStyle=U&&!l&&!b?L_:uu,c){const q=a==Ei,H=a==un;let ce=["C"];if((q||N>2e3||!H&&N>250||(!u||w)&&(!H&&N>125||N>1e3))&&ce.push("G"),(q||N>4e3||!H&&N>500||(!u||w)&&(!H&&N>250||N>2e3))&&ce.push("E"),(H&&N>4e3||(!u||w)&&(q||N>2e3||!H&&N>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(M,b&&l==-1?e-F:i+F,G,ae),(b||l&&(F>T||l==1))&&d.fillText(M,b&&l!=1?e+F:(i||r.width)-F,G,ae),I=F+Math.min(ae,d.measureText(M).width)/2),F>=A+E&&F<e-E&&(S(b&&l==1?e-F:F,M),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,M),A=F)}}_draw(e){this._runId=requestAnimationFrame($=>this._draw($));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:b,channelHeight:w,channelGap:C,initialX:k,innerRadius:L,outerRadius:R}=this._aux,{_bars:O,canvas:T,_canvasGradients:E,_chLayout:g,_colorMode:m,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:A,_fps:x,_linearAmplitude:N,_lineWidth:M,maxDecibels:F,minDecibels:G,_mirror:U,_mode:ae,overlay:q,_radial:H,showBgColor:ce,showPeaks:J,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,me=this._scaleR.canvas,Le=x*this._peakFadeTime/1e3,ye=x**2,he=this._gravity*1e3,se=x*this._peakHoldTime/1e3,ge=g==Jd,pe=g==es,St=g==vt,ct=g==xt,wn=a&&this._trueLeds&&m==ts,Ct=H?T.width:this._aux.analyzerWidth,Hr=k+Ct,Sn=J&&this._peakLine&&ae==Ti,$t=H?R-L:p,mw=$t/this._pixelRatio,[vw,Iw,Cn,Wr]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ci/60/x);const _w=$=>{if(this._reflexRatio>0&&!l&&!H){let de,Tt;this.reflexFit||St?(de=St&&$==0?w+C:0,Tt=w-p):(de=T.height-p*2,Tt=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,b[$].channelTop,T.width,p,0,de,T.width,Tt),f.restore()}},yw=()=>{this.showScaleX&&(H?(f.save(),f.translate(_,v),this._spinSpeed&&f.rotate(this._spinAngle+ur),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ie,0,T.height-ie.height))},bw=$=>{const de=$**2,Tt=424.36,Be=11599.29,Ts=25122.25,jt=544496.41,Ot=148693636,oi=ri=>20*Math.log10(ri);switch(te){case su:const ri=Ot*de**2/((de+Tt)*Math.sqrt((de+Be)*(de+jt))*(de+Ot));return 2+oi(ri);case ou:const ai=Ot*de*$/((de+Tt)*Math.sqrt(de+Ts)*(de+Ot));return .17+oi(ai);case ru:const zr=Ot*de/((de+Tt)*(de+Ot));return .06+oi(zr);case au:const Es=((103791848e-2-de)**2+108076816e-2*de)/((9837328-de)**2+11723776*de),Kr=$/68966888496476e-18*Math.sqrt(Es/((de+79919.29)*(de+1345600)));return oi(Kr);case lu:const ks=-4737338981378384e-39*$**6+2043828333606125e-30*$**4-1363894795463638e-22*de+1,li=1306612257412824e-34*$**5-2118150887518656e-26*$**3+.0005559488023498642*$,Je=.0001246332637532143*$/Math.hypot(ks,li);return 18.2+oi(Je)}return 0},Gr=($,de,Tt)=>{f.beginPath(),f.moveTo($,de),f.lineTo($,Tt),f.stroke()},qr=$=>{if($&&M){const de=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=de}},si=$=>Math.max(0,($*vw|0)*(Wr+Cn)-Cn),ww=$=>{S.val=$,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*he/ye/T.height*this._pixelRatio)),$>=S.peak&&(S.peak=$,S.hold=se)};q&&f.clearRect(0,0,T.width,T.height);let Wh=0;const Gh=O.length,qh=ct?1:2;for(let $=0;$<qh;$++){const{channelTop:de,channelBottom:Tt,analyzerBottom:Be}=b[$],Ts=this._gradients[this._selectedGrads[$]],jt=Ts.colorStops,Ot=jt.length,oi=!ce||a&&!q?"#000":Ts.bgColor,ri=St&&H&&$?-1:1,ai=!$&&U==-1||$&&U==1,zr=!pe||$&&U!=1?0:Ct>>($||!ai),Es=pe&&ai?-1:1,Kr=()=>{const z=ie.height,X=z>>1,Q=N?100:F,be=N?0:G,Re=N?20:5,Ke=p/(Q-be),Et=U!=-1&&(!pe||$==0||U==1),Ht=U!=1&&(!pe||$!=U);f.save(),f.fillStyle=hu,f.font=`${X}px ${is}`,f.textAlign="right",f.lineWidth=1;for(let Wt=Q;Wt>be;Wt-=Re){const Ni=de+(Q-Wt)*Ke,Me=Wt%2==0|0;if(Me){const We=Ni+X*(Ni==de?.8:.35);Et&&f.fillText(Wt,z*.85,We),Ht&&f.fillText(Wt,(pe?Ct:T.width)-z*.1,We),f.strokeStyle=hu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=D_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+z*Me*Et,~~Ni+.5),f.lineTo(Hr-z*Me*Ht,~~Ni+.5),f.stroke()}f.restore()},ks=(z,X)=>{const Q=dt[z]+(z<dt.length-1?(dt[z+1]-dt[z])*X:0);return isNaN(Q)?-1/0:Q},li=(z,X=Es)=>X*Ci*((z+zr)/T.width)+this._spinAngle,Je=(z,X,Q)=>{const be=L+X*ri,Re=li(z,Q);return[_+be*Math.cos(Re),v+be*Math.sin(Re)]},Yr=(z,X,Q,be,Re)=>{f.beginPath();for(const Ke of U&&!pe?[1,-1]:[Es]){const[Et,Ht]=d?[li(z,Ke),li(z+Q,Ke)]:[];f.moveTo(...Je(z,X,Ke)),f.lineTo(...Je(z,X+be,Ke)),d?f.arc(_,v,L+(X+be)*ri,Et,Ht,Ke!=1):f.lineTo(...Je(z+Q,X+be,Ke)),f.lineTo(...Je(z+Q,X,Ke)),d&&!Re&&f.arc(_,v,L+X*ri,Ht,Et,Ke==1)}qr(Re),f.fill()},Xr=(z=0,X=0)=>{let Q;if(m==ts&&!wn||ae==Ti)Q=E[$];else{const be=m==Zd?X%Ot:jt.findLastIndex(Re=>a?si(z)<=si(Re.level):z<=Re.level);Q=jt[be].color}f.fillStyle=f.strokeStyle=Q};if(ee){if(pe&&!H){const z=Ct*($+ai),X=ai?-1:1;f.setTransform(X,0,0,1,z,0)}if((!q||ce)&&(q&&(f.globalAlpha=this.bgAlpha),f.fillStyle=oi,($==0||!H&&!ge)&&f.fillRect(k,de-C,Ct,(q&&this.reflexAlpha==1?p:w)+C),f.globalAlpha=1),this.showScaleY&&!l&&!H&&($==0||!ge)&&Kr(),a?(f.setLineDash([Wr,Cn]),f.lineWidth=O[0].width):f.lineWidth=u?Math.min(M,O[0].width/2):M,f.save(),!H){const z=new Path2D;z.rect(0,de,T.width,p),f.clip(z)}}let dt=this._fftData[$];this._analyzer[$].getFloatFrequencyData(dt),te&&(dt=dt.map((z,X)=>z+bw(this._binToFreq(X)))),f.beginPath();let Tn=[];for(let z=0;z<Gh;z++){const X=O[z],{posX:Q,barCenter:be,width:Re,freq:Ke,binLo:Et,binHi:Ht,ratioLo:Wt,ratioHi:Ni}=X;let Me=Math.max(ks(Et,Wt),ks(Ht,Ni));for(let ve=Et+1;ve<Ht;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),X.value[$]=Me,Wh+=Me,X.peak[$]>0&&X.alpha[$]>0&&(X.hold[$]--,X.hold[$]<0)){if(I&&!Sn){const ve=!o||u&&M>0?1:o?X.peak[$]:A;X.alpha[$]=ve*(1+X.hold[$]/Le)}else X.peak[$]+=X.hold[$]*he/ye/mw;X.alpha[$]<=0&&(X.peak[$]=0)}if(Me>=X.peak[$]&&(X.peak[$]=Me,X.hold[$]=se,X.alpha[$]=!o||u&&M>0?1:o?Me:A),!ee)continue;f.globalAlpha=l||o?Me:u?A:1,Xr(Me,z);const We=l?$t:a?si(Me):Me*$t|0;if(ae==Ti){const ve=z?0:(this._normalizedB(dt[O[1].binLo])*$t+We)/2;if(H){if(z==0&&(pe&&f.moveTo(...Je(0,0)),f.lineTo(...Je(0,Q<0?ve:We))),Q>=0){const ot=[Q,We];f.lineTo(...Je(...ot)),Tn.push(ot)}}else{if(z==0)if(U==-1&&!pe)f.moveTo(k,Be-(Q<k?ve:We));else{const ot=Et?this._normalizedB(dt[Et-1])*$t:We;f.moveTo(k-M,Be-ot)}(pe||U!=-1||Q>=k)&&f.lineTo(Q,Be-We)}}else if(a){if(ce&&!q&&($==0||!ge)){const ve=f.globalAlpha;f.strokeStyle=I_,f.globalAlpha=1,Gr(be,de,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(wn){const ve=l?0:jt.findLastIndex(ci=>si(Me)<=si(ci.level));let ot=Be;for(let ci=Ot-1;ci>=ve;ci--){f.strokeStyle=jt[ci].color;let Kh=Be-(ci==ve?We:si(jt[ci].level));Gr(be,ot,Kh),ot=Kh-Cn}}else Gr(be,Be,Be-We)}else if(Q>=k)if(H)Yr(Q,0,Re,We,u);else if(d){const ve=Re/2,ot=Be+ve;f.beginPath(),f.moveTo(Q,ot),f.lineTo(Q,ot-We),f.arc(be,ot-We,ve,dr,Ci),f.lineTo(Q+Re,ot),qr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(Q,Be+ve,Re,-We-ve),qr(u),f.fill()}const Fi=X.peak[$],zh=X.alpha[$];if(Fi>0&&zh>0&&J&&!Sn&&!l&&Q>=k&&Q<Hr){if(I?f.globalAlpha=zh:u&&M>0?f.globalAlpha=1:o&&(f.globalAlpha=Fi),(m==Qd||wn)&&Xr(Fi),a){const ve=si(Fi);ve>=Cn&&f.fillRect(Q,Be-ve,Re,Wr)}else if(!H)f.fillRect(Q,Be-Fi*$t,Re,2);else if(ae!=Ti){const ve=Fi*$t;Yr(Q,ve,Re,!this._radialInvert||St||ve+L>=2?-2:2)}}}if(ee){if(f.globalAlpha=1,ae==Ti){if(Xr(),H&&!pe){if(U){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1))}f.closePath()}if(M>0&&f.stroke(),A>0){if(H){const z=pe?li(Ct>>1):0,X=pe?li(Ct):Ci;f.moveTo(...Je(pe?Ct>>1:0,0)),f.arc(_,v,L,z,X,pe?!ai:!0)}else f.lineTo(Hr,Be),f.lineTo(k,Be);f.globalAlpha=A,f.fill(),f.globalAlpha=1}if((Sn||H&&J)&&(Tn=[],f.beginPath(),O.forEach((z,X)=>{let Q=z.posX,be=z.peak[$],Re=X?"lineTo":"moveTo";if(H&&Q<0){const Ke=O[X+1];be=j_(Q,be,Ke.posX,Ke.peak[$],0),Q=0}be*=$t,Sn?(f[Re](...H?Je(Q,be):[Q,Be-be]),H&&U&&!pe&&Tn.push([Q,be])):be>0&&Yr(Q,be,1,-2)}),Sn)){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1));f.lineWidth=1,f.stroke()}}f.restore(),pe&&!H&&f.setTransform(1,0,0,1,0,0),(!pe&&!ge||$)&&_w($)}}if(ww(Wh/(Gh<<qh-1)),ee&&(U&&!H&&!pe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,_,T.height,0,0,_,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),yw()),this.showFPS){const $=ie.height;f.font=`bold ${$}px ${is}`,f.fillStyle=k_,f.textAlign="right",f.fillText(Math.round(x),T.width-$,$*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 Ei:return Math.log2(e);case fr:return 26.81*e/(1960+e)-.53;case pr:return Math.log2(1+e/700);case un: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 b=this._gradients[this._selectedGrads[v]],w=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,_]),w){const L=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+L;R++){const O=w.length-1;w.forEach((T,E)=>{let g=T.pos;if(L&&(g/=2),h&&!d&&!n&&!C&&(g*=p,!L&&g>.5*p&&(g+=.5*s)),R==1)if(n||d){const m=O-E;T=w[m],g=1-T.pos/2}else E==0&&g>0&&k.addColorStop(.5,T.color),g+=.5;k.addColorStop(g,T.color),h&&E==O&&g<.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!=cu&&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=du),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new nt(P_,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(hn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...hn,...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 W_={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}]}},vu=({stream:t,className:e,onClick:i})=>{var o;const n=ue(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new H_(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",W_[((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:At("w-full",e),ref:n})},_u=Dn(null),yu=({className:t,debug:e=!1})=>{const i=Ys(_u);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 E_="4.5.1",hr=Math.PI,Ci=2*hr,fr=hr/2,Zd=8.17579892,Qd="dual-combined",es="dual-horizontal",xt="single",vt="dual-vertical",eu="bar-index",tu="bar-level",ts="gradient",iu=60,nu="click",k_="fullscreenchange",su="resize",I_="#111",ou="",ru="A",au="B",lu="C",cu="D",du="468",is="sans-serif",R_="#0f0",A_="#7f7f7f22",Ti=10,uu="create",hu="fschange",x_="lores",L_=su,pr="user",D_="#000c",fu="#fff",O_="#4f4",pu="#888",M_="#555",gr="bark",un="linear",Ei="log",mr="mel",gu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],mu=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:gu}],["rainbow",{dir:"h",colorStops:["#817",...gu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],hn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:xt,colorMode:ts,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ei,gradient:mu[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:ou,width:void 0},P_=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],N_=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],F_=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],vr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],B_=["ERR_INVALID_MODE","Invalid mode"],V_=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],U_=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],j_=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],$_=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],H_=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class nt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const vu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),_u=t=>{for(const e in t)return!1;return!0},ns=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],W_=(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 G_{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||(_u(i)&&!_u(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 mu)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 nt(P_)}}if(!s.createGain)throw new nt(N_);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(L_),this._fsTimeout=0)},iu))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(su,l,{signal:c}),n.addEventListener(k_,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(hu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},iu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(nu,u))};window.addEventListener(nu,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(uu)}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=ns(e,[xt,es,vt,Qd]),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=ns(e,[ts,eu,tu])}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=ns(e,[Ei,gr,mr,un]),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||hn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(pr)}get ledBars(){return this._showLeds}set ledBars(e){this._showLeds=!!e,this._calcBars()}get linearAmplitude(){return this._linearAmplitude}set linearAmplitude(e){this._linearAmplitude=!!e}get linearBoost(){return this._linearBoost}set linearBoost(e){this._linearBoost=e>=1?+e:1}get lineWidth(){return this._lineWidth}set lineWidth(e){this._lineWidth=+e||0}get loRes(){return this._loRes}set loRes(e){this._loRes=!!e,this._setCanvas(x_)}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 nt(vr);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 nt(vr);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 nt(B_,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||hn.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 nt(V_);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=-fr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return vu("stereo","channelLayout"),this._chLayout!=xt}set stereo(e){vu("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=ns(e,[ou,ru,au,lu,cu,du],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(pr)}get audioCtx(){return this._input.context}get canvas(){return this._ctx.canvas}get canvasCtx(){return this._ctx}get connectedSources(){return this._sources}get connectedTo(){return this._outNodes}get fps(){return this._fps}get fsHeight(){return this._fsHeight}get fsWidth(){return this._fsWidth}get isAlphaBars(){return this._flg.isAlpha}get isBandsMode(){return this._flg.isBands}get isDestroyed(){return this._destroyed}get isFullscreen(){return this._fsEl&&(document.fullscreenElement||document.webkitFullscreenElement)===this._fsEl}get isLedBars(){return this._flg.isLeds}get isLumiBars(){return this._flg.isLumi}get isOctaveBands(){return this._flg.isOctaves}get isOn(){return!!this._runId}get isOutlineBars(){return this._flg.isOutline}get pixelRatio(){return this._pixelRatio}get isRoundBars(){return this._flg.isRound}static get version(){return E_}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new nt(U_);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(hn))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 nt(j_);if(typeof i!="object")throw new nt($_);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new nt(H_);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||I_,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(pr)}setFreqRange(e,i){if(e<1||i<1)throw new nt(vr);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,b=o==es,w=c%10!=0,C=w&&this._frequencyScale==Ei,k=this._showLeds&&w&&!u,L=this._lumiBars&&w&&!u,R=this._alphaBars&&!L&&c!=Ti,O=this._outlineBars&&w&&!L&&!k,T=this._roundBars&&w&&!L&&!k,E=o!=vt||h>0&&!L,g=s.height-(v&&!k?.5:0)>>v,m=g*(L||u?1:1-h)|0,f=s.width-p*(b||l!=0),S=v?s.height-g*2:0,I=p*(l==-1&&!b&&!u);let A=Math.min(s.width,s.height)*.375*(o==vt?1:this._radius)|0,x=Math.min(p,_);d&&o!=vt&&([A,x]=[x,A]);const N=J=>e.push({...J,peak:[0,0],hold:[0],alpha:[0],value:[0]}),M=J=>{const ee=this._freqToBin(J,"floor"),te=this._binToFreq(ee),ie=this._binToFreq(ee+1),me=Math.log2(J/te)/Math.log2(ie/te);return[ee,me]};let F,G,U;if(C){const J=(se,ge,pe)=>+se.toPrecision(pe?Math.max(ge,1+Math.log10(se)|0):ge),ee=se=>{const ge=[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],pe=Math.log10(se)|0,St=se/10**pe;let ct=1;for(;ct<ge.length&&St>ge[ct];)ct++;return St-ge[ct-1]<ge[ct]-St&&ct--,(ge[ct]*10**(pe+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 Le=i?7.94328235/(te%2?1:me):Zd;do{let se=Le;const ge=J(se/me,4,!0),pe=J(se*me,4,!0),[St,ct]=M(ge),[wn,Ct]=M(pe);i?se=te<4?ee(se):J(se,se.toString()[0]<5?3:2):se=J(se,4,!0),se>=a&&N({posX:0,freq:se,freqLo:ge,freqHi:pe,binLo:St,binHi:wn,ratioLo:ct,ratioHi:Ct}),Le*=ie}while(Le<=r);F=f/e.length,e.forEach((se,ge)=>se.posX=I+ge*F);const ye=e[0],he=e[e.length-1];G=this._freqScaling(ye.freqLo),U=f/(this._freqScaling(he.freqHi)-G),ye.freqLo<a&&(ye.freqLo=a,[ye.binLo,ye.ratioLo]=M(a)),he.freqHi>r&&(he.freqHi=r,[he.binHi,he.ratioHi]=M(r))}else if(w){const J=[0,24,12,8,6,4,3,2,1][c]*10,ee=te=>{switch(this._frequencyScale){case gr:return 1960/(26.81/(te+.53)-1);case mr:return 700*(2**te-1);case un:return te}};F=f/J,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);for(let te=0,ie=0;te<J;te++,ie+=F){const me=ee(G+ie/U),Le=ee(G+(ie+F/2)/U),ye=ee(G+(ie+F)/U),[he,se]=M(me),[ge,pe]=M(ye);N({posX:I+ie,freq:Le,freqLo:me,freqHi:ye,binLo:he,binHi:ge,ratioLo:se,ratioHi:pe})}}else{F=1,G=this._freqScaling(a),U=f/(this._freqScaling(r)-G);const J=this._freqToBin(a,"floor"),ee=this._freqToBin(r);let te=-999;for(let ie=J;ie<=ee;ie++){const me=this._binToFreq(ie),Le=I+Math.round(U*(this._freqScaling(me)-G));if(Le>te)N({posX:Le,freq:me,freqLo:me,freqHi:me,binLo:ie,binHi:ie,ratioLo:0,ratioHi:0}),te=Le;else if(e.length){const ye=e[e.length-1];ye.binHi=ie,ye.freqHi=me,ye.freq=(ye.freqLo*me)**.5}}}let ae=0,q=0;if(k){const J=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,Le]=te||ee[c];let ye,he=m;if(te){const se=2*J;let ge;ye=ie+1;do ye--,ge=he/ye/(1+me),q=ge*me;while((ge<se||q<se)&&ye>1)}else{const se=540/me;q=Math.min(me*J,Math.max(2,he/se+.1|0))}E&&(he+=q),te||(ye=Math.min(ie,he/(q*2)|0)),ae=Le>=1?Le:F*Le,this._leds=[ye,ae,q,he/ye-q]}const H=Math.min(F-1,n*(n>0&&n<1?F:1));w&&(F-=Math.max(k?ae:0,H)),e.forEach((J,ee)=>{let te=J.posX,ie=F;w&&(n==0&&!k?(te|=0,ie|=0,ee>0&&te>e[ee-1].posX+e[ee-1].width&&(te--,ie++)):te+=Math.max(k?ae:0,H)/2,J.posX=te),J.barCenter=te+(F==1?0:ie/2),J.width=ie});const ce=[];for(const J of[0,1]){const ee=o==vt?(g+S)*J:0,te=ee+g,ie=ee+m-(!k||E?0:q);ce.push({channelTop:ee,channelBottom:te,analyzerBottom:ie})}this._aux={analyzerHeight:m,analyzerWidth:f,centerX:p,centerY:_,channelCoords:ce,channelHeight:g,channelGap:S,initialX:I,innerRadius:A,outerRadius:x,scaleMin:G,unitWidth:U},this._flg={isAlpha:R,isBands:w,isLeds:k,isLumi:L,isOctaves:C,isOutline:O,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,p=d.canvas,_=h.canvas,v=[],b=this._chLayout==es,w=this._chLayout==vt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],L=C/34|0,R=p.height>>1,O=L>>1,T=R*(c?.7:1.5),E=O*(c?1:2),g=2**(1/12);if(!c&&(this._ansiBands||a!=Ei))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==un?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=Zd;for(let N=-1;N<11;N++)for(let M=0;M<12;M++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[M],G=F=="C";(F&&c&&!l&&!b||G)&&v.push(c?[x,F+(G?N:"")]:x)}x*=g}}_.width=_.height=Math.max(C*.15,(n<<1)+w*L);const m=_.width>>1,f=m-L*.7,S=(x,N)=>{const M=Ci*(x/r.width),F=M-fr,G=f*Math.cos(F),U=f*Math.sin(F);h.save(),h.translate(m+G,m+U),h.rotate(M),h.fillText(N,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=D_,d.fillRect(0,0,p.width,p.height),h.arc(m,m,m-L/2,0,Ci),h.lineWidth=L,h.stroke(),d.fillStyle=h.fillStyle=fu,d.font=`${R}px ${is}`,h.font=`${O}px ${is}`,d.textAlign=h.textAlign="center";let I=-T/4,A=-E;for(const x of v){const[N,M]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(N)-s),G=p.height*.75,U=M[0]=="C",ae=R*(c&&!l&&!b?U?1.2:.6:3);if(d.fillStyle=h.fillStyle=U&&!l&&!b?O_:fu,c){const q=a==Ei,H=a==un;let ce=["C"];if((q||N>2e3||!H&&N>250||(!u||w)&&(!H&&N>125||N>1e3))&&ce.push("G"),(q||N>4e3||!H&&N>500||(!u||w)&&(!H&&N>250||N>2e3))&&ce.push("E"),(H&&N>4e3||(!u||w)&&(q||N>2e3||!H&&N>500))&&ce.push("D","F","A","B"),!ce.includes(M[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(M,b&&l==-1?e-F:i+F,G,ae),(b||l&&(F>T||l==1))&&d.fillText(M,b&&l!=1?e+F:(i||r.width)-F,G,ae),I=F+Math.min(ae,d.measureText(M).width)/2),F>=A+E&&F<e-E&&(S(b&&l==1?e-F:F,M),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,M),A=F)}}_draw(e){this._runId=requestAnimationFrame(j=>this._draw(j));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:b,channelHeight:w,channelGap:C,initialX:k,innerRadius:L,outerRadius:R}=this._aux,{_bars:O,canvas:T,_canvasGradients:E,_chLayout:g,_colorMode:m,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:A,_fps:x,_linearAmplitude:N,_lineWidth:M,maxDecibels:F,minDecibels:G,_mirror:U,_mode:ae,overlay:q,_radial:H,showBgColor:ce,showPeaks:J,useCanvas:ee,_weightingFilter:te}=this,ie=this._scaleX.canvas,me=this._scaleR.canvas,Le=x*this._peakFadeTime/1e3,ye=x**2,he=this._gravity*1e3,se=x*this._peakHoldTime/1e3,ge=g==Qd,pe=g==es,St=g==vt,ct=g==xt,wn=a&&this._trueLeds&&m==ts,Ct=H?T.width:this._aux.analyzerWidth,Gr=k+Ct,Sn=J&&this._peakLine&&ae==Ti,jt=H?R-L:p,_w=jt/this._pixelRatio,[yw,Aw,Cn,qr]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ci/60/x);const bw=j=>{if(this._reflexRatio>0&&!l&&!H){let de,Tt;this.reflexFit||St?(de=St&&j==0?w+C:0,Tt=w-p):(de=T.height-p*2,Tt=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,b[j].channelTop,T.width,p,0,de,T.width,Tt),f.restore()}},ww=()=>{this.showScaleX&&(H?(f.save(),f.translate(_,v),this._spinSpeed&&f.rotate(this._spinAngle+fr),f.drawImage(me,-me.width>>1,-me.width>>1),f.restore()):f.drawImage(ie,0,T.height-ie.height))},Sw=j=>{const de=j**2,Tt=424.36,Be=11599.29,ks=25122.25,$t=544496.41,Ot=148693636,oi=ri=>20*Math.log10(ri);switch(te){case ru:const ri=Ot*de**2/((de+Tt)*Math.sqrt((de+Be)*(de+$t))*(de+Ot));return 2+oi(ri);case au:const ai=Ot*de*j/((de+Tt)*Math.sqrt(de+ks)*(de+Ot));return .17+oi(ai);case lu:const Yr=Ot*de/((de+Tt)*(de+Ot));return .06+oi(Yr);case cu:const Is=((103791848e-2-de)**2+108076816e-2*de)/((9837328-de)**2+11723776*de),Xr=j/68966888496476e-18*Math.sqrt(Is/((de+79919.29)*(de+1345600)));return oi(Xr);case du:const Rs=-4737338981378384e-39*j**6+2043828333606125e-30*j**4-1363894795463638e-22*de+1,li=1306612257412824e-34*j**5-2118150887518656e-26*j**3+.0005559488023498642*j,Je=.0001246332637532143*j/Math.hypot(Rs,li);return 18.2+oi(Je)}return 0},zr=(j,de,Tt)=>{f.beginPath(),f.moveTo(j,de),f.lineTo(j,Tt),f.stroke()},Kr=j=>{if(j&&M){const de=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=de}},si=j=>Math.max(0,(j*yw|0)*(qr+Cn)-Cn),Cw=j=>{S.val=j,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*he/ye/T.height*this._pixelRatio)),j>=S.peak&&(S.peak=j,S.hold=se)};q&&f.clearRect(0,0,T.width,T.height);let qh=0;const zh=O.length,Kh=ct?1:2;for(let j=0;j<Kh;j++){const{channelTop:de,channelBottom:Tt,analyzerBottom:Be}=b[j],ks=this._gradients[this._selectedGrads[j]],$t=ks.colorStops,Ot=$t.length,oi=!ce||a&&!q?"#000":ks.bgColor,ri=St&&H&&j?-1:1,ai=!j&&U==-1||j&&U==1,Yr=!pe||j&&U!=1?0:Ct>>(j||!ai),Is=pe&&ai?-1:1,Xr=()=>{const z=ie.height,X=z>>1,Q=N?100:F,be=N?0:G,Re=N?20:5,Ke=p/(Q-be),Et=U!=-1&&(!pe||j==0||U==1),Ht=U!=1&&(!pe||j!=U);f.save(),f.fillStyle=pu,f.font=`${X}px ${is}`,f.textAlign="right",f.lineWidth=1;for(let Wt=Q;Wt>be;Wt-=Re){const Ni=de+(Q-Wt)*Ke,Me=Wt%2==0|0;if(Me){const We=Ni+X*(Ni==de?.8:.35);Et&&f.fillText(Wt,z*.85,We),Ht&&f.fillText(Wt,(pe?Ct:T.width)-z*.1,We),f.strokeStyle=pu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=M_,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+z*Me*Et,~~Ni+.5),f.lineTo(Gr-z*Me*Ht,~~Ni+.5),f.stroke()}f.restore()},Rs=(z,X)=>{const Q=dt[z]+(z<dt.length-1?(dt[z+1]-dt[z])*X:0);return isNaN(Q)?-1/0:Q},li=(z,X=Is)=>X*Ci*((z+Yr)/T.width)+this._spinAngle,Je=(z,X,Q)=>{const be=L+X*ri,Re=li(z,Q);return[_+be*Math.cos(Re),v+be*Math.sin(Re)]},Jr=(z,X,Q,be,Re)=>{f.beginPath();for(const Ke of U&&!pe?[1,-1]:[Is]){const[Et,Ht]=d?[li(z,Ke),li(z+Q,Ke)]:[];f.moveTo(...Je(z,X,Ke)),f.lineTo(...Je(z,X+be,Ke)),d?f.arc(_,v,L+(X+be)*ri,Et,Ht,Ke!=1):f.lineTo(...Je(z+Q,X+be,Ke)),f.lineTo(...Je(z+Q,X,Ke)),d&&!Re&&f.arc(_,v,L+X*ri,Ht,Et,Ke==1)}Kr(Re),f.fill()},Zr=(z=0,X=0)=>{let Q;if(m==ts&&!wn||ae==Ti)Q=E[j];else{const be=m==eu?X%Ot:$t.findLastIndex(Re=>a?si(z)<=si(Re.level):z<=Re.level);Q=$t[be].color}f.fillStyle=f.strokeStyle=Q};if(ee){if(pe&&!H){const z=Ct*(j+ai),X=ai?-1:1;f.setTransform(X,0,0,1,z,0)}if((!q||ce)&&(q&&(f.globalAlpha=this.bgAlpha),f.fillStyle=oi,(j==0||!H&&!ge)&&f.fillRect(k,de-C,Ct,(q&&this.reflexAlpha==1?p:w)+C),f.globalAlpha=1),this.showScaleY&&!l&&!H&&(j==0||!ge)&&Xr(),a?(f.setLineDash([qr,Cn]),f.lineWidth=O[0].width):f.lineWidth=u?Math.min(M,O[0].width/2):M,f.save(),!H){const z=new Path2D;z.rect(0,de,T.width,p),f.clip(z)}}let dt=this._fftData[j];this._analyzer[j].getFloatFrequencyData(dt),te&&(dt=dt.map((z,X)=>z+Sw(this._binToFreq(X)))),f.beginPath();let Tn=[];for(let z=0;z<zh;z++){const X=O[z],{posX:Q,barCenter:be,width:Re,freq:Ke,binLo:Et,binHi:Ht,ratioLo:Wt,ratioHi:Ni}=X;let Me=Math.max(Rs(Et,Wt),Rs(Ht,Ni));for(let ve=Et+1;ve<Ht;ve++)dt[ve]>Me&&(Me=dt[ve]);if(Me=this._normalizedB(Me),X.value[j]=Me,qh+=Me,X.peak[j]>0&&X.alpha[j]>0&&(X.hold[j]--,X.hold[j]<0)){if(I&&!Sn){const ve=!o||u&&M>0?1:o?X.peak[j]:A;X.alpha[j]=ve*(1+X.hold[j]/Le)}else X.peak[j]+=X.hold[j]*he/ye/_w;X.alpha[j]<=0&&(X.peak[j]=0)}if(Me>=X.peak[j]&&(X.peak[j]=Me,X.hold[j]=se,X.alpha[j]=!o||u&&M>0?1:o?Me:A),!ee)continue;f.globalAlpha=l||o?Me:u?A:1,Zr(Me,z);const We=l?jt:a?si(Me):Me*jt|0;if(ae==Ti){const ve=z?0:(this._normalizedB(dt[O[1].binLo])*jt+We)/2;if(H){if(z==0&&(pe&&f.moveTo(...Je(0,0)),f.lineTo(...Je(0,Q<0?ve:We))),Q>=0){const ot=[Q,We];f.lineTo(...Je(...ot)),Tn.push(ot)}}else{if(z==0)if(U==-1&&!pe)f.moveTo(k,Be-(Q<k?ve:We));else{const ot=Et?this._normalizedB(dt[Et-1])*jt:We;f.moveTo(k-M,Be-ot)}(pe||U!=-1||Q>=k)&&f.lineTo(Q,Be-We)}}else if(a){if(ce&&!q&&(j==0||!ge)){const ve=f.globalAlpha;f.strokeStyle=A_,f.globalAlpha=1,zr(be,de,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(wn){const ve=l?0:$t.findLastIndex(ci=>si(Me)<=si(ci.level));let ot=Be;for(let ci=Ot-1;ci>=ve;ci--){f.strokeStyle=$t[ci].color;let Xh=Be-(ci==ve?We:si($t[ci].level));zr(be,ot,Xh),ot=Xh-Cn}}else zr(be,Be,Be-We)}else if(Q>=k)if(H)Jr(Q,0,Re,We,u);else if(d){const ve=Re/2,ot=Be+ve;f.beginPath(),f.moveTo(Q,ot),f.lineTo(Q,ot-We),f.arc(be,ot-We,ve,hr,Ci),f.lineTo(Q+Re,ot),Kr(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(Q,Be+ve,Re,-We-ve),Kr(u),f.fill()}const Fi=X.peak[j],Yh=X.alpha[j];if(Fi>0&&Yh>0&&J&&!Sn&&!l&&Q>=k&&Q<Gr){if(I?f.globalAlpha=Yh:u&&M>0?f.globalAlpha=1:o&&(f.globalAlpha=Fi),(m==tu||wn)&&Zr(Fi),a){const ve=si(Fi);ve>=Cn&&f.fillRect(Q,Be-ve,Re,qr)}else if(!H)f.fillRect(Q,Be-Fi*jt,Re,2);else if(ae!=Ti){const ve=Fi*jt;Jr(Q,ve,Re,!this._radialInvert||St||ve+L>=2?-2:2)}}}if(ee){if(f.globalAlpha=1,ae==Ti){if(Zr(),H&&!pe){if(U){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1))}f.closePath()}if(M>0&&f.stroke(),A>0){if(H){const z=pe?li(Ct>>1):0,X=pe?li(Ct):Ci;f.moveTo(...Je(pe?Ct>>1:0,0)),f.arc(_,v,L,z,X,pe?!ai:!0)}else f.lineTo(Gr,Be),f.lineTo(k,Be);f.globalAlpha=A,f.fill(),f.globalAlpha=1}if((Sn||H&&J)&&(Tn=[],f.beginPath(),O.forEach((z,X)=>{let Q=z.posX,be=z.peak[j],Re=X?"lineTo":"moveTo";if(H&&Q<0){const Ke=O[X+1];be=W_(Q,be,Ke.posX,Ke.peak[j],0),Q=0}be*=jt,Sn?(f[Re](...H?Je(Q,be):[Q,Be-be]),H&&U&&!pe&&Tn.push([Q,be])):be>0&&Jr(Q,be,1,-2)}),Sn)){let z;for(;z=Tn.pop();)f.lineTo(...Je(...z,-1));f.lineWidth=1,f.stroke()}}f.restore(),pe&&!H&&f.setTransform(1,0,0,1,0,0),(!pe&&!ge||j)&&bw(j)}}if(Cw(qh/(zh<<Kh-1)),ee&&(U&&!H&&!pe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,_,T.height,0,0,_,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),ww()),this.showFPS){const j=ie.height;f.font=`bold ${j}px ${is}`,f.fillStyle=R_,f.textAlign="right",f.fillText(Math.round(x),T.width-j,j*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 Ei:return Math.log2(e);case gr:return 26.81*e/(1960+e)-.53;case mr:return Math.log2(1+e/700);case un: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 b=this._gradients[this._selectedGrads[v]],w=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,_]),w){const L=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+L;R++){const O=w.length-1;w.forEach((T,E)=>{let g=T.pos;if(L&&(g/=2),h&&!d&&!n&&!C&&(g*=p,!L&&g>.5*p&&(g+=.5*s)),R==1)if(n||d){const m=O-E;T=w[m],g=1-T.pos/2}else E==0&&g>0&&k.addColorStop(.5,T.color),g+=.5;k.addColorStop(g,T.color),h&&E==O&&g<.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!=uu&&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=hu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new nt(F_,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(hn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...hn,...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 q_={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}]}},yu=({stream:t,className:e,onClick:i})=>{var o;const n=ue(null),s=Qt();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new G_(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",q_[((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:At("w-full",e),ref:n})},bu=Dn(null),wu=({className:t,debug:e=!1})=>{const i=Js(bu);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 bu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),G_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),wu=t=>{const e=G_(t);return e.charAt(0).toUpperCase()+e.slice(1)},q_=(...t)=>t.filter((e,i,n)=>!!e&&e.trim()!==""&&n.indexOf(e)===i).join(" ").trim();/**
21
+ */const Su=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),z_=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),Cu=t=>{const e=z_(t);return e.charAt(0).toUpperCase()+e.slice(1)},K_=(...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 z_={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 Y_={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 K_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Ze("svg",{...z_,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])=>Ze(l,c)),...ft(s)]);/**
31
+ */const X_=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>Ze("svg",{...Y_,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])=>Ze(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 He=(t,e)=>{const i=({class:n="",children:s,...o})=>Ze(K_,{...o,iconNode:e,class:q_(`lucide-${bu(wu(t))}`,`lucide-${bu(t)}`,n)},s);return i.displayName=wu(t),i};/**
36
+ */const He=(t,e)=>{const i=({class:n="",children:s,...o})=>Ze(X_,{...o,iconNode:e,class:K_(`lucide-${Su(Cu(t))}`,`lucide-${Su(t)}`,n)},s);return i.displayName=Cu(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 Su=He("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 Tu=He("camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/**
42
42
  * @license lucide-preact v0.515.0 - ISC
43
43
  *
44
44
  * This source code is licensed under the ISC license.
45
45
  * See the LICENSE file in the root directory of this source tree.
46
- */const Y_=He("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 J_=He("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 Cu=He("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 Eu=He("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 X_=He("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 Z_=He("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_=He("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/**
61
+ */const Q_=He("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 Z_=He("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 ey=He("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 Q_=He("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 ty=He("mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/**
72
72
  * @license lucide-preact v0.515.0 - ISC
73
73
  *
74
74
  * This source code is licensed under the ISC license.
75
75
  * See the LICENSE file in the root directory of this source tree.
76
- */const ey=He("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 iy=He("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);/**
77
77
  * @license lucide-preact v0.515.0 - ISC
78
78
  *
79
79
  * This source code is licensed under the ISC license.
80
80
  * See the LICENSE file in the root directory of this source tree.
81
- */const ty=He("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]]);/**
81
+ */const ny=He("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 iy=He("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 sy=He("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 ny=He("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 oy=He("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 sy=He("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 ry=He("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 oy=He("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
101
+ */const ay=He("thumbs-up",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/**
102
102
  * @license lucide-preact v0.515.0 - ISC
103
103
  *
104
104
  * This source code is licensed under the ISC license.
105
105
  * See the LICENSE file in the root directory of this source tree.
106
- */const ry=He("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 ly=He("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 mr=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Tu=Dn(!1),ay=()=>el(Tu),Lt=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:At("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Eu=({call:t,chatMode:e})=>{const[i,n]=ay(),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(Lt,{tooltip:i?"Unmute":"Mute",onClick:s,className:At(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(Z_,{className:"w-5 h-5 text-black dark:text-white"}):D(Q_,{className:"w-5 h-5 text-black dark:text-white"})}),D(Lt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(ty,{className:"w-4 h-4 text-black dark:text-white"})})]})},ku=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Si.div,{layoutId:dn,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(vu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Yd,{stream:t.remoteStream,chatMode:i}),D(Kd,{size:"small"}),D(Eu,{call:t,chatMode:i}),D(yu,{debug:n})]});function ly(){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(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Cu,{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(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Cu,{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(oy,{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(ry,{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(X_,{className:"w-4 h-4"})]})]})]})]})}function cy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ss={exports:{}},dy=ss.exports,Iu;function uy(){return Iu||(Iu=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(dy,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 w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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 w=s[b];this[w]=b<v?e:this.methodFactory(w,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,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(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,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){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"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,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 w=o[b];return w||(w=o[b]=new p(b,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})}(ss)),ss.exports}var hy=uy();const fy=cy(hy),py=()=>new Date().toISOString().replace("T"," ").replace("Z",""),gy="[ai-agent-widget]",oe=fy.getLogger("telnyx-ai-agent-widget"),my=oe.methodFactory;oe.methodFactory=(t,e,i)=>{const n=my(t,e,i);return function(...s){n(py(),gy,...s)}},oe.setLevel("info");function vy({onCapture:t,onClose:e}){const i=ue(null),n=ue(null),s=ue(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(Lt,{tooltip:"Close",onClick:u,children:D(mr,{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:At("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(Su,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const vr=["amazon:domain","amazon:effect","amazon:emotion","audio","break","build-intensity","decrease-intensity","emphasis","emotion","fast","google:style","higher-pitch","lang","laugh-speak","loud","lower-pitch","mark","mstts:express-as","p","phoneme","prosody","s","say-as","sing-song","singing","slow","soft","speak","sub","voice","w","whisper"],_y=["audio","lang","mark","p","s","sub","w"],Ru=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function Au(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function xu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Lu=vr.filter(t=>!_y.includes(t)),yy=Au(vr,"gi"),Du=Au(Lu,"gi"),by=xu(vr,"i"),wy=xu(Lu,"i"),Sy=new RegExp(`${Du.source}|${Ru.source}`,"i");function Cy(t){const e=Sy.test(t),i=e?yy:Du,n=e?by:wy;return t.replace(i,"").replace(n,"").replace(Ru,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function Ty({item:t,containerRef:e}){const i=ue(null),n=t.role==="assistant"?Cy(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:At("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:At("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:At("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const Ey=({transcript:t,call:e})=>{const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=cr();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{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(g=>g.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,g)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=g,m.readAsDataURL(T)}),p=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),g=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:E,preview:g};r(f=>[...f,m])}catch(E){oe.error("Error processing image:",E)}},_=T=>{r(E=>{const g=E.find(m=>m.id===T);return g&&URL.revokeObjectURL(g.preview),E.filter(m=>m.id!==T)})},v=T=>{const E=T.target,g=E.files;g&&g.length>0&&(Array.from(g).forEach(p),E.value="")},b=T=>{var g;const E=(g=T.clipboardData)==null?void 0:g.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&p(f)}})},w=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const g=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});p(g)}).catch(E=>{oe.error("Error processing camera capture:",E)})},L=async()=>{var g;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){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(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),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([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),L())},O=[...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:O.map((T,E)=>D(Ty,{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:()=>_(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(mr,{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: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(Lt,{tooltip:"Attach image",onClick:w,children:D(ey,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Take photo",onClick:C,children:D(Su,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Send",children:D(ny,{onClick:L,className:"text-[#969696] w-4 h-4"})})]}),a&&D(vy,{onCapture:k,onClose:()=>l(!1)})]})};function ky({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(ly,{}),D(Lt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(mr,{className:"text-black dark:text-white"})})]})}const Iy=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Bg,{children:D(Si.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(ky,{onCollapse:e}),!n&&D(vu,{className:"h-[144px]",stream:t.remoteStream}),D(Kd,{size:"large",className:"mb-4"}),D(Eu,{call:t,chatMode:n}),D(yu,{className:"mt-2",debug:s})]}),D(Yd,{stream:t.remoteStream,chatMode:n}),D(Ey,{call:t,transcript:i})]})});function Ou(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 Mu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),Ry=new Uint8Array(16);function Ay(){if(!Mu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mu(Ry)}for(var Pu=[],os=0;os<256;++os)Pu[os]=(os+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||Ay)();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=Pu;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 xy={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},Ly={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,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,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:Dy,SDP_CREATE_ANSWER_FAILED:Oy,SDP_SET_LOCAL_DESCRIPTION_FAILED:My,SDP_SET_REMOTE_DESCRIPTION_FAILED:Nu,SDP_SEND_FAILED:_r,MEDIA_MICROPHONE_PERMISSION_DENIED:Py,MEDIA_DEVICE_NOT_FOUND:Ny,MEDIA_GET_USER_MEDIA_FAILED:Fu,HOLD_FAILED:Fy,INVALID_CALL_PARAMETERS:By,BYE_SEND_FAILED:Vy,SUBSCRIBE_FAILED:Uy,PEER_CLOSED_DURING_INIT:yr,WEBSOCKET_CONNECTION_FAILED:$y,WEBSOCKET_ERROR:jy,RECONNECTION_EXHAUSTED:br,GATEWAY_FAILED:Hy,LOGIN_FAILED:Bu,INVALID_CREDENTIALS:Wy,AUTHENTICATION_REQUIRED:Gy,ICE_RESTART_FAILED:qy,NETWORK_OFFLINE:zy,SESSION_NOT_REATTACHED:Vu,UNEXPECTED_ERROR:Uu}=xy,{HIGH_RTT:Ky,HIGH_JITTER:Yy,HIGH_PACKET_LOSS:Xy,LOW_MOS:$u,LOW_LOCAL_AUDIO:rs,LOW_INBOUND_AUDIO:as,LOW_BYTES_RECEIVED:wr,LOW_BYTES_SENT:ju,RECORDING_UNAVAILABLE:Jy,RECORDING_BUFFER_OVERFLOW:Zy,ICE_CONNECTIVITY_LOST:Qy,ICE_GATHERING_TIMEOUT:e0,ICE_GATHERING_EMPTY:t0,PEER_CONNECTION_FAILED:i0,ONLY_HOST_ICE_CANDIDATES:n0,ANSWER_WHILE_PEER_ACTIVE:s0,ICE_CANDIDATE_PAIR_CHANGED:o0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:r0,MULTIPLE_ACTIVE_CALLS_DETECTED:a0,DUPLICATE_INBOUND_ANSWER:l0,SHARED_REMOTE_ELEMENT_OVERWRITE:c0,TOKEN_EXPIRING_SOON:d0,UNKNOWN_REATTACHED_SESSION:u0,SIGNALING_RECOVERY_REQUIRED:h0,MEDIA_RECOVERY_REQUIRED:f0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:p0}=Ly,g0=/^a=candidate:.+typ (srflx|prflx|relay)/m,Hu="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},Gu={urls:"stun:stun.l.google.com:19302"},m0={urls:"stun:stun.telnyx.com:3478"},v0={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},_0={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},y0={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},b0={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},w0=[m0,Gu,v0,_0,y0,b0],S0=[{urls:"stun:stundev.telnyx.com:3478"},Gu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var P;(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"})(P||(P={}));const C0={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}},T0={31001:{name:"HIGH_RTT",message:"High network latency detected",description:"Round-trip time (RTT) exceeded the threshold for multiple consecutive samples. High latency causes perceptible audio delays.",causes:["Poor network connection","Geographic distance to media server","Network congestion"],solutions:["Check network connectivity","Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications"]},31002:{name:"HIGH_JITTER",message:"High jitter detected",description:"Jitter (variability in packet arrival time) exceeded the threshold for multiple consecutive samples. High jitter causes crackling and choppy audio.",causes:["Network congestion","Unstable Wi-Fi connection","Overloaded network equipment"],solutions:["Use a wired connection instead of Wi-Fi","Close bandwidth-heavy applications","Check network equipment"]},31003:{name:"HIGH_PACKET_LOSS",message:"High packet loss detected",description:"Packet loss exceeded the threshold for multiple consecutive samples. High packet loss causes choppy audio or dropped calls.",causes:["Network congestion","Unstable connection","Firewall or QoS misconfiguration"],solutions:["Check network connectivity","Use a wired connection","Contact network administrator"]},31004:{name:"LOW_MOS",message:"Low call quality score",description:"Mean Opinion Score (MOS) dropped below the acceptable threshold for multiple consecutive samples. This is a composite indicator of overall call quality.",causes:["Combination of high latency, jitter, and/or packet loss","Poor network conditions"],solutions:["Check network connectivity","Use a wired connection","Close bandwidth-heavy applications"]},31005:{name:"LOW_LOCAL_AUDIO",message:"Low local microphone audio detected",description:"Local outbound audio level stayed below the acceptable threshold before the microphone produced real audio, or stayed silent for a long continuous window after audio was confirmed. This may indicate that the microphone is not capturing enough audio even while RTP is being sent.",causes:["Microphone input level is too low","Wrong microphone selected","Microphone is obstructed or too far from the speaker","Operating system input gain is muted or very low"],solutions:["Check the selected microphone","Increase microphone input gain","Move closer to the microphone","Verify the microphone is not muted at the operating system or hardware level"]},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"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},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 Ne(t,e){const i=T0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Vt 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,Vt.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 Py;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return Ny}return Fu}function ne(t,e,i,n){const s=C0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Vt({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 E0 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 Sr 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 k0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function qu(t,e){return t(e={exports:{}},e.exports),e.exports}var I0=qu(function(t){var e,i;e=k0,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,w){var C=b[w];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,w){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,w)}this.log=this.debug}function u(b,w,C){return function(){typeof console!==s&&(c.call(this,w,C),this[b].apply(this,arguments))}}function d(b,w,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,w,C){var k,L=this;w=w??"WARN";var R="loglevel";function O(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var g=window.document.cookie,m=g.indexOf(encodeURIComponent(R)+"=");m!==-1&&(E=/^([^;]+)/.exec(g.slice(m))[1])}catch{}return L.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=void 0),L.name=b,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=C||d,L.getLevel=function(){return k},L.setLevel=function(E,g){if(typeof E=="string"&&L.levels[E.toUpperCase()]!==void 0&&(E=L.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=L.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,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{}}}(E),c.call(L,E,b),typeof console===s&&E<L.levels.SILENT)return"No console available for logging"},L.setDefaultLevel=function(E){w=E,O()||L.setLevel(E,!1)},L.resetLevel=function(){L.setLevel(w,!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{}}}()},L.enableAll=function(E){L.setLevel(L.levels.TRACE,E)},L.disableAll=function(E){L.setLevel(L.levels.SILENT,E)};var T=O();T==null&&(T=w),L.setLevel(T,!1)}var p=new h,_={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[b];return w||(w=_[b]=new h(b,p.getLevel(),p.methodFactory)),w};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 zu={debug:0,info:1,warn:2,error:3};class R0{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||zu[e]<zu[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 Ku=null;const y=I0.getLogger("telnyx"),ls={trace:0,debug:1,info:2,warn:3,error:4};let Yu=ls.info;function Xu(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 A0=y.methodFactory;y.methodFactory=(t,e,i)=>{const n=A0(t,e,i);return function(...s){if(ls[t]>=Yu){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Ku;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?Xu(a[0]):{args:a.map(Xu)}),o.addEntry(t,l,c)}}},y.setLevel("debug",!1);const cs=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{y.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Ju=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ri=t=>t instanceof Function||typeof t=="function",fn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,x0=/^(ws|wss):\/\//,Zu=(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?Zu(a,r):{result:s}},ds=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),pn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Cr=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?L0(n,t):n,i=s}),resolve:e,reject:i}}const L0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Tr="telnyx-voice-sdk-id",us="telnyx-voice-sdk-session-id",hs="telnyx-voice-sdk-session-id-stored-at",Er="telnyx-voice-sdk-active-calls",D0=9e4;function eh(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(hs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=D0}function gn(){return sessionStorage.getItem(Tr)}function kr(t,e=Date.now()){sessionStorage.setItem(us,t),sessionStorage.setItem(hs,String(e))}function th(){sessionStorage.removeItem(Tr),sessionStorage.removeItem(us),sessionStorage.removeItem(hs)}function ei(){(function(t){try{sessionStorage.removeItem(t)}catch(e){y.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Er)}function ih(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return y.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Er);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return y.debug("Active-calls recovery marker payload was malformed — discarded."),ei(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(y.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),ei(),null):i.calls.length===0?(y.debug("Active-calls recovery marker had no call records — discarded."),ei(),null):i}catch(i){return y.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),ei(),null}}function nh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void ei();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){y.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Er,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Fe,_t,Z;(function(t){t.Offer="offer",t.Answer="answer"})(Fe||(Fe={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(_t||(_t={})),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 st={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},O0={invalidCredentialsOptions:"InvalidCredentialsOptions"},sh=8e6,M0={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 W,Ir,Ye,yt,Oe,Ai;(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"})(W||(W={})),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"}(Ye||(Ye={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(yt||(yt={})),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"}(Oe||(Oe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ai||(Ai={}));const xi="GLOBAL",ze={},mn=(t,e)=>`${t}|${e}`,oh=(t,e=xi)=>mn(t,e)in ze,Ut=(t,e,i=xi)=>{const n=mn(t,i);n in ze||(ze[n]=[]),ze[n].push(e)},rh=(t,e,i=xi)=>{const n=function(s){bt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},bt=(t,e,i=xi)=>{if(!oh(t,i))return!1;const n=mn(t,i);if(Ri(e))for(let s=ze[n].length-1;s>=0;s--){const o=ze[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&ze[n].splice(s,1)}else ze[n]=[];return ze[n].length===0&&delete ze[n],!0},B=(t,e,i=xi,n=!0)=>{const s=n&&i!==xi;if(!oh(t,i))return s&&B(t,e),!1;const o=mn(t,i),r=ze[o].length;if(!r)return s&&B(t,e),!1;for(let a=r-1;a>=0;a--)ze[o][a](e);return s&&B(t,e),!0},Rr=t=>{const e=mn(t,"");Object.keys(ze).filter(i=>i.indexOf(e)===0).forEach(i=>delete ze[i])};let P0=typeof WebSocket<"u"?WebSocket:null;const N0=0,F0=1,B0=2,ah=3;class fs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Hu,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;y.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Hu),i&&(this._host=(r=>`${x0.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===F0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===N0}get closing(){return!!this._wsClient&&this._wsClient.readyState===B0}get closed(){return!!this._wsClient&&this._wsClient.readyState===ah}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){y.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=gn();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"),y.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 P0(e.toString()),this.socketGeneration+=1,y.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){y.error("WebSocket connection failed:",n);const s=ne($y,n);B(P.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}=Zu(p);return v?c(v):l(_)};rh(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),bt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return y.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Sr(s.id,o,this.socketGeneration));c(new E0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return y.debug(`SEND:
111
+ */const _r=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),ku=Dn(!1),cy=()=>il(ku),Lt=({children:t,className:e,onClick:i,tooltip:n})=>D("button",{title:n,onClick:i,className:At("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Iu=({call:t,chatMode:e})=>{const[i,n]=cy(),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(Lt,{tooltip:i?"Unmute":"Mute",onClick:s,className:At(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(ey,{className:"w-5 h-5 text-black dark:text-white"}):D(ty,{className:"w-5 h-5 text-black dark:text-white"})}),D(Lt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(ny,{className:"w-4 h-4 text-black dark:text-white"})})]})},Ru=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Si.div,{layoutId:dn,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(yu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Jd,{stream:t.remoteStream,chatMode:i}),D(Xd,{size:"small"}),D(Iu,{call:t,chatMode:i}),D(wu,{debug:n})]});function dy(){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(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Eu,{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(Lt,{tooltip:"More",onClick:()=>e(!t),children:D(Eu,{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(ay,{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(ly,{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(Z_,{className:"w-4 h-4"})]})]})]})]})}function uy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ss={exports:{}},hy=ss.exports,Au;function fy(){return Au||(Au=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(hy,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 w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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 w=s[b];this[w]=b<v?e:this.methodFactory(w,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,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(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,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){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"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}r=new p,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 w=o[b];return w||(w=o[b]=new p(b,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})}(ss)),ss.exports}var py=fy();const gy=uy(py),my=()=>new Date().toISOString().replace("T"," ").replace("Z",""),vy="[ai-agent-widget]",oe=gy.getLogger("telnyx-ai-agent-widget"),_y=oe.methodFactory;oe.methodFactory=(t,e,i)=>{const n=_y(t,e,i);return function(...s){n(my(),vy,...s)}},oe.setLevel("info");function yy({onCapture:t,onClose:e}){const i=ue(null),n=ue(null),s=ue(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(Lt,{tooltip:"Close",onClick:u,children:D(_r,{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:At("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(Tu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const yr=["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"],by=["audio","lang","mark","p","s","sub","w"],xu=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function Lu(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function Du(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const Ou=yr.filter(t=>!by.includes(t)),wy=Lu(yr,"gi"),Mu=Lu(Ou,"gi"),Sy=Du(yr,"i"),Cy=Du(Ou,"i"),Ty=new RegExp(`${Mu.source}|${xu.source}`,"i");function Ey(t){const e=Ty.test(t),i=e?wy:Mu,n=e?Sy:Cy;return t.replace(i,"").replace(n,"").replace(xu,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function ky({item:t,containerRef:e}){const i=ue(null),n=t.role==="assistant"?Ey(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:At("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:At("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:At("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const Iy=({transcript:t,call:e})=>{const i=ue(null),n=ue(null),s=ue(null),[o,r]=Ae([]),[a,l]=Ae(!1),[c,u]=Ae([]),[,d]=ur();xe(()=>()=>{o.forEach(T=>URL.revokeObjectURL(T.preview))},[o]),xe(()=>{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(g=>g.filter(m=>m.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,g)=>{const m=new FileReader;m.onload=()=>E(m.result),m.onerror=g,m.readAsDataURL(T)}),p=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),g=URL.createObjectURL(T),m={id:Date.now().toString(),file:T,base64:E,preview:g};r(f=>[...f,m])}catch(E){oe.error("Error processing image:",E)}},_=T=>{r(E=>{const g=E.find(m=>m.id===T);return g&&URL.revokeObjectURL(g.preview),E.filter(m=>m.id!==T)})},v=T=>{const E=T.target,g=E.files;g&&g.length>0&&(Array.from(g).forEach(p),E.value="")},b=T=>{var g;const E=(g=T.clipboardData)==null?void 0:g.items;E&&Array.from(E).forEach(m=>{if(m.type.startsWith("image/")){const f=m.getAsFile();f&&p(f)}})},w=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const g=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});p(g)}).catch(E=>{oe.error("Error processing camera capture:",E)})},L=async()=>{var g;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){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(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),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([])}},R=T=>{T.key==="Enter"&&(T.preventDefault(),L())},O=[...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:O.map((T,E)=>D(ky,{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:()=>_(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(_r,{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: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(Lt,{tooltip:"Attach image",onClick:w,children:D(iy,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Take photo",onClick:C,children:D(Tu,{className:"text-[#969696] w-4 h-4"})}),D(Lt,{tooltip:"Send",children:D(oy,{onClick:L,className:"text-[#969696] w-4 h-4"})})]}),a&&D(yy,{onCapture:k,onClose:()=>l(!1)})]})};function Ry({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(dy,{}),D(Lt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(_r,{className:"text-black dark:text-white"})})]})}const Ay=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Ug,{children:D(Si.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(Ry,{onCollapse:e}),!n&&D(yu,{className:"h-[144px]",stream:t.remoteStream}),D(Xd,{size:"large",className:"mb-4"}),D(Iu,{call:t,chatMode:n}),D(wu,{className:"mt-2",debug:s})]}),D(Jd,{stream:t.remoteStream,chatMode:n}),D(Iy,{call:t,transcript:i})]})});function Pu(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 Nu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),xy=new Uint8Array(16);function Ly(){if(!Nu)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Nu(xy)}for(var Fu=[],os=0;os<256;++os)Fu[os]=(os+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||Ly)();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=Fu;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 Dy={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},Oy={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,SHARED_REMOTE_ELEMENT_OVERWRITE:33011,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:My,SDP_CREATE_ANSWER_FAILED:Py,SDP_SET_LOCAL_DESCRIPTION_FAILED:Ny,SDP_SET_REMOTE_DESCRIPTION_FAILED:Bu,SDP_SEND_FAILED:br,MEDIA_MICROPHONE_PERMISSION_DENIED:Fy,MEDIA_DEVICE_NOT_FOUND:By,MEDIA_GET_USER_MEDIA_FAILED:Vu,HOLD_FAILED:Vy,INVALID_CALL_PARAMETERS:Uy,BYE_SEND_FAILED:jy,SUBSCRIBE_FAILED:$y,PEER_CLOSED_DURING_INIT:wr,WEBSOCKET_CONNECTION_FAILED:Hy,WEBSOCKET_ERROR:Wy,RECONNECTION_EXHAUSTED:Sr,GATEWAY_FAILED:Gy,LOGIN_FAILED:Uu,INVALID_CREDENTIALS:qy,AUTHENTICATION_REQUIRED:zy,ICE_RESTART_FAILED:Ky,NETWORK_OFFLINE:Yy,SESSION_NOT_REATTACHED:ju,UNEXPECTED_ERROR:$u}=Dy,{HIGH_RTT:Xy,HIGH_JITTER:Jy,HIGH_PACKET_LOSS:Zy,LOW_MOS:Hu,LOW_LOCAL_AUDIO:rs,LOW_INBOUND_AUDIO:as,LOW_BYTES_RECEIVED:Cr,LOW_BYTES_SENT:Wu,RECORDING_UNAVAILABLE:Qy,RECORDING_BUFFER_OVERFLOW:e0,ICE_CONNECTIVITY_LOST:t0,ICE_GATHERING_TIMEOUT:i0,ICE_GATHERING_EMPTY:n0,PEER_CONNECTION_FAILED:s0,ONLY_HOST_ICE_CANDIDATES:o0,ANSWER_WHILE_PEER_ACTIVE:r0,ICE_CANDIDATE_PAIR_CHANGED:a0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:l0,MULTIPLE_ACTIVE_CALLS_DETECTED:c0,DUPLICATE_INBOUND_ANSWER:d0,SHARED_REMOTE_ELEMENT_OVERWRITE:u0,TOKEN_EXPIRING_SOON:h0,UNKNOWN_REATTACHED_SESSION:f0,SIGNALING_RECOVERY_REQUIRED:p0,MEDIA_RECOVERY_REQUIRED:g0,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:m0}=Oy,v0=/^a=candidate:.+typ (srflx|prflx|relay)/m,Gu="wss://rtc.telnyx.com",qu={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},zu={urls:"stun:stun.l.google.com:19302"},_0={urls:"stun:stun.telnyx.com:3478"},y0={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},b0={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},w0={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},S0={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},C0=[_0,zu,y0,b0,w0,S0],T0=[{urls:"stun:stundev.telnyx.com:3478"},zu,{urls:"turn:turndev.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},{urls:"turn:turndev.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},{urls:"turns:turndev.telnyx.com:443",username:"testuser",credential:"testpassword"}];var P;(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"})(P||(P={}));const E0={40001:{name:"SDP_CREATE_OFFER_FAILED",message:"Failed to create call offer",description:"The browser was unable to generate a local SDP offer. This typically indicates a WebRTC API error or invalid media constraints.",causes:["Browser WebRTC API error","Missing or invalid media constraints"],solutions:["Check getUserMedia permissions","Verify ICE server configuration"],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}},k0={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"]},33011:{name:"SHARED_REMOTE_ELEMENT_OVERWRITE",message:"Remote media element overwritten by another call",description:"A new MediaStream was attached to an HTML media element (audio/video) that already held a different MediaStream from another active call. The SDK overwrote the existing stream (last-writer-wins), which disrupts the other call remote media playout. This happens when two concurrent calls share a single remoteElement instead of each having its own. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) so each call owns a distinct element.",causes:["Two concurrent calls share one remoteElement (legacy single-element app)","Application did not pass a per-call remoteElement to newCall() or answer()","A second inbound call rang into a session using one session-level remoteElement"],solutions:["Pass a distinct remoteElement per call via client.newCall({ remoteElement })","For inbound calls, override at answer time via call.answer({ remoteElement })","Give each call its own <audio>/<video> element so attach/detach lifecycles are independent"]},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 Ne(t,e){const i=k0[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Vt 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,Vt.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 Fy;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return By}return Vu}function ne(t,e,i,n){const s=E0[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Vt({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 I0 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 Tr 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 R0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ku(t,e){return t(e={exports:{}},e.exports),e.exports}var A0=Ku(function(t){var e,i;e=R0,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,w){var C=b[w];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,w){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,w)}this.log=this.debug}function u(b,w,C){return function(){typeof console!==s&&(c.call(this,w,C),this[b].apply(this,arguments))}}function d(b,w,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,w,C){var k,L=this;w=w??"WARN";var R="loglevel";function O(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var g=window.document.cookie,m=g.indexOf(encodeURIComponent(R)+"=");m!==-1&&(E=/^([^;]+)/.exec(g.slice(m))[1])}catch{}return L.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=void 0),L.name=b,L.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},L.methodFactory=C||d,L.getLevel=function(){return k},L.setLevel=function(E,g){if(typeof E=="string"&&L.levels[E.toUpperCase()]!==void 0&&(E=L.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=L.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,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{}}}(E),c.call(L,E,b),typeof console===s&&E<L.levels.SILENT)return"No console available for logging"},L.setDefaultLevel=function(E){w=E,O()||L.setLevel(E,!1)},L.resetLevel=function(){L.setLevel(w,!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{}}}()},L.enableAll=function(E){L.setLevel(L.levels.TRACE,E)},L.disableAll=function(E){L.setLevel(L.levels.SILENT,E)};var T=O();T==null&&(T=w),L.setLevel(T,!1)}var p=new h,_={};p.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var w=_[b];return w||(w=_[b]=new h(b,p.getLevel(),p.methodFactory)),w};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 Yu={debug:0,info:1,warn:2,error:3};class x0{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||Yu[e]<Yu[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 Xu=null;const y=A0.getLogger("telnyx"),ls={trace:0,debug:1,info:2,warn:3,error:4};let Ju=ls.info;function Zu(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 L0=y.methodFactory;y.methodFactory=(t,e,i)=>{const n=L0(t,e,i);return function(...s){if(ls[t]>=Ju){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Xu;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?Zu(a[0]):{args:a.map(Zu)}),o.addEntry(t,l,c)}}},y.setLevel("debug",!1);const cs=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{y.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Qu=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},Ri=t=>t instanceof Function||typeof t=="function",fn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,D0=/^(ws|wss):\/\//,eh=(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?eh(a,r):{result:s}},ds=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),pn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Er=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 th({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?O0(n,t):n,i=s}),resolve:e,reject:i}}const O0=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},kr="telnyx-voice-sdk-id",us="telnyx-voice-sdk-session-id",hs="telnyx-voice-sdk-session-id-stored-at",Ir="telnyx-voice-sdk-active-calls",M0=9e4;function ih(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(hs));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=M0}function gn(){return sessionStorage.getItem(kr)}function Rr(t,e=Date.now()){sessionStorage.setItem(us,t),sessionStorage.setItem(hs,String(e))}function nh(){sessionStorage.removeItem(kr),sessionStorage.removeItem(us),sessionStorage.removeItem(hs)}function ei(){(function(t){try{sessionStorage.removeItem(t)}catch(e){y.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Ir)}function sh(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return y.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Ir);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return y.debug("Active-calls recovery marker payload was malformed — discarded."),ei(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(y.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),ei(),null):i.calls.length===0?(y.debug("Active-calls recovery marker had no call records — discarded."),ei(),null):i}catch(i){return y.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),ei(),null}}function oh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void ei();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){y.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Ir,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Fe,_t,Z;(function(t){t.Offer="offer",t.Answer="answer"})(Fe||(Fe={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(_t||(_t={})),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 st={generic:"event",[Z.Display]:"participantData",[Z.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},P0={invalidCredentialsOptions:"InvalidCredentialsOptions"},rh=8e6,N0={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 W,Ar,Ye,yt,Oe,Ai;(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"})(W||(W={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Ar||(Ar={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(Ye||(Ye={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(yt||(yt={})),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"}(Oe||(Oe={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Ai||(Ai={}));const xi="GLOBAL",ze={},mn=(t,e)=>`${t}|${e}`,ah=(t,e=xi)=>mn(t,e)in ze,Ut=(t,e,i=xi)=>{const n=mn(t,i);n in ze||(ze[n]=[]),ze[n].push(e)},lh=(t,e,i=xi)=>{const n=function(s){bt(t,n,i),e(s)};return n.prototype.targetRef=e,Ut(t,n,i)},bt=(t,e,i=xi)=>{if(!ah(t,i))return!1;const n=mn(t,i);if(Ri(e))for(let s=ze[n].length-1;s>=0;s--){const o=ze[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&ze[n].splice(s,1)}else ze[n]=[];return ze[n].length===0&&delete ze[n],!0},B=(t,e,i=xi,n=!0)=>{const s=n&&i!==xi;if(!ah(t,i))return s&&B(t,e),!1;const o=mn(t,i),r=ze[o].length;if(!r)return s&&B(t,e),!1;for(let a=r-1;a>=0;a--)ze[o][a](e);return s&&B(t,e),!0},xr=t=>{const e=mn(t,"");Object.keys(ze).filter(i=>i.indexOf(e)===0).forEach(i=>delete ze[i])};let F0=typeof WebSocket<"u"?WebSocket:null;const B0=0,V0=1,U0=2,ch=3;class fs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Gu,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;y.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Gu),i&&(this._host=(r=>`${D0.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===V0}get connecting(){return!!this._wsClient&&this._wsClient.readyState===B0}get closing(){return!!this._wsClient&&this._wsClient.readyState===U0}get closed(){return!!this._wsClient&&this._wsClient.readyState===ch}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){y.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=gn();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"),y.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 F0(e.toString()),this.socketGeneration+=1,y.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){y.error("WebSocket connection failed:",n);const s=ne(Hy,n);B(P.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}=eh(p);return v?c(v):l(_)};lh(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),bt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return y.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Tr(s.id,o,this.socketGeneration));c(new I0(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return y.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(y.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;Ri(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=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),B(P.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.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(P.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ne(jy);return B(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),B(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),B(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Ju(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(Tr,a)),this._unsetTimer(r.id),y.debug(`RECV:
113
+ `),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(y.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;Ri(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=>(y.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),B(P.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),y.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(P.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),y.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ne(Wy);return B(P.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),B(P.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),B(P.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Qu(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(kr,a)),this._unsetTimer(r.id),y.debug(`RECV:
114
114
  `,JSON.stringify(r,null,2),`
115
- `),Oe[`${(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=Cr(r);B(P.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!==ah?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(P.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))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Sr(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(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const lh={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 Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Ou(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in lh)n&&i.hasOwnProperty(n)&&(i[lh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class ch extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class V0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Cr(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new ch(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Qu({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Qu({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Ar extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.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(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.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&&(Di.isCriticalMethod(n)?(y.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")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.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){y.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")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ne(zy);B(P.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.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 y.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&&(y.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 Ar(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.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`)):(y.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,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(h0);B(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.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){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(f0);B(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var dh="2.27.8-beta.0",xr=dh;class U0 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:xr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class $0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class uh extends Ue{toString(){return Z.Invite}}class hh extends Ue{toString(){return Z.Answer}}class fh extends Ue{toString(){return Z.Attach}}class j0 extends Ue{toString(){return Z.Bye}}class H0 extends Ue{toString(){return Z.Candidate}}class W0 extends Ue{toString(){return Z.EndOfCandidates}}class ps extends Ue{toString(){return Z.Modify}}class ph extends Ue{toString(){return Z.Info}}class G0 extends Ue{toString(){return Z.Broadcast}}class q0 extends Ue{toString(){return Z.Subscribe}}class z0 extends Ue{toString(){return Z.Unsubscribe}}class K0 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:xr,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 ti{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 Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Yu=(n=ls[i])!==null&&n!==void 0?n:ls.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 fs(this),this.registerAgent=new V0(this)}get __logger(){return y}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 y.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}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.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 Sr)throw y.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(Gy,s,void 0,!0);B(P.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()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||pn(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(),y.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 bt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Bu,e);B(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){th()}_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<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(d0);B(P.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)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=ne(Wy,void 0,s);return void B(P.Error,{error:o,type:O0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return V(this,void 0,void 0,function*(){let a;const l=!!gn(),c=l&&(this.sessionid&&eh()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?eh(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new U0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new K0({target_id:this.options.anonymous_login.target_id,target_type:this.options.anonymous_login.target_type,target_version_id:this.options.anonymous_login.target_version_id,target_params:this.options.anonymous_login.target_params,sessionId:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&kr(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){y.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)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.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&&Rr(this.relayProtocol);for(const l in this.subscriptions)Rr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&kr(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){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(br);return void B(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(p0);B(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.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],bt(e,null,i)):(delete this.subscriptions[e],Rr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.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(),y.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&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Ar(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([W.Early,W.Active,W.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){y.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 y.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 y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.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){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(c0);B(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},gh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},mh=(t,e)=>V(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),Y0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(Y0),t=null},vs=t=>V(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.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){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(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===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(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}),vh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield yn(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}),X0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Lr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,_h=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=>Lr(a)):[]},Dr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Or(t);return i.includes(e)||n.includes(e)},Or=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(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}})},Mr=t=>{Oi(t,"audio",!0)},ys=t=>{Oi(t,"audio",!1)};function J0(){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:!!vs}}catch(t){return t.message}}var Ee;function yh(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 bh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function wh(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 Sh=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 Z0 extends Li{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 Q0 extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{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._isHeld=!1,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 R0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Ku=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.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(),y.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 y.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 y.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 y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.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}`;y.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<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.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,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.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 L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.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=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||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)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(as,!1),this._trackBreach(wr,!1))}_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(le.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,b=this._getCodec(s,r==null?void 0:r.codecId),w=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,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=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}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(o0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.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 y.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>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;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 L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Ky,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Yy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Xy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(as,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach($u,O<le.THRESHOLD_MOS)}else this._trackBreach($u,!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,O=e.audio.inbound.bytesReceived;this._trackBreach(wr,!this._isHeld&&R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(ju,R!==void 0&&O-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<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!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(as,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(as,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]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.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=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.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 b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.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&&(b.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&&(b.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}),b.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&&(b.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&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.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;y.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 y.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,y.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:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class $e{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={local:!1,remote:!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 y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Jy),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 y.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(),y.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,y.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 y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}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||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.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+$e.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+$e.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Zy))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*$e.BYTES_PER_SAMPLE+$e.FRAMES_PER_SECOND*$e.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:sh}_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=>{y.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 y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{y.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!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<=$e.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=$e.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 y.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}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=$e.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.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=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.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)}}$e.RETRY_DELAYS_MS=[500,1e3,2e3],$e.KEEPALIVE_BODY_LIMIT_BYTES=61440,$e.PACKET_OVERHEAD_BYTES=160,$e.BYTES_PER_SAMPLE=4,$e.FRAMES_PER_SECOND=100;class eb{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,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.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){y.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)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Ch=qu(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 I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!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,I,A,x,N,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(N=this.domain,M){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=x[g]))return!1;var G=typeof f=="function";switch(S=arguments.length){case 1:(function(U,ae,q){if(ae)U.call(q);else for(var H=U.length,ce=c(U,H),J=0;J<H;++J)ce[J].call(q)})(f,G,this);break;case 2:(function(U,ae,q,H){if(ae)U.call(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].call(q,H)})(f,G,this,arguments[1]);break;case 3:(function(U,ae,q,H,ce){if(ae)U.call(q,H,ce);else for(var J=U.length,ee=c(U,J),te=0;te<J;++te)ee[te].call(q,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(U,ae,q,H,ce,J){if(ae)U.call(q,H,ce,J);else for(var ee=U.length,te=c(U,ee),ie=0;ie<ee;++ie)te[ie].call(q,H,ce,J)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function(U,ae,q,H){if(ae)U.apply(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].apply(q,H)})(f,G,this,I)}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,I,A,x;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(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;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 S[g]}else(function(N,M){for(var F=M,G=F+1,U=N.length;G<U;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||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,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="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(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(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 b(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 w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(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 k(g,m,f){return 8*function(S,I,A){const x=S[A],N=I?I[A]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(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 I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}N=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=g.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=g.get(N.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let N=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,m),S}let O,T={},E=[];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:I}=g;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(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];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 A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{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 I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}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(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,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]=A}else this.peersToMonitor[m]={[f]:A};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 I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,G=this.getTimestamp(),U=L(F),ae={remote:A.options.remote},q=R(F,A.stats.parsed,ae),H={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:G-N,data:q};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=U),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(U)),f.push(H),A.stats.parsed=q}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 I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,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."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.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 I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.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),E.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)}}}});(bs=Ch)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var tb=Ch.WebRTCStats;function ib(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 nb(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 sb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ob extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class rb extends Li{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 ab(t,e){const i=ki();let n=!1;const s=new tb({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(P.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=ib({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:nb(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new rb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new sb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.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(P.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 ob(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 Th=(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:st.conferenceUpdate,call:t.calls[s],canvasInfo:lb(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);B(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);B(P.Notification,l,t.uuid);break}}},lb=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Ju(e)},Eh=["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"],cb={"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 kh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Pr(t){for(const e of Eh)try{performance.clearMarks(re(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{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 y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.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){y.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=Ne(Qy);B(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(i0);B(P.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 y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.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;y.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)},y.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?(y.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&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.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 Vt&&B(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.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&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}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=kh(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Eh){if(d==="new-call-start")continue;const h=kh(re(s,d));h!==void 0&&l.push({label:cb[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 y.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+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Pr(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:Fe.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(yr);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(P.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(yr);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Fu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(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=Ne(t0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(e0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.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(yr);this.isDebugEnabled&&(this.statsReporter=ab(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(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Sh(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&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Sh(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);y.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,y.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 y.error("Peer _createOffer error:",e),e instanceof Vt?e:ne(Dy,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),ne(Nu,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 y.debug("Skipping negotiation, state:",this.instance.signalingState),y.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:Fe.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 y.error("Peer _createAnswer error:",e),e instanceof Vt?e:ne(Oy,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),ne(My,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(vn(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 _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.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 y.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Pr(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)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=xr;class Ih{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Ir.Participant,this.extension=null,this._state=W.New,this._prevState=W.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._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};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({},M0,{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=yh(this.options.ringtoneFile,"_ringtone"),this._ringback=yh(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=_t.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Vt?e:ne(Uu,e instanceof Error?e:void 0);return B(P.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&&y.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=Ne(s0);return B(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.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=_t.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})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Vt?d:ne(Uu,d instanceof Error?d:void 0);return B(P.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(){bh(this._ringtone)}stopRingtone(){wh(this._ringtone)}playRingback(){bh(this._ringback)}stopRingback(){wh(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<W.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:[]],y.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(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new j0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let w;try{yield Promise.race([this._execute(b),new Promise(C=>{w=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){y.error("telnyx_rtc.bye failed!",C);const k=ne(Vy,C);B(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{w&&clearTimeout(w)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new ps({sessid:this.session.sessionid,action:Ai.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new ph({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 ph({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ys(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Mr(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ys(this.options.localStream):Mr(this.options.localStream)}toggleAudioMute(){y.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 y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void B(P.Warning,{warning:Ne(r0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Lr(l.track),localTracks:_h(this.options.localStream)});try{c=yield gs({audio:{deviceId:{exact:e}}})}catch(h){const p=ne(Ii(h),h);return void B(P.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(P.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,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Lr(l.track),localTracks:_h(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Oi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Oi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Oi(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 gs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ms(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(){ys(this.options.remoteStream)}undeaf(){Mr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Oi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.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 y.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"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.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[W.Hangup,W.Destroy,W.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,a,l;switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case W.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(re(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(y.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(n=this._callReportCollector)===null||n===void 0||n.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&mh(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new eb,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.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>=W.Active)return;this._state>=W.Early&&this.setState(W.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>=W.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===_t.Inbound?_t.Outbound:_t.Inbound,c={type:st[i],call:this,displayName:o,displayNumber:r,displayDirection:l};B(P.Notification,c,this.id)||B(P.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:st.generic,call:this});B(P.Notification,o,this.id)||B(P.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 y.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:Ye.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(_)},cs(s[_][1])));this._dispatchConferenceUpdate({action:Ye.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ye.Add,callId:o,index:r},cs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ye.Modify,callId:o,index:r},cs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ye.Delete,callId:o,index:r},cs(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ye.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:Ye.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Dr(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,Th(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Dr(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(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=ne(Fy,e);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new ps(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ai.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.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?(y.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;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ne(qy,i);B(P.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:Fe.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(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>V(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=ne(Nu,n);B(P.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){y.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ri(this.peer.onSdpReadyTwice)){const e=ne(_r,new Error("SDP without candidates for the second time!"));B(P.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 y.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return y.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),!g0.test(o)){const c=Ne(n0);y.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),B(P.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-${ws}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(W.Requesting),a=new uh(l);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new fh(l):new hh(l);break;default:return y.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 y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=ne(_r,c);B(P.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){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return y.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-${ws}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(W.Requesting),o=new uh(r);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new fh(r):new hh(r);break;default:return y.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 y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=ne(_r,a);B(P.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){y.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?(y.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?(y.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 H0({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 y.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(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new W0({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=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(re(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.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&&ms(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_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:st.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),B(P.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:st.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&B(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(P.Notification,e,this.id,!1)||B(P.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=Ne(l0);return B(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var w;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),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(P.MediaError,this._onMediaError,this.id),Ut(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ri(_)&&Ut(P.Notification,_.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,L=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",O=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new le({enabled:!0,interval:k,intermediateReportInterval:L},{enabled:!0,level:R,maxEntries:O}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,g,m,f;B(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===wr&&this._state!==W.Held?(g=(E=this.session).reportNoRtp)===null||g===void 0||g.call(E,this.id,"inbound"):T.code===ju&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(m=this.session).reportNoRtp)===null||f===void 0||f.call(m,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const T={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:15e3,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:sh,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"},E={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new $e(T,E);const g=(l=this.session.connection)===null||l===void 0?void 0:l.host;g&&this._callRecorder._setHost(g),this._callRecorder.onWarning=m=>{B(P.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),y.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(),Pr(this.id),y.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;_n(s),_n(o),gh(r,s),gh(a,o),bt(P.MediaError,null,this.id),bt(P.PeerConnectionFailureError,null,this.id),bt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.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 y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.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=>{y.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 y.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=>{y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.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 y.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),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ih.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ni extends Ih{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Z0(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 Q0(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 ni&&(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 ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(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)&&mh(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+=`
115
+ `),Oe[`${(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=Er(r);B(P.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!==ch?(y.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?y.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(y.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),B(P.SocketClose,{code:qu.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))):y.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(y.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(y.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):y.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{bt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Tr(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(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else y.warn("Unknown message from socket",e)}}fs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Li{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:ki()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const dh={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 Li{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=Pu(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in dh)n&&i.hasOwnProperty(n)&&(i[dh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class uh extends Ue{constructor(e){super(),this.method=Z.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class j0{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>V(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Er(i))}),this.getIsRegistered=()=>V(this,void 0,void 0,function*(){const i=new uh(gn());this.pendingRequestId=i.request.id,this.gatewayStateTask=th({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Oe.REGISTER,Oe.REGED].includes(n)}),this.session=e,this.gatewayStateTask=th({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Lr extends Ue{constructor(e){super(),this.method=Z.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Di{constructor(e){this._session=e,this._lastInboundAt=0,this._lastProbeSentAt=0,this._probeInFlight=!1,this._intervalId=null,this._pendingMediaRecovery=null,this._browserWasOffline=!1,this._onlineHandler=null,this._offlineHandler=null}static isCriticalMethod(e){return Di.CRITICAL_METHODS.has(e)}start(){this._intervalId||(y.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._probeInFlight=!1,this._lastProbeSentAt=0,this._setupBrowserListeners(),this._intervalId=setInterval(()=>this._check(),3e3))}stop(){this._intervalId&&(clearInterval(this._intervalId),this._intervalId=null,this._probeInFlight=!1,this._lastProbeSentAt=0),this._pendingMediaRecovery=null,this._cleanupBrowserListeners(),y.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(),y.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void y.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(y.info(`Signaling health: signaling probe resolved, triggering pending ICE restart for call ${e.callId}`),this._triggerIceRestart(e.callId,e.reason))}_probeIfNeeded(e){var i;!((i=this._session.connection)===null||i===void 0)&&i.connected&&(this._probeInFlight?y.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(y.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&&(Di.isCriticalMethod(n)?(y.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")):y.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){y.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){y.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")}_setupBrowserListeners(){typeof window>"u"||this._onlineHandler||(this._onlineHandler=()=>{this._browserWasOffline&&(y.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,y.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ne(Yy);B(P.Error,{error:e,sessionId:this._session.sessionid},this._session.uuid),this.isRunning&&this._probeIfNeeded("browser offline signal while monitor is active")},window.addEventListener("online",this._onlineHandler),window.addEventListener("offline",this._offlineHandler))}_cleanupBrowserListeners(){typeof window<"u"&&this._onlineHandler&&this._offlineHandler&&(window.removeEventListener("online",this._onlineHandler),window.removeEventListener("offline",this._offlineHandler),this._onlineHandler=null,this._offlineHandler=null,this._browserWasOffline=!1)}onIceRestartFailed(e){y.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 y.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&&(y.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 Lr(gn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{y.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void y.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(y.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(y.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`)):(y.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,y.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Ne(p0);B(P.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(y.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):y.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){y.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void y.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Ne(g0);B(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Di.CRITICAL_METHODS=new Set([Z.Modify,Z.Bye,Z.Ping]);var hh="2.27.8-beta.0",Dr=hh;class $0 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:Dr,data:navigator.userAgent}};s&&(a.sessid=s),this.buildRequest({method:this.method,params:a})}}class H0 extends Ue{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class fh extends Ue{toString(){return Z.Invite}}class ph extends Ue{toString(){return Z.Answer}}class gh extends Ue{toString(){return Z.Attach}}class W0 extends Ue{toString(){return Z.Bye}}class G0 extends Ue{toString(){return Z.Candidate}}class q0 extends Ue{toString(){return Z.EndOfCandidates}}class ps extends Ue{toString(){return Z.Modify}}class mh extends Ue{toString(){return Z.Info}}class z0 extends Ue{toString(){return Z.Broadcast}}class K0 extends Ue{toString(){return Z.Subscribe}}class Y0 extends Ue{toString(){return Z.Unsubscribe}}class X0 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:Dr,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 ti{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 Di(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Ju=(n=ls[i])!==null&&n!==void 0?n:ls.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 fs(this),this.registerAgent=new j0(this)}get __logger(){return y}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 y.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}),y.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Di.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?fs.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 Tr)throw y.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(zy,s,void 0,!0);B(P.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()},ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&y.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return ds(this.options)||pn(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(),y.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 bt(e,i,this.uuid),this}connect(){return V(this,void 0,void 0,function*(){this.connection||(y.debug("No existing connection found, creating a new one."),this.connection=new fs(this)),this._attachListeners(),this._autoReconnect||(y.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(y.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),y.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ne(Uu,e);B(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){nh()}_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<=ti.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-ti.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{y.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Ne(h0);B(P.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)),ds(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(pn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";y.error(s);const o=ne(qy,void 0,s);return void B(P.Error,{error:o,type:P0.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r;return V(this,void 0,void 0,function*(){let a;const l=!!gn(),c=l&&(this.sessionid&&ih()?this.sessionid:function(d=Date.now()){const h=sessionStorage.getItem(us);return h?ih(d)?h:(sessionStorage.removeItem(us),sessionStorage.removeItem(hs),null):null}())||"";if(e==="login"){const d=(r=(s=this.options.pushWhenActive)!==null&&s!==void 0?s:(o=this.options.userVariables)===null||o===void 0?void 0:o.push_when_active)!==null&&r!==void 0&&r,h=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:d,pn_late_fanout:d});a=new $0(this.options.login,this.options.password||this.options.passwd,this.options.login_token,c,h,l)}else a=new X0({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:c,userVariables:this.options.userVariables,reconnection:l});const u=yield this.execute(a).catch(d=>{this._handleLoginError(d),n&&n(d)});u&&(this.sessionid=u.sessid,this.sessionid&&Rr(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){y.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(qu).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)y.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),y.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&&xr(this.relayProtocol);for(const l in this.subscriptions)xr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Rr(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){y.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ne(Sr);return void B(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;y.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{y.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(y.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Ne(m0);B(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else y.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],bt(e,null,i)):(delete this.subscriptions[e],xr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},Ri(i)&&Ut(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),y.debug("Attaching socket event listeners"),this.on(P.SocketOpen,this._onSocketOpen),this.on(P.SocketClose,this.onNetworkClose),this.on(P.SocketError,this.onNetworkClose),this.on(P.SocketMessage,this._onSocketMessage),this.on(P.SocketActivity,this._onSocketActivity)}_detachListeners(){y.debug("Detaching socket event listeners"),this.off(P.SocketOpen,this._onSocketOpen),this.off(P.SocketClose,this.onNetworkClose),this.off(P.SocketError,this.onNetworkClose),this.off(P.SocketMessage,this._onSocketMessage),this.off(P.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(),y.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&&(y.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Lr(gn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){y.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([W.Early,W.Active,W.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){y.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 y.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 y.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||y.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){bt(e)}static uuid(){return ki()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}ti.TOKEN_EXPIRY_WARNING_SECONDS=120,ti.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const gs=t=>navigator.mediaDevices.getUserMedia(t),vn=t=>t&&t instanceof MediaStream,ms=(t,e,i)=>{const n=fn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(y.warn("attachMediaStream: element already has a different MediaStream attached; overwriting will disrupt the existing call. Use a per-call remoteElement (client.newCall({ remoteElement }) or call.answer({ remoteElement })) for concurrent calls."),i)){const s=Ne(u0);B(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},vh=(t,e)=>{const i=fn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},_h=(t,e)=>V(void 0,void 0,void 0,function*(){const i=fn(t);if(i===null)return y.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return y.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),J0=t=>{t&&t.readyState==="live"&&t.stop()},_n=t=>{vn(t)&&t.getTracks().forEach(J0),t=null},vs=t=>V(void 0,void 0,void 0,function*(){y.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield gs(t)}catch(n){if(y.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){y.warn("Device not found or not readable, falling back to default device");try{return yield gs(s)}catch(o){throw y.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),yn=(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===yt.AudioIn||s===yt.AudioOut,video:!s||s===yt.Video}))(t)).catch(s=>(y.error(s),null));if(n){if(_n(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}),yh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],_s=(t,e,i)=>V(void 0,void 0,void 0,function*(){const n=yield yn(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}),Z0=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Or=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,bh=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=>Or(a)):[]},Mr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=Pr(t);return i.includes(e)||n.includes(e)},Pr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Oi=(t,e=null,i=null)=>{if(!vn(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}})},Nr=t=>{Oi(t,"audio",!0)},ys=t=>{Oi(t,"audio",!1)};function Q0(){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:!!vs}}catch(t){return t.message}}var Ee;function wh(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 Sh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{y.error("playAudio",e),t._playFulfilled=!0}))}function Ch(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 Th=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 eb extends Li{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 tb extends Li{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class le{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._isHeld=!1,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 x0(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Xu=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,y.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:le.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(),y.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 y.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 y.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 y.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void y.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}`;y.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<=le.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=le.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},_?{keepalive:!0}:{}));if(C.ok)return void y.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const k=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),y.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,y.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const w=le.RETRY_DELAYS_MS[b];if(w===void 0)break;y.info(`CallReportCollector: Retrying ${d} in ${w}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,w))}throw y.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,b;if(this.statsBuffer.length<2)return!1;const w=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=w.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 L=((i=w.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=w.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=w.transport)===null||s===void 0?void 0:s.iceState)==="failed",O=this._positiveDelta((o=w.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=w.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=O>0&&T===0,g=this._positiveDelta((u=(c=w.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=w.audio)===null||p===void 0?void 0:p.inbound)===null||_===void 0?void 0:_.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return L||R||E||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)}setHeld(e){this._isHeld!==e&&(this._isHeld=e,this._trackBreach(as,!1),this._trackBreach(Cr,!1))}_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(le.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,b=this._getCodec(s,r==null?void 0:r.codecId),w=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,k,L,R,O;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(L=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}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(y.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:L}),this._emitWarning(a0)),this.previousCandidatePairSnapshot=L),r&&(R=this._getLocalAudioTrackSnapshot(),O=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,O),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const g=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,p,R,O,l,c,u,b,w);this.statsBuffer.push(g),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),y.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(g,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){y.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:le.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 y.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>=le.STATS_FLUSH_THRESHOLD||o>=le.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){y.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){y.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,_,v,b,w;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 L;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,O=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=O-this._prevPacketsLost,g=T+E;g>0&&(L=E/g*100)}this._prevPacketsReceived=R,this._prevPacketsLost=O}if(this._trackBreach(Xy,C!==void 0&&C>le.THRESHOLD_RTT_MS),this._trackBreach(Jy,k!==void 0&&k>le.THRESHOLD_JITTER_MS),this._trackBreach(Zy,L!==void 0&&L>le.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(as,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&L!==void 0){const R=93.2-.11*k-2.5*L-.01*(1e3*C),O=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(Hu,O<le.THRESHOLD_MOS)}else this._trackBreach(Hu,!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,O=e.audio.inbound.bytesReceived;this._trackBreach(Cr,!this._isHeld&&R!==void 0&&O-R==0)}if(((_=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||_===void 0?void 0:_.bytesSent)!==void 0){const R=(w=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||w===void 0?void 0:w.bytesSent,O=e.audio.outbound.bytesSent;this._trackBreach(Wu,R!==void 0&&O-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<=le.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(rs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(rs)):this._trackBreach(rs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(rs,!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(as,!1);const o=s<=le.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(as,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]>=le.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=le.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=Ne(e);y.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.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 b={intervalStartUtc:e.toISOString(),intervalEndUtc:i.toISOString(),audio:{}};if(n&&(b.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&&(b.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&&(b.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}),b.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&&(b.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&&(b.mediaPlayout=this._withoutUndefined({synthesizedSamples:d.synthesizedSamples,synthesizedDuration:d.synthesizedDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSampleCount:d.totalSampleCount})),h||p){const w={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let k;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(k=h.totalRoundTripTime/h.roundTripTimeMeasurements),w.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(w.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=w}return b}_resolveCandidate(e,i){if(!i)return void y.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void y.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;y.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 y.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,y.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:[]}}}le.INITIAL_COLLECTION_INTERVAL_MS=1e3,le.STATS_FLUSH_THRESHOLD=300,le.LOGS_FLUSH_THRESHOLD=800,le.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,le.CONSECUTIVE_BREACHES_REQUIRED=3,le.THRESHOLD_RTT_MS=.4,le.THRESHOLD_JITTER_MS=30,le.THRESHOLD_PACKET_LOSS_PCT=1,le.THRESHOLD_MOS=3.5,le.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,le.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,le.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,le.WARNING_THROTTLE_MS=15e3,le.RETRY_DELAYS_MS=[500,1e3,2e3],le.KEEPALIVE_BODY_LIMIT_BYTES=61440;class je{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={local:!1,remote:!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 y.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Qy),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 y.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(),y.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,y.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 y.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void y.debug("CallRecorder: postFinalReport skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt,s=this._endedAt||new Date,o=i.flatMap(l=>{const c=this._drain(l);if(c.length===0)return[];const u=this._buildEnvelope(c,l,"final",n,s);return[{envelope:u,bodyBytes:JSON.stringify(u).length}]}),r=o.reduce((l,c)=>l+c.bodyBytes,0)<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=(yield Promise.allSettled(o.map(({envelope:l})=>this._postRecording(e,l,r)))).find(l=>l.status==="rejected");if(a)throw a.reason})}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||y.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){y.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+je.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+je.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,y.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(e0))}}_flushIntervalMs(){var e;const i=(e=this.options.flushIntervalMs)!==null&&e!==void 0?e:15e3;return i<=0?i:Math.min(i,this._maxSafeFlushIntervalMs())}_maxSafeFlushIntervalMs(){const e=this._sampleRate()*je.BYTES_PER_SAMPLE+je.FRAMES_PER_SECOND*je.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:rh}_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=>{y.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 y.debug("CallRecorder: periodic flush skipped — no host available");const i=this.options.tracks||["local","remote"],n=this._startedAt||new Date,s=new Date;yield Promise.allSettled(i.map(o=>{const r=this._drain(o);if(r.length===0)return Promise.resolve();const a=this._buildEnvelope(r,o,"intermediate",n,s);return this._postRecording(e,a,!1).catch(l=>{y.error("CallRecorder: intermediate flush failed",{track:o,error:l})})})),this._overflowWarnedThisWindow={local:!1,remote:!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<=je.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=je.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 y.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}`),y.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,y.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=je.RETRY_DELAYS_MS[c];if(u===void 0)break;y.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw y.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=Ne(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){y.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)}}je.RETRY_DELAYS_MS=[500,1e3,2e3],je.KEEPALIVE_BODY_LIMIT_BYTES=61440,je.PACKET_OVERHEAD_BYTES=160,je.BYTES_PER_SAMPLE=4,je.FRAMES_PER_SECOND=100;class ib{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,y.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){y.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){y.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)&&y.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){y.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var bs,Eh=Ku(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 I,A,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((A=g._events)?(A.newListener&&(g.emit("newListener",m,f.listener?f.listener:f),A=g._events),x=A[m]):(A=g._events=new n,g._eventsCount=0),x){if(typeof x=="function"?x=A[m]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(g))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+m+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=g,N.type=m,N.count=x.length,function(M){typeof console.warn=="function"?console.warn(M):console.log(M)}(N)}}else x=A[m]=f,++g._eventsCount;return g}function a(g,m,f){function S(){g.removeListener(m,S),I||(I=!0,f.apply(g,arguments))}var I=!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,I,A,x,N,M=g==="error";if(x=this._events)M=M&&x.error==null;else if(!M)return!1;if(N=this.domain,M){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=x[g]))return!1;var G=typeof f=="function";switch(S=arguments.length){case 1:(function(U,ae,q){if(ae)U.call(q);else for(var H=U.length,ce=c(U,H),J=0;J<H;++J)ce[J].call(q)})(f,G,this);break;case 2:(function(U,ae,q,H){if(ae)U.call(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].call(q,H)})(f,G,this,arguments[1]);break;case 3:(function(U,ae,q,H,ce){if(ae)U.call(q,H,ce);else for(var J=U.length,ee=c(U,J),te=0;te<J;++te)ee[te].call(q,H,ce)})(f,G,this,arguments[1],arguments[2]);break;case 4:(function(U,ae,q,H,ce,J){if(ae)U.call(q,H,ce,J);else for(var ee=U.length,te=c(U,ee),ie=0;ie<ee;++ie)te[ie].call(q,H,ce,J)})(f,G,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),A=1;A<S;A++)I[A-1]=arguments[A];(function(U,ae,q,H){if(ae)U.apply(q,H);else for(var ce=U.length,J=c(U,ce),ee=0;ee<ce;++ee)J[ee].apply(q,H)})(f,G,this,I)}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,I,A,x;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(I=-1,A=f.length;0<A--;)if(f[A]===m||f[A].listener&&f[A].listener===m){x=f[A].listener,I=A;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 S[g]}else(function(N,M){for(var F=M,G=F+1,U=N.length;G<U;F+=1,G+=1)N[F]=N[G];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",g,x||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,I=Object.keys(f),A=0;A<I.length;++A)(S=I[A])!=="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(I){for(var A=Array(I.length),x=0;x<A.length;++x)A[x]=I[x].listener||I[x];return A}(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 b(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 w(g,m,f){var S=(g=g||{}).random||(g.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(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 k(g,m,f){return 8*function(S,I,A){const x=S[A],N=I?I[A]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(g,m,f)}function L(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 I of g.values())switch(I.type){case"outbound-rtp":{const A=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(A))continue;if(I.codecId){const M=g.get(I.codecId);M&&(x.clockRate=M.clockRate,x.mimeType=M.mimeType,x.payloadType=M.payloadType)}N=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let A=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const M=g.get(I.codecId);M&&(N.clockRate=M.clockRate,N.mimeType=M.mimeType,N.payloadType=M.payloadType)}if(!S.connection.id&&I.transportId){const M=g.get(I.transportId);if(M&&M.selectedCandidatePairId){const F=g.get(M.selectedCandidatePairId);S.connection=C(F,g)}}x=g.get(I.mediaSourceId)||g.get(I.trackId)||{},S[A].inbound.push({...I,...N,track:{...x}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!f.remote)break;let A=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(A))if(I.id.includes("Video"))A="video";else{if(!I.id.includes("Audio"))continue;A="audio"}if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=g.get(I.transportId);if(N&&N.selectedCandidatePairId){const M=g.get(N.selectedCandidatePairId);S.connection=C(M,g)}}S.remote[A].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const A=I.mediaType||I.kind,x={};if(!["audio","video"].includes(A))continue;if(I.codecId){const N=g.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[A].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of g.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,g));return S=function(I,A){return A&&(I.audio.inbound.map(x=>{let N=A.audio.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=A.audio.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=A.video.inbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=A.video.outbound.find(M=>M.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,m),S}let O,T={},E=[];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:I}=g;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(S&&S in this.peersToMonitor[f])throw new Error(`We are already monitoring connection with id ${S}.`);for(let x in this.peersToMonitor[f]){const N=this.peersToMonitor[f][x];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 A=m.getConfiguration();return A.iceServers&&A.iceServers.forEach(function(x){delete x.credential}),S||(S=w()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:g,peerConfiguration:A}}),this.monitorPeer({peerId:f,connectionId:S,pc:m,remote:I}),{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 I in this.peersToMonitor)f in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][f].pc,m=I)}else if(S){if(!(S instanceof RTCPeerConnection))throw new Error("pc must be an instance of RTCPeerConnection.");for(let I in this.peersToMonitor)for(let A in this.peersToMonitor[I])this.peersToMonitor[I][A].pc===S&&(f=A,m=I)}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(),E.forEach(g=>{this.removeTrackEventListeners(g)}),E=[],this.shouldWrapGetUserMedia&&O&&(navigator.mediaDevices.getUserMedia=O)}monitorPeer(g){let{peerId:m,connectionId:f,pc:S,remote:I}=g;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const A={pc:S,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]=A}else this.peersToMonitor[m]={[f]:A};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 I in m[S]){const A=m[S][I],x=A.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),M=x.getStats(null);if(M){const F=await M,G=this.getTimestamp(),U=L(F),ae={remote:A.options.remote},q=R(F,A.stats.parsed,ae),H={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:G-N,data:q};this.rawStats===!0&&(H.rawStats=F),this.statsObject===!0&&(H.statsObject=U),this.filteredStats===!0&&(H.filteredStats=this.filteroutStats(U)),f.push(H),A.stats.parsed=q}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 I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,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."),O=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const g=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return g({constraints:arguments[0]}),O.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 I=S.track,A=S.streams[0];g in this.peersToMonitor&&m in this.peersToMonitor[g]&&(this.peersToMonitor[g][m].stream=A),this.addTrackEventListeners(I,m),this.emitEvent({event:"ontrack",tag:"track",peerId:g,connectionId:m,data:{stream:A?this.getStreamDetails(A):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.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),E.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)}}}});(bs=Eh)&&bs.__esModule&&Object.prototype.hasOwnProperty.call(bs,"default")&&bs.default;var nb=Eh.WebRTCStats;function sb(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 ob(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 rb extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class ab extends Li{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class lb extends Li{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 cb(t,e){const i=ki();let n=!1;const s=new nb({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(P.StatsFrame,function({data:a}){var l,c,u,d,h,p,_,v;const{audio:b,remote:w}=a,{audio:C}=w,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,L=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,O=(v=(_=b.inbound[0])===null||_===void 0?void 0:_.packetsLost)!==null&&v!==void 0?v:-1,T=sb({jitter:1e3*k,rtt:1e3*L,packetsLost:O,packetsReceived:R});return{jitter:k,rtt:L,mos:T,quality:ob(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new lb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>V(this,void 0,void 0,function*(){if(n)y.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new rb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){y.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(P.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 ab(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 kh=(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:st.conferenceUpdate,call:t.calls[s],canvasInfo:db(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Ye.LayerInfo},a);B(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Ye.LayoutInfo},a);B(P.Notification,l,t.uuid);break}}},db=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Qu(e)},Ih=["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"],ub={"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 Rh(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function Fr(t){for(const e of Ih)try{performance.clearMarks(re(t,e))}catch{y.warn("Clearing performance marks is failed")}}class ii{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 y.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(y.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){y.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=Ne(t0);B(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Ne(s0);B(P.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 y.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;y.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;y.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)},y.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?(y.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&&(y.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ii.ICE_RESTART_TIMEOUT_MS),y.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(y.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(y.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Fe.Offer}get isAnswer(){return this.type===Fe.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 Vt&&B(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(y.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{y.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),y.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):y.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(y.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":B(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(y.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){y.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?y.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&&ms(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}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=Rh(re(s,"new-call-start"));if(a===void 0)return{mode:o,direction:r,steps:[]};const l=[];for(const d of Ih){if(d==="new-call-start")continue;const h=Rh(re(s,d));h!==void 0&&l.push({label:ub[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 y.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+="-";y.info(`${l} Call establishment timing breakdown:`),y.info(`${l} ${h}`),y.info(`${l} ${p}`),y.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const _ of a){const v=_.delta.toFixed(2)+"ms",b=_.fromStart.toFixed(2)+"ms";y.info(`${l} ${u(_.label,c)}${d(v,14)}${d(b,14)}`)}y.info(`${l} ${p}`)})(n),Fr(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:Fe.Offer}),performance.mark(re(this.options.id,"set-remote-description")),!this.instance))throw ne(wr);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(P.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(wr);if(!this.options.localStream&&!i)throw ne(n?Ii(n):Vu,n??void 0);performance.mark(re(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&vn(this.options.localStream)&&(y.info("Muting local audio tracks on start"),ys(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=Ne(n0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Ne(i0);B(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ii.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(wr);this.isDebugEnabled&&(this.statsReporter=cb(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(vn(n)){const o=n.getAudioTracks();let r=[...o];if(y.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{y.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],y.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{y.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Th(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&&ms(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});y.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Th(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);y.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,y.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 y.error("Peer _createOffer error:",e),e instanceof Vt?e:ne(My,e)}}})}_setRemoteDescription(e){return V(this,void 0,void 0,function*(){y.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw y.error("Peer _setRemoteDescription error:",i),ne(Bu,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 y.debug("Skipping negotiation, state:",this.instance.signalingState),y.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:Fe.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 y.error("Peer _createAnswer error:",e),e instanceof Vt?e:ne(Py,e)}}})}_setLocalDescription(e){return V(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw y.error("Peer _setLocalDescription error:",i),ne(Ny,i)}})}_sdpReady(){Ri(this.onSdpReadyTwice)&&this.onSdpReadyTwice(this.instance.localDescription)}_retrieveLocalStream(){return V(this,void 0,void 0,function*(){if(vn(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 _s(s,a,yt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield _s(r,l,yt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return vs(e)})}_isOffer(){return this.type===Fe.Offer}_isAnswer(){return this.type===Fe.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 y.info("RTC config",s),s}restartStatsReporter(){return V(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?y.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(y.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):y.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return V(this,void 0,void 0,function*(){Fr(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)})}}ii.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ii.ICE_RESTART_TIMEOUT_MS=15e3;const ws=Dr;class Ah{constructor(e,i){this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=W[W.New],this.prevState="",this.channels=[],this.role=Ar.Participant,this.extension=null,this._state=W.New,this._prevState=W.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._wasHeldBeforeRecovery=!1,this._checkConferenceSerno=b=>{const w=b<0||!this._lastSerno||this._lastSerno&&b===this._lastSerno+1;return w&&b>=0&&(this._lastSerno=b),w},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(b=>{b.forEach(w=>{this._statsBindings.forEach(C=>{if(C.callback){if(C.constraints){for(const k in C.constraints)if(C.constraints.hasOwnProperty(k)&&C.constraints[k]!==w[k])return}C.callback(w)}})})})};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({},N0,{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=wh(this.options.ringtoneFile,"_ringtone"),this._ringback=wh(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=_t.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){y.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Vt?e:ne($u,e instanceof Error?e:void 0);return B(P.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&&y.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=Ne(r0);return B(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void y.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=_t.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})),e.remoteElement===void 0&&e.localElement===void 0||(this.options=Object.assign(Object.assign(Object.assign({},this.options),e.remoteElement!==void 0&&{remoteElement:e.remoteElement}),e.localElement!==void 0&&{localElement:e.localElement})),this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(re(this.id,"new-peer")),this.peer=new ii(Fe.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){y.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Vt?d:ne($u,d instanceof Error?d:void 0);return B(P.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(){Sh(this._ringtone)}stopRingtone(){Ch(this._ringtone)}playRingback(){Sh(this._ringback)}stopRingback(){Ch(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<W.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:[]],y.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(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new W0({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let w;try{yield Promise.race([this._execute(b),new Promise(C=>{w=setTimeout(()=>{y.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){y.error("telnyx_rtc.bye failed!",C);const k=ne(jy,C);B(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{w&&clearTimeout(w)}}y.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new ps({sessid:this.session.sessionid,action:Ai.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new ps({sessid:this.session.sessionid,action:Ai.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new mh({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 mh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){y.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,ys(this.options.localStream)}unmuteAudio(){y.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Nr(this.options.localStream)}_applyDesiredAudioMuteState(){y.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?ys(this.options.localStream):Nr(this.options.localStream)}toggleAudioMute(){y.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 y.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void B(P.Warning,{warning:Ne(l0),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;y.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Or(l.track),localTracks:bh(this.options.localStream)});try{c=yield gs({audio:{deviceId:{exact:e}}})}catch(h){const p=ne(Ii(h),h);return void B(P.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(P.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,y.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Or(l.track),localTracks:bh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Oi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Oi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Oi(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 gs({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;ms(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(){ys(this.options.remoteStream)}undeaf(){Nr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Oi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return V(this,void 0,void 0,function*(){if(!this||!this.peer)return void y.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 y.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"}]),y.info("Parameters: ",r),y.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{y.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>y.error(a))}else y.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[W.Hangup,W.Destroy,W.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,a,l;switch(this._prevState=this._state,this._state=e,this.state=W[this._state].toLowerCase(),this.prevState=W[this._prevState].toLowerCase(),y.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:st.callUpdate,call:this}),e){case W.Purge:y.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(re(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,y.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(y.debug(`[${this.id}] Cleared held-before-recovery intent on transition to Active`),this._wasHeldBeforeRecovery=!1),(n=this._callReportCollector)===null||n===void 0||n.setHeld(!1),this.session.startSignalingHealthMonitor(),setTimeout(()=>{const{remoteElement:c,speakerId:u}=this.options;c&&u&&_h(c,u)},0),this._callReportCollector&&!((s=this.peer)===null||s===void 0)&&s.instance&&this.session.callReportId&&this._callReportCollector.start(this.peer.instance),this._callRecorder){const c=(o=this.session.connection)===null||o===void 0?void 0:o.host;c&&this._callRecorder._setHost(c),this.session.callReportId&&this._callRecorder._setCallReportId(this.session.callReportId);const u=(r=this.options.localStream)===null||r===void 0?void 0:r.getAudioTracks()[0],d=(a=this.options.remoteStream)===null||a===void 0?void 0:a.getAudioTracks()[0];this._callRecorder.start(u,d)}this._mediaDeviceCollector=new ib,this._mediaDeviceCollector.logDevicesAtStart();break;case W.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case W.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>=W.Active)return;this._state>=W.Early&&this.setState(W.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>=W.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===_t.Inbound?_t.Outbound:_t.Inbound,c={type:st[i],call:this,displayName:o,displayNumber:r,displayDirection:l};B(P.Notification,c,this.id)||B(P.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:st.generic,call:this});B(P.Notification,o,this.id)||B(P.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 y.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:Ye.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(_)},cs(s[_][1])));this._dispatchConferenceUpdate({action:Ye.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Ye.Add,callId:o,index:r},cs(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Ye.Modify,callId:o,index:r},cs(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Ye.Delete,callId:o,index:r},cs(s)));break;case"clear":this._dispatchConferenceUpdate({action:Ye.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:Ye.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfChat subscription error:",s)});Mr(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,kh(this.session,o)):y.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{y.error("ConfInfo subscription error:",s)});Mr(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(W.Active):this.setState(W.Held),!0}_handleChangeHoldStateError(e){y.error(`Failed to ${e.action} on call ${this.id}`);const i=ne(Vy,e);return B(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new ps(Object.assign(Object.assign({sessid:this.session.sessionid,action:Ai.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));y.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?(y.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;y.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ne(Ky,i);B(P.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:Fe.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(W.Early),this.gotAnswer&&this._state!==W.Held&&this.setState(W.Active)}).catch(n=>V(this,void 0,void 0,function*(){y.error("Call setRemoteDescription Error: ",n);const s=ne(Bu,n);B(P.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){y.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_requestAnotherLocalDescription(){if(Ri(this.peer.onSdpReadyTwice)){const e=ne(br,new Error("SDP without candidates for the second time!"));B(P.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 y.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;if(o.indexOf("candidate")===-1)return y.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),!v0.test(o)){const c=Ne(o0);y.warn(`[${this.id}] Warning ${c.code}: ${c.message}`),B(P.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-${ws}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Fe.Offer:this.setState(W.Requesting),a=new fh(l);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new gh(l):new ph(l);break;default:return y.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 y.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${r} error:`,c);const u=ne(br,c);B(P.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){y.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(!e)return y.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-${ws}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Fe.Offer:this.setState(W.Requesting),o=new fh(r);break;case Fe.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new gh(r):new ph(r);break;default:return y.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 y.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Fe.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>V(this,void 0,void 0,function*(){y.error(`${this.id} - Sending ${s} error:`,a);const l=ne(br,a);B(P.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){y.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?(y.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?(y.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 G0({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 y.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(()=>{y.debug("Successfully added ICE candidate:",e)}).catch(n=>{y.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new q0({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=>{y.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(y.debug("Finished gathering candidates"),performance.mark(re(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(y.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&&ms(n,s,{callId:this.id,sessionId:this.session.sessionid,eventTarget:this.session.uuid})})}_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:st.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),y.error(`Media error (${i}): ${n}`,e),B(P.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:st.peerConnectionFailureError,error:e.error}),y.error("Peer connection failure error"),e.warning&&B(P.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:st.signalingStateClosed},e)),y.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:st.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(B(P.Notification,e,this.id,!1)||B(P.Notification,e,this.session.uuid))}_execute(e){return this.nodeId&&(e.targetNodeId=this.nodeId),this.session.execute(e)}_registerInboundAnswerAttempt(){var e;if(this.options.attach||this._isRecovering)return!0;const i=(e=this.session.calls)===null||e===void 0?void 0:e[this.id];if(i&&i!==this){const n=Ne(d0);return B(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),y.warn(`[${this.id}] answer() ignored: callID ${this.id} already has an active call (${i.id})`),!1}return!0}_init(){var e,i,n,s,o,r,a,l,c,u;const{id:d,userVariables:h,remoteCallerNumber:p,onNotification:_,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var w;this.options.id=d?d.toString():ki(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),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(P.MediaError,this._onMediaError,this.id),Ut(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Ut(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),Ri(_)&&Ut(P.Notification,_.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,L=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",O=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new le({enabled:!0,interval:k,intermediateReportInterval:L},{enabled:!0,level:R,maxEntries:O}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,g,m,f;B(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===Cr&&this._state!==W.Held?(g=(E=this.session).reportNoRtp)===null||g===void 0||g.call(E,this.id,"inbound"):T.code===Wu&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(m=this.session).reportNoRtp)===null||f===void 0||f.call(m,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const T={enabled:!0,flushIntervalMs:(i=this.session.options.callRecordingFlushIntervalMs)!==null&&i!==void 0?i:15e3,maxBufferBytes:(n=this.session.options.callRecordingMaxBufferBytes)!==null&&n!==void 0?n:rh,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"},E={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new je(T,E);const g=(l=this.session.connection)===null||l===void 0?void 0:l.host;g&&this._callRecorder._setHost(g),this._callRecorder.onWarning=m=>{B(P.Warning,{warning:m,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),y.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(),Fr(this.id),y.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;_n(s),_n(o),vh(r,s),vh(a,o),bt(P.MediaError,null,this.id),bt(P.PeerConnectionFailureError,null,this.id),bt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{y.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 y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;y.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=>{y.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 y.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=>{y.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 y.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===_t.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:ws,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void y.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 y.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),y.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),y.debug("Stats stopped")}}Ah.setStateTelnyx=t=>{if(t){switch(t._state){case W.Recovering:t.state="recovering";break;case W.Requesting:case W.Trying:case W.Early:t.state="connecting";break;case W.Active:t.state="active";break;case W.Held:t.state="held";break;case W.Hangup:case W.Destroy:t.state="done";break;case W.Answering:t.state="ringing";break;case W.New:t.state="new"}return t}};class ni extends Ah{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new eb(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 tb(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 ni&&(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 ni(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return V(this,void 0,void 0,function*(){this.screenShare instanceof ni&&(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)&&_h(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
- `)}))}),y.info(n)}),2e3)}}class Ss extends ti{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>Ss.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=Ne(a0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};B(P.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),y.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*(){y.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 vs({audio:e,video:i});return _n(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*(){y.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(W.Purge),y.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){y.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(W.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(rh(P.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 yn().catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return yn(yt.Video).catch(e=>(B(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return yn(yt.AudioIn).catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return yn(yt.AudioOut).catch(e=>(y.error("getAudioOutDevices",e),B(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return _s(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 vs({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<vh.length;r++){const[a,l]=vh[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 _n(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=Ou(e,["micId","micLabel"]);return X0(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 _s(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?S0:w0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=fn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=fn(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new G0({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 q0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Or(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 z0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Or(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ni.setStateTelnyx(e)}}Ss.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class Rh{constructor(e,i){this.code=i,this.message=e}}class db{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new $0(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:b={},voice_sdk_id:w}=e,C=b==null?void 0:b.callID,k=b==null?void 0:b.eventChannel,L=b==null?void 0:b.eventType,R=p.calls[C],O=(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(b==null?void 0:b.reattached_sessions)&&T.size){y.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=b.reattached_sessions.length===0,S=b.reattached_sessions.some(I=>T.has(I));if(f||!S)for(const I of Object.keys(p.calls)){const A=p.calls[I];y.debug(`Session not reattached — terminating active call ${I} `);const x=ne(Vu);B(P.Error,{error:x,callId:I,sessionId:p.sessionid},p.uuid),A.hangup({},!1)}}if(Array.isArray(b==null?void 0:b.reattached_sessions)&&p.sessionid){const f=ih();if(f&&f.calls.length>0)if(f.sessionId!==p.sessionid)y.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${p.sessionid}) — ignoring all.`),ei();else{const S=new Set(b.reattached_sessions),I=[];for(const A of f.calls)try{if(S.has(A.id)){y.debug(`Recovery marker for call ${A.id} was reattached — keeping for Attach element restore.`),I.push(A);continue}y.info(`Recovery marker for call ${A.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const x=ne(Vu);B(P.Error,{error:x,callId:A.id,sessionId:p.sessionid,customHeaders:A.customHeaders},p.uuid)}catch(x){y.debug(`Recovery marker for a saved call failed to process (callId=${A==null?void 0:A.id}) — skipping: ${x instanceof Error?x.message:String(x)}`),I.push(A)}nh(I,f.sessionId,f.storedAt)}}if(L==="channelPvtData")return this._handlePvtEvent(b.pvtData);const E=({recoveredCallId:f,forceRelayCandidateForRecovery:S,mutedMicOnStart:I,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N}={})=>{var M,F,G,U,ae;const q={audio:!0,video:p.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Z.Attach,mediaSettings:b.mediaSettings,debug:(M=p.options.debug)!==null&&M!==void 0&&M,debugOutput:(F=p.options.debugOutput)!==null&&F!==void 0?F:"socket",trickleIce:(G=p.options.trickleIce)!==null&&G!==void 0&&G,prefetchIceCandidates:(U=p.options.prefetchIceCandidates)===null||U===void 0||U,forceRelayCandidate:S||p.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(ae=p.options.keepConnectionAliveOnSocketClose)!==null&&ae!==void 0&&ae,mutedMicOnStart:I??p.options.mutedMicOnStart};C&&(q.id=C),b.telnyx_call_control_id&&(q.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(q.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(q.telnyxLegId=b.telnyx_leg_id),b.client_state&&(q.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(q.customHeaders=b.dialogParams.custom_headers),f&&(q.recoveredCallId=f),N&&(q.wasHeldBeforeRecovery=N),A!==void 0&&(q.remoteElement=A),x!==void 0&&(q.localElement=x),performance.mark(re(q.id,"new-call-start"));const H=new ni(p,q);return H.nodeId=this.nodeId,H},g=new ch(w),m=new Ar(w);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 y.error(`Received ${v} for non existing call:`,b);R.handleMessage(e),this._ack(_,v);break;case Z.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Z.Punt:p.options.keepConnectionAliveOnSocketClose&&O?(y.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(_,v)):(y.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Z.Invite:{const I=E();I.direction=_t.Inbound,I.playRingtone(),I.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(I.id),this._ack(_,v);break}case Z.Attach:{const I=R||null;if(Object.keys(p.calls).length===0){let A,x;y.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`);let N=!1;const M=ih();if(M&&M.sessionId===p.sessionid){const G=M.calls.find(U=>U.id===C);G&&(A=G.remoteElement,x=G.localElement,N=G.wasHeld===!0,(A||x)&&y.info(`[${C}] Attach: restoring per-call media elements from recovery marker (remoteElement=${A??"<none>"}, localElement=${x??"<none>"}).`))}const F=E({recoveredCallId:C,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N});F.answer(),this.session.emitMultipleActiveCallsWarning(F.id),this._ack(_,v);break}if(I){const A=I.id,x=(s=(n=I.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(I))!==null&&s!==void 0&&s,N=I.state==="held";x&&y.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),y.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${A}.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const M=E({recoveredCallId:A,forceRelayCandidateForRecovery:x,mutedMicOnStart:I.isAudioMuted,remoteElement:I.options.remoteElement,localElement:I.options.localElement,wasHeldBeforeRecovery:N});M.answer(),this.session.emitMultipleActiveCallsWarning(M.id),this._ack(_,v);break}y.warn(`Attach: callID ${C} does not match any active calls. `),B(P.Warning,{warning:Ne(u0),callId:C,params:b,sessionId:p.sessionid},p.uuid),this._ack(_,v);break}case Z.Event:case"webrtc.event":if(!k)return void y.error("Verto received an unknown event:",b);const f=p.relayProtocol,S=k.split(".")[0];p._existsSubscription(f,k)?B(f,b,k):k===p.sessionid?this._handleSessionEvent(b.eventData):p._existsSubscription(f,S)?B(f,b,S):p.calls.hasOwnProperty(k)?p.calls[k].handleMessage(e):B(P.Notification,b,p.uuid);break;case Z.Info:b.type=st.generic,B(P.Notification,b,p.uuid);break;case Z.ClientReady:this.session.execute(g);break;case"ai_conversation":B(P.AIConversationMessage,{method:"ai_conversation",params:b,voice_sdk_id:w},p.uuid);break;default:{const I=Cr(e);if(I){switch(I){case Oe.REGISTER:case Oe.REGED:if(!this.isDuplicateGatewayState(I,[Oe.REGED,Oe.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,I===Oe.REGED&&this.session.resetReconnectAttempts();const A=(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;A&&(p.callReportId=A,y.debug("Captured call_report_id from REGED:",A));const x=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;x&&(p.dc=x);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),y.info(`Connected to Telnyx — region: ${(d=p.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),b.type=st.vertoClientReady,B(P.Ready,b,p.uuid)}break;case Oe.UNREGED:case Oe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const A=new Rh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),x=ne(Bu,A);B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{this.session.execute(g)},this.reconnectDelay());break;case Oe.FAILED:case Oe.FAIL_WAIT:case Oe.TIMEOUT:if(!this.isDuplicateGatewayState(I,[Oe.FAILED,Oe.FAIL_WAIT,Oe.TIMEOUT])){const A=ne(Hy,new Error(`Gateway state: ${I}`));if(B(P.Error,{error:A,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,y.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 x=new Rh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const N=ne(br,x);B(P.Error,{error:N,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const x=ne(br,new Error("Connection Retry Failed"));B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{if(y.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some(x=>{var N;return((N=x.peer)===null||N===void 0?void 0:N.instance)&&!x.signalingStateClosed}))return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();y.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:y.warn("GatewayState message unknown method:",e)}break}y.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&y.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:b})=>{const w=h||this._retrieveCallId(b,o);if(w&&i.calls.hasOwnProperty(w)){const C=i.calls[w];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(_).catch(b=>{y.error("liveArray subscription error:",b);const w=ne(Uy,b);B(P.Error,{error:w,sessionId:i.sessionid},i.uuid)});Dr(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 b={type:st.conferenceUpdate,action:Ye.Leave,conferenceName:r,participantId:Number(u),role:d};B(P.Notification,b,v,!1)||B(P.Notification,b,i.uuid),p===null&&bt(P.Notification,null,v)}}const _=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{y.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":Th(this.session,e);break;case"logo-info":{const i={type:st.conferenceUpdate,action:Ye.LogoInfo,logo:e.logoURL};B(P.Notification,i,this.session.uuid);break}}}}class ub extends Ss{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 db(this),window.addEventListener("beforeunload",i=>{if(y.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return th(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(y.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&&(y.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=>{const o={id:s.id,customHeaders:s.options.customHeaders};return s.state==="held"&&(o.wasHeld=!0),typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(!this.sessionid||n.length===0)return y.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void ei();y.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),nh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];y.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()&&(y.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),kr(this.sessionid))})}validateOptions(){return ds(this.options)||pn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ne(By,void 0,"Error: destinationNumber is required");const i=new ni(this,e);return e.id||y.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!!pn(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),ds(this.options)?this.handleLoginOnSocketOpen():pn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class hb extends ub{constructor(e){super(e),y.info(`SDK version: ${dh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return J0()}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 fb(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 Ah(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var xh={exports:{}},Lh;function pb(){return Lh||(Lh=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[_],b=arguments.length,w,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,p),!0}for(C=1,w=new Array(b-1);C<b;C++)w[C-1]=arguments[C];v.fn.apply(v.context,w)}else{var k=v.length,L;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(!w)for(L=1,w=new Array(b-1);L<b;L++)w[L-1]=arguments[L];v[C].fn.apply(v[C].context,w)}}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=[],b=p.length;_<b;_++)(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}(xh)),xh.exports}var gb=pb();const Nr=Ah(gb),Fr=new Nr;var Br={exports:{}},mb=Br.exports,Dh;function vb(){return Dh||(Dh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(mb,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 w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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 w=s[b];this[w]=b<v?e:this.methodFactory(w,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,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(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,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){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"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}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 b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};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})}(Br)),Br.exports}var _b=vb();const yb=Ah(_b),bb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=yb.getLogger("telnyx-ai-agent"),wb=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=wb(t,e,i);return function(...s){n(bb(),"-",...s)}},fe.setLevel("info");function Sb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Cb=10,Tb=500,Eb=100,kb=300,Oh=20;class Ib{constructor(e){j(this,"remoteIntervalId",null);j(this,"localIntervalId",null);j(this,"remoteStream",null);j(this,"localStream",null);j(this,"remoteAudioContext",null);j(this,"remoteSource",null);j(this,"remoteAnalyser",null);j(this,"localAudioContext",null);j(this,"localSource",null);j(this,"localAnalyser",null);j(this,"thinkingStartTime",null);j(this,"lastState",null);j(this,"userIsSpeaking",!1);j(this,"lastUserAudioTime",null);j(this,"userSpeechStartTime",null);j(this,"remoteSilenceStartTime",null);j(this,"remoteSilenceThresholdMs");j(this,"userSilenceStartTime",null);j(this,"isFirstAgentSpeech",!0);j(this,"monitorStartTime",null);j(this,"volumeThreshold");j(this,"silenceDurationMs");j(this,"minSpeechDurationMs");j(this,"maxLatencyMs");j(this,"updateAgentState",Sb(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Fr.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Cb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Tb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Eb,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??kb}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,this.remoteSilenceStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){fe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,fe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(fe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;fe.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&&fe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(this.remoteSilenceStartTime=null,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.remoteSilenceStartTime===null&&(this.remoteSilenceStartTime=performance.now()),performance.now()-this.remoteSilenceStartTime>=this.remoteSilenceThresholdMs&&this.updateAgentState({state:"listening"}));n=r};this.remoteIntervalId=window.setInterval(s,Oh)}startLocalMonitor(){if(!this.localStream){fe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,fe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(fe.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&&fe.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,Oh)}destroy(){this.stopAudioStreamMonitor()}}function Rb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Ab(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function xb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Vr(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Lb(t){if(!Vr(t))return null;const e=t.params;return fb(e)?e.item:null}function Db(t){if(!Vr(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const n of e.client_side_tools)if(n&&typeof n=="object"&&typeof n.name=="string"){const s=n;i.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return i}function Ob(t){if(!Vr(t))return null;const e=t.params;if(!e||typeof e!="object")return null;const i=e;if(i.type==="response.audio.delta"){const n=i.format;if(!n||typeof n!="object")return null;const s=n;return typeof i.response_id!="string"||typeof i.delta!="string"||typeof i.sequence!="number"||!Number.isInteger(i.sequence)||typeof s.encoding!="string"||typeof s.sample_rate!="number"||typeof s.channels!="number"?null:{type:"response.audio.delta",response_id:i.response_id,item_id:typeof i.item_id=="string"?i.item_id:void 0,sequence:i.sequence,delta:i.delta,format:{encoding:s.encoding,sample_rate:s.sample_rate,channels:s.channels}}}return i.type==="response.audio.done"&&typeof i.response_id=="string"?{type:"response.audio.done",response_id:i.response_id}:i.type==="response.audio.interrupted"?{type:"response.audio.interrupted",response_id:typeof i.response_id=="string"?i.response_id:void 0}:null}function Mb(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 Pb=3e4;function Nb(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 Ur(t){return JSON.stringify({error:t})}class Fb{constructor(e){j(this,"registry",new Map);j(this,"toolTimeouts",new Map);j(this,"inFlight",new Set);j(this,"completed",new Set);j(this,"generation",0);j(this,"getActiveCall");j(this,"timeoutMs");j(this,"events");j(this,"handleEvent",e=>{const i=Db(e);if(i){this.ingestToolSettings(i);return}const n=Lb(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Pb,this.events={onInvoked:i=>this.safeEmit(()=>e.events.onInvoked(i)),onCompleted:i=>this.safeEmit(()=>e.events.onCompleted(i)),onError:i=>this.safeEmit(()=>e.events.onError(i))}}safeEmit(e){try{e()}catch(i){fe.warn(`[client-tools] lifecycle listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}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())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:i,timeout_ms:n}of e)typeof n=="number"&&n>0&&this.toolTimeouts.set(i,n)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.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)){fe.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){fe.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,Ur("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{fe.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,Ur("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},c=this.toolTimeouts.get(n)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n,c);this.sendOutput(i,n,Nb(u),!1,s,o)}catch(u){const d=u instanceof Mh?"timeout":"handler_error";fe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,Ur(d),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Mh(n,i,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){fe.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){fe.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){fe.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){fe.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 Mh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}class Bb{constructor(e){j(this,"enabled");j(this,"getActiveCall");j(this,"events");j(this,"subscriptionConfirmed",!1);j(this,"handleEvent",e=>{if(!this.enabled)return;this.subscriptionConfirmed||this.sendSubscription();const i=Ob(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Vb(i.delta)}catch(s){fe.warn(`[streaming-audio] invalid base64 delta for response ${i.response_id}: ${s instanceof Error?s.message:"unknown error"}`);return}this.emitSafely(()=>this.events.onDelta({responseId:i.response_id,itemId:i.item_id,sequence:i.sequence,audio:n,format:{encoding:i.format.encoding,sampleRate:i.format.sample_rate,channels:i.format.channels}}));return}if(i.type==="response.audio.done"){this.emitSafely(()=>this.events.onDone({responseId:i.response_id}));return}this.emitSafely(()=>this.events.onInterrupted({responseId:i.response_id}))}});this.enabled=e.enabled,this.getActiveCall=e.getActiveCall,this.events=e.events}onCallActive(){this.subscriptionConfirmed=!1,this.sendSubscription()}reset(){this.subscriptionConfirmed=!1}sendSubscription(){if(!this.enabled)return;const e=this.getActiveCall();if(e)try{const i={type:"response.audio_stream.subscribe"};e.sendAIConversationMessage(i)}catch(i){fe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){fe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}}function Vb(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Ub(t){return Ab(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function $b(t){if(!xb(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 jb extends Nr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcript",[]);j(this,"onSocketMessage",i=>{if(Rb(i))switch(i.params.type){case"response.text.delta":{const n=Ub(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Mb(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=$b(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(P.SocketMessage,this.onSocketMessage)}}const Dt=t=>typeof t=="object"&&t!==null,Ph=t=>{const e=Dt(t)&&Dt(t.result)?t.result:t;if(!(!Dt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Hb=t=>Dt(t)&&Dt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Wb=(t,e)=>{if(!e||!Dt(t)||!Dt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Dt(i.params))return;const n=i.params;Dt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class Gb extends Nr{constructor(i){super();j(this,"telnyxRTC");j(this,"transcription");j(this,"removeLoginSuccessHook",null);j(this,"authenticated",!1);j(this,"authenticating",!1);j(this,"agentId");j(this,"versionId");j(this,"widgetVersion");j(this,"conversationId");j(this,"debug");j(this,"audioStreamMonitor");j(this,"clientTools");j(this,"streamingAudio");j(this,"activeCall");j(this,"chatMode");j(this,"dc",null);j(this,"region",null);j(this,"callReportId",null);j(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)});j(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});j(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});j(this,"onSocketMessage",i=>{const n=Ph(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});j(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,this.streamingAudio.onCallActive(),i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.streamingAudio.reset(),this.audioStreamMonitor.stopAudioStreamMonitor()))});j(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});j(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,fe.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 hb({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(P.Ready,this.onClientReady),this.telnyxRTC.on(P.Error,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketClose,this.onSocketClose),this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(P.Notification,this.onNotification),this.transcription=new jb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Fr.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Ib(i.vad),this.clientTools=new Fb({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(P.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new Bb({enabled:i.streamingAudio??!1,getActiveCall:()=>this.activeCall,events:{onDelta:s=>this.emit("assistant.audio.delta",s),onDone:s=>this.emit("assistant.audio.done",s),onInterrupted:s=>this.emit("assistant.audio.interrupted",s)}}),this.telnyxRTC.on(P.AIConversationMessage,this.streamingAudio.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(P.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(P.AIConversationMessage,this.streamingAudio.handleEvent),this.clientTools.reset(),this.streamingAudio.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(P.Ready,this.onClientReady),this.telnyxRTC.off(P.Error,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketClose,this.onSocketClose),this.telnyxRTC.off(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(P.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(),Fr.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){fe.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 fe.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 fe.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 _=Hb(p),v=c;return _&&Wb(p,a),n.call(this,p).then(b=>{const w=_?Ph(b):void 0;return l&&w!==void 0&&(u(v),r({sessionId:w})),b})},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 Nh={exports:{}},bn={},Fh;function qb(){if(Fh)return bn;Fh=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 bn.Fragment=e,bn.jsx=i,bn.jsxs=i,bn}var Bh;function zb(){return Bh||(Bh=1,Nh.exports=qb()),Nh.exports}zb(),kt(void 0),kt(null);const Kb=(t,e,i,n,s,o,r,a,l,c)=>new Gb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Cs=10,Vh=5e3,Yb=[46001,46003],Xb=["login incorrect","authentication required","authentication failed"];function Uh(t){var n;const e=t.code;if(e&&Yb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Xb.some(s=>i.includes(s))}const Jb=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[p,_]=Ae(!1),[v,b]=Ae(null),[w,C]=Ae(!1),k=ue(0),L=ue(null),R=ue(null),O=ue(!1),T=ue(!1),E=ue(0),g=ue(0),m=Ge(()=>{L.current&&(clearTimeout(L.current),L.current=null)},[]),f=Ge(()=>{m(),k.current=0,T.current=!0,C(!1),b(null)},[m]),S=Ge(()=>{m(),C(!1)},[m]),I=Ge(A=>{if(m(),k.current>=Cs){oe.error(`Max login retry attempts (${Cs}) exceeded`),C(!1);return}k.current+=1;const x=E.current,N=g.current;oe.info(`Scheduling login retry attempt ${k.current}/${Cs} in ${Vh}ms due to: ${A}`),C(!0),L.current=window.setTimeout(()=>{var G;L.current=null;const M=R.current,F=M==null?void 0:M.telnyxRTC;if(E.current!==x||g.current!==N||M!=null&&M.isAuthenticating){oe.info("Skipping login retry because a newer socket/login is already in progress"),S();return}if(O.current||T.current||M!=null&&M.isAuthenticated){oe.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(oe.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(G=F==null?void 0:F.socketDisconnect)==null||G.call(F))},Vh)},[m,S,f]);return xe(()=>{if(!t)return;const A=Kb(t,e,i,n,s,o,r,a,l,u);O.current=!1,T.current=!1,_(!1),b(null),C(!1),R.current=A;const x=()=>{oe.info("Agent connected successfully"),O.current=!0,_(!0),f()},N=()=>{oe.info("Agent disconnected"),O.current=!1,T.current=!1,_(!1)},M=H=>{if(oe.error("AI Agent error:",H),Uh(H)){if(O.current||T.current){oe.debug("Ignoring retryable error — login already succeeded");return}k.current<Cs?(b(null),I(H.message)):(b(H),C(!1))}else b(H),C(!1)},F=A.telnyxRTC??null,G=()=>{g.current+=1,T.current=!1},U=()=>{oe.info("Login succeeded; clearing pending login retry flow"),f()},ae=()=>{E.current+=1,T.current=!1},q=()=>{T.current=!1};return A.on("agent.connected",x),A.on("agent.disconnected",N),A.on("agent.error",M),A.on("agent.login.started",G),A.on("agent.login.success",U),F&&typeof F=="object"&&(F.on(P.SocketOpen,ae),F.on(P.SocketClose,q)),A.connect(),h(A),()=>{m(),A.off("agent.connected",x),A.off("agent.disconnected",N),A.off("agent.error",M),A.off("agent.login.started",G),A.off("agent.login.success",U),F&&typeof F=="object"&&(F.off(P.SocketOpen,ae),F.off(P.SocketClose,q)),A.disconnect(),O.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:p,error:v,isReconnecting:w}},Zb="telnyx-ai-agent",Xe={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",CLIENT_TOOLS_CONFIGURED:"client.tools.configured"};function Qb(t){var n,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;i.push({name:r.name,description:(n=r.client_side_tool)==null?void 0:n.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return i}function $h(){const t=document.querySelector(Zb);return t instanceof HTMLElement?t:null}function wt(t,e,i){const n=i||$h();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 ew=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=Mn(_u);xe(()=>{const c=i==null?void 0:i.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??$h()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const O=t.telnyxRTC,T={dc:(O==null?void 0:O.dc)??null,region:(O==null?void 0:O.region)??null,callReportId:(O==null?void 0:O.callReportId)??null};l(T),wt(Xe.AGENT_CONNECTED,T,c)},d=()=>{l(null),wt(Xe.AGENT_DISCONNECTED,void 0,c)},h=R=>{const O={message:R.message,name:R.name};if(Uh(R)){oe.debug("Ignoring retryable agent.error in widget event layer"),wt(Xe.AGENT_ERROR,O,c);return}o(R),wt(Xe.AGENT_ERROR,O,c)},p=R=>{var O;s(R),wt(Xe.CONVERSATION_UPDATE,{type:R.type,callState:(O=R.call)==null?void 0:O.state},c)},_=R=>{wt(Xe.TRANSCRIPT_ITEM,R,c)},v=R=>{wt(Xe.CONVERSATION_AGENT_STATE,R,c)},b=R=>{wt(Xe.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const O=Qb(R);O&&wt(Xe.CLIENT_TOOLS_CONFIGURED,{tools:O},c)},L=R=>{const O=R,T={code:O==null?void 0:O.code,reason:O==null?void 0:O.reason,wasClean:O==null?void 0:O.wasClean,timestamp:new Date().toISOString()};oe.info("[socket.close]",T),wt(Xe.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(P.SocketMessage,k),C.on(P.SocketClose,L)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",_),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",_),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),C&&typeof C=="object"&&(C.off(P.SocketMessage,k),C.off(P.SocketClose,L))}},[t,n,s,o,r,l])},tw=2e3;async function iw(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function jh(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 nw=(t,e)=>{const[i,n]=Ae([]),[,s]=cr(),o=ue(e);xe(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return xe(()=>{if(!t)return;const c=h=>{n(p=>{const _=p[p.length-1];if(h.role==="assistant"&&_&&jh(_.id)===jh(h.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,w={..._,content:_.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),[...p.slice(0,-1),w]}if(h.role==="assistant"){s(w=>w==="thinking"||w==="processing_image"?"speaking":w);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const w={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,w]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(w=>w.id===h.id);if(v!==-1){const w=[...p];return w[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},w}if(_&&_.role==="user"&&h.timestamp.getTime()-_.timestamp.getTime()<tw){const C={..._,id:h.id,content:_.content+" "+h.content,timestamp:h.timestamp,attachments:[..._.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"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(b=>b==="processing_image"||b==="thinking"?b:"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 iw(h);d.push(p)}catch(p){throw oe.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Mi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class sw{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(Mi.INVOKED,this.boundInvoked),e.on(Mi.COMPLETED,this.boundCompleted),e.on(Mi.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(Mi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Mi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Mi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function $r(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const ow=(t,e)=>{const i=ue(null);i.current===null&&(i.current=new sw),Fs(()=>{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=>{$r(s(),Xe.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{$r(s(),Xe.CLIENT_TOOL_COMPLETED,o)},onError:o=>{$r(s(),Xe.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},rw=({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}=nw(e,i),d=ue(!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(ku,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(Iy,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(ku,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},jr=()=>D(Si.div,{layoutId:dn,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_,{})})}),aw=({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(jr,{});case"done":case"purged":case"destroy":return null;case"active":return D(rw,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(jr,{})}},lw=({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 Hh(){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(lw,{className:"w-8 h-8 mr-2"})}const cw=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=ue(!1),r=Ge(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(Si.div,{layoutId:dn,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(Hh,{}),"Connecting..."]}):D(Si.button,{layoutId:dn,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(Hh,{}),s.start_call_text]})},dw='@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)}}',uw=({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})}),hw={duration:.1,ease:"circOut"},fw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?D(uw,{children:t}):t;return D("div",{ref:i,className:At(n.theme==="dark"&&"dark"),children:D(jg,{transition:hw,children:[D("style",{children:dw}),o]})})},pw=t=>D(Si.div,{layoutId:dn,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(Y_,{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(sy,{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(iy,{className:"w-4 h-4"}),"Retry"]})]});function Pi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function gw({"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:b="fixed","version-id":w}){const C=Pi(e),k=Pi(i),L=Pi(h),R=_===void 0?!0:Pi(_),O=Qe(()=>{if(l)try{return JSON.parse(l)}catch(he){oe.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Qe(()=>({showUserPerceivedLatency:Pi(c),showGreetingLatency:Pi(u)}),[c,u]),{client:E,error:g,isConnected:m,isReconnecting:f}=Jb(t,v,w,C,k,O,d,L,p,R),[S,I]=Ae(null),[A,x]=Ae(!1),[N,M]=Ae(!1),[F,G]=Ae(!1),[U,ae]=Ae(!1),q=Mn(Tu),H=S_(),ce={};if(n&&(ce.destinationNumber=n),s&&(ce.callerNumber=s),o&&(ce.callerName=o),r)try{ce.customHeaders=JSON.parse(r)}catch(he){oe.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{ce.audio=JSON.parse(a);const he=ce.audio;if(typeof he=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(ge=>{se[ge]||oe.warn(`Audio constraint not supported by browser: ${ge}`)})}}catch(he){oe.error("Invalid JSON for call-audio attribute:",a,he)}const J=Ge(()=>{x(!1)},[]),ee=Ge(he=>{var se;if(((se=he.call)==null?void 0:se.state)==="destroy")return q(!1),ae(!0),I(null);I(he)},[q]),te=Ge(()=>{x(!1),f||M(!0)},[f]),ie=Ge(()=>{oe.info("User triggered retry"),M(!1),x(!0),E&&E.connect()},[E]),me=Ge(he=>{if(w_(he)){const se=he.params.widget_settings;se&&Object.keys(se).length>0&&(H(se),G(!0))}},[H]),Le=ue(null);return ew(E,{onReady:J,onConversationUpdate:ee,onError:te,onConfigMessage:me},Le),ow(E,Le),D(fw,{position:b,rootRef:Le,children:t?N||g?D(pw,{agentId:t,onRetry:ie}):A||f?D(jr,{message:f?"Retrying...":void 0}):S!=null&&S.call?D(aw,{call:S.call,client:E,latencySettings:T,chatMode:L,debug:C}):F?D(cw,{client:E,callProps:ce,chatMode:L&&!U,isReady:m&&!!E}):null:D("div",{children:"Please provide an assistant ID."})})}af(gw,"telnyx-ai-agent",y_,{shadow:!0})})();
120
+ `)}))}),y.info(n)}),2e3)}}class Ss extends ti{constructor(e){super(e),this.calls={},this.autoRecoverCalls=!0,this._iceServers=[],this._localElement=null,this._localElementId=null,this._remoteElement=null,this._remoteElementId=null,this._jwtAuth=!0,this._audioConstraints=!0,this._previousAudioConstraints=!0,this._videoConstraints=!1,this._speaker=null,this._videoConstraints=e.video||!1,this.iceServers=e.iceServers,this.ringtoneFile=e.ringtoneFile,this.ringbackFile=e.ringbackFile}getActiveCalls(){return Object.values(this.calls).filter(e=>Ss.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=Ne(c0),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};B(P.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),y.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*(){y.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 vs({audio:e,video:i});return _n(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*(){y.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(W.Purge),y.info("Start hangup for ",n),yield n.hangup({initiator:"app:client.disconnect"},!0)}this.calls={},yield e.disconnect.call(this)})}serverDisconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return V(this,void 0,void 0,function*(){y.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(W.Purge),n.hangup({initiator:"sdk:server-disconnect"},!1)}this.calls={},yield e.disconnect.call(this)})}socketDisconnect(){this._closeConnection()}handleLoginError(e){super._handleLoginError(e)}speedTest(e){return new Promise((i,n)=>{if(lh(P.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 yn().catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return yn(yt.Video).catch(e=>(B(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return yn(yt.AudioIn).catch(e=>{const i=ne(Ii(e),e);return B(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return yn(yt.AudioOut).catch(e=>(y.error("getAudioOutDevices",e),B(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return _s(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 vs({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<yh.length;r++){const[a,l]=yh[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 _n(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=Pu(e,["micId","micLabel"]);return Z0(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 _s(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?T0:C0}}get iceServers(){return this._iceServers}set speaker(e){this._speaker=e}get speaker(){return this._speaker}set localElement(e){this._localElementId=typeof e=="string"?e:null,this._localElement=fn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=fn(e)}get remoteElement(){return this._remoteElement}get remoteElementId(){return this._remoteElementId}vertoBroadcast({nodeId:e,channel:i="",data:n}){if(!i)throw new Error(`Invalid channel for broadcast: ${i}`);const s=new z0({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 K0({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=Pr(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 Y0({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=Pr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ni.setStateTelnyx(e)}}Ss.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class xh{constructor(e,i){this.code=i,this.message=e}}class hb{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new H0(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:b={},voice_sdk_id:w}=e,C=b==null?void 0:b.callID,k=b==null?void 0:b.eventChannel,L=b==null?void 0:b.eventType,R=p.calls[C],O=(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(b==null?void 0:b.reattached_sessions)&&T.size){y.debug(`Reattach: active call IDs before cleanup check: [${Array.from(T).join(", ")}].`);const f=b.reattached_sessions.length===0,S=b.reattached_sessions.some(I=>T.has(I));if(f||!S)for(const I of Object.keys(p.calls)){const A=p.calls[I];y.debug(`Session not reattached — terminating active call ${I} `);const x=ne(ju);B(P.Error,{error:x,callId:I,sessionId:p.sessionid},p.uuid),A.hangup({},!1)}}if(Array.isArray(b==null?void 0:b.reattached_sessions)&&p.sessionid){const f=sh();if(f&&f.calls.length>0)if(f.sessionId!==p.sessionid)y.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${p.sessionid}) — ignoring all.`),ei();else{const S=new Set(b.reattached_sessions),I=[];for(const A of f.calls)try{if(S.has(A.id)){y.debug(`Recovery marker for call ${A.id} was reattached — keeping for Attach element restore.`),I.push(A);continue}y.info(`Recovery marker for call ${A.id} (sessid=${p.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const x=ne(ju);B(P.Error,{error:x,callId:A.id,sessionId:p.sessionid,customHeaders:A.customHeaders},p.uuid)}catch(x){y.debug(`Recovery marker for a saved call failed to process (callId=${A==null?void 0:A.id}) — skipping: ${x instanceof Error?x.message:String(x)}`),I.push(A)}oh(I,f.sessionId,f.storedAt)}}if(L==="channelPvtData")return this._handlePvtEvent(b.pvtData);const E=({recoveredCallId:f,forceRelayCandidateForRecovery:S,mutedMicOnStart:I,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N}={})=>{var M,F,G,U,ae;const q={audio:!0,video:p.options.video,remoteSdp:b.sdp,destinationNumber:b.callee_id_number,remoteCallerName:b.caller_id_name,remoteCallerNumber:b.caller_id_number,callerName:b.callee_id_name,callerNumber:b.callee_id_number,attach:v===Z.Attach,mediaSettings:b.mediaSettings,debug:(M=p.options.debug)!==null&&M!==void 0&&M,debugOutput:(F=p.options.debugOutput)!==null&&F!==void 0?F:"socket",trickleIce:(G=p.options.trickleIce)!==null&&G!==void 0&&G,prefetchIceCandidates:(U=p.options.prefetchIceCandidates)===null||U===void 0||U,forceRelayCandidate:S||p.options.forceRelayCandidate||!1,keepConnectionAliveOnSocketClose:(ae=p.options.keepConnectionAliveOnSocketClose)!==null&&ae!==void 0&&ae,mutedMicOnStart:I??p.options.mutedMicOnStart};C&&(q.id=C),b.telnyx_call_control_id&&(q.telnyxCallControlId=b.telnyx_call_control_id),b.telnyx_session_id&&(q.telnyxSessionId=b.telnyx_session_id),b.telnyx_leg_id&&(q.telnyxLegId=b.telnyx_leg_id),b.client_state&&(q.clientState=b.client_state),b.dialogParams&&b.dialogParams.custom_headers&&b.dialogParams.custom_headers.length&&(q.customHeaders=b.dialogParams.custom_headers),f&&(q.recoveredCallId=f),N&&(q.wasHeldBeforeRecovery=N),A!==void 0&&(q.remoteElement=A),x!==void 0&&(q.localElement=x),performance.mark(re(q.id,"new-call-start"));const H=new ni(p,q);return H.nodeId=this.nodeId,H},g=new uh(w),m=new Lr(w);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 y.error(`Received ${v} for non existing call:`,b);R.handleMessage(e),this._ack(_,v);break;case Z.Ping:this.session.setPingReceived(),this.session.execute(m);break;case Z.Punt:p.options.keepConnectionAliveOnSocketClose&&O?(y.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),p.socketDisconnect(),this._ack(_,v)):(y.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),p.serverDisconnect());break;case Z.Invite:{const I=E();I.direction=_t.Inbound,I.playRingtone(),I.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(I.id),this._ack(_,v);break}case Z.Attach:{const I=R||null;if(Object.keys(p.calls).length===0){let A,x;y.warn(`[${new Date().toISOString()}][${C}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${C}`);let N=!1;const M=sh();if(M&&M.sessionId===p.sessionid){const G=M.calls.find(U=>U.id===C);G&&(A=G.remoteElement,x=G.localElement,N=G.wasHeld===!0,(A||x)&&y.info(`[${C}] Attach: restoring per-call media elements from recovery marker (remoteElement=${A??"<none>"}, localElement=${x??"<none>"}).`))}const F=E({recoveredCallId:C,remoteElement:A,localElement:x,wasHeldBeforeRecovery:N});F.answer(),this.session.emitMultipleActiveCallsWarning(F.id),this._ack(_,v);break}if(I){const A=I.id,x=(s=(n=I.shouldForceRelayCandidateForRecovery)===null||n===void 0?void 0:n.call(I))!==null&&s!==void 0&&s,N=I.state==="held";x&&y.warn(`[${new Date().toISOString()}][${C}] Attach: forcing relay candidate because recovered VPN media path is still stalled`),y.info(`[${new Date().toISOString()}][${C}] Attach: recovering active call ${A}.`),I.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const M=E({recoveredCallId:A,forceRelayCandidateForRecovery:x,mutedMicOnStart:I.isAudioMuted,remoteElement:I.options.remoteElement,localElement:I.options.localElement,wasHeldBeforeRecovery:N});M.answer(),this.session.emitMultipleActiveCallsWarning(M.id),this._ack(_,v);break}y.warn(`Attach: callID ${C} does not match any active calls. `),B(P.Warning,{warning:Ne(f0),callId:C,params:b,sessionId:p.sessionid},p.uuid),this._ack(_,v);break}case Z.Event:case"webrtc.event":if(!k)return void y.error("Verto received an unknown event:",b);const f=p.relayProtocol,S=k.split(".")[0];p._existsSubscription(f,k)?B(f,b,k):k===p.sessionid?this._handleSessionEvent(b.eventData):p._existsSubscription(f,S)?B(f,b,S):p.calls.hasOwnProperty(k)?p.calls[k].handleMessage(e):B(P.Notification,b,p.uuid);break;case Z.Info:b.type=st.generic,B(P.Notification,b,p.uuid);break;case Z.ClientReady:this.session.execute(g);break;case"ai_conversation":B(P.AIConversationMessage,{method:"ai_conversation",params:b,voice_sdk_id:w},p.uuid);break;default:{const I=Er(e);if(I){switch(I){case Oe.REGISTER:case Oe.REGED:if(!this.isDuplicateGatewayState(I,[Oe.REGED,Oe.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,I===Oe.REGED&&this.session.resetReconnectAttempts();const A=(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;A&&(p.callReportId=A,y.debug("Captured call_report_id from REGED:",A));const x=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.dc;x&&(p.dc=x);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),y.info(`Connected to Telnyx — region: ${(d=p.region)!==null&&d!==void 0?d:"unknown"}, dc: ${(h=p.dc)!==null&&h!==void 0?h:"unknown"}`),b.type=st.vertoClientReady,B(P.Ready,b,p.uuid)}break;case Oe.UNREGED:case Oe.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const A=new xh("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),x=ne(Uu,A);B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{this.session.execute(g)},this.reconnectDelay());break;case Oe.FAILED:case Oe.FAIL_WAIT:case Oe.TIMEOUT:if(!this.isDuplicateGatewayState(I,[Oe.FAILED,Oe.FAIL_WAIT,Oe.TIMEOUT])){const A=ne(Gy,new Error(`Gateway state: ${I}`));if(B(P.Error,{error:A,sessionId:p.sessionid},p.uuid),p.options.skipLastVoiceSdkId=!0,y.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 x=new xh("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const N=ne(Sr,x);B(P.Error,{error:N,sessionId:p.sessionid},p.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const x=ne(Sr,new Error("Connection Retry Failed"));B(P.Error,{error:x,sessionId:p.sessionid},p.uuid);break}setTimeout(()=>{if(y.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(p.calls).some(x=>{var N;return((N=x.peer)===null||N===void 0?void 0:N.instance)&&!x.signalingStateClosed}))return y.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();y.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:y.warn("GatewayState message unknown method:",e)}break}y.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&y.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:b})=>{const w=h||this._retrieveCallId(b,o);if(w&&i.calls.hasOwnProperty(w)){const C=i.calls[w];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(_).catch(b=>{y.error("liveArray subscription error:",b);const w=ne($y,b);B(P.Error,{error:w,sessionId:i.sessionid},i.uuid)});Mr(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 b={type:st.conferenceUpdate,action:Ye.Leave,conferenceName:r,participantId:Number(u),role:d};B(P.Notification,b,v,!1)||B(P.Notification,b,i.uuid),p===null&&bt(P.Notification,null,v)}}const _=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:_}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{y.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":kh(this.session,e);break;case"logo-info":{const i={type:st.conferenceUpdate,action:Ye.LogoInfo,logo:e.logoURL};B(P.Notification,i,this.session.uuid);break}}}}class fb extends Ss{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 hb(this),window.addEventListener("beforeunload",i=>{if(y.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return nh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(y.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&&(y.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=>{const o={id:s.id,customHeaders:s.options.customHeaders};return s.state==="held"&&(o.wasHeld=!0),typeof s.options.remoteElement=="string"?o.remoteElement=s.options.remoteElement:this.remoteElementId&&s.options.remoteElement===this.remoteElement&&(o.remoteElement=this.remoteElementId),typeof s.options.localElement=="string"?o.localElement=s.options.localElement:this.localElementId&&s.options.localElement===this.localElement&&(o.localElement=this.localElementId),o});if(!this.sessionid||n.length===0)return y.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void ei();y.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),oh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];y.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()&&(y.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Rr(this.sessionid))})}validateOptions(){return ds(this.options)||pn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ne(Uy,void 0,"Error: destinationNumber is required");const i=new ni(this,e);return e.id||y.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!!pn(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),ds(this.options)?this.handleLoginOnSocketOpen():pn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}class pb extends fb{constructor(e){super(e),y.info(`SDK version: ${hh}`)}newCall(e){return super.newCall(e)}static webRTCInfo(){return Q0()}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 gb(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 Lh(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Dh={exports:{}},Oh;function mb(){return Oh||(Oh=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[_],b=arguments.length,w,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,p),!0}for(C=1,w=new Array(b-1);C<b;C++)w[C-1]=arguments[C];v.fn.apply(v.context,w)}else{var k=v.length,L;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(!w)for(L=1,w=new Array(b-1);L<b;L++)w[L-1]=arguments[L];v[C].fn.apply(v[C].context,w)}}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=[],b=p.length;_<b;_++)(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}(Dh)),Dh.exports}var vb=mb();const Br=Lh(vb),Vr=new Br;var Ur={exports:{}},_b=Ur.exports,Mh;function yb(){return Mh||(Mh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(_b,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 w=v[b];if(typeof w.bind=="function")return w.bind(v);try{return Function.prototype.bind.call(w,v)}catch{return function(){return Function.prototype.apply.apply(w,[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 w=s[b];this[w]=b<v?e:this.methodFactory(w,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,w){return c(v)||d.apply(this,arguments)}function p(v,b){var w=this,C,k,L,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function O(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,I=encodeURIComponent(R),A=S.indexOf(I+"=");A!==-1&&(f=/^([^;]+)/.exec(S.slice(A+I.length+1))[1])}catch{}return w.levels[f]===void 0&&(f=void 0),f}}function E(){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"&&w.levels[S.toUpperCase()]!==void 0&&(S=w.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=w.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}w.name=v,w.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},w.methodFactory=b||h,w.getLevel=function(){return L??k??C},w.setLevel=function(f,S){return L=g(f),S!==!1&&O(L),u.call(w)},w.setDefaultLevel=function(f){k=g(f),T()||w.setLevel(f,!1)},w.resetLevel=function(){L=null,E(),u.call(w)},w.enableAll=function(f){w.setLevel(w.levels.TRACE,f)},w.disableAll=function(f){w.setLevel(w.levels.SILENT,f)},w.rebuild=function(){if(r!==w&&(C=g(r.getLevel())),u.call(w),r===w)for(var f in o)o[f].rebuild()},C=g(r?r.getLevel():"WARN");var m=T();m!=null&&(L=g(m)),u.call(w)}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 b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};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})}(Ur)),Ur.exports}var bb=yb();const wb=Lh(bb),Sb=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=wb.getLogger("telnyx-ai-agent"),Cb=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=Cb(t,e,i);return function(...s){n(Sb(),"-",...s)}},fe.setLevel("info");function Tb(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Eb=10,kb=500,Ib=100,Rb=300,Ph=20;class Ab{constructor(e){$(this,"remoteIntervalId",null);$(this,"localIntervalId",null);$(this,"remoteStream",null);$(this,"localStream",null);$(this,"remoteAudioContext",null);$(this,"remoteSource",null);$(this,"remoteAnalyser",null);$(this,"localAudioContext",null);$(this,"localSource",null);$(this,"localAnalyser",null);$(this,"thinkingStartTime",null);$(this,"lastState",null);$(this,"userIsSpeaking",!1);$(this,"lastUserAudioTime",null);$(this,"userSpeechStartTime",null);$(this,"remoteSilenceStartTime",null);$(this,"remoteSilenceThresholdMs");$(this,"userSilenceStartTime",null);$(this,"isFirstAgentSpeech",!0);$(this,"monitorStartTime",null);$(this,"volumeThreshold");$(this,"silenceDurationMs");$(this,"minSpeechDurationMs");$(this,"maxLatencyMs");$(this,"updateAgentState",Tb(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,Vr.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Eb,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??kb,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Ib,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??Rb}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,this.remoteSilenceStartTime=null}stopAudioStreamMonitor(){this.stopRemoteMonitor(),this.stopLocalMonitor(),this.resetLatencyState()}startRemoteMonitor(){if(!this.remoteStream){fe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,fe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(fe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;fe.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&&fe.debug("Remote audio volume:",o,"threshold:",this.volumeThreshold,"above:",r),r)if(this.remoteSilenceStartTime=null,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.remoteSilenceStartTime===null&&(this.remoteSilenceStartTime=performance.now()),performance.now()-this.remoteSilenceStartTime>=this.remoteSilenceThresholdMs&&this.updateAgentState({state:"listening"}));n=r};this.remoteIntervalId=window.setInterval(s,Ph)}startLocalMonitor(){if(!this.localStream){fe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,fe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(fe.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&&fe.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,Ph)}destroy(){this.stopAudioStreamMonitor()}}function xb(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Lb(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Db(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Cs(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Ob(t){if(!Cs(t))return null;const e=t.params;return gb(e)?e.item:null}function Mb(t){if(!Cs(t))return null;const e=t.params;if(e.type!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const n of e.client_side_tools)if(n&&typeof n=="object"&&typeof n.name=="string"){const s=n;i.push({name:s.name,timeout_ms:typeof s.timeout_ms=="number"?s.timeout_ms:void 0})}return i}function Pb(t){if(!Cs(t))return null;const e=t.params;if(!e||typeof e!="object")return null;const i=e;if(i.type==="response.audio.delta"){const n=i.format;if(!n||typeof n!="object")return null;const s=n;return typeof i.response_id!="string"||typeof i.delta!="string"||typeof i.sequence!="number"||!Number.isInteger(i.sequence)||typeof s.encoding!="string"||typeof s.sample_rate!="number"||typeof s.channels!="number"?null:{type:"response.audio.delta",response_id:i.response_id,item_id:typeof i.item_id=="string"?i.item_id:void 0,sequence:i.sequence,delta:i.delta,format:{encoding:s.encoding,sample_rate:s.sample_rate,channels:s.channels}}}return i.type==="response.audio.done"&&typeof i.response_id=="string"?{type:"response.audio.done",response_id:i.response_id}:i.type==="response.audio.interrupted"?{type:"response.audio.interrupted",response_id:typeof i.response_id=="string"?i.response_id:void 0}:null}function Nb(t){var e;return Cs(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function Fb(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 Bb=3e4;function Vb(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 jr(t){return JSON.stringify({error:t})}class Ub{constructor(e){$(this,"registry",new Map);$(this,"toolTimeouts",new Map);$(this,"inFlight",new Set);$(this,"completed",new Set);$(this,"generation",0);$(this,"getActiveCall");$(this,"timeoutMs");$(this,"events");$(this,"handleEvent",e=>{const i=Mb(e);if(i){this.ingestToolSettings(i);return}const n=Ob(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Bb,this.events={onInvoked:i=>this.safeEmit(()=>e.events.onInvoked(i)),onCompleted:i=>this.safeEmit(()=>e.events.onCompleted(i)),onError:i=>this.safeEmit(()=>e.events.onError(i))}}safeEmit(e){try{e()}catch(i){fe.warn(`[client-tools] lifecycle listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}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())}ingestToolSettings(e){this.toolTimeouts.clear();for(const{name:i,timeout_ms:n}of e)typeof n=="number"&&n>0&&this.toolTimeouts.set(i,n)}reset(){this.generation+=1,this.toolTimeouts.clear(),this.inFlight.clear(),this.completed.clear()}destroy(){this.generation+=1,this.registry.clear(),this.toolTimeouts.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)){fe.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){fe.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,jr("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{fe.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,jr("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},c=this.toolTimeouts.get(n)??this.timeoutMs;try{const u=await this.withTimeout(Promise.resolve().then(()=>r(a,l)),i,n,c);this.sendOutput(i,n,Vb(u),!1,s,o)}catch(u){const d=u instanceof Nh?"timeout":"handler_error";fe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,jr(d),!0,s,o)}finally{this.inFlight.delete(i),this.markCompleted(i,s)}}withTimeout(e,i,n,s){return new Promise((o,r)=>{const a=setTimeout(()=>{r(new Nh(n,i,s))},s);e.then(l=>{clearTimeout(a),o(l)},l=>{clearTimeout(a),r(l)})})}sendOutput(e,i,n,s,o,r){if(this.generation!==o){fe.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){fe.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){fe.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){fe.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 Nh extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Es=class Es{constructor(e){$(this,"enabled");$(this,"getActiveCall");$(this,"events");$(this,"subscriptionConfirmed",!1);$(this,"subscribeAttempts",0);$(this,"handleEvent",e=>{if(!this.enabled)return;if(Nb(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Pb(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=jb(i.delta)}catch(s){fe.warn(`[streaming-audio] invalid base64 delta for response ${i.response_id}: ${s instanceof Error?s.message:"unknown error"}`);return}this.emitSafely(()=>this.events.onDelta({responseId:i.response_id,itemId:i.item_id,sequence:i.sequence,audio:n,format:{encoding:i.format.encoding,sampleRate:i.format.sample_rate,channels:i.format.channels}}));return}if(i.type==="response.audio.done"){this.emitSafely(()=>this.events.onDone({responseId:i.response_id}));return}this.emitSafely(()=>this.events.onInterrupted({responseId:i.response_id}))}});this.enabled=e.enabled,this.getActiveCall=e.getActiveCall,this.events=e.events}onCallActive(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0,this.sendSubscription()}reset(){this.subscriptionConfirmed=!1,this.subscribeAttempts=0}sendSubscription(){if(!this.enabled||this.subscribeAttempts>=Es.MAX_SUBSCRIBE_ATTEMPTS)return;const e=this.getActiveCall();if(e)try{const i={type:"response.audio_stream.subscribe"};e.sendAIConversationMessage(i),this.subscribeAttempts+=1}catch(i){fe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){fe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}};$(Es,"MAX_SUBSCRIBE_ATTEMPTS",10);let $r=Es;function jb(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function $b(t){return Lb(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Hb(t){if(!Db(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 Wb extends Br{constructor(i){super();$(this,"telnyxRTC");$(this,"transcript",[]);$(this,"onSocketMessage",i=>{if(xb(i))switch(i.params.type){case"response.text.delta":{const n=$b(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Fb(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=Hb(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(P.SocketMessage,this.onSocketMessage)}}const Dt=t=>typeof t=="object"&&t!==null,Fh=t=>{const e=Dt(t)&&Dt(t.result)?t.result:t;if(!(!Dt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Gb=t=>Dt(t)&&Dt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),qb=(t,e)=>{if(!e||!Dt(t)||!Dt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Dt(i.params))return;const n=i.params;Dt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class zb extends Br{constructor(i){super();$(this,"telnyxRTC");$(this,"transcription");$(this,"removeLoginSuccessHook",null);$(this,"authenticated",!1);$(this,"authenticating",!1);$(this,"agentId");$(this,"versionId");$(this,"widgetVersion");$(this,"conversationId");$(this,"debug");$(this,"audioStreamMonitor");$(this,"clientTools");$(this,"streamingAudio");$(this,"activeCall");$(this,"chatMode");$(this,"dc",null);$(this,"region",null);$(this,"callReportId",null);$(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)});$(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});$(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});$(this,"onSocketMessage",i=>{const n=Fh(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});$(this,"onNotification",i=>{i.type!=="callUpdate"||!i.call||(this.emit("conversation.update",i),i.call.state==="active"?(this.activeCall=i.call,this.streamingAudio.onCallActive(),i.call.remoteStream&&this.audioStreamMonitor.setRemoteStream(i.call.remoteStream),i.call.localStream&&this.audioStreamMonitor.setLocalStream(i.call.localStream)):(this.activeCall=null,this.streamingAudio.reset(),this.audioStreamMonitor.stopAudioStreamMonitor()))});$(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});$(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,fe.setLevel(this.debug?"debug":"info");const n={target_id:i.agentId,target_type:"ai_assistant",target_version_id:i.versionId},s={};i.conversationId&&(s.conversation_id=i.conversationId),i.streamingAudio&&(s.streamingAudio=!0),Object.keys(s).length>0&&(n.target_params=s),i.widgetVersion&&(n.widget_version=i.widgetVersion),this.telnyxRTC=new pb({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(P.Ready,this.onClientReady),this.telnyxRTC.on(P.Error,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(P.SocketClose,this.onSocketClose),this.telnyxRTC.on(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(P.Notification,this.onNotification),this.transcription=new Wb(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),Vr.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Ab(i.vad),this.clientTools=new Ub({getActiveCall:()=>this.activeCall,timeoutMs:i.clientToolTimeoutMs,events:{onInvoked:o=>this.emit("client.tool.invoked",o),onCompleted:o=>this.emit("client.tool.completed",o),onError:o=>this.emit("client.tool.error",o)}}),i.clientTools&&this.clientTools.registerAll(i.clientTools),this.telnyxRTC.on(P.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new $r({enabled:i.streamingAudio??!1,getActiveCall:()=>this.activeCall,events:{onDelta:o=>this.emit("assistant.audio.delta",o),onDone:o=>this.emit("assistant.audio.done",o),onInterrupted:o=>this.emit("assistant.audio.interrupted",o)}}),this.telnyxRTC.on(P.AIConversationMessage,this.streamingAudio.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(P.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(P.AIConversationMessage,this.streamingAudio.handleEvent),this.clientTools.reset(),this.streamingAudio.reset(),(i=this.removeLoginSuccessHook)==null||i.call(this),this.removeLoginSuccessHook=null,this.telnyxRTC.disconnect(),this.telnyxRTC.off(P.Ready,this.onClientReady),this.telnyxRTC.off(P.Error,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(P.SocketClose,this.onSocketClose),this.telnyxRTC.off(P.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(P.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(),Vr.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){fe.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 fe.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 fe.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 _=Gb(p),v=c;return _&&qb(p,a),n.call(this,p).then(b=>{const w=_?Fh(b):void 0;return l&&w!==void 0&&(u(v),r({sessionId:w})),b})},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 Bh={exports:{}},bn={},Vh;function Kb(){if(Vh)return bn;Vh=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 bn.Fragment=e,bn.jsx=i,bn.jsxs=i,bn}var Uh;function Yb(){return Uh||(Uh=1,Bh.exports=Kb()),Bh.exports}Yb(),kt(void 0),kt(null);const Xb=(t,e,i,n,s,o,r,a,l,c)=>new zb({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,vad:o,conversationId:r,chatMode:a,region:l,skipLastVoiceSdkId:c??!0}),Ts=10,jh=5e3,Jb=[46001,46003],Zb=["login incorrect","authentication required","authentication failed"];function $h(t){var n;const e=t.code;if(e&&Jb.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return Zb.some(s=>i.includes(s))}const Qb=(t,e,i,n,s,o,r,a,l,c)=>{const u=c??!0,[d,h]=Ae(null),[p,_]=Ae(!1),[v,b]=Ae(null),[w,C]=Ae(!1),k=ue(0),L=ue(null),R=ue(null),O=ue(!1),T=ue(!1),E=ue(0),g=ue(0),m=Ge(()=>{L.current&&(clearTimeout(L.current),L.current=null)},[]),f=Ge(()=>{m(),k.current=0,T.current=!0,C(!1),b(null)},[m]),S=Ge(()=>{m(),C(!1)},[m]),I=Ge(A=>{if(m(),k.current>=Ts){oe.error(`Max login retry attempts (${Ts}) exceeded`),C(!1);return}k.current+=1;const x=E.current,N=g.current;oe.info(`Scheduling login retry attempt ${k.current}/${Ts} in ${jh}ms due to: ${A}`),C(!0),L.current=window.setTimeout(()=>{var G;L.current=null;const M=R.current,F=M==null?void 0:M.telnyxRTC;if(E.current!==x||g.current!==N||M!=null&&M.isAuthenticating){oe.info("Skipping login retry because a newer socket/login is already in progress"),S();return}if(O.current||T.current||M!=null&&M.isAuthenticated){oe.info("Skipping login retry because login already succeeded before retry timeout fired"),f();return}R.current&&(oe.info(`Executing reconnect attempt ${k.current} (socket disconnect)`),(G=F==null?void 0:F.socketDisconnect)==null||G.call(F))},jh)},[m,S,f]);return xe(()=>{if(!t)return;const A=Xb(t,e,i,n,s,o,r,a,l,u);O.current=!1,T.current=!1,_(!1),b(null),C(!1),R.current=A;const x=()=>{oe.info("Agent connected successfully"),O.current=!0,_(!0),f()},N=()=>{oe.info("Agent disconnected"),O.current=!1,T.current=!1,_(!1)},M=H=>{if(oe.error("AI Agent error:",H),$h(H)){if(O.current||T.current){oe.debug("Ignoring retryable error — login already succeeded");return}k.current<Ts?(b(null),I(H.message)):(b(H),C(!1))}else b(H),C(!1)},F=A.telnyxRTC??null,G=()=>{g.current+=1,T.current=!1},U=()=>{oe.info("Login succeeded; clearing pending login retry flow"),f()},ae=()=>{E.current+=1,T.current=!1},q=()=>{T.current=!1};return A.on("agent.connected",x),A.on("agent.disconnected",N),A.on("agent.error",M),A.on("agent.login.started",G),A.on("agent.login.success",U),F&&typeof F=="object"&&(F.on(P.SocketOpen,ae),F.on(P.SocketClose,q)),A.connect(),h(A),()=>{m(),A.off("agent.connected",x),A.off("agent.disconnected",N),A.off("agent.error",M),A.off("agent.login.started",G),A.off("agent.login.success",U),F&&typeof F=="object"&&(F.off(P.SocketOpen,ae),F.off(P.SocketClose,q)),A.disconnect(),O.current=!1,R.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,f,I]),{client:d,isConnected:p,error:v,isReconnecting:w}},ew="telnyx-ai-agent",Xe={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",CLIENT_TOOLS_CONFIGURED:"client.tools.configured"};function tw(t){var n,s;if(typeof t!="object"||t===null)return null;const e=t.params;if(t.method!=="ai_conversation"||(e==null?void 0:e.type)!=="widget_settings"||!Array.isArray(e.client_side_tools))return null;const i=[];for(const o of e.client_side_tools)if(o&&typeof o=="object"&&typeof o.name=="string"){const r=o;i.push({name:r.name,description:(n=r.client_side_tool)==null?void 0:n.description,parameters:(s=r.client_side_tool)==null?void 0:s.parameters,timeout_ms:r.timeout_ms,tool_id:r.tool_id})}return i}function Hh(){const t=document.querySelector(ew);return t instanceof HTMLElement?t:null}function wt(t,e,i){const n=i||Hh();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 iw=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ue(null),l=Mn(bu);xe(()=>{const c=i==null?void 0:i.current,u=c==null?void 0:c.getRootNode(),d=u instanceof ShadowRoot?u.host:null;a.current=d??Hh()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const O=t.telnyxRTC,T={dc:(O==null?void 0:O.dc)??null,region:(O==null?void 0:O.region)??null,callReportId:(O==null?void 0:O.callReportId)??null};l(T),wt(Xe.AGENT_CONNECTED,T,c)},d=()=>{l(null),wt(Xe.AGENT_DISCONNECTED,void 0,c)},h=R=>{const O={message:R.message,name:R.name};if($h(R)){oe.debug("Ignoring retryable agent.error in widget event layer"),wt(Xe.AGENT_ERROR,O,c);return}o(R),wt(Xe.AGENT_ERROR,O,c)},p=R=>{var O;s(R),wt(Xe.CONVERSATION_UPDATE,{type:R.type,callState:(O=R.call)==null?void 0:O.state},c)},_=R=>{wt(Xe.TRANSCRIPT_ITEM,R,c)},v=R=>{wt(Xe.CONVERSATION_AGENT_STATE,R,c)},b=R=>{wt(Xe.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const O=tw(R);O&&wt(Xe.CLIENT_TOOLS_CONFIGURED,{tools:O},c)},L=R=>{const O=R,T={code:O==null?void 0:O.code,reason:O==null?void 0:O.reason,wasClean:O==null?void 0:O.wasClean,timestamp:new Date().toISOString()};oe.info("[socket.close]",T),wt(Xe.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(P.SocketMessage,k),C.on(P.SocketClose,L)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",_),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",_),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),C&&typeof C=="object"&&(C.off(P.SocketMessage,k),C.off(P.SocketClose,L))}},[t,n,s,o,r,l])},nw=2e3;async function sw(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Wh(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 ow=(t,e)=>{const[i,n]=Ae([]),[,s]=ur(),o=ue(e);xe(()=>{o.current=e},[e]);const r=ue(void 0),a=ue(void 0);return xe(()=>{if(!t)return;const c=h=>{n(p=>{const _=p[p.length-1];if(h.role==="assistant"&&_&&Wh(_.id)===Wh(h.id)&&_.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&_.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&_.greetingLatencyMs===void 0,w={..._,content:_.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),[...p.slice(0,-1),w]}if(h.role==="assistant"){s(w=>w==="thinking"||w==="processing_image"?"speaking":w);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const w={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,w]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(w=>w.id===h.id);if(v!==-1){const w=[...p];return w[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},w}if(_&&_.role==="user"&&h.timestamp.getTime()-_.timestamp.getTime()<nw){const C={..._,id:h.id,content:_.content+" "+h.content,timestamp:h.timestamp,attachments:[..._.attachments||[],...h.attachments||[]]};return[...p.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"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(b=>b==="processing_image"||b==="thinking"?b:"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 sw(h);d.push(p)}catch(p){throw oe.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Mi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class rw{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(Mi.INVOKED,this.boundInvoked),e.on(Mi.COMPLETED,this.boundCompleted),e.on(Mi.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(Mi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Mi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Mi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function Hr(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const aw=(t,e)=>{const i=ue(null);i.current===null&&(i.current=new rw),Vs(()=>{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=>{Hr(s(),Xe.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{Hr(s(),Xe.CLIENT_TOOL_COMPLETED,o)},onError:o=>{Hr(s(),Xe.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},lw=({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}=ow(e,i),d=ue(!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(Ru,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(Ay,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(Ru,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Wr=()=>D(Si.div,{layoutId:dn,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(Q_,{})})}),cw=({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(Wr,{});case"done":case"purged":case"destroy":return null;case"active":return D(lw,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(Wr,{})}},dw=({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 Gh(){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(dw,{className:"w-8 h-8 mr-2"})}const uw=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=Qt(),o=ue(!1),r=Ge(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(Si.div,{layoutId:dn,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(Gh,{}),"Connecting..."]}):D(Si.button,{layoutId:dn,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(Gh,{}),s.start_call_text]})},hw='@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)}}',fw=({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})}),pw={duration:.1,ease:"circOut"},gw=({children:t,position:e="fixed",rootRef:i})=>{const n=Qt(),o=(e??n.position??"fixed")==="fixed"?D(fw,{children:t}):t;return D("div",{ref:i,className:At(n.theme==="dark"&&"dark"),children:D(Wg,{transition:pw,children:[D("style",{children:hw}),o]})})},mw=t=>D(Si.div,{layoutId:dn,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(J_,{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(ry,{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(sy,{className:"w-4 h-4"}),"Retry"]})]});function Pi(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function vw({"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:b="fixed","version-id":w}){const C=Pi(e),k=Pi(i),L=Pi(h),R=_===void 0?!0:Pi(_),O=Qe(()=>{if(l)try{return JSON.parse(l)}catch(he){oe.error("Invalid JSON for vad attribute:",l,he);return}},[l]),T=Qe(()=>({showUserPerceivedLatency:Pi(c),showGreetingLatency:Pi(u)}),[c,u]),{client:E,error:g,isConnected:m,isReconnecting:f}=Qb(t,v,w,C,k,O,d,L,p,R),[S,I]=Ae(null),[A,x]=Ae(!1),[N,M]=Ae(!1),[F,G]=Ae(!1),[U,ae]=Ae(!1),q=Mn(ku),H=T_(),ce={};if(n&&(ce.destinationNumber=n),s&&(ce.callerNumber=s),o&&(ce.callerName=o),r)try{ce.customHeaders=JSON.parse(r)}catch(he){oe.error("Invalid JSON for call-custom-headers attribute:",r,he)}if(a)try{ce.audio=JSON.parse(a);const he=ce.audio;if(typeof he=="object"){const se=navigator.mediaDevices.getSupportedConstraints();Object.keys(he).forEach(ge=>{se[ge]||oe.warn(`Audio constraint not supported by browser: ${ge}`)})}}catch(he){oe.error("Invalid JSON for call-audio attribute:",a,he)}const J=Ge(()=>{x(!1)},[]),ee=Ge(he=>{var se;if(((se=he.call)==null?void 0:se.state)==="destroy")return q(!1),ae(!0),I(null);I(he)},[q]),te=Ge(()=>{x(!1),f||M(!0)},[f]),ie=Ge(()=>{oe.info("User triggered retry"),M(!1),x(!0),E&&E.connect()},[E]),me=Ge(he=>{if(C_(he)){const se=he.params.widget_settings;se&&Object.keys(se).length>0&&(H(se),G(!0))}},[H]),Le=ue(null);return iw(E,{onReady:J,onConversationUpdate:ee,onError:te,onConfigMessage:me},Le),aw(E,Le),D(gw,{position:b,rootRef:Le,children:t?N||g?D(mw,{agentId:t,onRetry:ie}):A||f?D(Wr,{message:f?"Retrying...":void 0}):S!=null&&S.call?D(cw,{call:S.call,client:E,latencySettings:T,chatMode:L,debug:C}):F?D(uw,{client:E,callProps:ce,chatMode:L&&!U,isReady:m&&!!E}):null:D("div",{children:"Please provide an assistant ID."})})}cf(vw,"telnyx-ai-agent",w_,{shadow:!0})})();