@telnyx/ai-agent-widget 0.35.1 → 0.36.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -1
- package/dist/bundle.min.js +27 -27
- package/package.json +3 -2
package/dist/bundle.min.js
CHANGED
|
@@ -1,119 +1,119 @@
|
|
|
1
|
-
var ES=Object.defineProperty;var IS=(dt,z,Yt)=>z in dt?ES(dt,z,{enumerable:!0,configurable:!0,writable:!0,value:Yt}):dt[z]=Yt;var H=(dt,z,Yt)=>IS(dt,typeof z!="symbol"?z+"":z,Yt);(function(){"use strict";var dt,z,Yt,Xt,Ta,ka,Ea,Ia,$s,js,Hs,Ra,Gi={},Aa=[],qf=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qi=Array.isArray;function gt(t,e){for(var i in e)t[i]=e[i];return t}function Ws(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function tt(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?dt.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 zi(t,r,n,s,null)}function zi(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??++Yt,__i:-1,__u:0};return s==null&&z.vnode!=null&&z.vnode(o),o}function mt(t){return t.children}function ut(t,e){this.props=t,this.context=e}function gi(t,e){if(e==null)return t.__?gi(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"?gi(t):null}function xa(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 xa(t)}}function Gs(t){(!t.__d&&(t.__d=!0)&&Xt.push(t)&&!On.__r++||Ta!=z.debounceRendering)&&((Ta=z.debounceRendering)||ka)(On)}function On(){for(var t,e,i,n,s,o,r,a=1;Xt.length;)Xt.length>a&&Xt.sort(Ea),t=Xt.shift(),a=Xt.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=gt({},n)).__v=n.__v+1,z.vnode&&z.vnode(i),qs(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??gi(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,Pa(o,i,r),i.__e!=s&&xa(i)));On.__r=0}function Da(t,e,i,n,s,o,r,a,l,c,u){var d,h,g,m,v,b,y=n&&n.__k||Aa,C=e.length;for(l=zf(i,e,y,l,C),d=0;d<C;d++)(g=i.__k[d])!=null&&(h=g.__i==-1?Gi:y[g.__i]||Gi,g.__i=d,b=qs(t,g,h,s,o,r,a,l,c,u),m=g.__e,g.ref&&h.ref!=g.ref&&(h.ref&&zs(h.ref,null,g),u.push(g.ref,g.__c||m,g)),v==null&&m!=null&&(v=m),4&g.__u||h.__k===g.__k?l=La(g,l,t):typeof g.type=="function"&&b!==void 0?l=b:m&&(l=m.nextSibling),g.__u&=-7);return i.__e=v,l}function zf(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?zi(null,r,null,null,null):qi(r)?zi(mt,{children:r},null,null,null):r.constructor==null&&r.__b>0?zi(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=Kf(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=gi(a)),Fa(a,a));return n}function La(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=La(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=gi(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function vt(t,e){return e=e||[],t==null||typeof t=="boolean"||(qi(t)?t.some(function(i){vt(i,e)}):e.push(t)),e}function Kf(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 Ma(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||qf.test(e)?i:i+"px"}function Pn(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||Ma(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||Ma(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=$s,t.addEventListener(e,o?Hs:js,o)):t.removeEventListener(e,o?Hs:js,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 Oa(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=$s++;else if(e.t<i.u)return;return i(z.event?z.event(e):e)}}}function qs(t,e,i,n,s,o,r,a,l,c){var u,d,h,g,m,v,b,y,C,k,A,R,D,T,E,p,_,f=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=z.__b)&&u(e);e:if(typeof f=="function")try{if(y=e.props,C="prototype"in f&&f.prototype.render,k=(u=f.contextType)&&n[u.__c],A=u?k?k.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new f(y,A):(e.__c=d=new ut(y,A),d.constructor=f,d.render=Xf),k&&k.sub(d),d.props=y,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&f.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=gt({},d.__s)),gt(d.__s,f.getDerivedStateFromProps(y,d.__s))),g=d.props,m=d.state,d.__v=e,h)C&&f.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&f.getDerivedStateFromProps==null&&y!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),R=0;R<d._sb.length;R++)d.__h.push(d._sb[R]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,m,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,D=z.__r,T=0,C){for(d.state=d.__s,d.__d=!1,D&&D(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,D&&D(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=gt(gt({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(g,m)),p=u,u!=null&&u.type===mt&&u.key==null&&(p=Na(u.props.children)),a=Da(t,qi(p)?p:[p],e,i,n,s,o,r,a,l,c),d.base=e.__e,e.__u&=-161,d.__h.length&&r.push(d),b&&(d.__E=d.__=null)}catch(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(_=o.length;_--;)Ws(o[_]);else e.__e=i.__e,e.__k=i.__k;z.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=Yf(i.__e,e,i,n,s,o,r,l,c);return(u=z.diffed)&&u(e),128&e.__u?void 0:a}function Pa(t,e,i){for(var n=0;n<i.length;n++)zs(i[n],i[++n],i[++n]);z.__c&&z.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){z.__e(o,s.__v)}})}function Na(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:qi(t)?t.map(Na):gt({},t)}function Yf(t,e,i,n,s,o,r,a,l){var c,u,d,h,g,m,v,b=i.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((g=o[c])&&"setAttribute"in g==!!C&&(C?g.localName==C:g.nodeType==3)){t=g,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(z.__m&&z.__m(e,o),a=!1),o=null}if(C==null)b===y||a&&t.data==y||(t.data=y);else{if(o=o&&dt.call(t.childNodes),b=i.props||Gi,!a&&o!=null)for(b={},c=0;c<t.attributes.length;c++)b[(g=t.attributes[c]).name]=g.value;for(c in b)if(g=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")d=g;else if(!(c in y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Pn(t,c,null,g,s)}}for(c in y)g=y[c],c=="children"?h=g:c=="dangerouslySetInnerHTML"?u=g:c=="value"?m=g:c=="checked"?v=g:a&&typeof g!="function"||b[c]===g||Pn(t,c,g,b[c],s);if(u)a||d&&(u.__html==d.__html||u.__html==t.innerHTML)||(t.innerHTML=u.__html),e.__k=[];else if(d&&(t.innerHTML=""),Da(e.type=="template"?t.content:t,qi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&gi(i,0),a,l),o!=null)for(c=o.length;c--;)Ws(o[c]);a||(c="value",C=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[c]||C=="progress"&&!m||C=="option"&&m!=b[c])&&Pn(t,c,m,b[c],s),c="checked",v!=null&&v!=t[c]&&Pn(t,c,v,b[c],s))}return t}function zs(t,e,i){try{if(typeof t=="function"){var n=typeof t.__u=="function";n&&t.__u(),n&&e==null||(t.__u=t(e))}else t.current=e}catch(s){z.__e(s,i)}}function Fa(t,e,i){var n,s;if(z.unmount&&z.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||zs(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){z.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&Fa(n[s],e,i||typeof t.type!="function");i||Ws(t.__e),t.__c=t.__=t.__e=void 0}function Xf(t,e,i){return this.constructor(t,i)}function Nn(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),z.__&&z.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],qs(e,t=(!n&&i||e).__k=tt(mt,null,[t]),s||Gi,Gi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?dt.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),Pa(o,t,r)}function Ba(t,e){Nn(t,e,Ba)}function Ks(t,e,i){var n,s,o,r,a=gt({},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?dt.call(arguments,2):i),zi(t.type,a,n||t.key,s||t.ref,null)}function At(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,Gs(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"+Ra++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}dt=Aa.slice,z={__e:function(t,e,i,n){for(var s,o,r;e=e.__;)if((s=e.__c)&&!s.__)try{if((o=s.constructor)&&o.getDerivedStateFromError!=null&&(s.setState(o.getDerivedStateFromError(t)),r=s.__d),s.componentDidCatch!=null&&(s.componentDidCatch(t,n||{}),r=s.__d),r)return s.__E=s}catch(a){t=a}throw t}},Yt=0,ut.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=gt({},this.state),typeof t=="function"&&(t=t(gt({},i),this.props)),t&>(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Gs(this))},ut.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Gs(this))},ut.prototype.render=mt,Xt=[],ka=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ea=function(t,e){return t.__v.__b-e.__v.__b},On.__r=0,Ia=/(PointerCapture)$|Capture$/i,$s=0,js=Oa(!1),Hs=Oa(!0),Ra=0;var Jf=0;function L(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:--Jf,__i:-1,__u:0,__source:s,__self:o};if(typeof t=="function"&&(r=t.defaultProps))for(a in r)l[a]===void 0&&(l[a]=r[a]);return z.vnode&&z.vnode(c),c}function Ys(){return(Ys=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 Zf=["context","children"];function Qf(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,Zf);return Ks(e,i)}function ep(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=tt(Qf,Ys({},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[Ua(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=tt(Va,{name:u},c):s[r]=c}var d=n?tt(Va,null,s):s;return tt(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ba:Nn)(this._vdom,this._root)}function Ua(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function tp(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[Ua(t)]=i,this._vdom=Ks(this._vdom,n),Nn(this._vdom,this._root)}}function ip(){Nn(this._vdom=null,this._root)}function Va(t,e){var i=this;return tt("slot",Ys({},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 np(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=ep,s.prototype.attributeChangedCallback=tp,s.prototype.disconnectedCallback=ip,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 Bt,_e,Xs,$a,Ki=0,ja=[],we=z,Ha=we.__b,Wa=we.__r,Ga=we.diffed,qa=we.__c,za=we.unmount,Ka=we.__;function mi(t,e){we.__h&&we.__h(_e,t,Ki||e),Ki=0;var i=_e.__H||(_e.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function Ae(t){return Ki=1,Ya(Ja,t)}function Ya(t,e,i){var n=mi(Bt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):Ja(void 0,e),function(a){var l=n.__N?n.__N[0]:n.__[0],c=n.t(l,a);l!==c&&(n.__N=[c,n.__[1]],n.__c.setState({}))}],n.__c=_e,!_e.__f)){var s=function(a,l,c){if(!n.__c.__H)return!0;var u=n.__c.__H.__.filter(function(h){return!!h.__c});if(u.every(function(h){return!h.__N}))return!o||o.call(this,a,l,c);var d=n.__c.props!==a;return u.forEach(function(h){if(h.__N){var g=h.__[0];h.__=h.__N,h.__N=void 0,g!==h.__[0]&&(d=!0)}}),o&&o.call(this,a,l,c)||d};_e.__f=!0;var o=_e.shouldComponentUpdate,r=_e.componentWillUpdate;_e.componentWillUpdate=function(a,l,c){if(this.__e){var u=o;o=void 0,s(a,l,c),o=u}r&&r.call(this,a,l,c)},_e.shouldComponentUpdate=s}return n.__N||n.__}function xe(t,e){var i=mi(Bt++,3);!we.__s&&eo(i.__H,e)&&(i.__=t,i.u=e,_e.__H.__h.push(i))}function Js(t,e){var i=mi(Bt++,4);!we.__s&&eo(i.__H,e)&&(i.__=t,i.u=e,_e.__h.push(i))}function he(t){return Ki=5,it(function(){return{current:t}},[])}function it(t,e){var i=mi(Bt++,7);return eo(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function qe(t,e){return Ki=8,it(function(){return t},e)}function De(t){var e=_e.context[t.__c],i=mi(Bt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(_e)),e.props.value):t.__}function sp(t,e){we.useDebugValue&&we.useDebugValue(e?e(t):t)}function Zs(){var t=mi(Bt++,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 op(){for(var t;t=ja.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Fn),t.__H.__h.forEach(Qs),t.__H.__h=[]}catch(e){t.__H.__h=[],we.__e(e,t.__v)}}we.__b=function(t){_e=null,Ha&&Ha(t)},we.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Ka&&Ka(t,e)},we.__r=function(t){Wa&&Wa(t),Bt=0;var e=(_e=t.__c).__H;e&&(Xs===_e?(e.__h=[],_e.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Fn),e.__h.forEach(Qs),e.__h=[],Bt=0)),Xs=_e},we.diffed=function(t){Ga&&Ga(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ja.push(e)!==1&&$a===we.requestAnimationFrame||(($a=we.requestAnimationFrame)||rp)(op)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),Xs=_e=null},we.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Fn),i.__h=i.__h.filter(function(n){return!n.__||Qs(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],we.__e(n,i.__v)}}),qa&&qa(t,e)},we.unmount=function(t){za&&za(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Fn(n)}catch(s){e=s}}),i.__H=void 0,e&&we.__e(e,i.__v))};var Xa=typeof requestAnimationFrame=="function";function rp(t){var e,i=function(){clearTimeout(n),Xa&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);Xa&&(e=requestAnimationFrame(i))}function Fn(t){var e=_e,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),_e=e}function Qs(t){var e=_e;t.__c=t.__(),_e=e}function eo(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function Ja(t,e){return typeof e=="function"?e(t):e}const Yi={},Za=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Qa=t=>"init"in t,to=t=>!!t.write,el=t=>"v"in t||"e"in t,Bn=t=>{if("e"in t)throw t.e;if((Yi?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},Un=new WeakMap,tl=t=>{var e;return Vn(t)&&!!((e=Un.get(t))!=null&&e[0])},ap=t=>{const e=Un.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},il=(t,e)=>{let i=Un.get(t);if(!i){i=[!0,new Set],Un.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Vn=t=>typeof(t==null?void 0:t.then)=="function",nl=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},io=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Vn(e))for(const r of n.d.keys())nl(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Vn(o)&&ap(o))},sl=(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},lp=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},no=()=>{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},cp=t=>(t.c||(t.c=no()),t.m||(t.m=no()),t.u||(t.u=no()),t.f||(t.f=lp()),t),dp=Symbol(),ol=(t=new WeakMap,e=new WeakMap,i=new WeakMap,n=new Set,s=new Set,o=new Set,r={},a=(h,...g)=>h.read(...g),l=(h,...g)=>h.write(...g),c=(h,g)=>{var m;return(m=h.unstable_onInit)==null?void 0:m.call(h,g)},u=(h,g)=>{var m;return(m=h.onMount)==null?void 0:m.call(h,g)},...d)=>{const h=d[0]||(T=>{if((Yi?"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,D)),E}),g=d[1]||(()=>{const T=[],E=p=>{try{p()}catch(_){T.push(_)}};do{r.f&&E(r.f);const p=new Set,_=p.add.bind(p);n.forEach(f=>{var S;return(S=e.get(f))==null?void 0:S.l.forEach(_)}),n.clear(),o.forEach(_),o.clear(),s.forEach(_),s.clear(),p.forEach(E),n.size&&m()}while(n.size||o.size||s.size);if(T.length)throw new AggregateError(T)}),m=d[2]||(()=>{const T=[],E=new WeakSet,p=new WeakSet,_=Array.from(n);for(;_.length;){const f=_[_.length-1],S=h(f);if(p.has(f)){_.pop();continue}if(E.has(f)){if(i.get(f)===S.n)T.push([f,S]);else if((Yi?"production":void 0)!=="production"&&i.has(f))throw new Error("[Bug] invalidated atom exists");p.add(f),_.pop();continue}E.add(f);for(const I of sl(f,S,e))E.has(I)||_.push(I)}for(let f=T.length-1;f>=0;--f){const[S,I]=T[f];let M=!1;for(const x of I.d.keys())if(x!==S&&n.has(x)){M=!0;break}M&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(T=>{var E;const p=h(T);if(el(p)&&(e.has(T)&&i.get(T)!==p.n||Array.from(p.d).every(([O,F])=>v(O).n===F)))return p;p.d.clear();let _=!0;const f=()=>{e.has(T)&&(C(T),m(),g())},S=O=>{var F;if(Za(T,O)){const $=h(O);if(!el($))if(Qa(O))io(O,O.init,h);else throw new Error("no atom init");return Bn($)}const V=v(O);try{return Bn(V)}finally{p.d.set(O,V.n),tl(p.v)&&nl(T,p.v,V),(F=e.get(O))==null||F.t.add(T),_||f()}};let I,M;const x={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(Yi?"production":void 0)!=="production"&&!to(T)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&to(T)&&(M=(...O)=>{if((Yi?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return y(T,...O)}finally{m(),g()}}),M}},N=p.n;try{const O=a(T,S,x);return io(T,O,h),Vn(O)&&(il(O,()=>I==null?void 0:I.abort()),O.then(f,f)),p}catch(O){return delete p.v,p.e=O,++p.n,p}finally{_=!1,N!==p.n&&i.get(T)===N&&(i.set(T,p.n),n.add(T),(E=r.c)==null||E.call(r,T))}}),b=d[4]||(T=>{const E=[T];for(;E.length;){const p=E.pop(),_=h(p);for(const f of sl(p,_,e)){const S=h(f);i.set(f,S.n),E.push(f)}}}),y=d[5]||((T,...E)=>{let p=!0;const _=S=>Bn(v(S)),f=(S,...I)=>{var M;const x=h(S);try{if(Za(T,S)){if(!Qa(S))throw new Error("atom not writable");const N=x.n,O=I[0];io(S,O,h),C(S),N!==x.n&&(n.add(S),(M=r.c)==null||M.call(r,S),b(S));return}else return y(S,...I)}finally{p||(m(),g())}};try{return l(T,_,f,...E)}finally{p=!1}}),C=d[6]||(T=>{var E;const p=h(T),_=e.get(T);if(_&&!tl(p.v)){for(const[f,S]of p.d)if(!_.d.has(f)){const I=h(f);k(f).t.add(T),_.d.add(f),S!==I.n&&(n.add(f),(E=r.c)==null||E.call(r,f),b(f))}for(const f of _.d||[])if(!p.d.has(f)){_.d.delete(f);const S=A(f);S==null||S.t.delete(T)}}}),k=d[7]||(T=>{var E;const p=h(T);let _=e.get(T);if(!_){v(T);for(const f of p.d.keys())k(f).t.add(T);if(_={l:new Set,d:new Set(p.d.keys()),t:new Set},e.set(T,_),(E=r.m)==null||E.call(r,T),to(T)){const f=()=>{let S=!0;const I=(...M)=>{try{return y(T,...M)}finally{S||(m(),g())}};try{const M=u(T,I);M&&(_.u=()=>{S=!0;try{M()}finally{S=!1}})}finally{S=!1}};s.add(f)}}return _}),A=d[8]||(T=>{var E;const p=h(T);let _=e.get(T);if(_&&!_.l.size&&!Array.from(_.t).some(f=>{var S;return(S=e.get(f))==null?void 0:S.d.has(T)})){_.u&&o.add(_.u),_=void 0,e.delete(T),(E=r.u)==null||E.call(r,T);for(const f of p.d.keys()){const S=A(f);S==null||S.t.delete(T)}return}return _}),R=[t,e,i,n,s,o,r,a,l,c,u,h,g,m,v,b,y,C,k,A],D={get:T=>Bn(v(T)),set:(T,...E)=>{try{return y(T,...E)}finally{m(),g()}},sub:(T,E)=>{const _=k(T).l;return _.add(E),g(),()=>{_.delete(E),A(T),g()}}};return Object.defineProperty(D,dp,{value:R}),D},up=cp,rl=il,so={};let hp=0;function $n(t,e){const i=`atom${++hp}`,n={toString(){return(so?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=fp,n.write=pp),n}function fp(t){return t(this)}function pp(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const gp=()=>{let t=0;const e=up({}),i=new WeakMap,n=new WeakMap,s=ol(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 mp(){return(so?"production":void 0)!=="production"?gp():ol()}let Xi;function vp(){return Xi||(Xi=mp(),(so?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Xi),globalThis.__JOTAI_DEFAULT_STORE__!==Xi&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Xi}function al(t,e){for(var i in e)t[i]=e[i];return t}function ll(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 cl=Js;function dl(t,e){this.props=t,this.context=e}(dl.prototype=new ut).isPureReactComponent=!0,dl.prototype.shouldComponentUpdate=function(t,e){return ll(this.props,t)||ll(this.state,e)};var ul=z.__b;z.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ul&&ul(t)};var _p=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function yp(t){function e(i){var n=al({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=_p,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var hl=function(t,e){return t==null?null:vt(vt(t).map(e))},bp={map:hl,forEach:hl,count:function(t){return t?vt(t).length:0},only:function(t){var e=vt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:vt},wp=z.__e;z.__e=function(t,e,i,n){if(t.then){for(var s,o=e;o=o.__;)if((s=o.__c)&&s.__c)return e.__e==null&&(e.__e=i.__e,e.__k=i.__k),s.__c(t,e)}wp(t,e,i,n)};var fl=z.unmount;function pl(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=al({},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 pl(n,e,i)})),t}function gl(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return gl(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 oo(){this.__u=0,this.o=null,this.__b=null}function ml(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function jn(){this.i=null,this.l=null}z.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),fl&&fl(t)},(oo.prototype=new ut).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=ml(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]=gl(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)},oo.prototype.componentWillUnmount=function(){this.o=[]},oo.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]=pl(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&tt(mt,null,t.fallback);return s&&(s.__u&=-33),[tt(mt,null,e.__a?null:t.children),s]};var vl=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]}};(jn.prototype=new ut).__a=function(t){var e=this,i=ml(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),vl(e,t,n)):s()};i?i(o):o()}},jn.prototype.render=function(t){this.i=null,this.l=new Map;var e=vt(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},jn.prototype.componentDidUpdate=jn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){vl(t,i,e)})};var _l=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Sp=/^(?: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]/,Cp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Tp=/[A-Z0-9]/g,kp=typeof document<"u",Ep=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};ut.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(ut.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var yl=z.event;function Ip(){}function Rp(){return this.cancelBubble}function Ap(){return this.defaultPrevented}z.event=function(t){return yl&&(t=yl(t)),t.persist=Ip,t.isPropagationStopped=Rp,t.isDefaultPrevented=Ap,t.nativeEvent=t};var xp={enumerable:!1,configurable:!0,get:function(){return this.class}},bl=z.vnode;z.vnode=function(t){typeof t.type=="string"&&function(e){var i=e.props,n=e.type,s={},o=n.indexOf("-")===-1;for(var r in i){var a=i[r];if(!(r==="value"&&"defaultValue"in i&&a==null||kp&&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"||Ep(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Cp.test(r)&&(r=l):l=r="oninput":o&&Sp.test(r)?r=r.replace(Tp,"-$&").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=vt(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=vt(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",xp)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=_l,bl&&bl(t)};var wl=z.__r;z.__r=function(t){wl&&wl(t),t.__c};var Sl=z.diffed;z.diffed=function(t){Sl&&Sl(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 Cl(t){return!!t&&t.$$typeof===_l}function Dp(t){return Cl(t)?Ks.apply(null,arguments):t}var Tl={};const Lp={},Mp=At(void 0);function kl(t){return De(Mp)||vp()}const ro=t=>typeof(t==null?void 0:t.then)=="function",ao=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},Op=Tl.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(ao(t),t)}),lo=new WeakMap,El=(t,e)=>{let i=lo.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();ro(c)?(lo.set(c,i),o=c,c.then(r(c),a(c)),rl(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),rl(t,l)}),lo.set(t,i)),i};function co(t,e){const{delay:i,unstable_promiseStatus:n=!Tl.use}={},s=kl(),[[o,r,a],l]=Ya(u=>{const d=s.get(t);return Object.is(u[0],d)&&u[1]===s&&u[2]===t?u:[d,s,t]},void 0,()=>[s.get(t),s,t]);let c=o;if((r!==s||a!==t)&&(l(),c=s.get(t)),xe(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);ro(d)&&ao(El(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),sp(c),ro(c)){const u=El(c,()=>s.get(t));return n&&ao(u),Op(u)}return c}function Hn(t,e){const i=kl();return qe((...s)=>{if((Lp?"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[co(t),Hn(t)]}const uo=At({});function Wn(t){const e=he(null);return e.current===null&&(e.current=t()),e.current}const ho=typeof window<"u",Rl=ho?Js:xe,Gn=At(null);function fo(t,e){t.indexOf(e)===-1&&t.push(e)}function po(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const xt=(t,e,i)=>i>e?e:i<t?t:i;let go=()=>{};const Dt={},Al=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function xl(t){return typeof t=="object"&&t!==null}const Dl=t=>/^0[^.\s]+$/u.test(t);function mo(t){let e;return()=>(e===void 0&&(e=t()),e)}const nt=t=>t,Pp=(t,e)=>i=>e(t(i)),Ji=(...t)=>t.reduce(Pp),Zi=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class vo{constructor(){this.subscriptions=[]}add(e){return fo(this.subscriptions,e),()=>po(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 _t=t=>t*1e3,yt=t=>t/1e3;function Ll(t,e){return e?t*(1e3/e):0}const Ml=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Np=1e-7,Fp=12;function Bp(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=Ml(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Np&&++a<Fp);return r}function Qi(t,e,i,n){if(t===e&&i===n)return nt;const s=o=>Bp(o,0,1,t,i);return o=>o===0||o===1?o:Ml(s(o),e,n)}const Ol=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Pl=t=>e=>1-t(1-e),Nl=Qi(.33,1.53,.69,.99),_o=Pl(Nl),Fl=Ol(_o),Bl=t=>(t*=2)<1?.5*_o(t):.5*(2-Math.pow(2,-10*(t-1))),yo=t=>1-Math.sin(Math.acos(t)),Ul=Pl(yo),Vl=Ol(yo),Up=Qi(.42,0,1,1),Vp=Qi(0,0,.58,1),$l=Qi(.42,0,.58,1),$p=t=>Array.isArray(t)&&typeof t[0]!="number",jl=t=>Array.isArray(t)&&typeof t[0]=="number",jp={linear:nt,easeIn:Up,easeInOut:$l,easeOut:Vp,circIn:yo,circInOut:Vl,circOut:Ul,backIn:_o,backInOut:Fl,backOut:Nl,anticipate:Bl},Hp=t=>typeof t=="string",Hl=t=>{if(jl(t)){go(t.length===4);const[e,i,n,s]=t;return Qi(e,i,n,s)}else if(Hp(t))return jp[t];return t},qn=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Wl={value:null};function Wp(t,e){let i=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1},l=0;function c(d){r.has(d)&&(u.schedule(d),t()),l++,d(a)}const u={schedule:(d,h=!1,g=!1)=>{const v=g&&s?i:n;return h&&r.add(d),v.has(d)||v.add(d),d},cancel:d=>{n.delete(d),r.delete(d)},process:d=>{if(a=d,s){o=!0;return}s=!0,[i,n]=[n,i],i.forEach(c),e&&Wl.value&&Wl.value.frameloop[e].push(l),l=0,i.clear(),s=!1,o&&(o=!1,u.process(d))}};return u}const Gp=40;function Gl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=qn.reduce((k,A)=>(k[A]=Wp(o,e?A:void 0),k),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:g,postRender:m}=r,v=()=>{const k=Dt.useManualTiming?s.timestamp:performance.now();i=!1,Dt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(k-s.timestamp,Gp),1)),s.timestamp=k,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),g.process(s),m.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:qn.reduce((k,A)=>{const R=r[A];return k[A]=(D,T=!1,E=!1)=>(i||b(),R.schedule(D,T,E)),k},{}),cancel:k=>{for(let A=0;A<qn.length;A++)r[qn[A]].cancel(k)},state:s,steps:r}}const{schedule:be,cancel:Ut,state:Oe,steps:bo}=Gl(typeof requestAnimationFrame<"u"?requestAnimationFrame:nt,!0);let zn;function qp(){zn=void 0}const ze={now:()=>(zn===void 0&&ze.set(Oe.isProcessing||Dt.useManualTiming?Oe.timestamp:performance.now()),zn),set:t=>{zn=t,queueMicrotask(qp)}},ql=t=>e=>typeof e=="string"&&e.startsWith(t),wo=ql("--"),zp=ql("var(--"),So=t=>zp(t)?Kp.test(t.split("/*")[0].trim()):!1,Kp=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,vi={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},en={...vi,transform:t=>xt(0,1,t)},Kn={...vi,default:1},tn=t=>Math.round(t*1e5)/1e5,Co=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function Yp(t){return t==null}const Xp=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,To=(t,e)=>i=>!!(typeof i=="string"&&Xp.test(i)&&i.startsWith(t)||e&&!Yp(i)&&Object.prototype.hasOwnProperty.call(i,e)),zl=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(Co);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},Jp=t=>xt(0,255,t),ko={...vi,transform:t=>Math.round(Jp(t))},Jt={test:To("rgb","red"),parse:zl("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+ko.transform(t)+", "+ko.transform(e)+", "+ko.transform(i)+", "+tn(en.transform(n))+")"};function Zp(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 Eo={test:To("#"),parse:Zp,transform:Jt.transform},nn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),Vt=nn("deg"),bt=nn("%"),K=nn("px"),Qp=nn("vh"),eg=nn("vw"),Kl={...bt,parse:t=>bt.parse(t)/100,transform:t=>bt.transform(t*100)},_i={test:To("hsl","hue"),parse:zl("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+bt.transform(tn(e))+", "+bt.transform(tn(i))+", "+tn(en.transform(n))+")"},Ee={test:t=>Jt.test(t)||Eo.test(t)||_i.test(t),parse:t=>Jt.test(t)?Jt.parse(t):_i.test(t)?_i.parse(t):Eo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?Jt.transform(t):_i.transform(t),getAnimatableNone:t=>{const e=Ee.parse(t);return e.alpha=0,Ee.transform(e)}},tg=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function ig(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Co))==null?void 0:e.length)||0)+(((i=t.match(tg))==null?void 0:i.length)||0)>0}const Yl="number",Xl="color",ng="var",sg="var(",Jl="${}",og=/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 sn(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(og,l=>(Ee.test(l)?(n.color.push(o),s.push(Xl),i.push(Ee.parse(l))):l.startsWith(sg)?(n.var.push(o),s.push(ng),i.push(l)):(n.number.push(o),s.push(Yl),i.push(parseFloat(l))),++o,Jl)).split(Jl);return{values:i,split:a,indexes:n,types:s}}function Zl(t){return sn(t).values}function Ql(t){const{split:e,types:i}=sn(t),n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=i[r];a===Yl?o+=tn(s[r]):a===Xl?o+=Ee.transform(s[r]):o+=s[r]}return o}}const rg=t=>typeof t=="number"?0:Ee.test(t)?Ee.getAnimatableNone(t):t;function ag(t){const e=Zl(t);return Ql(t)(e.map(rg))}const $t={test:ig,parse:Zl,createTransformer:Ql,getAnimatableNone:ag};function Io(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 lg({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=Io(l,a,t+1/3),o=Io(l,a,t),r=Io(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function Yn(t,e){return i=>i>0?e:t}const Se=(t,e,i)=>t+(e-t)*i,Ro=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},cg=[Eo,Jt,_i],dg=t=>cg.find(e=>e.test(t));function ec(t){const e=dg(t);if(!e)return!1;let i=e.parse(t);return e===_i&&(i=lg(i)),i}const tc=(t,e)=>{const i=ec(t),n=ec(e);if(!i||!n)return Yn(t,e);const s={...i};return o=>(s.red=Ro(i.red,n.red,o),s.green=Ro(i.green,n.green,o),s.blue=Ro(i.blue,n.blue,o),s.alpha=Se(i.alpha,n.alpha,o),Jt.transform(s))},Ao=new Set(["none","hidden"]);function ug(t,e){return Ao.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function hg(t,e){return i=>Se(t,e,i)}function xo(t){return typeof t=="number"?hg:typeof t=="string"?So(t)?Yn:Ee.test(t)?tc:gg:Array.isArray(t)?ic:typeof t=="object"?Ee.test(t)?tc:fg:Yn}function ic(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>xo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function fg(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=xo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function pg(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 gg=(t,e)=>{const i=$t.createTransformer(e),n=sn(t),s=sn(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?Ao.has(t)&&!s.values.length||Ao.has(e)&&!n.values.length?ug(t,e):Ji(ic(pg(n,s),s.values),i):Yn(t,e)};function nc(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?Se(t,e,i):xo(t)(t,e)}const mg=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>be.update(e,i),stop:()=>Ut(e),now:()=>Oe.isProcessing?Oe.timestamp:ze.now()}},sc=(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)})`},Xn=2e4;function Do(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<Xn;)e+=i,n=t.next(e);return e>=Xn?1/0:e}function vg(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(Do(n),Xn);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:yt(s)}}const _g=5;function oc(t,e,i){const n=Math.max(e-_g,0);return Ll(i-t(n),e-n)}const Ce={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Lo=.001;function yg({duration:t=Ce.duration,bounce:e=Ce.bounce,velocity:i=Ce.velocity,mass:n=Ce.mass}){let s,o,r=1-e;r=xt(Ce.minDamping,Ce.maxDamping,r),t=xt(Ce.minDuration,Ce.maxDuration,yt(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,g=Mo(c,r),m=Math.exp(-d);return Lo-h/g*m},o=c=>{const d=c*r*t,h=d*i+i,g=Math.pow(r,2)*Math.pow(c,2)*t,m=Math.exp(-d),v=Mo(Math.pow(c,2),r);return(-s(c)+Lo>0?-1:1)*((h-g)*m)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-Lo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=wg(s,o,a);if(t=_t(t),isNaN(l))return{stiffness:Ce.stiffness,damping:Ce.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const bg=12;function wg(t,e,i){let n=i;for(let s=1;s<bg;s++)n=n-t(n)/e(n);return n}function Mo(t,e){return t*Math.sqrt(1-e*e)}const Sg=["duration","bounce"],Cg=["stiffness","damping","mass"];function rc(t,e){return e.some(i=>t[i]!==void 0)}function Tg(t){let e={velocity:Ce.velocity,stiffness:Ce.stiffness,damping:Ce.damping,mass:Ce.mass,isResolvedFromDuration:!1,...t};if(!rc(t,Cg)&&rc(t,Sg))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*xt(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ce.mass,stiffness:s,damping:o}}else{const i=yg(t);e={...e,...i,mass:Ce.mass},e.isResolvedFromDuration=!0}return e}function Jn(t=Ce.visualDuration,e=Ce.bounce){const i=typeof t!="object"?{visualDuration:t,keyframes:[0,1],bounce:e}:t;let{restSpeed:n,restDelta:s}=i;const o=i.keyframes[0],r=i.keyframes[i.keyframes.length-1],a={done:!1,value:o},{stiffness:l,damping:c,mass:u,duration:d,velocity:h,isResolvedFromDuration:g}=Tg({...i,velocity:-yt(i.velocity||0)}),m=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,y=yt(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Ce.restSpeed.granular:Ce.restSpeed.default),s||(s=C?Ce.restDelta.granular:Ce.restDelta.default);let k;if(v<1){const R=Mo(y,v);k=D=>{const T=Math.exp(-v*y*D);return r-T*((m+v*y*b)/R*Math.sin(R*D)+b*Math.cos(R*D))}}else if(v===1)k=R=>r-Math.exp(-y*R)*(b+(m+y*b)*R);else{const R=y*Math.sqrt(v*v-1);k=D=>{const T=Math.exp(-v*y*D),E=Math.min(R*D,300);return r-T*((m+v*y*b)*Math.sinh(E)+R*b*Math.cosh(E))/R}}const A={calculatedDuration:g&&d||null,next:R=>{const D=k(R);if(g)a.done=R>=d;else{let T=R===0?m:0;v<1&&(T=R===0?_t(m):oc(k,R,D));const E=Math.abs(T)<=n,p=Math.abs(r-D)<=s;a.done=E&&p}return a.value=a.done?r:D,a},toString:()=>{const R=Math.min(Do(A),Xn),D=sc(T=>A.next(R*T).value,R,30);return R+"ms "+D},toTransition:()=>{}};return A}Jn.applyToOptions=t=>{const e=vg(t,100,Jn);return t.ease=e.ease,t.duration=_t(e.duration),t.type="keyframes",t};function Oo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},g=E=>a!==void 0&&E<a||l!==void 0&&E>l,m=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,y=r===void 0?b:r(b);y!==b&&(v=y-d);const C=E=>-v*Math.exp(-E/n),k=E=>y+C(E),A=E=>{const p=C(E),_=k(E);h.done=Math.abs(p)<=c,h.value=h.done?y:_};let R,D;const T=E=>{g(h.value)&&(R=E,D=Jn({keyframes:[h.value,m(h.value)],velocity:oc(k,E,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return T(0),{calculatedDuration:null,next:E=>{let p=!1;return!D&&R===void 0&&(p=!0,A(E),T(E)),R!==void 0&&E>=R?D.next(E-R):(!p&&A(E),h)}}}function kg(t,e,i){const n=[],s=i||Dt.mix||nc,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]||nt:e;a=Ji(l,a)}n.push(a)}return n}function Eg(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(go(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=kg(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=Zi(t[d],t[d+1],u);return a[d](h)};return i?u=>c(xt(t[0],t[o-1],u)):c}function Ig(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=Zi(0,e,n);t.push(Se(i,1,s))}}function Rg(t){const e=[0];return Ig(e,t.length-1),e}function Ag(t,e){return t.map(i=>i*e)}function xg(t,e){return t.map(()=>e||$l).splice(0,t.length-1)}function on({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=$p(n)?n.map(Hl):Hl(n),o={done:!1,value:e[0]},r=Ag(i&&i.length===e.length?i:Rg(e),t),a=Eg(r,e,{ease:Array.isArray(s)?s:xg(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Dg=t=>t!==null;function Po(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Dg),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Lg={decay:Oo,inertia:Oo,tween:on,keyframes:on,spring:Jn};function ac(t){typeof t.type=="string"&&(t.type=Lg[t.type])}class No{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 Mg=t=>t/100;class Fo extends No{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!==ze.now()&&this.tick(ze.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;ac(e);const{type:i=on,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||on;l!==on&&typeof a[0]!="number"&&(this.mixKeyframes=Ji(Mg,nc(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=Do(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+s,this.totalDuration=this.resolvedDuration*(n+1)-s,this.generator=c}updateTime(e){const i=Math.round(e-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=i}tick(e,i=!1){const{generator:n,totalDuration:s,mixKeyframes:o,mirroredGenerator:r,resolvedDuration:a,calculatedDuration:l}=this;if(this.startTime===null)return n.next(0);const{delay:c=0,keyframes:u,repeat:d,repeatType:h,repeatDelay:g,type:m,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 y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let k=this.currentTime,A=n;if(d){const E=Math.min(this.currentTime,s)/a;let p=Math.floor(E),_=E%1;!_&&E>=1&&(_=1),_===1&&p--,p=Math.min(p,d+1),!!(p%2)&&(h==="reverse"?(_=1-_,g&&(_-=g/a)):h==="mirror"&&(A=r)),k=xt(0,1,_)*a}const R=C?{done:!1,value:u[0]}:A.next(k);o&&(R.value=o(R.value));let{done:D}=R;!C&&l!==null&&(D=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const T=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&D);return T&&m!==Oo&&(R.value=Po(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 yt(this.calculatedDuration)}get time(){return yt(this.currentTime)}set time(e){var i;e=_t(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(ze.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=yt(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=mg,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(ze.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 Og(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const Zt=t=>t*180/Math.PI,Bo=t=>{const e=Zt(Math.atan2(t[1],t[0]));return Uo(e)},Pg={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:Bo,rotateZ:Bo,skewX:t=>Zt(Math.atan(t[1])),skewY:t=>Zt(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},Uo=t=>(t=t%360,t<0&&(t+=360),t),lc=Bo,cc=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),dc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Ng={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:cc,scaleY:dc,scale:t=>(cc(t)+dc(t))/2,rotateX:t=>Uo(Zt(Math.atan2(t[6],t[5]))),rotateY:t=>Uo(Zt(Math.atan2(-t[2],t[0]))),rotateZ:lc,rotate:lc,skewX:t=>Zt(Math.atan(t[4])),skewY:t=>Zt(Math.atan(t[1])),skew:t=>(Math.abs(t[1])+Math.abs(t[4]))/2};function Vo(t){return t.includes("scale")?1:0}function $o(t,e){if(!t||t==="none")return Vo(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Ng,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=Pg,s=a}if(!s)return Vo(e);const o=n[e],r=s[1].split(",").map(Bg);return typeof o=="function"?o(r):r[o]}const Fg=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return $o(i,e)};function Bg(t){return parseFloat(t.trim())}const yi=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],bi=new Set(yi),uc=t=>t===vi||t===K,Ug=new Set(["x","y","z"]),Vg=yi.filter(t=>!Ug.has(t));function $g(t){const e=[];return Vg.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const Qt={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})=>$o(e,"x"),y:(t,{transform:e})=>$o(e,"y")};Qt.translateX=Qt.x,Qt.translateY=Qt.y;const ei=new Set;let jo=!1,Ho=!1,Wo=!1;function hc(){if(Ho){const t=Array.from(ei).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=$g(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)})}Ho=!1,jo=!1,ei.forEach(t=>t.complete(Wo)),ei.clear()}function fc(){ei.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Ho=!0)})}function jg(){Wo=!0,fc(),hc(),Wo=!1}class Go{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?(ei.add(this),jo||(jo=!0,be.read(fc),be.resolveKeyframes(hc))):(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])}Og(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),ei.delete(this)}cancel(){this.state==="scheduled"&&(ei.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const Hg=t=>t.startsWith("--");function Wg(t,e,i){Hg(e)?t.style.setProperty(e,i):t.style[e]=i}const Gg=mo(()=>window.ScrollTimeline!==void 0),qg={};function zg(t,e){const i=mo(t);return()=>qg[e]??i()}const pc=zg(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),rn=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,gc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:rn([0,.65,.55,1]),circOut:rn([.55,0,1,.45]),backIn:rn([.31,.01,.66,-.59]),backOut:rn([.33,1.53,.69,.99])};function mc(t,e){if(t)return typeof t=="function"?pc()?sc(t,e):"ease-out":jl(t)?rn(t):Array.isArray(t)?t.map(i=>mc(i,e)||gc.easeOut):gc[t]}function Kg(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=mc(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 vc(t){return typeof t=="function"&&"applyToOptions"in t}function Yg({type:t,...e}){return vc(t)&&pc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class Xg extends No{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,go(typeof e.type!="string");const c=Yg(e);this.animation=Kg(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Po(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):Wg(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 yt(Number(e))}get time(){return yt(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=_t(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&&Gg()?(this.animation.timeline=e,nt):i(this)}}const _c={anticipate:Bl,backInOut:Fl,circInOut:Vl};function Jg(t){return t in _c}function Zg(t){typeof t.ease=="string"&&Jg(t.ease)&&(t.ease=_c[t.ease])}const yc=10;class Qg extends Xg{constructor(e){Zg(e),ac(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 Fo({...r,autoplay:!1}),l=_t(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-yc).value,a.sample(l).value,yc),a.stop()}}const bc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&($t.test(t)||t==="0")&&!t.startsWith("url("));function em(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 tm(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=bc(s,e),a=bc(o,e);return!r||!a?!1:em(t)||(i==="spring"||vc(i))&&n}function qo(t){return xl(t)&&"offsetHeight"in t}const im=new Set(["opacity","clipPath","filter","transform"]),nm=mo(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function sm(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!qo((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return nm()&&i&&im.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const om=40;class rm extends No{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 m;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=ze.now();const h={autoplay:e,delay:i,type:n,repeat:s,repeatDelay:o,repeatType:r,name:l,motionValue:c,element:u,...d},g=(u==null?void 0:u.KeyframeResolver)||Go;this.keyframeResolver=new g(a,(v,b,y)=>this.onKeyframesResolved(v,b,h,!y),l,c,u),(m=this.keyframeResolver)==null||m.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=ze.now(),tm(e,o,r,a)||((Dt.instantAnimations||!l)&&(u==null||u(Po(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>om?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},g=!c&&sm(h)?new Qg({...h,element:h.motionValue.owner.current}):new Fo(h);g.finished.then(()=>this.notifyFinished()).catch(nt),this.pendingTimeline&&(this.stopTimeline=g.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=g}get finished(){return this._animation?this.animation.finished:this._finished}then(e,i){return this.finished.finally(e).then(()=>{})}get animation(){var e;return this._animation||((e=this.keyframeResolver)==null||e.resume(),jg()),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 am=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function lm(t){const e=am.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function wc(t,e,i=1){const[n,s]=lm(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Al(r)?parseFloat(r):r}return So(s)?wc(s,e,i+1):s}function zo(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Sc=new Set(["width","height","top","left","right","bottom",...yi]),cm={test:t=>t==="auto",parse:t=>t},Cc=t=>e=>e.test(t),Tc=[vi,K,bt,Vt,eg,Qp,cm],kc=t=>Tc.find(Cc(t));function dm(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Dl(t):!0}const um=new Set(["brightness","contrast","saturate","opacity"]);function hm(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(Co)||[];if(!n)return t;const s=i.replace(n,"");let o=um.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const fm=/\b([a-z-]*)\(.*?\)/gu,Ko={...$t,getAnimatableNone:t=>{const e=t.match(fm);return e?e.map(hm).join(" "):t}},Ec={...vi,transform:Math.round},Yo={borderWidth:K,borderTopWidth:K,borderRightWidth:K,borderBottomWidth:K,borderLeftWidth:K,borderRadius:K,radius:K,borderTopLeftRadius:K,borderTopRightRadius:K,borderBottomRightRadius:K,borderBottomLeftRadius:K,width:K,maxWidth:K,height:K,maxHeight:K,top:K,right:K,bottom:K,left:K,padding:K,paddingTop:K,paddingRight:K,paddingBottom:K,paddingLeft:K,margin:K,marginTop:K,marginRight:K,marginBottom:K,marginLeft:K,backgroundPositionX:K,backgroundPositionY:K,...{rotate:Vt,rotateX:Vt,rotateY:Vt,rotateZ:Vt,scale:Kn,scaleX:Kn,scaleY:Kn,scaleZ:Kn,skew:Vt,skewX:Vt,skewY:Vt,distance:K,translateX:K,translateY:K,translateZ:K,x:K,y:K,z:K,perspective:K,transformPerspective:K,opacity:en,originX:Kl,originY:Kl,originZ:K},zIndex:Ec,fillOpacity:en,strokeOpacity:en,numOctaves:Ec},pm={...Yo,color:Ee,backgroundColor:Ee,outlineColor:Ee,fill:Ee,stroke:Ee,borderColor:Ee,borderTopColor:Ee,borderRightColor:Ee,borderBottomColor:Ee,borderLeftColor:Ee,filter:Ko,WebkitFilter:Ko},Ic=t=>pm[t];function Rc(t,e){let i=Ic(t);return i!==Ko&&(i=$t),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const gm=new Set(["auto","none","0"]);function mm(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!gm.has(o)&&sn(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Rc(i,s)}class vm extends Go{constructor(e,i,n,s,o){super(e,i,n,s,o,!0)}readKeyframes(){const{unresolvedKeyframes:e,element:i,name:n}=this;if(!i||!i.current)return;super.readKeyframes();for(let l=0;l<e.length;l++){let c=e[l];if(typeof c=="string"&&(c=c.trim(),So(c))){const u=wc(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Sc.has(n)||e.length!==2)return;const[s,o]=e,r=kc(s),a=kc(o);if(r!==a)if(uc(r)&&uc(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else Qt[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||dm(e[s]))&&n.push(s);n.length&&mm(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=Qt[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]=Qt[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 _m(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 Ac=(t,e)=>e&&typeof t=="number"?e.transform(t):t,xc=30,ym=t=>!isNaN(parseFloat(t));class bm{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=ze.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=ze.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=ym(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 vo);const n=this.events[e].add(i);return e==="change"?()=>{n(),be.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=ze.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>xc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,xc);return Ll(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 wi(t,e){return new bm(t,e)}const{schedule:Xo}=Gl(queueMicrotask,!1),ht={x:!1,y:!1};function Dc(){return ht.x||ht.y}function wm(t){return t==="x"||t==="y"?ht[t]?null:(ht[t]=!0,()=>{ht[t]=!1}):ht.x||ht.y?null:(ht.x=ht.y=!0,()=>{ht.x=ht.y=!1})}function Lc(t,e){const i=_m(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function Mc(t){return!(t.pointerType==="touch"||Dc())}function Sm(t,e,i={}){const[n,s,o]=Lc(t,i),r=a=>{if(!Mc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Mc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Oc=(t,e)=>e?t===e?!0:Oc(t,e.parentElement):!1,Jo=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Cm=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Tm(t){return Cm.has(t.tagName)||t.tabIndex!==-1}const Zn=new WeakSet;function Pc(t){return e=>{e.key==="Enter"&&t(e)}}function Zo(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const km=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=Pc(()=>{if(Zn.has(i))return;Zo(i,"down");const s=Pc(()=>{Zo(i,"up")}),o=()=>Zo(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 Nc(t){return Jo(t)&&!Dc()}function Em(t,e,i={}){const[n,s,o]=Lc(t,i),r=a=>{const l=a.currentTarget;if(!Nc(a))return;Zn.add(l);const c=e(l,a),u=(g,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),Zn.has(l)&&Zn.delete(l),Nc(g)&&typeof c=="function"&&c(g,{success:m})},d=g=>{u(g,l===window||l===document||i.useGlobalTarget||Oc(l,g.target))},h=g=>{u(g,!1)};window.addEventListener("pointerup",d,s),window.addEventListener("pointercancel",h,s)};return n.forEach(a=>{(i.useGlobalTarget?window:a).addEventListener("pointerdown",r,s),qo(a)&&(a.addEventListener("focus",c=>km(c,s)),!Tm(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function Fc(t){return xl(t)&&"ownerSVGElement"in t}function Im(t){return Fc(t)&&t.tagName==="svg"}const Ue=t=>!!(t&&t.getVelocity),Rm=[...Tc,Ee,$t],Am=t=>Rm.find(Cc(t)),an=At({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class xm extends ut{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=qo(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 Dm({children:t,isPresent:e,anchorX:i,root:n}){const s=Zs(),o=he(null),r=he({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=De(an);return cl(()=>{const{width:l,height:c,top:u,left:d,right:h}=r.current;if(e||!o.current||!l||!c)return;const g=i==="left"?`left: ${d}`:`right: ${h}`;o.current.dataset.motionPopId=s;const m=document.createElement("style");a&&(m.nonce=a);const v=n??document.head;return v.appendChild(m),m.sheet&&m.sheet.insertRule(`
|
|
1
|
+
var FS=Object.defineProperty;var US=(_t,J,ni)=>J in _t?FS(_t,J,{enumerable:!0,configurable:!0,writable:!0,value:ni}):_t[J]=ni;var B=(_t,J,ni)=>US(_t,typeof J!="symbol"?J+"":J,ni);(function(){"use strict";var _t,J,ni,si,Ra,xa,Da,La,Ys,Xs,Js,Ma,Qi={},Oa=[],sp=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Zi=Array.isArray;function Tt(t,e){for(var i in e)t[i]=e[i];return t}function Qs(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ct(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?_t.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 en(t,r,n,s,null)}function en(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??++ni,__i:-1,__u:0};return s==null&&J.vnode!=null&&J.vnode(o),o}function yt(t){return t.children}function bt(t,e){this.props=t,this.context=e}function Ti(t,e){if(e==null)return t.__?Ti(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"?Ti(t):null}function Pa(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 Pa(t)}}function Zs(t){(!t.__d&&(t.__d=!0)&&si.push(t)&&!jn.__r++||Ra!=J.debounceRendering)&&((Ra=J.debounceRendering)||xa)(jn)}function jn(){for(var t,e,i,n,s,o,r,a=1;si.length;)si.length>a&&si.sort(Da),t=si.shift(),a=si.length,t.__d&&(i=void 0,s=(n=(e=t).__v).__e,o=[],r=[],e.__P&&((i=Tt({},n)).__v=n.__v+1,J.vnode&&J.vnode(i),eo(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,o,s??Ti(n),!!(32&n.__u),r),i.__v=n.__v,i.__.__k[i.__i]=i,Va(o,i,r),i.__e!=s&&Pa(i)));jn.__r=0}function Na(t,e,i,n,s,o,r,a,l,c,u){var d,h,p,m,v,b,y=n&&n.__k||Oa,C=e.length;for(l=op(i,e,y,l,C),d=0;d<C;d++)(p=i.__k[d])!=null&&(h=p.__i==-1?Qi:y[p.__i]||Qi,p.__i=d,b=eo(t,p,h,s,o,r,a,l,c,u),m=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&to(h.ref,null,p),u.push(p.ref,p.__c||m,p)),v==null&&m!=null&&(v=m),4&p.__u||h.__k===p.__k?l=Fa(p,l,t):typeof p.type=="function"&&b!==void 0?l=b:m&&(l=m.nextSibling),p.__u&=-7);return i.__e=v,l}function op(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?en(null,r,null,null,null):Zi(r)?en(yt,{children:r},null,null,null):r.constructor==null&&r.__b>0?en(r.type,r.props,r.key,r.ref?r.ref:null,r.__v):r).__=t,r.__b=t.__b+1,a=null,(c=r.__i=rp(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=Ti(a)),ja(a,a));return n}function Fa(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=Fa(n[s],e,i));return e}t.__e!=e&&(e&&t.type&&!i.contains(e)&&(e=Ti(t)),i.insertBefore(t.__e,e||null),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function kt(t,e){return e=e||[],t==null||typeof t=="boolean"||(Zi(t)?t.some(function(i){kt(i,e)}):e.push(t)),e}function rp(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 Ua(t,e,i){e[0]=="-"?t.setProperty(e,i??""):t[e]=i==null?"":typeof i!="number"||sp.test(e)?i:i+"px"}function Hn(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||Ua(t.style,e,"");if(i)for(e in i)n&&i[e]==n[e]||Ua(t.style,e,i[e])}else if(e[0]=="o"&&e[1]=="n")o=e!=(e=e.replace(La,"$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=Ys,t.addEventListener(e,o?Js:Xs,o)):t.removeEventListener(e,o?Js: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 Ba(t){return function(e){if(this.l){var i=this.l[e.type+t];if(e.t==null)e.t=Ys++;else if(e.t<i.u)return;return i(J.event?J.event(e):e)}}}function eo(t,e,i,n,s,o,r,a,l,c){var u,d,h,p,m,v,b,y,C,T,A,x,N,E,k,f,_,g=e.type;if(e.constructor!=null)return null;128&i.__u&&(l=!!(32&i.__u),o=[a=e.__e=i.__e]),(u=J.__b)&&u(e);e:if(typeof g=="function")try{if(y=e.props,C="prototype"in g&&g.prototype.render,T=(u=g.contextType)&&n[u.__c],A=u?T?T.props.value:u.__:n,i.__c?b=(d=e.__c=i.__c).__=d.__E:(C?e.__c=d=new g(y,A):(e.__c=d=new bt(y,A),d.constructor=g,d.render=lp),T&&T.sub(d),d.props=y,d.state||(d.state={}),d.context=A,d.__n=n,h=d.__d=!0,d.__h=[],d._sb=[]),C&&d.__s==null&&(d.__s=d.state),C&&g.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=Tt({},d.__s)),Tt(d.__s,g.getDerivedStateFromProps(y,d.__s))),p=d.props,m=d.state,d.__v=e,h)C&&g.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),C&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(C&&g.getDerivedStateFromProps==null&&y!==p&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(y,A),!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(y,d.__s,A)===!1||e.__v==i.__v){for(e.__v!=i.__v&&(d.props=y,d.state=d.__s,d.__d=!1),e.__e=i.__e,e.__k=i.__k,e.__k.some(function(S){S&&(S.__=e)}),x=0;x<d._sb.length;x++)d.__h.push(d._sb[x]);d._sb=[],d.__h.length&&r.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(y,d.__s,A),C&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(p,m,v)})}if(d.context=A,d.props=y,d.__P=t,d.__e=!1,N=J.__r,E=0,C){for(d.state=d.__s,d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[]}else do d.__d=!1,N&&N(e),u=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++E<25);d.state=d.__s,d.getChildContext!=null&&(n=Tt(Tt({},n),d.getChildContext())),C&&!h&&d.getSnapshotBeforeUpdate!=null&&(v=d.getSnapshotBeforeUpdate(p,m)),f=u,u!=null&&u.type===yt&&u.key==null&&(f=$a(u.props.children)),a=Na(t,Zi(f)?f:[f],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(_=o.length;_--;)Qs(o[_]);else e.__e=i.__e,e.__k=i.__k;J.__e(S,e,i)}else o==null&&e.__v==i.__v?(e.__k=i.__k,e.__e=i.__e):a=e.__e=ap(i.__e,e,i,n,s,o,r,l,c);return(u=J.diffed)&&u(e),128&e.__u?void 0:a}function Va(t,e,i){for(var n=0;n<i.length;n++)to(i[n],i[++n],i[++n]);J.__c&&J.__c(e,t),t.some(function(s){try{t=s.__h,s.__h=[],t.some(function(o){o.call(s)})}catch(o){J.__e(o,s.__v)}})}function $a(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Zi(t)?t.map($a):Tt({},t)}function ap(t,e,i,n,s,o,r,a,l){var c,u,d,h,p,m,v,b=i.props,y=e.props,C=e.type;if(C=="svg"?s="http://www.w3.org/2000/svg":C=="math"?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),o!=null){for(c=0;c<o.length;c++)if((p=o[c])&&"setAttribute"in p==!!C&&(C?p.localName==C:p.nodeType==3)){t=p,o[c]=null;break}}if(t==null){if(C==null)return document.createTextNode(y);t=document.createElementNS(s,C,y.is&&y),a&&(J.__m&&J.__m(e,o),a=!1),o=null}if(C==null)b===y||a&&t.data==y||(t.data=y);else{if(o=o&&_t.call(t.childNodes),b=i.props||Qi,!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 y)){if(c=="value"&&"defaultValue"in y||c=="checked"&&"defaultChecked"in y)continue;Hn(t,c,null,p,s)}}for(c in y)p=y[c],c=="children"?h=p:c=="dangerouslySetInnerHTML"?u=p:c=="value"?m=p:c=="checked"?v=p:a&&typeof p!="function"||b[c]===p||Hn(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=""),Na(e.type=="template"?t.content:t,Zi(h)?h:[h],e,i,n,C=="foreignObject"?"http://www.w3.org/1999/xhtml":s,o,r,o?o[0]:i.__k&&Ti(i,0),a,l),o!=null)for(c=o.length;c--;)Qs(o[c]);a||(c="value",C=="progress"&&m==null?t.removeAttribute("value"):m!=null&&(m!==t[c]||C=="progress"&&!m||C=="option"&&m!=b[c])&&Hn(t,c,m,b[c],s),c="checked",v!=null&&v!=t[c]&&Hn(t,c,v,b[c],s))}return t}function to(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){J.__e(s,i)}}function ja(t,e,i){var n,s;if(J.unmount&&J.unmount(t),(n=t.ref)&&(n.current&&n.current!=t.__e||to(n,null,e)),(n=t.__c)!=null){if(n.componentWillUnmount)try{n.componentWillUnmount()}catch(o){J.__e(o,e)}n.base=n.__P=null}if(n=t.__k)for(s=0;s<n.length;s++)n[s]&&ja(n[s],e,i||typeof t.type!="function");i||Qs(t.__e),t.__c=t.__=t.__e=void 0}function lp(t,e,i){return this.constructor(t,i)}function Wn(t,e,i){var n,s,o,r;e==document&&(e=document.documentElement),J.__&&J.__(t,e),s=(n=typeof i=="function")?null:i&&i.__k||e.__k,o=[],r=[],eo(e,t=(!n&&i||e).__k=ct(yt,null,[t]),s||Qi,Qi,e.namespaceURI,!n&&i?[i]:s?null:e.firstChild?_t.call(e.childNodes):null,o,!n&&i?i:s?s.__e:e.firstChild,n,r),Va(o,t,r)}function Ha(t,e){Wn(t,e,Ha)}function io(t,e,i){var n,s,o,r,a=Tt({},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?_t.call(arguments,2):i),en(t.type,a,n||t.key,s||t.ref,null)}function Ft(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,Zs(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"+Ma++,e.__=t,e.Provider=e.__l=(e.Consumer=function(i,n){return i.children(n)}).contextType=e,e}_t=Oa.slice,J={__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}},ni=0,bt.prototype.setState=function(t,e){var i;i=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Tt({},this.state),typeof t=="function"&&(t=t(Tt({},i),this.props)),t&&Tt(i,t),t!=null&&this.__v&&(e&&this._sb.push(e),Zs(this))},bt.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Zs(this))},bt.prototype.render=yt,si=[],xa=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Da=function(t,e){return t.__v.__b-e.__v.__b},jn.__r=0,La=/(PointerCapture)$|Capture$/i,Ys=0,Xs=Ba(!1),Js=Ba(!0),Ma=0;var cp=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:--cp,__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 J.vnode&&J.vnode(c),c}function no(){return(no=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 dp=["context","children"];function up(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,dp);return io(e,i)}function hp(){var t=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(t),this._vdom=ct(up,no({},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[Wa(a[r].name)]=a[r].value);for(r=l.length;r--;){var c=e(l[r],null),u=l[r].slot;u?o[u]=ct(Ga,{name:u},c):s[r]=c}var d=n?ct(Ga,null,s):s;return ct(n||i.nodeName.toLowerCase(),o,d)}(this,this._vdomComponent)),(this.hasAttribute("hydrate")?Ha:Wn)(this._vdom,this._root)}function Wa(t){return t.replace(/-(\w)/g,function(e,i){return i?i.toUpperCase():""})}function fp(t,e,i){if(this._vdom){var n={};n[t]=i=i??void 0,n[Wa(t)]=i,this._vdom=io(this._vdom,n),Wn(this._vdom,this._root)}}function pp(){Wn(this._vdom=null,this._root)}function Ga(t,e){var i=this;return ct("slot",no({},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 gp(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=hp,s.prototype.attributeChangedCallback=fp,s.prototype.disconnectedCallback=pp,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 Gt,we,so,qa,tn=0,za=[],Te=J,Ka=Te.__b,Ya=Te.__r,Xa=Te.diffed,Ja=Te.__c,Qa=Te.unmount,Za=Te.__;function ki(t,e){Te.__h&&Te.__h(we,t,tn||e),tn=0;var i=we.__H||(we.__H={__:[],__h:[]});return t>=i.__.length&&i.__.push({}),i.__[t]}function ve(t){return tn=1,el(il,t)}function el(t,e,i){var n=ki(Gt++,2);if(n.t=t,!n.__c&&(n.__=[i?i(e):il(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=we,!we.__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};we.__f=!0;var o=we.shouldComponentUpdate,r=we.componentWillUpdate;we.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)},we.shouldComponentUpdate=s}return n.__N||n.__}function Le(t,e){var i=ki(Gt++,3);!Te.__s&&lo(i.__H,e)&&(i.__=t,i.u=e,we.__H.__h.push(i))}function oo(t,e){var i=ki(Gt++,4);!Te.__s&&lo(i.__H,e)&&(i.__=t,i.u=e,we.__h.push(i))}function ce(t){return tn=5,dt(function(){return{current:t}},[])}function dt(t,e){var i=ki(Gt++,7);return lo(i.__H,e)&&(i.__=t(),i.__H=e,i.__h=t),i.__}function Ne(t,e){return tn=8,dt(function(){return t},e)}function Fe(t){var e=we.context[t.__c],i=ki(Gt++,9);return i.c=t,e?(i.__==null&&(i.__=!0,e.sub(we)),e.props.value):t.__}function mp(t,e){Te.useDebugValue&&Te.useDebugValue(e?e(t):t)}function ro(){var t=ki(Gt++,11);if(!t.__){for(var e=we.__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 vp(){for(var t;t=za.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Gn),t.__H.__h.forEach(ao),t.__H.__h=[]}catch(e){t.__H.__h=[],Te.__e(e,t.__v)}}Te.__b=function(t){we=null,Ka&&Ka(t)},Te.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Za&&Za(t,e)},Te.__r=function(t){Ya&&Ya(t),Gt=0;var e=(we=t.__c).__H;e&&(so===we?(e.__h=[],we.__h=[],e.__.forEach(function(i){i.__N&&(i.__=i.__N),i.u=i.__N=void 0})):(e.__h.forEach(Gn),e.__h.forEach(ao),e.__h=[],Gt=0)),so=we},Te.diffed=function(t){Xa&&Xa(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(za.push(e)!==1&&qa===Te.requestAnimationFrame||((qa=Te.requestAnimationFrame)||_p)(vp)),e.__H.__.forEach(function(i){i.u&&(i.__H=i.u),i.u=void 0})),so=we=null},Te.__c=function(t,e){e.some(function(i){try{i.__h.forEach(Gn),i.__h=i.__h.filter(function(n){return!n.__||ao(n)})}catch(n){e.some(function(s){s.__h&&(s.__h=[])}),e=[],Te.__e(n,i.__v)}}),Ja&&Ja(t,e)},Te.unmount=function(t){Qa&&Qa(t);var e,i=t.__c;i&&i.__H&&(i.__H.__.forEach(function(n){try{Gn(n)}catch(s){e=s}}),i.__H=void 0,e&&Te.__e(e,i.__v))};var tl=typeof requestAnimationFrame=="function";function _p(t){var e,i=function(){clearTimeout(n),tl&&cancelAnimationFrame(e),setTimeout(t)},n=setTimeout(i,35);tl&&(e=requestAnimationFrame(i))}function Gn(t){var e=we,i=t.__c;typeof i=="function"&&(t.__c=void 0,i()),we=e}function ao(t){var e=we;t.__c=t.__(),we=e}function lo(t,e){return!t||t.length!==e.length||e.some(function(i,n){return i!==t[n]})}function il(t,e){return typeof e=="function"?e(t):e}const nn={},nl=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,sl=t=>"init"in t,co=t=>!!t.write,ol=t=>"v"in t||"e"in t,qn=t=>{if("e"in t)throw t.e;if((nn?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},zn=new WeakMap,rl=t=>{var e;return Kn(t)&&!!((e=zn.get(t))!=null&&e[0])},yp=t=>{const e=zn.get(t);e!=null&&e[0]&&(e[0]=!1,e[1].forEach(i=>i()))},al=(t,e)=>{let i=zn.get(t);if(!i){i=[!0,new Set],zn.set(t,i);const n=()=>{i[0]=!1};t.then(n,n)}i[1].add(e)},Kn=t=>typeof(t==null?void 0:t.then)=="function",ll=(t,e,i)=>{i.p.has(t)||(i.p.add(t),e.then(()=>{i.p.delete(t)},()=>{i.p.delete(t)}))},uo=(t,e,i)=>{const n=i(t),s="v"in n,o=n.v;if(Kn(e))for(const r of n.d.keys())ll(t,e,i(r));n.v=e,delete n.e,(!s||!Object.is(o,n.v))&&(++n.n,Kn(o)&&yp(o))},cl=(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},bp=()=>{const t=new Set,e=()=>{t.forEach(i=>i())};return e.add=i=>(t.add(i),()=>{t.delete(i)}),e},ho=()=>{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},wp=t=>(t.c||(t.c=ho()),t.m||(t.m=ho()),t.u||(t.u=ho()),t.f||(t.f=bp()),t),Sp=Symbol(),dl=(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 m;return(m=h.unstable_onInit)==null?void 0:m.call(h,p)},u=(h,p)=>{var m;return(m=h.onMount)==null?void 0:m.call(h,p)},...d)=>{const h=d[0]||(E=>{if((nn?"production":void 0)!=="production"&&!E)throw new Error("Atom is undefined or null");let k=t.get(E);return k||(k={d:new Map,p:new Set,n:0},t.set(E,k),c==null||c(E,N)),k}),p=d[1]||(()=>{const E=[],k=f=>{try{f()}catch(_){E.push(_)}};do{r.f&&k(r.f);const f=new Set,_=f.add.bind(f);n.forEach(g=>{var S;return(S=e.get(g))==null?void 0:S.l.forEach(_)}),n.clear(),o.forEach(_),o.clear(),s.forEach(_),s.clear(),f.forEach(k),n.size&&m()}while(n.size||o.size||s.size);if(E.length)throw new AggregateError(E)}),m=d[2]||(()=>{const E=[],k=new WeakSet,f=new WeakSet,_=Array.from(n);for(;_.length;){const g=_[_.length-1],S=h(g);if(f.has(g)){_.pop();continue}if(k.has(g)){if(i.get(g)===S.n)E.push([g,S]);else if((nn?"production":void 0)!=="production"&&i.has(g))throw new Error("[Bug] invalidated atom exists");f.add(g),_.pop();continue}k.add(g);for(const I of cl(g,S,e))k.has(I)||_.push(I)}for(let g=E.length-1;g>=0;--g){const[S,I]=E[g];let M=!1;for(const R of I.d.keys())if(R!==S&&n.has(R)){M=!0;break}M&&(v(S),C(S)),i.delete(S)}}),v=d[3]||(E=>{var k;const f=h(E);if(ol(f)&&(e.has(E)&&i.get(E)!==f.n||Array.from(f.d).every(([O,L])=>v(O).n===L)))return f;f.d.clear();let _=!0;const g=()=>{e.has(E)&&(C(E),m(),p())},S=O=>{var L;if(nl(E,O)){const $=h(O);if(!ol($))if(sl(O))uo(O,O.init,h);else throw new Error("no atom init");return qn($)}const V=v(O);try{return qn(V)}finally{f.d.set(O,V.n),rl(f.v)&&ll(E,f.v,V),(L=e.get(O))==null||L.t.add(E),_||g()}};let I,M;const R={get signal(){return I||(I=new AbortController),I.signal},get setSelf(){return(nn?"production":void 0)!=="production"&&!co(E)&&console.warn("setSelf function cannot be used with read-only atom"),!M&&co(E)&&(M=(...O)=>{if((nn?"production":void 0)!=="production"&&_&&console.warn("setSelf function cannot be called in sync"),!_)try{return y(E,...O)}finally{m(),p()}}),M}},P=f.n;try{const O=a(E,S,R);return uo(E,O,h),Kn(O)&&(al(O,()=>I==null?void 0:I.abort()),O.then(g,g)),f}catch(O){return delete f.v,f.e=O,++f.n,f}finally{_=!1,P!==f.n&&i.get(E)===P&&(i.set(E,f.n),n.add(E),(k=r.c)==null||k.call(r,E))}}),b=d[4]||(E=>{const k=[E];for(;k.length;){const f=k.pop(),_=h(f);for(const g of cl(f,_,e)){const S=h(g);i.set(g,S.n),k.push(g)}}}),y=d[5]||((E,...k)=>{let f=!0;const _=S=>qn(v(S)),g=(S,...I)=>{var M;const R=h(S);try{if(nl(E,S)){if(!sl(S))throw new Error("atom not writable");const P=R.n,O=I[0];uo(S,O,h),C(S),P!==R.n&&(n.add(S),(M=r.c)==null||M.call(r,S),b(S));return}else return y(S,...I)}finally{f||(m(),p())}};try{return l(E,_,g,...k)}finally{f=!1}}),C=d[6]||(E=>{var k;const f=h(E),_=e.get(E);if(_&&!rl(f.v)){for(const[g,S]of f.d)if(!_.d.has(g)){const I=h(g);T(g).t.add(E),_.d.add(g),S!==I.n&&(n.add(g),(k=r.c)==null||k.call(r,g),b(g))}for(const g of _.d||[])if(!f.d.has(g)){_.d.delete(g);const S=A(g);S==null||S.t.delete(E)}}}),T=d[7]||(E=>{var k;const f=h(E);let _=e.get(E);if(!_){v(E);for(const g of f.d.keys())T(g).t.add(E);if(_={l:new Set,d:new Set(f.d.keys()),t:new Set},e.set(E,_),(k=r.m)==null||k.call(r,E),co(E)){const g=()=>{let S=!0;const I=(...M)=>{try{return y(E,...M)}finally{S||(m(),p())}};try{const M=u(E,I);M&&(_.u=()=>{S=!0;try{M()}finally{S=!1}})}finally{S=!1}};s.add(g)}}return _}),A=d[8]||(E=>{var k;const f=h(E);let _=e.get(E);if(_&&!_.l.size&&!Array.from(_.t).some(g=>{var S;return(S=e.get(g))==null?void 0:S.d.has(E)})){_.u&&o.add(_.u),_=void 0,e.delete(E),(k=r.u)==null||k.call(r,E);for(const g of f.d.keys()){const S=A(g);S==null||S.t.delete(E)}return}return _}),x=[t,e,i,n,s,o,r,a,l,c,u,h,p,m,v,b,y,C,T,A],N={get:E=>qn(v(E)),set:(E,...k)=>{try{return y(E,...k)}finally{m(),p()}},sub:(E,k)=>{const _=T(E).l;return _.add(k),p(),()=>{_.delete(k),A(E),p()}}};return Object.defineProperty(N,Sp,{value:x}),N},Cp=wp,ul=al,fo={};let Tp=0;function Yn(t,e){const i=`atom${++Tp}`,n={toString(){return(fo?"production":void 0)!=="production"&&this.debugLabel?i+":"+this.debugLabel:i}};return typeof t=="function"?n.read=t:(n.init=t,n.read=kp,n.write=Ep),n}function kp(t){return t(this)}function Ep(t,e,i){return e(this,typeof i=="function"?i(t(this)):i)}const Ip=()=>{let t=0;const e=Cp({}),i=new WeakMap,n=new WeakMap,s=dl(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 Ap(){return(fo?"production":void 0)!=="production"?Ip():dl()}let sn;function Rp(){return sn||(sn=Ap(),(fo?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=sn),globalThis.__JOTAI_DEFAULT_STORE__!==sn&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),sn}function hl(t,e){for(var i in e)t[i]=e[i];return t}function fl(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 pl=oo;function gl(t,e){this.props=t,this.context=e}(gl.prototype=new bt).isPureReactComponent=!0,gl.prototype.shouldComponentUpdate=function(t,e){return fl(this.props,t)||fl(this.state,e)};var ml=J.__b;J.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ml&&ml(t)};var xp=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Dp(t){function e(i){var n=hl({},i);return delete n.ref,t(n,i.ref||null)}return e.$$typeof=xp,e.render=e,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var vl=function(t,e){return t==null?null:kt(kt(t).map(e))},Lp={map:vl,forEach:vl,count:function(t){return t?kt(t).length:0},only:function(t){var e=kt(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:kt},Mp=J.__e;J.__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)}Mp(t,e,i,n)};var _l=J.unmount;function yl(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=hl({},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 yl(n,e,i)})),t}function bl(t,e,i){return t&&i&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(n){return bl(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 po(){this.__u=0,this.o=null,this.__b=null}function wl(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Xn(){this.i=null,this.l=null}J.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),_l&&_l(t)},(po.prototype=new bt).__c=function(t,e){var i=e.__c,n=this;n.o==null&&(n.o=[]),n.o.push(i);var s=wl(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]=bl(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)},po.prototype.componentWillUnmount=function(){this.o=[]},po.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]=yl(this.__b,i,n.__O=n.__P)}this.__b=null}var s=e.__a&&ct(yt,null,t.fallback);return s&&(s.__u&=-33),[ct(yt,null,e.__a?null:t.children),s]};var Sl=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]}};(Xn.prototype=new bt).__a=function(t){var e=this,i=wl(e.__v),n=e.l.get(t);return n[0]++,function(s){var o=function(){e.props.revealOrder?(n.push(s),Sl(e,t,n)):s()};i?i(o):o()}},Xn.prototype.render=function(t){this.i=null,this.l=new Map;var e=kt(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},Xn.prototype.componentDidUpdate=Xn.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,i){Sl(t,i,e)})};var Cl=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Op=/^(?: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]/,Pp=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Np=/[A-Z0-9]/g,Fp=typeof document<"u",Up=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};bt.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(bt.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var Tl=J.event;function Bp(){}function Vp(){return this.cancelBubble}function $p(){return this.defaultPrevented}J.event=function(t){return Tl&&(t=Tl(t)),t.persist=Bp,t.isPropagationStopped=Vp,t.isDefaultPrevented=$p,t.nativeEvent=t};var jp={enumerable:!1,configurable:!0,get:function(){return this.class}},kl=J.vnode;J.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||Fp&&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"||Up(i.type)?l==="onfocus"?r="onfocusin":l==="onblur"?r="onfocusout":Pp.test(r)&&(r=l):l=r="oninput":o&&Op.test(r)?r=r.replace(Np,"-$&").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=kt(i.children).forEach(function(c){c.props.selected=s.value.indexOf(c.props.value)!=-1})),n=="select"&&s.defaultValue!=null&&(s.value=kt(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",jp)):(i.className&&!i.class||i.class&&i.className)&&(s.class=s.className=i.className),e.props=s}(t),t.$$typeof=Cl,kl&&kl(t)};var El=J.__r;J.__r=function(t){El&&El(t),t.__c};var Il=J.diffed;J.diffed=function(t){Il&&Il(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 Al(t){return!!t&&t.$$typeof===Cl}function Hp(t){return Al(t)?io.apply(null,arguments):t}var Rl={};const Wp={},Gp=Ft(void 0);function xl(t){return Fe(Gp)||Rp()}const go=t=>typeof(t==null?void 0:t.then)=="function",mo=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},qp=Rl.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(mo(t),t)}),vo=new WeakMap,Dl=(t,e)=>{let i=vo.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();go(c)?(vo.set(c,i),o=c,c.then(r(c),a(c)),ul(c,l)):n(c)}catch(c){s(c)}};t.then(r(t),a(t)),ul(t,l)}),vo.set(t,i)),i};function _o(t,e){const{delay:i,unstable_promiseStatus:n=!Rl.use}={},s=xl(),[[o,r,a],l]=el(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)),Le(()=>{const u=s.sub(t,()=>{if(n)try{const d=s.get(t);go(d)&&mo(Dl(d,()=>s.get(t)))}catch{}if(typeof i=="number"){setTimeout(l,i);return}l()});return l(),u},[s,t,i,n]),mp(c),go(c)){const u=Dl(c,()=>s.get(t));return n&&mo(u),qp(u)}return c}function Jn(t,e){const i=xl();return Ne((...s)=>{if((Wp?"production":void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return i.set(t,...s)},[i,t])}function Ll(t,e){return[_o(t),Jn(t)]}const yo=Ft({});function Qn(t){const e=ce(null);return e.current===null&&(e.current=t()),e.current}const bo=typeof window<"u",Ml=bo?oo:Le,Zn=Ft(null);function wo(t,e){t.indexOf(e)===-1&&t.push(e)}function So(t,e){const i=t.indexOf(e);i>-1&&t.splice(i,1)}const Ut=(t,e,i)=>i>e?e:i<t?t:i;let Co=()=>{};const Bt={},Ol=t=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(t);function Pl(t){return typeof t=="object"&&t!==null}const Nl=t=>/^0[^.\s]+$/u.test(t);function To(t){let e;return()=>(e===void 0&&(e=t()),e)}const ut=t=>t,zp=(t,e)=>i=>e(t(i)),on=(...t)=>t.reduce(zp),rn=(t,e,i)=>{const n=e-t;return n===0?1:(i-t)/n};class ko{constructor(){this.subscriptions=[]}add(e){return wo(this.subscriptions,e),()=>So(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 Et=t=>t*1e3,It=t=>t/1e3;function Fl(t,e){return e?t*(1e3/e):0}const Ul=(t,e,i)=>(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t,Kp=1e-7,Yp=12;function Xp(t,e,i,n,s){let o,r,a=0;do r=e+(i-e)/2,o=Ul(r,n,s)-t,o>0?i=r:e=r;while(Math.abs(o)>Kp&&++a<Yp);return r}function an(t,e,i,n){if(t===e&&i===n)return ut;const s=o=>Xp(o,0,1,t,i);return o=>o===0||o===1?o:Ul(s(o),e,n)}const Bl=t=>e=>e<=.5?t(2*e)/2:(2-t(2*(1-e)))/2,Vl=t=>e=>1-t(1-e),$l=an(.33,1.53,.69,.99),Eo=Vl($l),jl=Bl(Eo),Hl=t=>(t*=2)<1?.5*Eo(t):.5*(2-Math.pow(2,-10*(t-1))),Io=t=>1-Math.sin(Math.acos(t)),Wl=Vl(Io),Gl=Bl(Io),Jp=an(.42,0,1,1),Qp=an(0,0,.58,1),ql=an(.42,0,.58,1),Zp=t=>Array.isArray(t)&&typeof t[0]!="number",zl=t=>Array.isArray(t)&&typeof t[0]=="number",eg={linear:ut,easeIn:Jp,easeInOut:ql,easeOut:Qp,circIn:Io,circInOut:Gl,circOut:Wl,backIn:Eo,backInOut:jl,backOut:$l,anticipate:Hl},tg=t=>typeof t=="string",Kl=t=>{if(zl(t)){Co(t.length===4);const[e,i,n,s]=t;return an(e,i,n,s)}else if(tg(t))return eg[t];return t},es=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],Yl={value:null};function ig(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 ng=40;function Xl(t,e){let i=!1,n=!0;const s={delta:0,timestamp:0,isProcessing:!1},o=()=>i=!0,r=es.reduce((T,A)=>(T[A]=ig(o,e?A:void 0),T),{}),{setup:a,read:l,resolveKeyframes:c,preUpdate:u,update:d,preRender:h,render:p,postRender:m}=r,v=()=>{const T=Bt.useManualTiming?s.timestamp:performance.now();i=!1,Bt.useManualTiming||(s.delta=n?1e3/60:Math.max(Math.min(T-s.timestamp,ng),1)),s.timestamp=T,s.isProcessing=!0,a.process(s),l.process(s),c.process(s),u.process(s),d.process(s),h.process(s),p.process(s),m.process(s),s.isProcessing=!1,i&&e&&(n=!1,t(v))},b=()=>{i=!0,n=!0,s.isProcessing||t(v)};return{schedule:es.reduce((T,A)=>{const x=r[A];return T[A]=(N,E=!1,k=!1)=>(i||b(),x.schedule(N,E,k)),T},{}),cancel:T=>{for(let A=0;A<es.length;A++)r[es[A]].cancel(T)},state:s,steps:r}}const{schedule:Ce,cancel:qt,state:$e,steps:Ao}=Xl(typeof requestAnimationFrame<"u"?requestAnimationFrame:ut,!0);let ts;function sg(){ts=void 0}const tt={now:()=>(ts===void 0&&tt.set($e.isProcessing||Bt.useManualTiming?$e.timestamp:performance.now()),ts),set:t=>{ts=t,queueMicrotask(sg)}},Jl=t=>e=>typeof e=="string"&&e.startsWith(t),Ro=Jl("--"),og=Jl("var(--"),xo=t=>og(t)?rg.test(t.split("/*")[0].trim()):!1,rg=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,Ei={test:t=>typeof t=="number",parse:parseFloat,transform:t=>t},ln={...Ei,transform:t=>Ut(0,1,t)},is={...Ei,default:1},cn=t=>Math.round(t*1e5)/1e5,Do=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function ag(t){return t==null}const lg=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Lo=(t,e)=>i=>!!(typeof i=="string"&&lg.test(i)&&i.startsWith(t)||e&&!ag(i)&&Object.prototype.hasOwnProperty.call(i,e)),Ql=(t,e,i)=>n=>{if(typeof n!="string")return n;const[s,o,r,a]=n.match(Do);return{[t]:parseFloat(s),[e]:parseFloat(o),[i]:parseFloat(r),alpha:a!==void 0?parseFloat(a):1}},cg=t=>Ut(0,255,t),Mo={...Ei,transform:t=>Math.round(cg(t))},oi={test:Lo("rgb","red"),parse:Ql("red","green","blue"),transform:({red:t,green:e,blue:i,alpha:n=1})=>"rgba("+Mo.transform(t)+", "+Mo.transform(e)+", "+Mo.transform(i)+", "+cn(ln.transform(n))+")"};function dg(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 Oo={test:Lo("#"),parse:dg,transform:oi.transform},dn=t=>({test:e=>typeof e=="string"&&e.endsWith(t)&&e.split(" ").length===1,parse:parseFloat,transform:e=>`${e}${t}`}),zt=dn("deg"),At=dn("%"),Q=dn("px"),ug=dn("vh"),hg=dn("vw"),Zl={...At,parse:t=>At.parse(t)/100,transform:t=>At.transform(t*100)},Ii={test:Lo("hsl","hue"),parse:Ql("hue","saturation","lightness"),transform:({hue:t,saturation:e,lightness:i,alpha:n=1})=>"hsla("+Math.round(t)+", "+At.transform(cn(e))+", "+At.transform(cn(i))+", "+cn(ln.transform(n))+")"},Me={test:t=>oi.test(t)||Oo.test(t)||Ii.test(t),parse:t=>oi.test(t)?oi.parse(t):Ii.test(t)?Ii.parse(t):Oo.parse(t),transform:t=>typeof t=="string"?t:t.hasOwnProperty("red")?oi.transform(t):Ii.transform(t),getAnimatableNone:t=>{const e=Me.parse(t);return e.alpha=0,Me.transform(e)}},fg=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function pg(t){var e,i;return isNaN(t)&&typeof t=="string"&&(((e=t.match(Do))==null?void 0:e.length)||0)+(((i=t.match(fg))==null?void 0:i.length)||0)>0}const ec="number",tc="color",gg="var",mg="var(",ic="${}",vg=/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 un(t){const e=t.toString(),i=[],n={color:[],number:[],var:[]},s=[];let o=0;const a=e.replace(vg,l=>(Me.test(l)?(n.color.push(o),s.push(tc),i.push(Me.parse(l))):l.startsWith(mg)?(n.var.push(o),s.push(gg),i.push(l)):(n.number.push(o),s.push(ec),i.push(parseFloat(l))),++o,ic)).split(ic);return{values:i,split:a,indexes:n,types:s}}function nc(t){return un(t).values}function sc(t){const{split:e,types:i}=un(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===ec?o+=cn(s[r]):a===tc?o+=Me.transform(s[r]):o+=s[r]}return o}}const _g=t=>typeof t=="number"?0:Me.test(t)?Me.getAnimatableNone(t):t;function yg(t){const e=nc(t);return sc(t)(e.map(_g))}const Kt={test:pg,parse:nc,createTransformer:sc,getAnimatableNone:yg};function Po(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 bg({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=Po(l,a,t+1/3),o=Po(l,a,t),r=Po(l,a,t-1/3)}return{red:Math.round(s*255),green:Math.round(o*255),blue:Math.round(r*255),alpha:n}}function ns(t,e){return i=>i>0?e:t}const ke=(t,e,i)=>t+(e-t)*i,No=(t,e,i)=>{const n=t*t,s=i*(e*e-n)+n;return s<0?0:Math.sqrt(s)},wg=[Oo,oi,Ii],Sg=t=>wg.find(e=>e.test(t));function oc(t){const e=Sg(t);if(!e)return!1;let i=e.parse(t);return e===Ii&&(i=bg(i)),i}const rc=(t,e)=>{const i=oc(t),n=oc(e);if(!i||!n)return ns(t,e);const s={...i};return o=>(s.red=No(i.red,n.red,o),s.green=No(i.green,n.green,o),s.blue=No(i.blue,n.blue,o),s.alpha=ke(i.alpha,n.alpha,o),oi.transform(s))},Fo=new Set(["none","hidden"]);function Cg(t,e){return Fo.has(t)?i=>i<=0?t:e:i=>i>=1?e:t}function Tg(t,e){return i=>ke(t,e,i)}function Uo(t){return typeof t=="number"?Tg:typeof t=="string"?xo(t)?ns:Me.test(t)?rc:Ig:Array.isArray(t)?ac:typeof t=="object"?Me.test(t)?rc:kg:ns}function ac(t,e){const i=[...t],n=i.length,s=t.map((o,r)=>Uo(o)(o,e[r]));return o=>{for(let r=0;r<n;r++)i[r]=s[r](o);return i}}function kg(t,e){const i={...t,...e},n={};for(const s in i)t[s]!==void 0&&e[s]!==void 0&&(n[s]=Uo(t[s])(t[s],e[s]));return s=>{for(const o in n)i[o]=n[o](s);return i}}function Eg(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 Ig=(t,e)=>{const i=Kt.createTransformer(e),n=un(t),s=un(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?Fo.has(t)&&!s.values.length||Fo.has(e)&&!n.values.length?Cg(t,e):on(ac(Eg(n,s),s.values),i):ns(t,e)};function lc(t,e,i){return typeof t=="number"&&typeof e=="number"&&typeof i=="number"?ke(t,e,i):Uo(t)(t,e)}const Ag=t=>{const e=({timestamp:i})=>t(i);return{start:(i=!0)=>Ce.update(e,i),stop:()=>qt(e),now:()=>$e.isProcessing?$e.timestamp:tt.now()}},cc=(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)})`},ss=2e4;function Bo(t){let e=0;const i=50;let n=t.next(e);for(;!n.done&&e<ss;)e+=i,n=t.next(e);return e>=ss?1/0:e}function Rg(t,e=100,i){const n=i({...t,keyframes:[0,e]}),s=Math.min(Bo(n),ss);return{type:"keyframes",ease:o=>n.next(s*o).value/e,duration:It(s)}}const xg=5;function dc(t,e,i){const n=Math.max(e-xg,0);return Fl(i-t(n),e-n)}const Ie={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1},Vo=.001;function Dg({duration:t=Ie.duration,bounce:e=Ie.bounce,velocity:i=Ie.velocity,mass:n=Ie.mass}){let s,o,r=1-e;r=Ut(Ie.minDamping,Ie.maxDamping,r),t=Ut(Ie.minDuration,Ie.maxDuration,It(t)),r<1?(s=c=>{const u=c*r,d=u*t,h=u-i,p=$o(c,r),m=Math.exp(-d);return Vo-h/p*m},o=c=>{const d=c*r*t,h=d*i+i,p=Math.pow(r,2)*Math.pow(c,2)*t,m=Math.exp(-d),v=$o(Math.pow(c,2),r);return(-s(c)+Vo>0?-1:1)*((h-p)*m)/v}):(s=c=>{const u=Math.exp(-c*t),d=(c-i)*t+1;return-Vo+u*d},o=c=>{const u=Math.exp(-c*t),d=(i-c)*(t*t);return u*d});const a=5/t,l=Mg(s,o,a);if(t=Et(t),isNaN(l))return{stiffness:Ie.stiffness,damping:Ie.damping,duration:t};{const c=Math.pow(l,2)*n;return{stiffness:c,damping:r*2*Math.sqrt(n*c),duration:t}}}const Lg=12;function Mg(t,e,i){let n=i;for(let s=1;s<Lg;s++)n=n-t(n)/e(n);return n}function $o(t,e){return t*Math.sqrt(1-e*e)}const Og=["duration","bounce"],Pg=["stiffness","damping","mass"];function uc(t,e){return e.some(i=>t[i]!==void 0)}function Ng(t){let e={velocity:Ie.velocity,stiffness:Ie.stiffness,damping:Ie.damping,mass:Ie.mass,isResolvedFromDuration:!1,...t};if(!uc(t,Pg)&&uc(t,Og))if(t.visualDuration){const i=t.visualDuration,n=2*Math.PI/(i*1.2),s=n*n,o=2*Ut(.05,1,1-(t.bounce||0))*Math.sqrt(s);e={...e,mass:Ie.mass,stiffness:s,damping:o}}else{const i=Dg(t);e={...e,...i,mass:Ie.mass},e.isResolvedFromDuration=!0}return e}function os(t=Ie.visualDuration,e=Ie.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}=Ng({...i,velocity:-It(i.velocity||0)}),m=h||0,v=c/(2*Math.sqrt(l*u)),b=r-o,y=It(Math.sqrt(l/u)),C=Math.abs(b)<5;n||(n=C?Ie.restSpeed.granular:Ie.restSpeed.default),s||(s=C?Ie.restDelta.granular:Ie.restDelta.default);let T;if(v<1){const x=$o(y,v);T=N=>{const E=Math.exp(-v*y*N);return r-E*((m+v*y*b)/x*Math.sin(x*N)+b*Math.cos(x*N))}}else if(v===1)T=x=>r-Math.exp(-y*x)*(b+(m+y*b)*x);else{const x=y*Math.sqrt(v*v-1);T=N=>{const E=Math.exp(-v*y*N),k=Math.min(x*N,300);return r-E*((m+v*y*b)*Math.sinh(k)+x*b*Math.cosh(k))/x}}const A={calculatedDuration:p&&d||null,next:x=>{const N=T(x);if(p)a.done=x>=d;else{let E=x===0?m:0;v<1&&(E=x===0?Et(m):dc(T,x,N));const k=Math.abs(E)<=n,f=Math.abs(r-N)<=s;a.done=k&&f}return a.value=a.done?r:N,a},toString:()=>{const x=Math.min(Bo(A),ss),N=cc(E=>A.next(x*E).value,x,30);return x+"ms "+N},toTransition:()=>{}};return A}os.applyToOptions=t=>{const e=Rg(t,100,os);return t.ease=e.ease,t.duration=Et(e.duration),t.type="keyframes",t};function jo({keyframes:t,velocity:e=0,power:i=.8,timeConstant:n=325,bounceDamping:s=10,bounceStiffness:o=500,modifyTarget:r,min:a,max:l,restDelta:c=.5,restSpeed:u}){const d=t[0],h={done:!1,value:d},p=k=>a!==void 0&&k<a||l!==void 0&&k>l,m=k=>a===void 0?l:l===void 0||Math.abs(a-k)<Math.abs(l-k)?a:l;let v=i*e;const b=d+v,y=r===void 0?b:r(b);y!==b&&(v=y-d);const C=k=>-v*Math.exp(-k/n),T=k=>y+C(k),A=k=>{const f=C(k),_=T(k);h.done=Math.abs(f)<=c,h.value=h.done?y:_};let x,N;const E=k=>{p(h.value)&&(x=k,N=os({keyframes:[h.value,m(h.value)],velocity:dc(T,k,h.value),damping:s,stiffness:o,restDelta:c,restSpeed:u}))};return E(0),{calculatedDuration:null,next:k=>{let f=!1;return!N&&x===void 0&&(f=!0,A(k),E(k)),x!==void 0&&k>=x?N.next(k-x):(!f&&A(k),h)}}}function Fg(t,e,i){const n=[],s=i||Bt.mix||lc,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]||ut:e;a=on(l,a)}n.push(a)}return n}function Ug(t,e,{clamp:i=!0,ease:n,mixer:s}={}){const o=t.length;if(Co(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=Fg(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=rn(t[d],t[d+1],u);return a[d](h)};return i?u=>c(Ut(t[0],t[o-1],u)):c}function Bg(t,e){const i=t[t.length-1];for(let n=1;n<=e;n++){const s=rn(0,e,n);t.push(ke(i,1,s))}}function Vg(t){const e=[0];return Bg(e,t.length-1),e}function $g(t,e){return t.map(i=>i*e)}function jg(t,e){return t.map(()=>e||ql).splice(0,t.length-1)}function hn({duration:t=300,keyframes:e,times:i,ease:n="easeInOut"}){const s=Zp(n)?n.map(Kl):Kl(n),o={done:!1,value:e[0]},r=$g(i&&i.length===e.length?i:Vg(e),t),a=Ug(r,e,{ease:Array.isArray(s)?s:jg(e,s)});return{calculatedDuration:t,next:l=>(o.value=a(l),o.done=l>=t,o)}}const Hg=t=>t!==null;function Ho(t,{repeat:e,repeatType:i="loop"},n,s=1){const o=t.filter(Hg),a=s<0||e&&i!=="loop"&&e%2===1?0:o.length-1;return!a||n===void 0?o[a]:n}const Wg={decay:jo,inertia:jo,tween:hn,keyframes:hn,spring:os};function hc(t){typeof t.type=="string"&&(t.type=Wg[t.type])}class Wo{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(e=>{this.resolve=e})}notifyFinished(){this.resolve()}then(e,i){return this.finished.then(e,i)}}const Gg=t=>t/100;class Go extends Wo{constructor(e){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.stop=()=>{var n,s;const{motionValue:i}=this.options;i&&i.updatedAt!==tt.now()&&this.tick(tt.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;hc(e);const{type:i=hn,repeat:n=0,repeatDelay:s=0,repeatType:o,velocity:r=0}=e;let{keyframes:a}=e;const l=i||hn;l!==hn&&typeof a[0]!="number"&&(this.mixKeyframes=on(Gg,lc(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=Bo(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:m,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 y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),C=this.playbackSpeed>=0?y<0:y>s;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=s);let T=this.currentTime,A=n;if(d){const k=Math.min(this.currentTime,s)/a;let f=Math.floor(k),_=k%1;!_&&k>=1&&(_=1),_===1&&f--,f=Math.min(f,d+1),!!(f%2)&&(h==="reverse"?(_=1-_,p&&(_-=p/a)):h==="mirror"&&(A=r)),T=Ut(0,1,_)*a}const x=C?{done:!1,value:u[0]}:A.next(T);o&&(x.value=o(x.value));let{done:N}=x;!C&&l!==null&&(N=this.playbackSpeed>=0?this.currentTime>=s:this.currentTime<=0);const E=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return E&&m!==jo&&(x.value=Ho(u,this.options,b,this.speed)),v&&v(x.value),E&&this.finish(),x}then(e,i){return this.finished.then(e,i)}get duration(){return It(this.calculatedDuration)}get time(){return It(this.currentTime)}set time(e){var i;e=Et(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(tt.now());const i=this.playbackSpeed!==e;this.playbackSpeed=e,i&&(this.time=It(this.currentTime))}play(){var s,o;if(this.isStopped)return;const{driver:e=Ag,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(tt.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 qg(t){for(let e=1;e<t.length;e++)t[e]??(t[e]=t[e-1])}const ri=t=>t*180/Math.PI,qo=t=>{const e=ri(Math.atan2(t[1],t[0]));return zo(e)},zg={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:t=>(Math.abs(t[0])+Math.abs(t[3]))/2,rotate:qo,rotateZ:qo,skewX:t=>ri(Math.atan(t[1])),skewY:t=>ri(Math.atan(t[2])),skew:t=>(Math.abs(t[1])+Math.abs(t[2]))/2},zo=t=>(t=t%360,t<0&&(t+=360),t),fc=qo,pc=t=>Math.sqrt(t[0]*t[0]+t[1]*t[1]),gc=t=>Math.sqrt(t[4]*t[4]+t[5]*t[5]),Kg={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:pc,scaleY:gc,scale:t=>(pc(t)+gc(t))/2,rotateX:t=>zo(ri(Math.atan2(t[6],t[5]))),rotateY:t=>zo(ri(Math.atan2(-t[2],t[0]))),rotateZ:fc,rotate:fc,skewX:t=>ri(Math.atan(t[4])),skewY:t=>ri(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 Yo(t,e){if(!t||t==="none")return Ko(e);const i=t.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let n,s;if(i)n=Kg,s=i;else{const a=t.match(/^matrix\(([-\d.e\s,]+)\)$/u);n=zg,s=a}if(!s)return Ko(e);const o=n[e],r=s[1].split(",").map(Xg);return typeof o=="function"?o(r):r[o]}const Yg=(t,e)=>{const{transform:i="none"}=getComputedStyle(t);return Yo(i,e)};function Xg(t){return parseFloat(t.trim())}const Ai=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Ri=new Set(Ai),mc=t=>t===Ei||t===Q,Jg=new Set(["x","y","z"]),Qg=Ai.filter(t=>!Jg.has(t));function Zg(t){const e=[];return Qg.forEach(i=>{const n=t.getValue(i);n!==void 0&&(e.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),e}const ai={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})=>Yo(e,"x"),y:(t,{transform:e})=>Yo(e,"y")};ai.translateX=ai.x,ai.translateY=ai.y;const li=new Set;let Xo=!1,Jo=!1,Qo=!1;function vc(){if(Jo){const t=Array.from(li).filter(n=>n.needsMeasurement),e=new Set(t.map(n=>n.element)),i=new Map;e.forEach(n=>{const s=Zg(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)})}Jo=!1,Xo=!1,li.forEach(t=>t.complete(Qo)),li.clear()}function _c(){li.forEach(t=>{t.readKeyframes(),t.needsMeasurement&&(Jo=!0)})}function em(){Qo=!0,_c(),vc(),Qo=!1}class Zo{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?(li.add(this),Xo||(Xo=!0,Ce.read(_c),Ce.resolveKeyframes(vc))):(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])}qg(e)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(e=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,e),li.delete(this)}cancel(){this.state==="scheduled"&&(li.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const tm=t=>t.startsWith("--");function im(t,e,i){tm(e)?t.style.setProperty(e,i):t.style[e]=i}const nm=To(()=>window.ScrollTimeline!==void 0),sm={};function om(t,e){const i=To(t);return()=>sm[e]??i()}const yc=om(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),fn=([t,e,i,n])=>`cubic-bezier(${t}, ${e}, ${i}, ${n})`,bc={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:fn([0,.65,.55,1]),circOut:fn([.55,0,1,.45]),backIn:fn([.31,.01,.66,-.59]),backOut:fn([.33,1.53,.69,.99])};function wc(t,e){if(t)return typeof t=="function"?yc()?cc(t,e):"ease-out":zl(t)?fn(t):Array.isArray(t)?t.map(i=>wc(i,e)||bc.easeOut):bc[t]}function rm(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=wc(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 Sc(t){return typeof t=="function"&&"applyToOptions"in t}function am({type:t,...e}){return Sc(t)&&yc()?t.applyToOptions(e):(e.duration??(e.duration=300),e.ease??(e.ease="easeOut"),e)}class lm extends Wo{constructor(e){if(super(),this.finishedTime=null,this.isStopped=!1,!e)return;const{element:i,name:n,keyframes:s,pseudoElement:o,allowFlatten:r=!1,finalKeyframe:a,onComplete:l}=e;this.isPseudoElement=!!o,this.allowFlatten=r,this.options=e,Co(typeof e.type!="string");const c=am(e);this.animation=rm(i,n,s,c,o),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!o){const u=Ho(s,this.options,a,this.speed);this.updateMotionValue?this.updateMotionValue(u):im(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 It(Number(e))}get time(){return It(Number(this.animation.currentTime)||0)}set time(e){this.finishedTime=null,this.animation.currentTime=Et(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&&nm()?(this.animation.timeline=e,ut):i(this)}}const Cc={anticipate:Hl,backInOut:jl,circInOut:Gl};function cm(t){return t in Cc}function dm(t){typeof t.ease=="string"&&cm(t.ease)&&(t.ease=Cc[t.ease])}const Tc=10;class um extends lm{constructor(e){dm(e),hc(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 Go({...r,autoplay:!1}),l=Et(this.finishedTime??this.time);i.setWithVelocity(a.sample(l-Tc).value,a.sample(l).value,Tc),a.stop()}}const kc=(t,e)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(Kt.test(t)||t==="0")&&!t.startsWith("url("));function hm(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 fm(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=kc(s,e),a=kc(o,e);return!r||!a?!1:hm(t)||(i==="spring"||Sc(i))&&n}function er(t){return Pl(t)&&"offsetHeight"in t}const pm=new Set(["opacity","clipPath","filter","transform"]),gm=To(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function mm(t){var c;const{motionValue:e,name:i,repeatDelay:n,repeatType:s,damping:o,type:r}=t;if(!er((c=e==null?void 0:e.owner)==null?void 0:c.current))return!1;const{onUpdate:a,transformTemplate:l}=e.owner.getProps();return gm()&&i&&pm.has(i)&&(i!=="transform"||!l)&&!a&&!n&&s!=="mirror"&&o!==0&&r!=="inertia"}const vm=40;class _m extends Wo{constructor({autoplay:e=!0,delay:i=0,type:n="keyframes",repeat:s=0,repeatDelay:o=0,repeatType:r="loop",keyframes:a,name:l,motionValue:c,element:u,...d}){var m;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=tt.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)||Zo;this.keyframeResolver=new p(a,(v,b,y)=>this.onKeyframesResolved(v,b,h,!y),l,c,u),(m=this.keyframeResolver)==null||m.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=tt.now(),fm(e,o,r,a)||((Bt.instantAnimations||!l)&&(u==null||u(Ho(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>vm?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:i,...n,keyframes:e},p=!c&&mm(h)?new um({...h,element:h.motionValue.owner.current}):new Go(h);p.finished.then(()=>this.notifyFinished()).catch(ut),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(),em()),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 ym=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function bm(t){const e=ym.exec(t);if(!e)return[,];const[,i,n,s]=e;return[`--${i??n}`,s]}function Ec(t,e,i=1){const[n,s]=bm(t);if(!n)return;const o=window.getComputedStyle(e).getPropertyValue(n);if(o){const r=o.trim();return Ol(r)?parseFloat(r):r}return xo(s)?Ec(s,e,i+1):s}function tr(t,e){return(t==null?void 0:t[e])??(t==null?void 0:t.default)??t}const Ic=new Set(["width","height","top","left","right","bottom",...Ai]),wm={test:t=>t==="auto",parse:t=>t},Ac=t=>e=>e.test(t),Rc=[Ei,Q,At,zt,hg,ug,wm],xc=t=>Rc.find(Ac(t));function Sm(t){return typeof t=="number"?t===0:t!==null?t==="none"||t==="0"||Nl(t):!0}const Cm=new Set(["brightness","contrast","saturate","opacity"]);function Tm(t){const[e,i]=t.slice(0,-1).split("(");if(e==="drop-shadow")return t;const[n]=i.match(Do)||[];if(!n)return t;const s=i.replace(n,"");let o=Cm.has(e)?1:0;return n!==i&&(o*=100),e+"("+o+s+")"}const km=/\b([a-z-]*)\(.*?\)/gu,ir={...Kt,getAnimatableNone:t=>{const e=t.match(km);return e?e.map(Tm).join(" "):t}},Dc={...Ei,transform:Math.round},nr={borderWidth:Q,borderTopWidth:Q,borderRightWidth:Q,borderBottomWidth:Q,borderLeftWidth:Q,borderRadius:Q,radius:Q,borderTopLeftRadius:Q,borderTopRightRadius:Q,borderBottomRightRadius:Q,borderBottomLeftRadius:Q,width:Q,maxWidth:Q,height:Q,maxHeight:Q,top:Q,right:Q,bottom:Q,left:Q,padding:Q,paddingTop:Q,paddingRight:Q,paddingBottom:Q,paddingLeft:Q,margin:Q,marginTop:Q,marginRight:Q,marginBottom:Q,marginLeft:Q,backgroundPositionX:Q,backgroundPositionY:Q,...{rotate:zt,rotateX:zt,rotateY:zt,rotateZ:zt,scale:is,scaleX:is,scaleY:is,scaleZ:is,skew:zt,skewX:zt,skewY:zt,distance:Q,translateX:Q,translateY:Q,translateZ:Q,x:Q,y:Q,z:Q,perspective:Q,transformPerspective:Q,opacity:ln,originX:Zl,originY:Zl,originZ:Q},zIndex:Dc,fillOpacity:ln,strokeOpacity:ln,numOctaves:Dc},Em={...nr,color:Me,backgroundColor:Me,outlineColor:Me,fill:Me,stroke:Me,borderColor:Me,borderTopColor:Me,borderRightColor:Me,borderBottomColor:Me,borderLeftColor:Me,filter:ir,WebkitFilter:ir},Lc=t=>Em[t];function Mc(t,e){let i=Lc(t);return i!==ir&&(i=Kt),i.getAnimatableNone?i.getAnimatableNone(e):void 0}const Im=new Set(["auto","none","0"]);function Am(t,e,i){let n=0,s;for(;n<t.length&&!s;){const o=t[n];typeof o=="string"&&!Im.has(o)&&un(o).values.length&&(s=t[n]),n++}if(s&&i)for(const o of e)t[o]=Mc(i,s)}class Rm extends Zo{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(),xo(c))){const u=Ec(c,i.current);u!==void 0&&(e[l]=u),l===e.length-1&&(this.finalKeyframe=c)}}if(this.resolveNoneKeyframes(),!Ic.has(n)||e.length!==2)return;const[s,o]=e,r=xc(s),a=xc(o);if(r!==a)if(mc(r)&&mc(a))for(let l=0;l<e.length;l++){const c=e[l];typeof c=="string"&&(e[l]=parseFloat(c))}else ai[n]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:e,name:i}=this,n=[];for(let s=0;s<e.length;s++)(e[s]===null||Sm(e[s]))&&n.push(s);n.length&&Am(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=ai[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]=ai[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 xm(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 Oc=(t,e)=>e&&typeof t=="number"?e.transform(t):t,Pc=30,Dm=t=>!isNaN(parseFloat(t));class Lm{constructor(e,i={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=(n,s=!0)=>{var r,a;const o=tt.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=tt.now(),this.canTrackVelocity===null&&e!==void 0&&(this.canTrackVelocity=Dm(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 ko);const n=this.events[e].add(i);return e==="change"?()=>{n(),Ce.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=tt.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||e-this.updatedAt>Pc)return 0;const i=Math.min(this.updatedAt-this.prevUpdatedAt,Pc);return Fl(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 xi(t,e){return new Lm(t,e)}const{schedule:sr}=Xl(queueMicrotask,!1),wt={x:!1,y:!1};function Nc(){return wt.x||wt.y}function Mm(t){return t==="x"||t==="y"?wt[t]?null:(wt[t]=!0,()=>{wt[t]=!1}):wt.x||wt.y?null:(wt.x=wt.y=!0,()=>{wt.x=wt.y=!1})}function Fc(t,e){const i=xm(t),n=new AbortController,s={passive:!0,...e,signal:n.signal};return[i,s,()=>n.abort()]}function Uc(t){return!(t.pointerType==="touch"||Nc())}function Om(t,e,i={}){const[n,s,o]=Fc(t,i),r=a=>{if(!Uc(a))return;const{target:l}=a,c=e(l,a);if(typeof c!="function"||!l)return;const u=d=>{Uc(d)&&(c(d),l.removeEventListener("pointerleave",u))};l.addEventListener("pointerleave",u,s)};return n.forEach(a=>{a.addEventListener("pointerenter",r,s)}),o}const Bc=(t,e)=>e?t===e?!0:Bc(t,e.parentElement):!1,or=t=>t.pointerType==="mouse"?typeof t.button!="number"||t.button<=0:t.isPrimary!==!1,Pm=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function Nm(t){return Pm.has(t.tagName)||t.tabIndex!==-1}const rs=new WeakSet;function Vc(t){return e=>{e.key==="Enter"&&t(e)}}function rr(t,e){t.dispatchEvent(new PointerEvent("pointer"+e,{isPrimary:!0,bubbles:!0}))}const Fm=(t,e)=>{const i=t.currentTarget;if(!i)return;const n=Vc(()=>{if(rs.has(i))return;rr(i,"down");const s=Vc(()=>{rr(i,"up")}),o=()=>rr(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 $c(t){return or(t)&&!Nc()}function Um(t,e,i={}){const[n,s,o]=Fc(t,i),r=a=>{const l=a.currentTarget;if(!$c(a))return;rs.add(l);const c=e(l,a),u=(p,m)=>{window.removeEventListener("pointerup",d),window.removeEventListener("pointercancel",h),rs.has(l)&&rs.delete(l),$c(p)&&typeof c=="function"&&c(p,{success:m})},d=p=>{u(p,l===window||l===document||i.useGlobalTarget||Bc(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),er(a)&&(a.addEventListener("focus",c=>Fm(c,s)),!Nm(a)&&!a.hasAttribute("tabindex")&&(a.tabIndex=0))}),o}function jc(t){return Pl(t)&&"ownerSVGElement"in t}function Bm(t){return jc(t)&&t.tagName==="svg"}const Ge=t=>!!(t&&t.getVelocity),Vm=[...Rc,Me,Kt],$m=t=>Vm.find(Ac(t)),pn=Ft({transformPagePoint:t=>t,isStatic:!1,reducedMotion:"never"});class jm extends bt{getSnapshotBeforeUpdate(e){const i=this.props.childRef.current;if(i&&e.isPresent&&!this.props.isPresent){const n=i.offsetParent,s=er(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 Hm({children:t,isPresent:e,anchorX:i,root:n}){const s=ro(),o=ce(null),r=ce({width:0,height:0,top:0,left:0,right:0}),{nonce:a}=Fe(pn);return pl(()=>{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 m=document.createElement("style");a&&(m.nonce=a);const v=n??document.head;return v.appendChild(m),m.sheet&&m.sheet.insertRule(`
|
|
2
2
|
[data-motion-pop-id="${s}"] {
|
|
3
3
|
position: absolute !important;
|
|
4
4
|
width: ${l}px !important;
|
|
5
5
|
height: ${c}px !important;
|
|
6
|
-
${
|
|
6
|
+
${p}px !important;
|
|
7
7
|
top: ${u}px !important;
|
|
8
8
|
}
|
|
9
|
-
`),()=>{v.removeChild(m),v.contains(m)&&v.removeChild(m)}},[e]),L(xm,{isPresent:e,childRef:o,sizeRef:r,children:Dp(t,{ref:o})})}const Lm=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Wn(Mm),u=Zs();let d=!0,h=it(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:g=>{c.set(g,!0);for(const m of c.values())if(!m)return;n&&n()},register:g=>(c.set(g,!1),()=>c.delete(g))}),[i,c,n]);return o&&d&&(h={...h}),it(()=>{c.forEach((g,m)=>c.set(m,!1))},[i]),xe(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=L(Dm,{isPresent:i,anchorX:a,root:l,children:t})),L(Gn.Provider,{value:h,children:t})};function Mm(){return new Map}function Bc(t=!0){const e=De(Gn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=Zs();xe(()=>{if(t)return s(o)},[t]);const r=qe(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const Qn=t=>t.key||"";function Uc(t){const e=[];return bp.forEach(t,i=>{Cl(i)&&e.push(i)}),e}const Om=({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]=Bc(r),d=it(()=>Uc(t),[t]),h=r&&!c?[]:d.map(Qn),g=he(!0),m=he(d),v=Wn(()=>new Map),[b,y]=Ae(d),[C,k]=Ae(d);Rl(()=>{g.current=!1,m.current=d;for(let D=0;D<C.length;D++){const T=Qn(C[D]);h.includes(T)?v.delete(T):v.get(T)!==!0&&v.set(T,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let D=[...d];for(let T=0;T<C.length;T++){const E=C[T],p=Qn(E);h.includes(p)||(D.splice(T,0,E),A.push(E))}return o==="wait"&&A.length&&(D=A),k(Uc(D)),y(d),null}const{forceRender:R}=De(uo);return L(mt,{children:C.map(D=>{const T=Qn(D),E=r&&!c?!1:d===C||h.includes(T),p=()=>{if(v.has(T))v.set(T,!0);else return;let _=!0;v.forEach(f=>{f||(_=!1)}),_&&(R==null||R(),k(m.current),r&&(u==null||u()),n&&n())};return L(Lm,{isPresent:E,initial:!g.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:E?void 0:p,anchorX:a,children:D},T)})})},Vc=At({strict:!1}),$c={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"]},Si={};for(const t in $c)Si[t]={isEnabled:e=>$c[t].some(i=>!!e[i])};function Pm(t){for(const e in t)Si[e]={...Si[e],...t[e]}}const Nm=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 es(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||Nm.has(t)}let jc=t=>!es(t);function Hc(t){typeof t=="function"&&(jc=e=>e.startsWith("on")?!es(e):t(e))}try{Hc(require("@emotion/is-prop-valid").default)}catch{}function Fm(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(jc(s)||i===!0&&es(s)||!e&&!es(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Bm({children:t,isValidProp:e,...i}){e&&Hc(e),i={...De(an),...i},i.isStatic=Wn(()=>i.isStatic);const n=it(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return L(an.Provider,{value:n,children:t})}function Um(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 ts=At({});function is(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function ln(t){return typeof t=="string"||Array.isArray(t)}const Qo=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],er=["initial",...Qo];function ns(t){return is(t.animate)||er.some(e=>ln(t[e]))}function Wc(t){return!!(ns(t)||t.variants)}function Vm(t,e){if(ns(t)){const{initial:i,animate:n}=t;return{initial:i===!1||ln(i)?i:void 0,animate:ln(n)?n:void 0}}return t.inherit!==!1?e:{}}function $m(t){const{initial:e,animate:i}=Vm(t,De(ts));return it(()=>({initial:e,animate:i}),[Gc(e),Gc(i)])}function Gc(t){return Array.isArray(t)?t.join(" "):t}const jm=Symbol.for("motionComponentSymbol");function Ci(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function Hm(t,e,i){return qe(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):Ci(i)&&(i.current=n))},[e])}const tr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),qc="data-"+tr("framerAppearId"),zc=At({});function Wm(t,e,i,n,s){var v,b;const{visualElement:o}=De(ts),r=De(Vc),a=De(Gn),l=De(an).reducedMotion,c=he(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(zc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&Gm(c.current,i,s,d);const h=he(!1);cl(()=>{u&&h.current&&u.update(i,a)});const g=i[qc],m=he(!!g&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,g))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,g)));return Rl(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),Xo.render(u.render),m.current&&u.animationState&&u.animationState.animateChanges())}),xe(()=>{u&&(!m.current&&u.animationState&&u.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,g)}),m.current=!1))}),u}function Gm(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:Kc(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Ci(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function Kc(t){if(t)return t.options.allowProjection!==!1?t.projection:Kc(t.parent)}function qm({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&Pm(t);function o(a,l){let c;const u={...De(an),...a,layoutId:zm(a)},{isStatic:d}=u,h=$m(a),g=n(a,d);if(!d&&ho){Km();const m=Ym(u);c=m.MeasureLayout,h.visualElement=Wm(s,g,u,e,m.ProjectionNode)}return L(ts.Provider,{value:h,children:[c&&h.visualElement?L(c,{visualElement:h.visualElement,...u}):null,i(s,a,Hm(g,h.visualElement,l),g,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=yp(o);return r[jm]=s,r}function zm({layoutId:t}){const e=De(uo).id;return e&&t!==void 0?e+"-"+t:t}function Km(t,e){De(Vc).strict}function Ym(t){const{drag:e,layout:i}=Si;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 cn={};function Xm(t){for(const e in t)cn[e]=t[e],wo(e)&&(cn[e].isCSSVariable=!0)}function Yc(t,{layout:e,layoutId:i}){return bi.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!cn[t]||t==="opacity")}const Jm={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Zm=yi.length;function Qm(t,e,i){let n="",s=!0;for(let o=0;o<Zm;o++){const r=yi[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=Ac(a,Yo[r]);if(!l){s=!1;const u=Jm[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function ir(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(bi.has(l)){r=!0;continue}else if(wo(l)){s[l]=c;continue}else{const u=Ac(c,Yo[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=Qm(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 nr=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Xc(t,e,i){for(const n in e)!Ue(e[n])&&!Yc(n,i)&&(t[n]=e[n])}function ev({transformTemplate:t},e){return it(()=>{const i=nr();return ir(i,e,t),Object.assign({},i.vars,i.style)},[e])}function tv(t,e){const i=t.style||{},n={};return Xc(n,i,t),Object.assign(n,ev(t,e)),n}function iv(t,e){const i={},n=tv(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 nv={offset:"stroke-dashoffset",array:"stroke-dasharray"},sv={offset:"strokeDashoffset",array:"strokeDasharray"};function ov(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?nv:sv;t[o.offset]=K.transform(-n);const r=K.transform(e),a=K.transform(i);t[o.array]=`${r} ${a}`}function Jc(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(ir(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&&ov(d,s,o,r,!1)}const Zc=()=>({...nr(),attrs:{}}),Qc=t=>typeof t=="string"&&t.toLowerCase()==="svg";function rv(t,e,i,n){const s=it(()=>{const o=Zc();return Jc(o,e,Qc(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};Xc(o,t.style,t),s.style={...o,...s.style}}return s}const av=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function sr(t){return typeof t!="string"||t.includes("-")?!1:!!(av.indexOf(t)>-1||/[A-Z]/u.test(t))}function lv(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(sr(i)?rv:iv)(n,o,r,i),c=Fm(n,typeof i=="string",t),u=i!==mt?{...c,...l,ref:s}:{},{children:d}=n,h=it(()=>Ue(d)?d.get():d,[d]);return tt(i,{...u,children:h})}}function ed(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function or(t,e,i,n){if(typeof e=="function"){const[s,o]=ed(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]=ed(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function ss(t){return Ue(t)?t.get():t}function cv({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:dv(i,n,s,t),renderState:e()}}const td=t=>(e,i)=>{const n=De(ts),s=De(Gn),o=()=>cv(t,e,n,s);return i?o():Wn(o)};function dv(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=ss(o[h]);let{initial:r,animate:a}=t;const l=ns(t),c=Wc(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"&&!is(d)){const h=Array.isArray(d)?d:[d];for(let g=0;g<h.length;g++){const m=or(t,h[g]);if(m){const{transitionEnd:v,transition:b,...y}=m;for(const C in y){let k=y[C];if(Array.isArray(k)){const A=u?k.length-1:0;k=k[A]}k!==null&&(s[C]=k)}for(const C in v)s[C]=v[C]}}}return s}function rr(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ue(n[r])||e.style&&Ue(e.style[r])||Yc(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const uv={useVisualState:td({scrapeMotionValuesFromProps:rr,createRenderState:nr})};function id(t,e,i){const n=rr(t,e,i);for(const s in t)if(Ue(t[s])||Ue(e[s])){const o=yi.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const hv={useVisualState:td({scrapeMotionValuesFromProps:id,createRenderState:Zc})};function fv(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...sr(n)?hv:uv,preloadedFeatures:t,useRender:lv(s),createVisualElement:e,Component:n};return qm(r)}}function dn(t,e,i){const n=t.getProps();return or(n,e,i!==void 0?i:n.custom,t)}const ar=t=>Array.isArray(t);function pv(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,wi(i))}function gv(t){return ar(t)?t[t.length-1]||0:t}function mv(t,e){const i=dn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=gv(o[r]);pv(t,r,a)}}function vv(t){return!!(Ue(t)&&t.add)}function lr(t,e){const i=t.getValue("willChange");if(vv(i))return i.add(e);if(!i&&Dt.WillChange){const n=new Dt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function nd(t){return t.props[qc]}const _v=t=>t!==null;function yv(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(_v),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const bv={type:"spring",stiffness:500,damping:25,restSpeed:10},wv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Sv={type:"keyframes",duration:.8},Cv={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Tv=(t,{keyframes:e})=>e.length>2?Sv:bi.has(t)?t.startsWith("scale")?wv(e[1]):bv:Cv;function kv({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 cr=(t,e,i,n={},s,o)=>r=>{const a=zo(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-_t(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};kv(a)||Object.assign(u,Tv(t,u)),u.duration&&(u.duration=_t(u.duration)),u.repeatDelay&&(u.repeatDelay=_t(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)),(Dt.instantAnimations||Dt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=yv(u.keyframes,a);if(h!==void 0){be.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Fo(u):new rm(u)};function Ev({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function sd(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&&Ev(c,u))continue;const g={delay:i,...zo(o||{},u)},m=d.get();if(m!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===m&&!g.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=nd(t);if(y){const C=window.MotionHandoffAnimation(y,u,be);C!==null&&(g.startTime=C,v=!0)}}lr(t,u),d.start(cr(u,d,h,t.shouldReduceMotion&&Sc.has(u)?{type:!1}:g,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{be.update(()=>{r&&mv(t,r)})}),l}function dr(t,e,i={}){var l;const n=dn(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(sd(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Iv(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 Iv(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(Rv).forEach((h,g)=>{h.notify("AnimationStart",e),a.push(dr(h,e,{...r,delay:i+(u?0:n)+d(g)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Rv(t,e){return t.sortNodePosition(e)}function Av(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>dr(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=dr(t,e,i);else{const s=typeof e=="function"?dn(t,e,i.custom):e;n=Promise.all(sd(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function od(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 xv=er.length;function rd(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?rd(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<xv;i++){const n=er[i],s=t.props[n];(ln(s)||s===!1)&&(e[n]=s)}return e}const Dv=[...Qo].reverse(),Lv=Qo.length;function Mv(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Av(t,i,n)))}function Ov(t){let e=Mv(t),i=ad(),n=!0;const s=l=>(c,u)=>{var h;const d=dn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:g,transitionEnd:m,...v}=d;c={...c,...v,...m}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=rd(t.parent)||{},d=[],h=new Set;let g={},m=1/0;for(let b=0;b<Lv;b++){const y=Dv[b],C=i[y],k=c[y]!==void 0?c[y]:u[y],A=ln(k),R=y===l?C.isActive:null;R===!1&&(m=b);let D=k===u[y]&&k!==c[y]&&A;if(D&&n&&t.manuallyAnimateOnMount&&(D=!1),C.protectedKeys={...g},!C.isActive&&R===null||!k&&!C.prevProp||is(k)||typeof k=="boolean")continue;const T=Pv(C.prevProp,k);let E=T||y===l&&C.isActive&&!D&&A||b>m&&A,p=!1;const _=Array.isArray(k)?k:[k];let f=_.reduce(s(y),{});R===!1&&(f={});const{prevResolvedValues:S={}}=C,I={...S,...f},M=O=>{E=!0,h.has(O)&&(p=!0,h.delete(O)),C.needsAnimating[O]=!0;const F=t.getValue(O);F&&(F.liveStyle=!1)};for(const O in I){const F=f[O],V=S[O];if(g.hasOwnProperty(O))continue;let $=!1;ar(F)&&ar(V)?$=!od(F,V):$=F!==V,$?F!=null?M(O):h.add(O):F!==void 0&&h.has(O)?M(O):C.protectedKeys[O]=!0}C.prevProp=k,C.prevResolvedValues=f,C.isActive&&(g={...g,...f}),n&&t.blockInitialAnimation&&(E=!1),E&&(!(D&&T)||p)&&d.push(..._.map(O=>({animation:O,options:{type:y}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const y=dn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(b.transition=y.transition)}h.forEach(y=>{const C=t.getBaseTarget(y),k=t.getValue(y);k&&(k.liveStyle=!0),b[y]=C??null}),d.push({animation:b})}let v=!!d.length;return n&&(c.initial===!1||c.initial===c.animate)&&!t.manuallyAnimateOnMount&&(v=!1),n=!1,v?e(d):Promise.resolve()}function a(l,c){var d;if(i[l].isActive===c)return Promise.resolve();(d=t.variantChildren)==null||d.forEach(h=>{var g;return(g=h.animationState)==null?void 0:g.setActive(l,c)}),i[l].isActive=c;const u=r(l);for(const h in i)i[h].protectedKeys={};return u}return{animateChanges:r,setActive:a,setAnimateFunction:o,getState:()=>i,reset:()=>{i=ad(),n=!0}}}function Pv(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!od(e,t):!1}function ti(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function ad(){return{animate:ti(!0),whileInView:ti(),whileHover:ti(),whileTap:ti(),whileDrag:ti(),whileFocus:ti(),exit:ti()}}class jt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class Nv extends jt{constructor(e){super(e),e.animationState||(e.animationState=Ov(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();is(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 Fv=0;class Bv extends jt{constructor(){super(...arguments),this.id=Fv++}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 Uv={animation:{Feature:Nv},exit:{Feature:Bv}};function un(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function hn(t){return{point:{x:t.pageX,y:t.pageY}}}const Vv=t=>e=>Jo(e)&&t(e,hn(e));function fn(t,e,i,n){return un(t,e,Vv(i),n)}function ld({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function $v({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function jv(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 cd=1e-4,Hv=1-cd,Wv=1+cd,dd=.01,Gv=0-dd,qv=0+dd;function je(t){return t.max-t.min}function zv(t,e,i){return Math.abs(t-e)<=i}function ud(t,e,i,n=.5){t.origin=n,t.originPoint=Se(e.min,e.max,t.origin),t.scale=je(i)/je(e),t.translate=Se(i.min,i.max,t.origin)-t.originPoint,(t.scale>=Hv&&t.scale<=Wv||isNaN(t.scale))&&(t.scale=1),(t.translate>=Gv&&t.translate<=qv||isNaN(t.translate))&&(t.translate=0)}function pn(t,e,i,n){ud(t.x,e.x,i.x,n?n.originX:void 0),ud(t.y,e.y,i.y,n?n.originY:void 0)}function hd(t,e,i){t.min=i.min+e.min,t.max=t.min+je(e)}function Kv(t,e,i){hd(t.x,e.x,i.x),hd(t.y,e.y,i.y)}function fd(t,e,i){t.min=e.min-i.min,t.max=t.min+je(e)}function gn(t,e,i){fd(t.x,e.x,i.x),fd(t.y,e.y,i.y)}const pd=()=>({translate:0,scale:1,origin:0,originPoint:0}),Ti=()=>({x:pd(),y:pd()}),gd=()=>({min:0,max:0}),ke=()=>({x:gd(),y:gd()});function st(t){return[t("x"),t("y")]}function ur(t){return t===void 0||t===1}function hr({scale:t,scaleX:e,scaleY:i}){return!ur(t)||!ur(e)||!ur(i)}function ii(t){return hr(t)||md(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function md(t){return vd(t.x)||vd(t.y)}function vd(t){return t&&t!=="0%"}function os(t,e,i){const n=t-i,s=e*n;return i+s}function _d(t,e,i,n,s){return s!==void 0&&(t=os(t,s,n)),os(t,i,n)+e}function fr(t,e=0,i=1,n,s){t.min=_d(t.min,e,i,n,s),t.max=_d(t.max,e,i,n,s)}function yd(t,{x:e,y:i}){fr(t.x,e.translate,e.scale,e.originPoint),fr(t.y,i.translate,i.scale,i.originPoint)}const bd=.999999999999,wd=1.0000000000001;function Yv(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&&Ei(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,yd(t,r)),n&&ii(o.latestValues)&&Ei(t,o.latestValues))}e.x<wd&&e.x>bd&&(e.x=1),e.y<wd&&e.y>bd&&(e.y=1)}function ki(t,e){t.min=t.min+e,t.max=t.max+e}function Sd(t,e,i,n,s=.5){const o=Se(t.min,t.max,s);fr(t,e,i,o,n)}function Ei(t,e){Sd(t.x,e.x,e.scaleX,e.scale,e.originX),Sd(t.y,e.y,e.scaleY,e.scale,e.originY)}function Cd(t,e){return ld(jv(t.getBoundingClientRect(),e))}function Xv(t,e,i){const n=Cd(t,i),{scroll:s}=e;return s&&(ki(n.x,s.offset.x),ki(n.y,s.offset.y)),n}const Td=({current:t})=>t?t.ownerDocument.defaultView:null,kd=(t,e)=>Math.abs(t-e);function Jv(t,e){const i=kd(t.x,e.x),n=kd(t.y,e.y);return Math.sqrt(i**2+n**2)}class Ed{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=gr(this.lastMoveEventInfo,this.history),g=this.startEvent!==null,m=Jv(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!g&&!m)return;const{point:v}=h,{timestamp:b}=Oe;this.history.push({...v,timestamp:b});const{onStart:y,onMove:C}=this.handlers;g||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,g)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=pr(g,this.transformPagePoint),be.update(this.updatePoint,!0)},this.handlePointerUp=(h,g)=>{this.end();const{onEnd:m,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=gr(h.type==="pointercancel"?this.lastMoveEventInfo:pr(g,this.transformPagePoint),this.history);this.startEvent&&m&&m(h,y),v&&v(h,y)},!Jo(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=hn(e),l=pr(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=Oe;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,gr(l,this.history)),this.removeListeners=Ji(fn(this.contextWindow,"pointermove",this.handlePointerMove),fn(this.contextWindow,"pointerup",this.handlePointerUp),fn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),Ut(this.updatePoint)}}function pr(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 gr({point:t},e){return{point:t,delta:Id(t,Rd(e)),offset:Id(t,Zv(e)),velocity:Qv(e,.1)}}function Zv(t){return t[0]}function Rd(t){return t[t.length-1]}function Qv(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Rd(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>_t(e)));)i--;if(!n)return{x:0,y:0};const o=yt(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 e_(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?Se(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?Se(i,t,n.max):Math.min(t,i)),t}function Ad(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 t_(t,{top:e,left:i,bottom:n,right:s}){return{x:Ad(t.x,i,s),y:Ad(t.y,e,n)}}function xd(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 i_(t,e){return{x:xd(t.x,e.x),y:xd(t.y,e.y)}}function n_(t,e){let i=.5;const n=je(t),s=je(e);return s>n?i=Zi(e.min,e.max-n,t.min):n>s&&(i=Zi(t.min,t.max-s,e.min)),xt(0,1,i)}function s_(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 mr=.35;function o_(t=mr){return t===!1?t=0:t===!0&&(t=mr),{x:Dd(t,"left","right"),y:Dd(t,"top","bottom")}}function Dd(t,e,i){return{min:Ld(t,e),max:Ld(t,i)}}function Ld(t,e){return typeof t=="number"?t:t[e]||0}const r_=new WeakMap;class a_{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(hn(d).point)},r=(d,h)=>{const{drag:g,dragPropagation:m,onDragStart:v}=this.getProps();if(g&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=wm(g),!this.openDragLock))return;this.latestPointerEvent=d,this.latestPanInfo=h,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),st(y=>{let C=this.getAxisMotionValue(y).get()||0;if(bt.test(C)){const{projection:k}=this.visualElement;if(k&&k.layout){const A=k.layout.layoutBox[y];A&&(C=je(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&be.postRender(()=>v(d,h)),lr(this.visualElement,"transform");const{animationState:b}=this.visualElement;b&&b.setActive("whileDrag",!0)},a=(d,h)=>{this.latestPointerEvent=d,this.latestPanInfo=h;const{dragPropagation:g,dragDirectionLock:m,onDirectionLock:v,onDrag:b}=this.getProps();if(!g&&!this.openDragLock)return;const{offset:y}=h;if(m&&this.currentDirection===null){this.currentDirection=l_(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),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=()=>st(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 Ed(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:Td(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&&be.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||!rs(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=e_(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&&Ci(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=t_(n.layoutBox,e):this.constraints=!1,this.elastic=o_(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&st(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=s_(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!Ci(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=Xv(n,s.root,this.visualElement.getTransformPagePoint());let r=i_(s.layout.layoutBox,o);if(i){const a=i($v(r));this.hasMutatedConstraints=!!a,a&&(r=ld(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=st(u=>{if(!rs(u,i,this.currentDirection))return;let d=l&&l[u]||{};r&&(d={min:0,max:0});const h=s?200:1e6,g=s?40:1e7,m={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:g,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,m)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return lr(this.visualElement,e),n.start(cr(e,n,0,i,this.visualElement,!1))}stopAnimation(){st(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){st(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){st(i=>{const{drag:n}=this.getProps();if(!rs(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]-Se(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!Ci(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};st(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=n_({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(),st(r=>{if(!rs(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(Se(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;r_.set(this.visualElement,this);const e=this.visualElement.current,i=fn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();Ci(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()),be.read(n);const r=un(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(st(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=mr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function rs(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function l_(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class c_ extends jt{constructor(e){super(e),this.removeGroupControls=nt,this.removeListeners=nt,this.controls=new a_(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||nt}unmount(){this.removeGroupControls(),this.removeListeners()}}const Md=t=>(e,i)=>{t&&be.postRender(()=>t(e,i))};class d_ extends jt{constructor(){super(...arguments),this.removePointerDownListener=nt}onPointerDown(e){this.session=new Ed(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Td(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:Md(e),onStart:Md(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&be.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=fn(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}const as={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Od(t,e){return e.max===e.min?0:t/(e.max-e.min)*100}const mn={correct:(t,e)=>{if(!e.target)return t;if(typeof t=="string")if(K.test(t))t=parseFloat(t);else return t;const i=Od(t,e.target.x),n=Od(t,e.target.y);return`${i}% ${n}%`}},u_={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=$t.parse(t);if(s.length>5)return n;const o=$t.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=Se(a,l,.5);return typeof s[2+r]=="number"&&(s[2+r]/=c),typeof s[3+r]=="number"&&(s[3+r]/=c),o(s)}};let Pd=!1;class h_ extends ut{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;Xm(f_),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),Pd&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),as.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,Pd=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||be.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),Xo.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 Nd(t){const[e,i]=Bc(),n=De(uo);return L(h_,{...t,layoutGroup:n,switchLayoutGroup:De(zc),isPresent:e,safeToRemove:i})}const f_={borderRadius:{...mn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:mn,borderTopRightRadius:mn,borderBottomLeftRadius:mn,borderBottomRightRadius:mn,boxShadow:u_};function p_(t,e,i){const n=Ue(t)?t:wi(t);return n.start(cr("",n,e,i)),n.animation}const g_=(t,e)=>t.depth-e.depth;class m_{constructor(){this.children=[],this.isDirty=!1}add(e){fo(this.children,e),this.isDirty=!0}remove(e){po(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(g_),this.isDirty=!1,this.children.forEach(e)}}function v_(t,e){const i=ze.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(Ut(n),t(o-e))};return be.setup(n,!0),()=>Ut(n)}const Fd=["TopLeft","TopRight","BottomLeft","BottomRight"],__=Fd.length,Bd=t=>typeof t=="string"?parseFloat(t):t,Ud=t=>typeof t=="number"||K.test(t);function y_(t,e,i,n,s,o){s?(t.opacity=Se(0,i.opacity??1,b_(n)),t.opacityExit=Se(e.opacity??1,0,w_(n))):o&&(t.opacity=Se(e.opacity??1,i.opacity??1,n));for(let r=0;r<__;r++){const a=`border${Fd[r]}Radius`;let l=Vd(e,a),c=Vd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Ud(l)===Ud(c)?(t[a]=Math.max(Se(Bd(l),Bd(c),n),0),(bt.test(c)||bt.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=Se(e.rotate||0,i.rotate||0,n))}function Vd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const b_=$d(0,.5,Ul),w_=$d(.5,.95,nt);function $d(t,e,i){return n=>n<t?0:n>e?1:i(Zi(t,e,n))}function jd(t,e){t.min=e.min,t.max=e.max}function ot(t,e){jd(t.x,e.x),jd(t.y,e.y)}function Hd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Wd(t,e,i,n,s){return t-=e,t=os(t,1/i,n),s!==void 0&&(t=os(t,1/s,n)),t}function S_(t,e=0,i=1,n=.5,s,o=t,r=t){if(bt.test(e)&&(e=parseFloat(e),e=Se(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=Se(o.min,o.max,n);t===o&&(a-=e),t.min=Wd(t.min,e,i,a,s),t.max=Wd(t.max,e,i,a,s)}function Gd(t,e,[i,n,s],o,r){S_(t,e[i],e[n],e[s],e.scale,o,r)}const C_=["x","scaleX","originX"],T_=["y","scaleY","originY"];function qd(t,e,i,n){Gd(t.x,e,C_,i?i.x:void 0,n?n.x:void 0),Gd(t.y,e,T_,i?i.y:void 0,n?n.y:void 0)}function zd(t){return t.translate===0&&t.scale===1}function Kd(t){return zd(t.x)&&zd(t.y)}function Yd(t,e){return t.min===e.min&&t.max===e.max}function k_(t,e){return Yd(t.x,e.x)&&Yd(t.y,e.y)}function Xd(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function Jd(t,e){return Xd(t.x,e.x)&&Xd(t.y,e.y)}function Zd(t){return je(t.x)/je(t.y)}function Qd(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class E_{constructor(){this.members=[]}add(e){fo(this.members,e),e.scheduleRender()}remove(e){if(po(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 I_(t,e,i){let n="";const s=t.x.translate/e.x,o=t.y.translate/e.y,r=(i==null?void 0:i.z)||0;if((s||o||r)&&(n=`translate3d(${s}px, ${o}px, ${r}px) `),(e.x!==1||e.y!==1)&&(n+=`scale(${1/e.x}, ${1/e.y}) `),i){const{transformPerspective:c,rotate:u,rotateX:d,rotateY:h,skewX:g,skewY:m}=i;c&&(n=`perspective(${c}px) ${n}`),u&&(n+=`rotate(${u}deg) `),d&&(n+=`rotateX(${d}deg) `),h&&(n+=`rotateY(${h}deg) `),g&&(n+=`skewX(${g}deg) `),m&&(n+=`skewY(${m}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 vr=["","X","Y","Z"],R_=1e3;let A_=0;function _r(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function eu(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=nd(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",be,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&eu(n)}function tu({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=A_++,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(L_),this.nodes.forEach(N_),this.nodes.forEach(F_),this.nodes.forEach(M_)},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 m_)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new vo),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=Fc(r)&&!Im(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;be.read(()=>{d=window.innerWidth}),t(r,()=>{const g=window.innerWidth;g!==d&&(d=g,this.root.updateBlockedByResize=!0,u&&u(),u=v_(h,250),as.hasAnimatedSinceResize&&(as.hasAnimatedSinceResize=!1,this.nodes.forEach(su)))})}a&&this.root.registerSharedNode(a,this),this.options.animate!==!1&&c&&(a||l)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:d,hasRelativeLayoutChanged:h,layout:g})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const m=this.options.transition||c.getDefaultTransition()||j_,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),y=!this.targetLayout||!Jd(this.targetLayout,g),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const k={...zo(m,"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||su(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=g})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const r=this.getStack();r&&r.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Ut(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(B_),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&&eu(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(iu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(nu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(P_),this.nodes.forEach(x_),this.nodes.forEach(D_)):this.nodes.forEach(nu),this.clearAllSnapshots();const a=ze.now();Oe.delta=xt(0,1e3/60,a-Oe.timestamp),Oe.timestamp=a,Oe.isProcessing=!0,bo.update.process(Oe),bo.preRender.process(Oe),bo.render.process(Oe),Oe.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,Xo.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(O_),this.sharedNodes.forEach(U_)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,be.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){be.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&&!Kd(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||ii(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)),H_(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(W_))){const{scroll:u}=this.root;u&&(ki(a.x,u.offset.x),ki(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=ke();if(ot(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&&ot(a,r),ki(a.x,d.offset.x),ki(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=ke();ot(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&&Ei(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),ii(u.latestValues)&&Ei(l,u.latestValues)}return ii(this.latestValues)&&Ei(l,this.latestValues),l}removeTransform(r){const a=ke();ot(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!ii(c.latestValues))continue;hr(c.latestValues)&&c.updateSnapshot();const u=ke(),d=c.measurePageBox();ot(u,d),qd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return ii(this.latestValues)&&qd(a,this.latestValues),a}setTargetDelta(r){this.targetDelta=r,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(r){this.options={...this.options,...r,crossfade:r.crossfade!==void 0?r.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==Oe.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(r=!1){var h;const a=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=a.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=a.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=a.isSharedProjectionDirty);const l=!!this.resumingFrom||this!==a;if(!(r||l&&this.isSharedProjectionDirty||this.isProjectionDirty||(h=this.parent)!=null&&h.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:d}=this.options;if(!(!this.layout||!(u||d))){if(this.resolvedRelativeTargetAt=Oe.timestamp,!this.targetDelta&&!this.relativeTarget){const g=this.getClosestProjectingParent();g&&g.layout&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),gn(this.relativeTargetOrigin,this.layout.layoutBox,g.layout.layoutBox),ot(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(),Kv(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ot(this.target,this.layout.layoutBox),yd(this.target,this.targetDelta)):ot(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget)){this.attemptToResolveRelativeTarget=!1;const g=this.getClosestProjectingParent();g&&!!g.resumingFrom==!!this.resumingFrom&&!g.options.layoutScroll&&g.target&&this.animationProgress!==1?(this.relativeParent=g,this.forceRelativeParentToResolveTarget(),this.relativeTarget=ke(),this.relativeTargetOrigin=ke(),gn(this.relativeTargetOrigin,this.target,g.target),ot(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||hr(this.parent.latestValues)||md(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 m;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===Oe.timestamp&&(l=!1),l)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;ot(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;Yv(this.layoutCorrected,this.treeScale,this.path,a),r.layout&&!r.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(r.target=r.layout.layoutBox,r.targetWithTransforms=ke());const{target:g}=r;if(!g){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Hd(this.prevProjectionDelta.x,this.projectionDelta.x),Hd(this.prevProjectionDelta.y,this.projectionDelta.y)),pn(this.projectionDelta,this.layoutCorrected,g,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!Qd(this.projectionDelta.x,this.prevProjectionDelta.x)||!Qd(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",g))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(r=!0){var a;if((a=this.options.visualElement)==null||a.scheduleRender(),r){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=Ti(),this.projectionDelta=Ti(),this.projectionDeltaWithTransform=Ti()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Ti();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=ke(),g=l?l.source:void 0,m=this.layout?this.layout.source:void 0,v=g!==m,b=this.getStack(),y=!b||b.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some($_));this.animationProgress=0;let k;this.mixTargetDelta=A=>{const R=A/1e3;ou(d.x,r.x,R),ou(d.y,r.y,R),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),V_(this.relativeTarget,this.relativeTargetOrigin,h,R),k&&k_(this.relativeTarget,k)&&(this.isProjectionDirty=!1),k||(k=ke()),ot(k,this.relativeTarget)),v&&(this.animationValues=u,y_(u,c,this.latestValues,R,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=R},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(Ut(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=be.update(()=>{as.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=wi(0)),this.currentAnimation=p_(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(R_),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&&du(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}ot(a,l),Ei(a,u),pn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new E_),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&&_r("z",r,c,this.animationValues);for(let u=0;u<vr.length;u++)_r(`rotate${vr[u]}`,r,c,this.animationValues),_r(`skew${vr[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=ss(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=ss(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!ii(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=I_(this.projectionDeltaWithTransform,this.treeScale,u);l&&(d=l(u,d)),r.transform=d;const{x:h,y:g}=this.projectionDelta;r.transformOrigin=`${h.origin*100}% ${g.origin*100}% 0`,c.animationValues?r.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:r.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const m in cn){if(u[m]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:y}=cn[m],C=d==="none"?u[m]:v(u[m],c);if(b){const k=b.length;for(let A=0;A<k;A++)r[b[A]]=C}else y?this.options.visualElement.renderState.vars[m]=C:r[m]=C}this.options.layoutId&&(r.pointerEvents=c===this?ss(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(iu),this.root.sharedNodes.clear()}}}function x_(t){t.updateLayout()}function D_(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"?st(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(h);h.min=n[d].min,h.max=h.min+g}):du(o,e.layoutBox,n)&&st(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],g=je(n[d]);h.max=h.min+g,t.relativeTarget&&!t.currentAnimation&&(t.isProjectionDirty=!0,t.relativeTarget[d].max=t.relativeTarget[d].min+g)});const a=Ti();pn(a,n,e.layoutBox);const l=Ti();r?pn(l,t.applyTransform(s,!0),e.measuredBox):pn(l,n,e.layoutBox);const c=!Kd(a);let u=!1;if(!t.resumeFrom){const d=t.getClosestProjectingParent();if(d&&!d.resumeFrom){const{snapshot:h,layout:g}=d;if(h&&g){const m=ke();gn(m,e.layoutBox,h.layoutBox);const v=ke();gn(v,n,g.layoutBox),Jd(m,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=m,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 L_(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 M_(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function O_(t){t.clearSnapshot()}function iu(t){t.clearMeasurements()}function nu(t){t.isLayoutDirty=!1}function P_(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function su(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function N_(t){t.resolveTargetDelta()}function F_(t){t.calcProjection()}function B_(t){t.resetSkewAndRotation()}function U_(t){t.removeLeadSnapshot()}function ou(t,e,i){t.translate=Se(e.translate,0,i),t.scale=Se(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function ru(t,e,i,n){t.min=Se(e.min,i.min,n),t.max=Se(e.max,i.max,n)}function V_(t,e,i,n){ru(t.x,e.x,i.x,n),ru(t.y,e.y,i.y,n)}function $_(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const j_={duration:.45,ease:[.4,0,.1,1]},au=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),lu=au("applewebkit/")&&!au("chrome/")?Math.round:nt;function cu(t){t.min=lu(t.min),t.max=lu(t.max)}function H_(t){cu(t.x),cu(t.y)}function du(t,e,i){return t==="position"||t==="preserve-aspect"&&!zv(Zd(e),Zd(i),.2)}function W_(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const G_=tu({attachResizeListener:(t,e)=>un(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),yr={current:void 0},uu=tu({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!yr.current){const t=new G_({});t.mount(window),t.setOptions({layoutScroll:!0}),yr.current=t}return yr.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),q_={pan:{Feature:d_},drag:{Feature:c_,ProjectionNode:uu,MeasureLayout:Nd}};function hu(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&&be.postRender(()=>o(e,hn(e)))}class z_ extends jt{mount(){const{current:e}=this.node;e&&(this.unmount=Sm(e,(i,n)=>(hu(this.node,n,"Start"),s=>hu(this.node,s,"End"))))}unmount(){}}class K_ extends jt{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=Ji(un(this.node.current,"focus",()=>this.onFocus()),un(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function fu(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&&be.postRender(()=>o(e,hn(e)))}class Y_ extends jt{mount(){const{current:e}=this.node;e&&(this.unmount=Em(e,(i,n)=>(fu(this.node,n,"Start"),(s,{success:o})=>fu(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const br=new WeakMap,wr=new WeakMap,X_=t=>{const e=br.get(t.target);e&&e(t)},J_=t=>{t.forEach(X_)};function Z_({root:t,...e}){const i=t||document;wr.has(i)||wr.set(i,{});const n=wr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(J_,{root:t,...e})),n[s]}function Q_(t,e,i){const n=Z_(e);return br.set(t,i),n.observe(t),()=>{br.delete(t),n.unobserve(t)}}const ey={some:0,all:1};class ty extends jt{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:ey[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 Q_(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(iy(e,i))&&this.startObserver()}unmount(){}}function iy({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const ny={inView:{Feature:ty},tap:{Feature:Y_},focus:{Feature:K_},hover:{Feature:z_}},sy={layout:{ProjectionNode:uu,MeasureLayout:Nd}},Sr={current:null},pu={current:!1};function oy(){if(pu.current=!0,!!ho)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>Sr.current=t.matches;t.addEventListener("change",e),e()}else Sr.current=!1}const ry=new WeakMap;function ay(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ue(s))t.addValue(n,s);else if(Ue(o))t.addValue(n,wi(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,wi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const gu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class ly{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=Go,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=ze.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,be.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=ns(i),this.isVariantNode=Wc(i),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);const{willChange:u,...d}=this.scrapeMotionValuesFromProps(i,{},this);for(const h in d){const g=d[h];l[h]!==void 0&&Ue(g)&&g.set(l[h],!1)}}mount(e){this.current=e,ry.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)),pu.current||oy(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:Sr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),Ut(this.notifyUpdate),Ut(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=bi.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&be.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 Si){const i=Si[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<gu.length;n++){const s=gu[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=ay(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=wi(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"&&(Al(n)||Dl(n))?n=parseFloat(n):!Am(n)&&$t.test(i)&&(n=Rc(e,i)),this.setBaseTarget(e,Ue(n)?n.get():n)),Ue(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=or(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&&!Ue(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 vo),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class mu extends ly{constructor(){super(...arguments),this.KeyframeResolver=vm}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;Ue(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function vu(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 cy(t){return window.getComputedStyle(t)}class dy extends mu{constructor(){super(...arguments),this.type="html",this.renderInstance=vu}readValueFromInstance(e,i){var n;if(bi.has(i))return(n=this.projection)!=null&&n.isProjecting?Vo(i):Fg(e,i);{const s=cy(e),o=(wo(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Cd(e,i)}build(e,i,n){ir(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return rr(e,i,n)}}const _u=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 uy(t,e,i,n){vu(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(_u.has(s)?s:tr(s),e.attrs[s])}class hy extends mu{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=ke}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(bi.has(i)){const n=Ic(i);return n&&n.default||0}return i=_u.has(i)?i:tr(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return id(e,i,n)}build(e,i,n){Jc(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){uy(e,i,n,s)}mount(e){this.isSVGTag=Qc(e.tagName),super.mount(e)}}const fy=(t,e)=>sr(t)?new hy(e):new dy(e,{allowProjection:t!==mt}),py=fv({...Uv,...ny,...q_,...sy},fy),Ii=Um(py),gy=["agent-id","debug","environment","position","version-id","trickle-ice","prefetch-ice-candidates","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"],vn="widget-layout-id";function yu(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=yu(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function Lt(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=yu(t))&&(n&&(n+=" "),n+=e);return n}const my=$n("listening"),Cr=()=>Il(my);function vy(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 ls={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},bu=$n(ls),_y=()=>{const t=Hn(bu);return qe(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=ls.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=ls.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=ls.speak_to_interrupt_text),i}),[t])},ni=()=>co(bu),wu=({size:t="large",className:e})=>{const i=ni(),[n]=Cr();return L("h1",{className:Lt({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Su=({stream:t,chatMode:e})=>{const i=he(null);return xe(()=>{!i.current||!t||(i.current.srcObject=t)},[t]),e?null:L("audio",{muted:!0,ref:i,autoPlay:!0})};/**!
|
|
9
|
+
`),()=>{v.removeChild(m),v.contains(m)&&v.removeChild(m)}},[e]),D(jm,{isPresent:e,childRef:o,sizeRef:r,children:Hp(t,{ref:o})})}const Wm=({children:t,initial:e,isPresent:i,onExitComplete:n,custom:s,presenceAffectsLayout:o,mode:r,anchorX:a,root:l})=>{const c=Qn(Gm),u=ro();let d=!0,h=dt(()=>(d=!1,{id:u,initial:e,isPresent:i,custom:s,onExitComplete:p=>{c.set(p,!0);for(const m of c.values())if(!m)return;n&&n()},register:p=>(c.set(p,!1),()=>c.delete(p))}),[i,c,n]);return o&&d&&(h={...h}),dt(()=>{c.forEach((p,m)=>c.set(m,!1))},[i]),Le(()=>{!i&&!c.size&&n&&n()},[i]),r==="popLayout"&&(t=D(Hm,{isPresent:i,anchorX:a,root:l,children:t})),D(Zn.Provider,{value:h,children:t})};function Gm(){return new Map}function Hc(t=!0){const e=Fe(Zn);if(e===null)return[!0,null];const{isPresent:i,onExitComplete:n,register:s}=e,o=ro();Le(()=>{if(t)return s(o)},[t]);const r=Ne(()=>t&&n&&n(o),[o,n,t]);return!i&&n?[!1,r]:[!0]}const as=t=>t.key||"";function Wc(t){const e=[];return Lp.forEach(t,i=>{Al(i)&&e.push(i)}),e}const Gc=({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]=Hc(r),d=dt(()=>Wc(t),[t]),h=r&&!c?[]:d.map(as),p=ce(!0),m=ce(d),v=Qn(()=>new Map),[b,y]=ve(d),[C,T]=ve(d);Ml(()=>{p.current=!1,m.current=d;for(let N=0;N<C.length;N++){const E=as(C[N]);h.includes(E)?v.delete(E):v.get(E)!==!0&&v.set(E,!1)}},[C,h.length,h.join("-")]);const A=[];if(d!==b){let N=[...d];for(let E=0;E<C.length;E++){const k=C[E],f=as(k);h.includes(f)||(N.splice(E,0,k),A.push(k))}return o==="wait"&&A.length&&(N=A),T(Wc(N)),y(d),null}const{forceRender:x}=Fe(yo);return D(yt,{children:C.map(N=>{const E=as(N),k=r&&!c?!1:d===C||h.includes(E),f=()=>{if(v.has(E))v.set(E,!0);else return;let _=!0;v.forEach(g=>{g||(_=!1)}),_&&(x==null||x(),T(m.current),r&&(u==null||u()),n&&n())};return D(Wm,{isPresent:k,initial:!p.current||i?void 0:!1,custom:e,presenceAffectsLayout:s,mode:o,root:l,onExitComplete:k?void 0:f,anchorX:a,children:N},E)})})},qc=Ft({strict:!1}),zc={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"]},Di={};for(const t in zc)Di[t]={isEnabled:e=>zc[t].some(i=>!!e[i])};function qm(t){for(const e in t)Di[e]={...Di[e],...t[e]}}const zm=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 ls(t){return t.startsWith("while")||t.startsWith("drag")&&t!=="draggable"||t.startsWith("layout")||t.startsWith("onTap")||t.startsWith("onPan")||t.startsWith("onLayout")||zm.has(t)}let Kc=t=>!ls(t);function Yc(t){typeof t=="function"&&(Kc=e=>e.startsWith("on")?!ls(e):t(e))}try{Yc(require("@emotion/is-prop-valid").default)}catch{}function Km(t,e,i){const n={};for(const s in t)s==="values"&&typeof t.values=="object"||(Kc(s)||i===!0&&ls(s)||!e&&!ls(s)||t.draggable&&s.startsWith("onDrag"))&&(n[s]=t[s]);return n}function Ym({children:t,isValidProp:e,...i}){e&&Yc(e),i={...Fe(pn),...i},i.isStatic=Qn(()=>i.isStatic);const n=dt(()=>i,[JSON.stringify(i.transition),i.transformPagePoint,i.reducedMotion]);return D(pn.Provider,{value:n,children:t})}function Xm(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 cs=Ft({});function ds(t){return t!==null&&typeof t=="object"&&typeof t.start=="function"}function gn(t){return typeof t=="string"||Array.isArray(t)}const ar=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],lr=["initial",...ar];function us(t){return ds(t.animate)||lr.some(e=>gn(t[e]))}function Xc(t){return!!(us(t)||t.variants)}function Jm(t,e){if(us(t)){const{initial:i,animate:n}=t;return{initial:i===!1||gn(i)?i:void 0,animate:gn(n)?n:void 0}}return t.inherit!==!1?e:{}}function Qm(t){const{initial:e,animate:i}=Jm(t,Fe(cs));return dt(()=>({initial:e,animate:i}),[Jc(e),Jc(i)])}function Jc(t){return Array.isArray(t)?t.join(" "):t}const Zm=Symbol.for("motionComponentSymbol");function Li(t){return t&&typeof t=="object"&&Object.prototype.hasOwnProperty.call(t,"current")}function ev(t,e,i){return Ne(n=>{n&&t.onMount&&t.onMount(n),e&&(n?e.mount(n):e.unmount()),i&&(typeof i=="function"?i(n):Li(i)&&(i.current=n))},[e])}const cr=t=>t.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),Qc="data-"+cr("framerAppearId"),Zc=Ft({});function tv(t,e,i,n,s){var v,b;const{visualElement:o}=Fe(cs),r=Fe(qc),a=Fe(Zn),l=Fe(pn).reducedMotion,c=ce(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=Fe(Zc);u&&!u.projection&&s&&(u.type==="html"||u.type==="svg")&&iv(c.current,i,s,d);const h=ce(!1);pl(()=>{u&&h.current&&u.update(i,a)});const p=i[Qc],m=ce(!!p&&!((v=window.MotionHandoffIsComplete)!=null&&v.call(window,p))&&((b=window.MotionHasOptimisedAnimation)==null?void 0:b.call(window,p)));return Ml(()=>{u&&(h.current=!0,window.MotionIsMounted=!0,u.updateFeatures(),sr.render(u.render),m.current&&u.animationState&&u.animationState.animateChanges())}),Le(()=>{u&&(!m.current&&u.animationState&&u.animationState.animateChanges(),m.current&&(queueMicrotask(()=>{var y;(y=window.MotionHandoffMarkAsComplete)==null||y.call(window,p)}),m.current=!1))}),u}function iv(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:ed(t.parent)),t.projection.setOptions({layoutId:s,layout:o,alwaysMeasureLayout:!!r||a&&Li(a),visualElement:t,animationType:typeof o=="string"?o:"both",initialPromotionConfig:n,crossfade:u,layoutScroll:l,layoutRoot:c})}function ed(t){if(t)return t.options.allowProjection!==!1?t.projection:ed(t.parent)}function nv({preloadedFeatures:t,createVisualElement:e,useRender:i,useVisualState:n,Component:s}){t&&qm(t);function o(a,l){let c;const u={...Fe(pn),...a,layoutId:sv(a)},{isStatic:d}=u,h=Qm(a),p=n(a,d);if(!d&&bo){ov();const m=rv(u);c=m.MeasureLayout,h.visualElement=tv(s,p,u,e,m.ProjectionNode)}return D(cs.Provider,{value:h,children:[c&&h.visualElement?D(c,{visualElement:h.visualElement,...u}):null,i(s,a,ev(p,h.visualElement,l),p,d,h.visualElement)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const r=Dp(o);return r[Zm]=s,r}function sv({layoutId:t}){const e=Fe(yo).id;return e&&t!==void 0?e+"-"+t:t}function ov(t,e){Fe(qc).strict}function rv(t){const{drag:e,layout:i}=Di;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 mn={};function av(t){for(const e in t)mn[e]=t[e],Ro(e)&&(mn[e].isCSSVariable=!0)}function td(t,{layout:e,layoutId:i}){return Ri.has(t)||t.startsWith("origin")||(e||i!==void 0)&&(!!mn[t]||t==="opacity")}const lv={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},cv=Ai.length;function dv(t,e,i){let n="",s=!0;for(let o=0;o<cv;o++){const r=Ai[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=Oc(a,nr[r]);if(!l){s=!1;const u=lv[r]||r;n+=`${u}(${c}) `}i&&(e[r]=c)}}return n=n.trim(),i?n=i(e,s?"":n):s&&(n="none"),n}function dr(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(Ri.has(l)){r=!0;continue}else if(Ro(l)){s[l]=c;continue}else{const u=Oc(c,nr[l]);l.startsWith("origin")?(a=!0,o[l]=u):n[l]=u}}if(e.transform||(r||i?n.transform=dv(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 ur=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function id(t,e,i){for(const n in e)!Ge(e[n])&&!td(n,i)&&(t[n]=e[n])}function uv({transformTemplate:t},e){return dt(()=>{const i=ur();return dr(i,e,t),Object.assign({},i.vars,i.style)},[e])}function hv(t,e){const i=t.style||{},n={};return id(n,i,t),Object.assign(n,uv(t,e)),n}function fv(t,e){const i={},n=hv(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 pv={offset:"stroke-dashoffset",array:"stroke-dasharray"},gv={offset:"strokeDashoffset",array:"strokeDasharray"};function mv(t,e,i=1,n=0,s=!0){t.pathLength=1;const o=s?pv:gv;t[o.offset]=Q.transform(-n);const r=Q.transform(e),a=Q.transform(i);t[o.array]=`${r} ${a}`}function nd(t,{attrX:e,attrY:i,attrScale:n,pathLength:s,pathSpacing:o=1,pathOffset:r=0,...a},l,c,u){if(dr(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&&mv(d,s,o,r,!1)}const sd=()=>({...ur(),attrs:{}}),od=t=>typeof t=="string"&&t.toLowerCase()==="svg";function vv(t,e,i,n){const s=dt(()=>{const o=sd();return nd(o,e,od(n),t.transformTemplate,t.style),{...o.attrs,style:{...o.style}}},[e]);if(t.style){const o={};id(o,t.style,t),s.style={...o,...s.style}}return s}const _v=["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 hr(t){return typeof t!="string"||t.includes("-")?!1:!!(_v.indexOf(t)>-1||/[A-Z]/u.test(t))}function yv(t=!1){return(i,n,s,{latestValues:o},r)=>{const l=(hr(i)?vv:fv)(n,o,r,i),c=Km(n,typeof i=="string",t),u=i!==yt?{...c,...l,ref:s}:{},{children:d}=n,h=dt(()=>Ge(d)?d.get():d,[d]);return ct(i,{...u,children:h})}}function rd(t){const e=[{},{}];return t==null||t.values.forEach((i,n)=>{e[0][n]=i.get(),e[1][n]=i.getVelocity()}),e}function fr(t,e,i,n){if(typeof e=="function"){const[s,o]=rd(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]=rd(n);e=e(i!==void 0?i:t.custom,s,o)}return e}function hs(t){return Ge(t)?t.get():t}function bv({scrapeMotionValuesFromProps:t,createRenderState:e},i,n,s){return{latestValues:wv(i,n,s,t),renderState:e()}}const ad=t=>(e,i)=>{const n=Fe(cs),s=Fe(Zn),o=()=>bv(t,e,n,s);return i?o():Qn(o)};function wv(t,e,i,n){const s={},o=n(t,{});for(const h in o)s[h]=hs(o[h]);let{initial:r,animate:a}=t;const l=us(t),c=Xc(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"&&!ds(d)){const h=Array.isArray(d)?d:[d];for(let p=0;p<h.length;p++){const m=fr(t,h[p]);if(m){const{transitionEnd:v,transition:b,...y}=m;for(const C in y){let T=y[C];if(Array.isArray(T)){const A=u?T.length-1:0;T=T[A]}T!==null&&(s[C]=T)}for(const C in v)s[C]=v[C]}}}return s}function pr(t,e,i){var o;const{style:n}=t,s={};for(const r in n)(Ge(n[r])||e.style&&Ge(e.style[r])||td(r,t)||((o=i==null?void 0:i.getValue(r))==null?void 0:o.liveStyle)!==void 0)&&(s[r]=n[r]);return s}const Sv={useVisualState:ad({scrapeMotionValuesFromProps:pr,createRenderState:ur})};function ld(t,e,i){const n=pr(t,e,i);for(const s in t)if(Ge(t[s])||Ge(e[s])){const o=Ai.indexOf(s)!==-1?"attr"+s.charAt(0).toUpperCase()+s.substring(1):s;n[o]=t[s]}return n}const Cv={useVisualState:ad({scrapeMotionValuesFromProps:ld,createRenderState:sd})};function Tv(t,e){return function(n,{forwardMotionProps:s}={forwardMotionProps:!1}){const r={...hr(n)?Cv:Sv,preloadedFeatures:t,useRender:yv(s),createVisualElement:e,Component:n};return nv(r)}}function vn(t,e,i){const n=t.getProps();return fr(n,e,i!==void 0?i:n.custom,t)}const gr=t=>Array.isArray(t);function kv(t,e,i){t.hasValue(e)?t.getValue(e).set(i):t.addValue(e,xi(i))}function Ev(t){return gr(t)?t[t.length-1]||0:t}function Iv(t,e){const i=vn(t,e);let{transitionEnd:n={},transition:s={},...o}=i||{};o={...o,...n};for(const r in o){const a=Ev(o[r]);kv(t,r,a)}}function Av(t){return!!(Ge(t)&&t.add)}function mr(t,e){const i=t.getValue("willChange");if(Av(i))return i.add(e);if(!i&&Bt.WillChange){const n=new Bt.WillChange("auto");t.addValue("willChange",n),n.add(e)}}function cd(t){return t.props[Qc]}const Rv=t=>t!==null;function xv(t,{repeat:e,repeatType:i="loop"},n){const s=t.filter(Rv),o=e&&i!=="loop"&&e%2===1?0:s.length-1;return s[o]}const Dv={type:"spring",stiffness:500,damping:25,restSpeed:10},Lv=t=>({type:"spring",stiffness:550,damping:t===0?2*Math.sqrt(550):30,restSpeed:10}),Mv={type:"keyframes",duration:.8},Ov={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},Pv=(t,{keyframes:e})=>e.length>2?Mv:Ri.has(t)?t.startsWith("scale")?Lv(e[1]):Dv:Ov;function Nv({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 vr=(t,e,i,n={},s,o)=>r=>{const a=tr(n,t)||{},l=a.delay||n.delay||0;let{elapsed:c=0}=n;c=c-Et(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};Nv(a)||Object.assign(u,Pv(t,u)),u.duration&&(u.duration=Et(u.duration)),u.repeatDelay&&(u.repeatDelay=Et(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)),(Bt.instantAnimations||Bt.skipAnimations)&&(d=!0,u.duration=0,u.delay=0),u.allowFlatten=!a.type&&!a.ease,d&&!o&&e.get()!==void 0){const h=xv(u.keyframes,a);if(h!==void 0){Ce.update(()=>{u.onUpdate(h),u.onComplete()});return}}return a.isSync?new Go(u):new _m(u)};function Fv({protectedKeys:t,needsAnimating:e},i){const n=t.hasOwnProperty(i)&&e[i]!==!0;return e[i]=!1,n}function dd(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&&Fv(c,u))continue;const p={delay:i,...tr(o||{},u)},m=d.get();if(m!==void 0&&!d.isAnimating&&!Array.isArray(h)&&h===m&&!p.velocity)continue;let v=!1;if(window.MotionHandoffAnimation){const y=cd(t);if(y){const C=window.MotionHandoffAnimation(y,u,Ce);C!==null&&(p.startTime=C,v=!0)}}mr(t,u),d.start(vr(u,d,h,t.shouldReduceMotion&&Ic.has(u)?{type:!1}:p,t,v));const b=d.animation;b&&l.push(b)}return r&&Promise.all(l).then(()=>{Ce.update(()=>{r&&Iv(t,r)})}),l}function _r(t,e,i={}){var l;const n=vn(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(dd(t,n,i)):()=>Promise.resolve(),r=t.variantChildren&&t.variantChildren.size?(c=0)=>{const{delayChildren:u=0,staggerChildren:d,staggerDirection:h}=s;return Uv(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 Uv(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(Bv).forEach((h,p)=>{h.notify("AnimationStart",e),a.push(_r(h,e,{...r,delay:i+(u?0:n)+d(p)}).then(()=>h.notify("AnimationComplete",e)))}),Promise.all(a)}function Bv(t,e){return t.sortNodePosition(e)}function Vv(t,e,i={}){t.notify("AnimationStart",e);let n;if(Array.isArray(e)){const s=e.map(o=>_r(t,o,i));n=Promise.all(s)}else if(typeof e=="string")n=_r(t,e,i);else{const s=typeof e=="function"?vn(t,e,i.custom):e;n=Promise.all(dd(t,s,i))}return n.then(()=>{t.notify("AnimationComplete",e)})}function ud(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 $v=lr.length;function hd(t){if(!t)return;if(!t.isControllingVariants){const i=t.parent?hd(t.parent)||{}:{};return t.props.initial!==void 0&&(i.initial=t.props.initial),i}const e={};for(let i=0;i<$v;i++){const n=lr[i],s=t.props[n];(gn(s)||s===!1)&&(e[n]=s)}return e}const jv=[...ar].reverse(),Hv=ar.length;function Wv(t){return e=>Promise.all(e.map(({animation:i,options:n})=>Vv(t,i,n)))}function Gv(t){let e=Wv(t),i=fd(),n=!0;const s=l=>(c,u)=>{var h;const d=vn(t,u,l==="exit"?(h=t.presenceContext)==null?void 0:h.custom:void 0);if(d){const{transition:p,transitionEnd:m,...v}=d;c={...c,...v,...m}}return c};function o(l){e=l(t)}function r(l){const{props:c}=t,u=hd(t.parent)||{},d=[],h=new Set;let p={},m=1/0;for(let b=0;b<Hv;b++){const y=jv[b],C=i[y],T=c[y]!==void 0?c[y]:u[y],A=gn(T),x=y===l?C.isActive:null;x===!1&&(m=b);let N=T===u[y]&&T!==c[y]&&A;if(N&&n&&t.manuallyAnimateOnMount&&(N=!1),C.protectedKeys={...p},!C.isActive&&x===null||!T&&!C.prevProp||ds(T)||typeof T=="boolean")continue;const E=qv(C.prevProp,T);let k=E||y===l&&C.isActive&&!N&&A||b>m&&A,f=!1;const _=Array.isArray(T)?T:[T];let g=_.reduce(s(y),{});x===!1&&(g={});const{prevResolvedValues:S={}}=C,I={...S,...g},M=O=>{k=!0,h.has(O)&&(f=!0,h.delete(O)),C.needsAnimating[O]=!0;const L=t.getValue(O);L&&(L.liveStyle=!1)};for(const O in I){const L=g[O],V=S[O];if(p.hasOwnProperty(O))continue;let $=!1;gr(L)&&gr(V)?$=!ud(L,V):$=L!==V,$?L!=null?M(O):h.add(O):L!==void 0&&h.has(O)?M(O):C.protectedKeys[O]=!0}C.prevProp=T,C.prevResolvedValues=g,C.isActive&&(p={...p,...g}),n&&t.blockInitialAnimation&&(k=!1),k&&(!(N&&E)||f)&&d.push(..._.map(O=>({animation:O,options:{type:y}})))}if(h.size){const b={};if(typeof c.initial!="boolean"){const y=vn(t,Array.isArray(c.initial)?c.initial[0]:c.initial);y&&y.transition&&(b.transition=y.transition)}h.forEach(y=>{const C=t.getBaseTarget(y),T=t.getValue(y);T&&(T.liveStyle=!0),b[y]=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=fd(),n=!0}}}function qv(t,e){return typeof e=="string"?e!==t:Array.isArray(e)?!ud(e,t):!1}function ci(t=!1){return{isActive:t,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function fd(){return{animate:ci(!0),whileInView:ci(),whileHover:ci(),whileTap:ci(),whileDrag:ci(),whileFocus:ci(),exit:ci()}}class Yt{constructor(e){this.isMounted=!1,this.node=e}update(){}}class zv extends Yt{constructor(e){super(e),e.animationState||(e.animationState=Gv(e))}updateAnimationControlsSubscription(){const{animate:e}=this.node.getProps();ds(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 Kv=0;class Yv extends Yt{constructor(){super(...arguments),this.id=Kv++}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 Xv={animation:{Feature:zv},exit:{Feature:Yv}};function _n(t,e,i,n={passive:!0}){return t.addEventListener(e,i,n),()=>t.removeEventListener(e,i)}function yn(t){return{point:{x:t.pageX,y:t.pageY}}}const Jv=t=>e=>or(e)&&t(e,yn(e));function bn(t,e,i,n){return _n(t,e,Jv(i),n)}function pd({top:t,left:e,right:i,bottom:n}){return{x:{min:e,max:i},y:{min:t,max:n}}}function Qv({x:t,y:e}){return{top:e.min,right:t.max,bottom:e.max,left:t.min}}function Zv(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 gd=1e-4,e_=1-gd,t_=1+gd,md=.01,i_=0-md,n_=0+md;function Ke(t){return t.max-t.min}function s_(t,e,i){return Math.abs(t-e)<=i}function vd(t,e,i,n=.5){t.origin=n,t.originPoint=ke(e.min,e.max,t.origin),t.scale=Ke(i)/Ke(e),t.translate=ke(i.min,i.max,t.origin)-t.originPoint,(t.scale>=e_&&t.scale<=t_||isNaN(t.scale))&&(t.scale=1),(t.translate>=i_&&t.translate<=n_||isNaN(t.translate))&&(t.translate=0)}function wn(t,e,i,n){vd(t.x,e.x,i.x,n?n.originX:void 0),vd(t.y,e.y,i.y,n?n.originY:void 0)}function _d(t,e,i){t.min=i.min+e.min,t.max=t.min+Ke(e)}function o_(t,e,i){_d(t.x,e.x,i.x),_d(t.y,e.y,i.y)}function yd(t,e,i){t.min=e.min-i.min,t.max=t.min+Ke(e)}function Sn(t,e,i){yd(t.x,e.x,i.x),yd(t.y,e.y,i.y)}const bd=()=>({translate:0,scale:1,origin:0,originPoint:0}),Mi=()=>({x:bd(),y:bd()}),wd=()=>({min:0,max:0}),De=()=>({x:wd(),y:wd()});function ht(t){return[t("x"),t("y")]}function yr(t){return t===void 0||t===1}function br({scale:t,scaleX:e,scaleY:i}){return!yr(t)||!yr(e)||!yr(i)}function di(t){return br(t)||Sd(t)||t.z||t.rotate||t.rotateX||t.rotateY||t.skewX||t.skewY}function Sd(t){return Cd(t.x)||Cd(t.y)}function Cd(t){return t&&t!=="0%"}function fs(t,e,i){const n=t-i,s=e*n;return i+s}function Td(t,e,i,n,s){return s!==void 0&&(t=fs(t,s,n)),fs(t,i,n)+e}function wr(t,e=0,i=1,n,s){t.min=Td(t.min,e,i,n,s),t.max=Td(t.max,e,i,n,s)}function kd(t,{x:e,y:i}){wr(t.x,e.translate,e.scale,e.originPoint),wr(t.y,i.translate,i.scale,i.originPoint)}const Ed=.999999999999,Id=1.0000000000001;function r_(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&&Pi(t,{x:-o.scroll.offset.x,y:-o.scroll.offset.y}),r&&(e.x*=r.x.scale,e.y*=r.y.scale,kd(t,r)),n&&di(o.latestValues)&&Pi(t,o.latestValues))}e.x<Id&&e.x>Ed&&(e.x=1),e.y<Id&&e.y>Ed&&(e.y=1)}function Oi(t,e){t.min=t.min+e,t.max=t.max+e}function Ad(t,e,i,n,s=.5){const o=ke(t.min,t.max,s);wr(t,e,i,o,n)}function Pi(t,e){Ad(t.x,e.x,e.scaleX,e.scale,e.originX),Ad(t.y,e.y,e.scaleY,e.scale,e.originY)}function Rd(t,e){return pd(Zv(t.getBoundingClientRect(),e))}function a_(t,e,i){const n=Rd(t,i),{scroll:s}=e;return s&&(Oi(n.x,s.offset.x),Oi(n.y,s.offset.y)),n}const xd=({current:t})=>t?t.ownerDocument.defaultView:null,Dd=(t,e)=>Math.abs(t-e);function l_(t,e){const i=Dd(t.x,e.x),n=Dd(t.y,e.y);return Math.sqrt(i**2+n**2)}class Ld{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=Cr(this.lastMoveEventInfo,this.history),p=this.startEvent!==null,m=l_(h.offset,{x:0,y:0})>=this.distanceThreshold;if(!p&&!m)return;const{point:v}=h,{timestamp:b}=$e;this.history.push({...v,timestamp:b});const{onStart:y,onMove:C}=this.handlers;p||(y&&y(this.lastMoveEvent,h),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,h)},this.handlePointerMove=(h,p)=>{this.lastMoveEvent=h,this.lastMoveEventInfo=Sr(p,this.transformPagePoint),Ce.update(this.updatePoint,!0)},this.handlePointerUp=(h,p)=>{this.end();const{onEnd:m,onSessionEnd:v,resumeAnimation:b}=this.handlers;if(this.dragSnapToOrigin&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const y=Cr(h.type==="pointercancel"?this.lastMoveEventInfo:Sr(p,this.transformPagePoint),this.history);this.startEvent&&m&&m(h,y),v&&v(h,y)},!or(e))return;this.dragSnapToOrigin=o,this.handlers=i,this.transformPagePoint=n,this.distanceThreshold=r,this.contextWindow=s||window;const a=yn(e),l=Sr(a,this.transformPagePoint),{point:c}=l,{timestamp:u}=$e;this.history=[{...c,timestamp:u}];const{onSessionStart:d}=i;d&&d(e,Cr(l,this.history)),this.removeListeners=on(bn(this.contextWindow,"pointermove",this.handlePointerMove),bn(this.contextWindow,"pointerup",this.handlePointerUp),bn(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),qt(this.updatePoint)}}function Sr(t,e){return e?{point:e(t.point)}:t}function Md(t,e){return{x:t.x-e.x,y:t.y-e.y}}function Cr({point:t},e){return{point:t,delta:Md(t,Od(e)),offset:Md(t,c_(e)),velocity:d_(e,.1)}}function c_(t){return t[0]}function Od(t){return t[t.length-1]}function d_(t,e){if(t.length<2)return{x:0,y:0};let i=t.length-1,n=null;const s=Od(t);for(;i>=0&&(n=t[i],!(s.timestamp-n.timestamp>Et(e)));)i--;if(!n)return{x:0,y:0};const o=It(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 u_(t,{min:e,max:i},n){return e!==void 0&&t<e?t=n?ke(e,t,n.min):Math.max(t,e):i!==void 0&&t>i&&(t=n?ke(i,t,n.max):Math.min(t,i)),t}function Pd(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 h_(t,{top:e,left:i,bottom:n,right:s}){return{x:Pd(t.x,i,s),y:Pd(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 f_(t,e){return{x:Nd(t.x,e.x),y:Nd(t.y,e.y)}}function p_(t,e){let i=.5;const n=Ke(t),s=Ke(e);return s>n?i=rn(e.min,e.max-n,t.min):n>s&&(i=rn(t.min,t.max-s,e.min)),Ut(0,1,i)}function g_(t,e){const i={};return e.min!==void 0&&(i.min=e.min-t.min),e.max!==void 0&&(i.max=e.max-t.min),i}const Tr=.35;function m_(t=Tr){return t===!1?t=0:t===!0&&(t=Tr),{x:Fd(t,"left","right"),y:Fd(t,"top","bottom")}}function Fd(t,e,i){return{min:Ud(t,e),max:Ud(t,i)}}function Ud(t,e){return typeof t=="number"?t:t[e]||0}const v_=new WeakMap;class __{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=De(),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(yn(d).point)},r=(d,h)=>{const{drag:p,dragPropagation:m,onDragStart:v}=this.getProps();if(p&&!m&&(this.openDragLock&&this.openDragLock(),this.openDragLock=Mm(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),ht(y=>{let C=this.getAxisMotionValue(y).get()||0;if(At.test(C)){const{projection:T}=this.visualElement;if(T&&T.layout){const A=T.layout.layoutBox[y];A&&(C=Ke(A)*(parseFloat(C)/100))}}this.originPoint[y]=C}),v&&Ce.postRender(()=>v(d,h)),mr(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:m,onDirectionLock:v,onDrag:b}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:y}=h;if(m&&this.currentDirection===null){this.currentDirection=y_(y),this.currentDirection!==null&&v&&v(this.currentDirection);return}this.updateAxis("x",h.point,y),this.updateAxis("y",h.point,y),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=()=>ht(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 Ld(e,{onSessionStart:o,onStart:r,onMove:a,onSessionEnd:l,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:n,contextWindow:xd(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&&Ce.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||!ps(e,s,this.currentDirection))return;const o=this.getAxisMotionValue(e);let r=this.originPoint[e]+n[e];this.constraints&&this.constraints[e]&&(r=u_(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&&Li(e)?this.constraints||(this.constraints=this.resolveRefConstraints()):e&&n?this.constraints=h_(n.layoutBox,e):this.constraints=!1,this.elastic=m_(i),s!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&ht(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=g_(n.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:e,onMeasureDragConstraints:i}=this.getProps();if(!e||!Li(e))return!1;const n=e.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const o=a_(n,s.root,this.visualElement.getTransformPagePoint());let r=f_(s.layout.layoutBox,o);if(i){const a=i(Qv(r));this.hasMutatedConstraints=!!a,a&&(r=pd(a))}return r}startAnimation(e){const{drag:i,dragMomentum:n,dragElastic:s,dragTransition:o,dragSnapToOrigin:r,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=ht(u=>{if(!ps(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,m={type:"inertia",velocity:n?e[u]:0,bounceStiffness:h,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...o,...d};return this.startAxisValueAnimation(u,m)});return Promise.all(c).then(a)}startAxisValueAnimation(e,i){const n=this.getAxisMotionValue(e);return mr(this.visualElement,e),n.start(vr(e,n,0,i,this.visualElement,!1))}stopAnimation(){ht(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){ht(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){ht(i=>{const{drag:n}=this.getProps();if(!ps(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]-ke(r,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:e,dragConstraints:i}=this.getProps(),{projection:n}=this.visualElement;if(!Li(i)||!n||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};ht(r=>{const a=this.getAxisMotionValue(r);if(a&&this.constraints!==!1){const l=a.get();s[r]=p_({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(),ht(r=>{if(!ps(r,e,null))return;const a=this.getAxisMotionValue(r),{min:l,max:c}=this.constraints[r];a.set(ke(l,c,s[r]))})}addListeners(){if(!this.visualElement.current)return;v_.set(this.visualElement,this);const e=this.visualElement.current,i=bn(e,"pointerdown",l=>{const{drag:c,dragListener:u=!0}=this.getProps();c&&u&&this.start(l)}),n=()=>{const{dragConstraints:l}=this.getProps();Li(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()),Ce.read(n);const r=_n(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(ht(u=>{const d=this.getAxisMotionValue(u);d&&(this.originPoint[u]+=l[u].translate,d.set(d.get()+l[u].translate))}),this.visualElement.render())});return()=>{r(),i(),o(),a&&a()}}getProps(){const e=this.visualElement.getProps(),{drag:i=!1,dragDirectionLock:n=!1,dragPropagation:s=!1,dragConstraints:o=!1,dragElastic:r=Tr,dragMomentum:a=!0}=e;return{...e,drag:i,dragDirectionLock:n,dragPropagation:s,dragConstraints:o,dragElastic:r,dragMomentum:a}}}function ps(t,e,i){return(e===!0||e===t)&&(i===null||i===t)}function y_(t,e=10){let i=null;return Math.abs(t.y)>e?i="y":Math.abs(t.x)>e&&(i="x"),i}class b_ extends Yt{constructor(e){super(e),this.removeGroupControls=ut,this.removeListeners=ut,this.controls=new __(e)}mount(){const{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ut}unmount(){this.removeGroupControls(),this.removeListeners()}}const Bd=t=>(e,i)=>{t&&Ce.postRender(()=>t(e,i))};class w_ extends Yt{constructor(){super(...arguments),this.removePointerDownListener=ut}onPointerDown(e){this.session=new Ld(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xd(this.node)})}createPanHandlers(){const{onPanSessionStart:e,onPanStart:i,onPan:n,onPanEnd:s}=this.node.getProps();return{onSessionStart:Bd(e),onStart:Bd(i),onMove:n,onEnd:(o,r)=>{delete this.session,s&&Ce.postRender(()=>s(o,r))}}}mount(){this.removePointerDownListener=bn(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 gs={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Vd(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(Q.test(t))t=parseFloat(t);else return t;const i=Vd(t,e.target.x),n=Vd(t,e.target.y);return`${i}% ${n}%`}},S_={correct:(t,{treeScale:e,projectionDelta:i})=>{const n=t,s=Kt.parse(t);if(s.length>5)return n;const o=Kt.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=ke(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 $d=!1;class C_ extends bt{componentDidMount(){const{visualElement:e,layoutGroup:i,switchLayoutGroup:n,layoutId:s}=this.props,{projection:o}=e;av(T_),o&&(i.group&&i.group.add(o),n&&n.register&&s&&n.register(o),$d&&o.root.didUpdate(),o.addEventListener("animationComplete",()=>{this.safeToRemove()}),o.setOptions({...o.options,onExitComplete:()=>this.safeToRemove()})),gs.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){const{layoutDependency:i,visualElement:n,drag:s,isPresent:o}=this.props,{projection:r}=n;return r&&(r.isPresent=o,$d=!0,s||e.layoutDependency!==i||i===void 0||e.isPresent!==o?r.willUpdate():this.safeToRemove(),e.isPresent!==o&&(o?r.promote():r.relegate()||Ce.postRender(()=>{const a=r.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),sr.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 jd(t){const[e,i]=Hc(),n=Fe(yo);return D(C_,{...t,layoutGroup:n,switchLayoutGroup:Fe(Zc),isPresent:e,safeToRemove:i})}const T_={borderRadius:{...Cn,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Cn,borderTopRightRadius:Cn,borderBottomLeftRadius:Cn,borderBottomRightRadius:Cn,boxShadow:S_};function k_(t,e,i){const n=Ge(t)?t:xi(t);return n.start(vr("",n,e,i)),n.animation}const E_=(t,e)=>t.depth-e.depth;class I_{constructor(){this.children=[],this.isDirty=!1}add(e){wo(this.children,e),this.isDirty=!0}remove(e){So(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(E_),this.isDirty=!1,this.children.forEach(e)}}function A_(t,e){const i=tt.now(),n=({timestamp:s})=>{const o=s-i;o>=e&&(qt(n),t(o-e))};return Ce.setup(n,!0),()=>qt(n)}const Hd=["TopLeft","TopRight","BottomLeft","BottomRight"],R_=Hd.length,Wd=t=>typeof t=="string"?parseFloat(t):t,Gd=t=>typeof t=="number"||Q.test(t);function x_(t,e,i,n,s,o){s?(t.opacity=ke(0,i.opacity??1,D_(n)),t.opacityExit=ke(e.opacity??1,0,L_(n))):o&&(t.opacity=ke(e.opacity??1,i.opacity??1,n));for(let r=0;r<R_;r++){const a=`border${Hd[r]}Radius`;let l=qd(e,a),c=qd(i,a);if(l===void 0&&c===void 0)continue;l||(l=0),c||(c=0),l===0||c===0||Gd(l)===Gd(c)?(t[a]=Math.max(ke(Wd(l),Wd(c),n),0),(At.test(c)||At.test(l))&&(t[a]+="%")):t[a]=c}(e.rotate||i.rotate)&&(t.rotate=ke(e.rotate||0,i.rotate||0,n))}function qd(t,e){return t[e]!==void 0?t[e]:t.borderRadius}const D_=zd(0,.5,Wl),L_=zd(.5,.95,ut);function zd(t,e,i){return n=>n<t?0:n>e?1:i(rn(t,e,n))}function Kd(t,e){t.min=e.min,t.max=e.max}function ft(t,e){Kd(t.x,e.x),Kd(t.y,e.y)}function Yd(t,e){t.translate=e.translate,t.scale=e.scale,t.originPoint=e.originPoint,t.origin=e.origin}function Xd(t,e,i,n,s){return t-=e,t=fs(t,1/i,n),s!==void 0&&(t=fs(t,1/s,n)),t}function M_(t,e=0,i=1,n=.5,s,o=t,r=t){if(At.test(e)&&(e=parseFloat(e),e=ke(r.min,r.max,e/100)-r.min),typeof e!="number")return;let a=ke(o.min,o.max,n);t===o&&(a-=e),t.min=Xd(t.min,e,i,a,s),t.max=Xd(t.max,e,i,a,s)}function Jd(t,e,[i,n,s],o,r){M_(t,e[i],e[n],e[s],e.scale,o,r)}const O_=["x","scaleX","originX"],P_=["y","scaleY","originY"];function Qd(t,e,i,n){Jd(t.x,e,O_,i?i.x:void 0,n?n.x:void 0),Jd(t.y,e,P_,i?i.y:void 0,n?n.y:void 0)}function Zd(t){return t.translate===0&&t.scale===1}function eu(t){return Zd(t.x)&&Zd(t.y)}function tu(t,e){return t.min===e.min&&t.max===e.max}function N_(t,e){return tu(t.x,e.x)&&tu(t.y,e.y)}function iu(t,e){return Math.round(t.min)===Math.round(e.min)&&Math.round(t.max)===Math.round(e.max)}function nu(t,e){return iu(t.x,e.x)&&iu(t.y,e.y)}function su(t){return Ke(t.x)/Ke(t.y)}function ou(t,e){return t.translate===e.translate&&t.scale===e.scale&&t.originPoint===e.originPoint}class F_{constructor(){this.members=[]}add(e){wo(this.members,e),e.scheduleRender()}remove(e){if(So(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 U_(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:m}=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) `),m&&(n+=`skewY(${m}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 kr=["","X","Y","Z"],B_=1e3;let V_=0;function Er(t,e,i,n){const{latestValues:s}=e;s[t]&&(i[t]=s[t],e.setStaticValue(t,0),n&&(n[t]=0))}function ru(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;const{visualElement:e}=t.options;if(!e)return;const i=cd(e);if(window.MotionHasOptimisedAnimation(i,"transform")){const{layout:s,layoutId:o}=t.options;window.MotionCancelOptimisedAnimation(i,"transform",Ce,!(s||o))}const{parent:n}=t;n&&!n.hasCheckedOptimisedAppear&&ru(n)}function au({attachResizeListener:t,defaultParent:e,measureScroll:i,checkIsScrollRoot:n,resetTransform:s}){return class{constructor(r={},a=e==null?void 0:e()){this.id=V_++,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(H_),this.nodes.forEach(z_),this.nodes.forEach(K_),this.nodes.forEach(W_)},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 I_)}addEventListener(r,a){return this.eventHandlers.has(r)||this.eventHandlers.set(r,new ko),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=jc(r)&&!Bm(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;Ce.read(()=>{d=window.innerWidth}),t(r,()=>{const p=window.innerWidth;p!==d&&(d=p,this.root.updateBlockedByResize=!0,u&&u(),u=A_(h,250),gs.hasAnimatedSinceResize&&(gs.hasAnimatedSinceResize=!1,this.nodes.forEach(du)))})}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 m=this.options.transition||c.getDefaultTransition()||Z_,{onLayoutAnimationStart:v,onLayoutAnimationComplete:b}=c.getProps(),y=!this.targetLayout||!nu(this.targetLayout,p),C=!d&&h;if(this.options.layoutRoot||this.resumeFrom||C||d&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const T={...tr(m,"layout"),onPlay:v,onComplete:b};(c.shouldReduceMotion||this.options.layoutRoot)&&(T.delay=0,T.type=!1),this.startAnimation(T),this.setAnimationOrigin(u,C)}else d||du(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(),qt(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(Y_),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&&ru(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(lu);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(cu);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(q_),this.nodes.forEach($_),this.nodes.forEach(j_)):this.nodes.forEach(cu),this.clearAllSnapshots();const a=tt.now();$e.delta=Ut(0,1e3/60,a-$e.timestamp),$e.timestamp=a,$e.isProcessing=!0,Ao.update.process($e),Ao.preRender.process($e),Ao.render.process($e),$e.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,sr.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(G_),this.sharedNodes.forEach(X_)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,Ce.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){Ce.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Ke(this.snapshot.measuredBox.x)&&!Ke(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=De(),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&&!eu(this.projectionDelta),l=this.getTransformTemplate(),c=l?l(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;r&&this.instance&&(a||di(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)),ey(l),{animationId:this.root.animationId,measuredBox:a,layoutBox:l,latestValues:{},source:this.id}}measurePageBox(){var c;const{visualElement:r}=this.options;if(!r)return De();const a=r.measureViewportBox();if(!(((c=this.scroll)==null?void 0:c.wasRoot)||this.path.some(ty))){const{scroll:u}=this.root;u&&(Oi(a.x,u.offset.x),Oi(a.y,u.offset.y))}return a}removeElementScroll(r){var l;const a=De();if(ft(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&&ft(a,r),Oi(a.x,d.offset.x),Oi(a.y,d.offset.y))}return a}applyTransform(r,a=!1){const l=De();ft(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&&Pi(l,{x:-u.scroll.offset.x,y:-u.scroll.offset.y}),di(u.latestValues)&&Pi(l,u.latestValues)}return di(this.latestValues)&&Pi(l,this.latestValues),l}removeTransform(r){const a=De();ft(a,r);for(let l=0;l<this.path.length;l++){const c=this.path[l];if(!c.instance||!di(c.latestValues))continue;br(c.latestValues)&&c.updateSnapshot();const u=De(),d=c.measurePageBox();ft(u,d),Qd(a,c.latestValues,c.snapshot?c.snapshot.layoutBox:void 0,u)}return di(this.latestValues)&&Qd(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!==$e.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=$e.timestamp,!this.targetDelta&&!this.relativeTarget){const p=this.getClosestProjectingParent();p&&p.layout&&this.animationProgress!==1?(this.relativeParent=p,this.forceRelativeParentToResolveTarget(),this.relativeTarget=De(),this.relativeTargetOrigin=De(),Sn(this.relativeTargetOrigin,this.layout.layoutBox,p.layout.layoutBox),ft(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=De(),this.targetWithTransforms=De()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),o_(this.target,this.relativeTarget,this.relativeParent.target)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):ft(this.target,this.layout.layoutBox),kd(this.target,this.targetDelta)):ft(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=De(),this.relativeTargetOrigin=De(),Sn(this.relativeTargetOrigin,this.target,p.target),ft(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}}}getClosestProjectingParent(){if(!(!this.parent||br(this.parent.latestValues)||Sd(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 m;const r=this.getLead(),a=!!this.resumingFrom||this!==r;let l=!0;if((this.isProjectionDirty||(m=this.parent)!=null&&m.isProjectionDirty)&&(l=!1),a&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(l=!1),this.resolvedRelativeTargetAt===$e.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;ft(this.layoutCorrected,this.layout.layoutBox);const d=this.treeScale.x,h=this.treeScale.y;r_(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=De());const{target:p}=r;if(!p){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(Yd(this.prevProjectionDelta.x,this.projectionDelta.x),Yd(this.prevProjectionDelta.y,this.projectionDelta.y)),wn(this.projectionDelta,this.layoutCorrected,p,this.latestValues),(this.treeScale.x!==d||this.treeScale.y!==h||!ou(this.projectionDelta.x,this.prevProjectionDelta.x)||!ou(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=Mi(),this.projectionDelta=Mi(),this.projectionDeltaWithTransform=Mi()}setAnimationOrigin(r,a=!1){const l=this.snapshot,c=l?l.latestValues:{},u={...this.latestValues},d=Mi();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!a;const h=De(),p=l?l.source:void 0,m=this.layout?this.layout.source:void 0,v=p!==m,b=this.getStack(),y=!b||b.members.length<=1,C=!!(v&&!y&&this.options.crossfade===!0&&!this.path.some(Q_));this.animationProgress=0;let T;this.mixTargetDelta=A=>{const x=A/1e3;uu(d.x,r.x,x),uu(d.y,r.y,x),this.setTargetDelta(d),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(Sn(h,this.layout.layoutBox,this.relativeParent.layout.layoutBox),J_(this.relativeTarget,this.relativeTargetOrigin,h,x),T&&N_(this.relativeTarget,T)&&(this.isProjectionDirty=!1),T||(T=De()),ft(T,this.relativeTarget)),v&&(this.animationValues=u,x_(u,c,this.latestValues,x,C,y)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=x},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(r){var a,l,c;this.notifyListeners("animationStart"),(a=this.currentAnimation)==null||a.stop(),(c=(l=this.resumingFrom)==null?void 0:l.currentAnimation)==null||c.stop(),this.pendingAnimation&&(qt(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=Ce.update(()=>{gs.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=xi(0)),this.currentAnimation=k_(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(B_),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&&mu(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||De();const d=Ke(this.layout.layoutBox.x);l.x.min=r.target.x.min,l.x.max=l.x.min+d;const h=Ke(this.layout.layoutBox.y);l.y.min=r.target.y.min,l.y.max=l.y.min+h}ft(a,l),Pi(a,u),wn(this.projectionDeltaWithTransform,this.layoutCorrected,a,u)}}registerSharedNode(r,a){this.sharedNodes.has(r)||this.sharedNodes.set(r,new F_),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&&Er("z",r,c,this.animationValues);for(let u=0;u<kr.length;u++)Er(`rotate${kr[u]}`,r,c,this.animationValues),Er(`skew${kr[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=hs(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=hs(a==null?void 0:a.pointerEvents)||""),this.hasProjected&&!di(this.latestValues)&&(r.transform=l?l({},""):"none",this.hasProjected=!1);return}r.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let d=U_(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 m in mn){if(u[m]===void 0)continue;const{correct:v,applyTo:b,isCSSVariable:y}=mn[m],C=d==="none"?u[m]:v(u[m],c);if(b){const T=b.length;for(let A=0;A<T;A++)r[b[A]]=C}else y?this.options.visualElement.renderState.vars[m]=C:r[m]=C}this.options.layoutId&&(r.pointerEvents=c===this?hs(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(lu),this.root.sharedNodes.clear()}}}function $_(t){t.updateLayout()}function j_(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"?ht(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(h);h.min=n[d].min,h.max=h.min+p}):mu(o,e.layoutBox,n)&&ht(d=>{const h=r?e.measuredBox[d]:e.layoutBox[d],p=Ke(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=Mi();wn(a,n,e.layoutBox);const l=Mi();r?wn(l,t.applyTransform(s,!0),e.measuredBox):wn(l,n,e.layoutBox);const c=!eu(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 m=De();Sn(m,e.layoutBox,h.layoutBox);const v=De();Sn(v,n,p.layoutBox),nu(m,v)||(u=!0),d.options.layoutRoot&&(t.relativeTarget=v,t.relativeTargetOrigin=m,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 H_(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 W_(t){t.isProjectionDirty=t.isSharedProjectionDirty=t.isTransformDirty=!1}function G_(t){t.clearSnapshot()}function lu(t){t.clearMeasurements()}function cu(t){t.isLayoutDirty=!1}function q_(t){const{visualElement:e}=t.options;e&&e.getProps().onBeforeLayoutMeasure&&e.notify("BeforeLayoutMeasure"),t.resetTransform()}function du(t){t.finishAnimation(),t.targetDelta=t.relativeTarget=t.target=void 0,t.isProjectionDirty=!0}function z_(t){t.resolveTargetDelta()}function K_(t){t.calcProjection()}function Y_(t){t.resetSkewAndRotation()}function X_(t){t.removeLeadSnapshot()}function uu(t,e,i){t.translate=ke(e.translate,0,i),t.scale=ke(e.scale,1,i),t.origin=e.origin,t.originPoint=e.originPoint}function hu(t,e,i,n){t.min=ke(e.min,i.min,n),t.max=ke(e.max,i.max,n)}function J_(t,e,i,n){hu(t.x,e.x,i.x,n),hu(t.y,e.y,i.y,n)}function Q_(t){return t.animationValues&&t.animationValues.opacityExit!==void 0}const Z_={duration:.45,ease:[.4,0,.1,1]},fu=t=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(t),pu=fu("applewebkit/")&&!fu("chrome/")?Math.round:ut;function gu(t){t.min=pu(t.min),t.max=pu(t.max)}function ey(t){gu(t.x),gu(t.y)}function mu(t,e,i){return t==="position"||t==="preserve-aspect"&&!s_(su(e),su(i),.2)}function ty(t){var e;return t!==t.root&&((e=t.scroll)==null?void 0:e.wasRoot)}const iy=au({attachResizeListener:(t,e)=>_n(t,"resize",e),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Ir={current:void 0},vu=au({measureScroll:t=>({x:t.scrollLeft,y:t.scrollTop}),defaultParent:()=>{if(!Ir.current){const t=new iy({});t.mount(window),t.setOptions({layoutScroll:!0}),Ir.current=t}return Ir.current},resetTransform:(t,e)=>{t.style.transform=e!==void 0?e:"none"},checkIsScrollRoot:t=>window.getComputedStyle(t).position==="fixed"}),ny={pan:{Feature:w_},drag:{Feature:b_,ProjectionNode:vu,MeasureLayout:jd}};function _u(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&&Ce.postRender(()=>o(e,yn(e)))}class sy extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Om(e,(i,n)=>(_u(this.node,n,"Start"),s=>_u(this.node,s,"End"))))}unmount(){}}class oy extends Yt{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=on(_n(this.node.current,"focus",()=>this.onFocus()),_n(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function yu(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&&Ce.postRender(()=>o(e,yn(e)))}class ry extends Yt{mount(){const{current:e}=this.node;e&&(this.unmount=Um(e,(i,n)=>(yu(this.node,n,"Start"),(s,{success:o})=>yu(this.node,s,o?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}const Ar=new WeakMap,Rr=new WeakMap,ay=t=>{const e=Ar.get(t.target);e&&e(t)},ly=t=>{t.forEach(ay)};function cy({root:t,...e}){const i=t||document;Rr.has(i)||Rr.set(i,{});const n=Rr.get(i),s=JSON.stringify(e);return n[s]||(n[s]=new IntersectionObserver(ly,{root:t,...e})),n[s]}function dy(t,e,i){const n=cy(e);return Ar.set(t,i),n.observe(t),()=>{Ar.delete(t),n.unobserve(t)}}const uy={some:0,all:1};class hy extends Yt{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:uy[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 dy(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(fy(e,i))&&this.startObserver()}unmount(){}}function fy({viewport:t={}},{viewport:e={}}={}){return i=>t[i]!==e[i]}const py={inView:{Feature:hy},tap:{Feature:ry},focus:{Feature:oy},hover:{Feature:sy}},gy={layout:{ProjectionNode:vu,MeasureLayout:jd}},xr={current:null},bu={current:!1};function my(){if(bu.current=!0,!!bo)if(window.matchMedia){const t=window.matchMedia("(prefers-reduced-motion)"),e=()=>xr.current=t.matches;t.addEventListener("change",e),e()}else xr.current=!1}const vy=new WeakMap;function _y(t,e,i){for(const n in e){const s=e[n],o=i[n];if(Ge(s))t.addValue(n,s);else if(Ge(o))t.addValue(n,xi(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,xi(r!==void 0?r:s,{owner:t}))}}for(const n in i)e[n]===void 0&&t.removeValue(n);return e}const wu=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class yy{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=Zo,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=tt.now();this.renderScheduledAt<h&&(this.renderScheduledAt=h,Ce.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=us(i),this.isVariantNode=Xc(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&&Ge(p)&&p.set(l[h],!1)}}mount(e){this.current=e,vy.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)),bu.current||my(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:xr.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){this.projection&&this.projection.unmount(),qt(this.notifyUpdate),qt(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=Ri.has(e);n&&this.onBindTransform&&this.onBindTransform();const s=i.on("change",a=>{this.latestValues[e]=a,this.props.onUpdate&&Ce.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 Di){const i=Di[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):De()}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<wu.length;n++){const s=wu[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=_y(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=xi(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"&&(Ol(n)||Nl(n))?n=parseFloat(n):!$m(n)&&Kt.test(i)&&(n=Mc(e,i)),this.setBaseTarget(e,Ge(n)?n.get():n)),Ge(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=fr(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&&!Ge(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 ko),this.events[e].add(i)}notify(e,...i){this.events[e]&&this.events[e].notify(...i)}}class Su extends yy{constructor(){super(...arguments),this.KeyframeResolver=Rm}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;Ge(e)&&(this.childSubscription=e.on("change",i=>{this.current&&(this.current.textContent=`${i}`)}))}}function Cu(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 by(t){return window.getComputedStyle(t)}class wy extends Su{constructor(){super(...arguments),this.type="html",this.renderInstance=Cu}readValueFromInstance(e,i){var n;if(Ri.has(i))return(n=this.projection)!=null&&n.isProjecting?Ko(i):Yg(e,i);{const s=by(e),o=(Ro(i)?s.getPropertyValue(i):s[i])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(e,{transformPagePoint:i}){return Rd(e,i)}build(e,i,n){dr(e,i,n.transformTemplate)}scrapeMotionValuesFromProps(e,i,n){return pr(e,i,n)}}const Tu=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 Sy(t,e,i,n){Cu(t,e,void 0,n);for(const s in e.attrs)t.setAttribute(Tu.has(s)?s:cr(s),e.attrs[s])}class Cy extends Su{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=De}getBaseTargetFromProps(e,i){return e[i]}readValueFromInstance(e,i){if(Ri.has(i)){const n=Lc(i);return n&&n.default||0}return i=Tu.has(i)?i:cr(i),e.getAttribute(i)}scrapeMotionValuesFromProps(e,i,n){return ld(e,i,n)}build(e,i,n){nd(e,i,this.isSVGTag,n.transformTemplate,n.style)}renderInstance(e,i,n,s){Sy(e,i,n,s)}mount(e){this.isSVGTag=od(e.tagName),super.mount(e)}}const Ty=(t,e)=>hr(t)?new Cy(e):new wy(e,{allowProjection:t!==yt}),ky=Tv({...Xv,...py,...ny,...gy},Ty),Xt=Xm(ky),Ey=["agent-id","debug","environment","position","version-id","trickle-ice","prefetch-ice-candidates","call-destination-number","call-caller-number","call-caller-name","call-custom-headers","vad","show-user-perceived-latency","show-greeting-latency","conversation-id","chat-mode","text-only","text-chat-url","region","rtc-ip","rtc-port","skip-last-voice-sdk-id","streaming-audio"],Tn="widget-layout-id";function ku(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=ku(t[e]))&&(n&&(n+=" "),n+=i)}else for(i in t)t[i]&&(n&&(n+=" "),n+=i);return n}function Vt(){for(var t,e,i=0,n="",s=arguments.length;i<s;i++)(t=arguments[i])&&(e=ku(t))&&(n&&(n+=" "),n+=e);return n}const Iy=Yn("listening"),ms=()=>Ll(Iy);function Eu(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 vs={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},Iu=Yn(vs),Au=()=>{const t=Jn(Iu);return Ne(e=>t(()=>{const i={...e};return i.start_call_text||(i.start_call_text=vs.start_call_text),i.agent_thinking_text||(i.agent_thinking_text=vs.agent_thinking_text),i.speak_to_interrupt_text||(i.speak_to_interrupt_text=vs.speak_to_interrupt_text),i}),[t])},ui=()=>_o(Iu),Dr=({size:t="large",className:e})=>{const i=ui(),[n]=ms();return D("h1",{className:Vt({"text-xs":t==="small"},e),children:n==="speaking"?i.speak_to_interrupt_text:n==="listening"?"":n==="processing_image"?"Processing image...":i.agent_thinking_text})},Ru=({stream:t,chatMode:e})=>{const i=ce(null);return Le(()=>{!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 yy="4.5.1",Tr=Math.PI,Ri=2*Tr,kr=Tr/2,Cu=8.17579892,Tu="dual-combined",cs="dual-horizontal",Mt="single",wt="dual-vertical",ku="bar-index",Eu="bar-level",ds="gradient",Iu=60,Ru="click",by="fullscreenchange",Au="resize",wy="#111",xu="",Du="A",Lu="B",Mu="C",Ou="D",Pu="468",us="sans-serif",Sy="#0f0",Cy="#7f7f7f22",Ai=10,Nu="create",Fu="fschange",Ty="lores",ky=Au,Er="user",Ey="#000c",Bu="#fff",Iy="#4f4",Uu="#888",Ry="#555",Ir="bark",_n="linear",xi="log",Rr="mel",Vu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],$u=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:Vu}],["rainbow",{dir:"h",colorStops:["#817",...Vu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],yn={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:Mt,colorMode:ds,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:xi,gradient:$u[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:xu,width:void 0},Ay=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],xy=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Dy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Ar=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],Ly=["ERR_INVALID_MODE","Invalid mode"],My=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Oy=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Py=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Ny=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],Fy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class rt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const ju=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Hu=t=>{for(const e in t)return!1;return!0},hs=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],By=(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 Uy{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||(Hu(i)&&!Hu(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 $u)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 rt(Ay)}}if(!s.createGain)throw new rt(xy);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(ky),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(Au,l,{signal:c}),n.addEventListener(by,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Fu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Iu)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Ru,u))};window.addEventListener(Ru,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(Nu)}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=hs(e,[Mt,cs,wt,Tu]),this._input.disconnect(),this._input.connect(this._chLayout!=Mt?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=Mt?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=hs(e,[ds,ku,Eu])}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=hs(e,[xi,Ir,Rr,_n]),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||yn.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Er)}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(Ty)}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 rt(Ar);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 rt(Ar);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 rt(Ly,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||yn.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 rt(My);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=-kr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return ju("stereo","channelLayout"),this._chLayout!=Mt}set stereo(e){ju("stereo","channelLayout"),this.channelLayout=e?wt:Mt}get trueLeds(){return this._trueLeds}set trueLeds(e){this._trueLeds=!!e}get volume(){return this._output.gain.value}set volume(e){this._output.gain.value=e}get weightingFilter(){return this._weightingFilter}set weightingFilter(e){this._weightingFilter=hs(e,[xu,Du,Lu,Mu,Ou,Pu],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Er)}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 yy}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new rt(Oy);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==Mt&&!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==Mt?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(yn))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 rt(Py);if(typeof i!="object")throw new rt(Ny);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new rt(Fy);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||wy,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(Er)}setFreqRange(e,i){if(e<1||i<1)throw new rt(Ar);this._minFreq=Math.min(e,i),this.maxFreq=Math.max(e,i)}setLedParams(e){let i,n,s;e&&(i=e.maxLeds|0,n=+e.spaceV,s=+e.spaceH),this._ledParams=i>0&&n>0&&s>=0?[i,n,s]:void 0,this._calcBars()}setOptions(e){this._setProps(e)}setSensitivity(e,i){for(const n of[0,1])this._analyzer[n].minDecibels=Math.min(e,i),this._analyzer[n].maxDecibels=Math.max(e,i)}start(){this.toggleAnalyzer(!0)}stop(){this.toggleAnalyzer(!1)}toggleAnalyzer(e){const i=this.isOn;return e===void 0&&(e=!i),i&&!e?(cancelAnimationFrame(this._runId),this._runId=0):!i&&e&&!this._destroyed&&(this._frames=0,this._time=performance.now(),this._runId=requestAnimationFrame(n=>this._draw(n))),this.isOn}toggleFullscreen(){if(this.isFullscreen)document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen();else{const e=this._fsEl;if(!e)return;e.requestFullscreen?e.requestFullscreen():e.webkitRequestFullscreen&&e.webkitRequestFullscreen()}}_binToFreq(e){return e*this.audioCtx.sampleRate/this.fftSize||1}_calcBars(){const e=this._bars=[];if(!this._ready){this._flg={isAlpha:!1,isBands:!1,isLeds:!1,isLumi:!1,isOctaves:!1,isOutline:!1,isRound:!1,noLedGap:!1};return}const{_ansiBands:i,_barSpace:n,canvas:s,_chLayout:o,_maxFreq:r,_minFreq:a,_mirror:l,_mode:c,_radial:u,_radialInvert:d,_reflexRatio:h}=this,g=s.width>>1,m=s.height>>1,v=o==wt&&!u,b=o==cs,y=c%10!=0,C=y&&this._frequencyScale==xi,k=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,R=this._alphaBars&&!A&&c!=Ai,D=this._outlineBars&&y&&!A&&!k,T=this._roundBars&&y&&!A&&!k,E=o!=wt||h>0&&!A,p=s.height-(v&&!k?.5:0)>>v,_=p*(A||u?1:1-h)|0,f=s.width-g*(b||l!=0),S=v?s.height-p*2:0,I=g*(l==-1&&!b&&!u);let M=Math.min(s.width,s.height)*.375*(o==wt?1:this._radius)|0,x=Math.min(g,m);d&&o!=wt&&([M,x]=[x,M]);const N=Z=>e.push({...Z,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=Z=>{const Y=this._freqToBin(Z,"floor"),ie=this._binToFreq(Y),se=this._binToFreq(Y+1),ge=Math.log2(Z/ie)/Math.log2(se/ie);return[Y,ge]};let F,V,$;if(C){const Z=(pe,ne,oe)=>+pe.toPrecision(oe?Math.max(ne,1+Math.log10(pe)|0):ne),Y=pe=>{const ne=[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],oe=Math.log10(pe)|0,Qe=pe/10**oe;let ft=1;for(;ft<ne.length&&Qe>ne[ft];)ft++;return Qe-ne[ft-1]<ne[ft]-Qe&&ft--,(ne[ft]*10**(oe+5)|0)/1e5},ie=[0,24,12,8,6,4,3,2,1][c],se=i?10**(3/(ie*10)):2**(1/ie),ge=se**.5;let Fe=i?7.94328235/(ie%2?1:ge):Cu;do{let pe=Fe;const ne=Z(pe/ge,4,!0),oe=Z(pe*ge,4,!0),[Qe,ft]=O(ne),[xn,Et]=O(oe);i?pe=ie<4?Y(pe):Z(pe,pe.toString()[0]<5?3:2):pe=Z(pe,4,!0),pe>=a&&N({posX:0,freq:pe,freqLo:ne,freqHi:oe,binLo:Qe,binHi:xn,ratioLo:ft,ratioHi:Et}),Fe*=se}while(Fe<=r);F=f/e.length,e.forEach((pe,ne)=>pe.posX=I+ne*F);const me=e[0],Ie=e[e.length-1];V=this._freqScaling(me.freqLo),$=f/(this._freqScaling(Ie.freqHi)-V),me.freqLo<a&&(me.freqLo=a,[me.binLo,me.ratioLo]=O(a)),Ie.freqHi>r&&(Ie.freqHi=r,[Ie.binHi,Ie.ratioHi]=O(r))}else if(y){const Z=[0,24,12,8,6,4,3,2,1][c]*10,Y=ie=>{switch(this._frequencyScale){case Ir:return 1960/(26.81/(ie+.53)-1);case Rr:return 700*(2**ie-1);case _n:return ie}};F=f/Z,V=this._freqScaling(a),$=f/(this._freqScaling(r)-V);for(let ie=0,se=0;ie<Z;ie++,se+=F){const ge=Y(V+se/$),Fe=Y(V+(se+F/2)/$),me=Y(V+(se+F)/$),[Ie,pe]=O(ge),[ne,oe]=O(me);N({posX:I+se,freq:Fe,freqLo:ge,freqHi:me,binLo:Ie,binHi:ne,ratioLo:pe,ratioHi:oe})}}else{F=1,V=this._freqScaling(a),$=f/(this._freqScaling(r)-V);const Z=this._freqToBin(a,"floor"),Y=this._freqToBin(r);let ie=-999;for(let se=Z;se<=Y;se++){const ge=this._binToFreq(se),Fe=I+Math.round($*(this._freqScaling(ge)-V));if(Fe>ie)N({posX:Fe,freq:ge,freqLo:ge,freqHi:ge,binLo:se,binHi:se,ratioLo:0,ratioHi:0}),ie=Fe;else if(e.length){const me=e[e.length-1];me.binHi=se,me.freqHi=ge,me.freq=(me.freqLo*ge)**.5}}}let Q=0,J=0;if(k){const Z=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Y=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],ie=this._ledParams,[se,ge,Fe]=ie||Y[c];let me,Ie=_;if(ie){const pe=2*Z;let ne;me=se+1;do me--,ne=Ie/me/(1+ge),J=ne*ge;while((ne<pe||J<pe)&&me>1)}else{const pe=540/ge;J=Math.min(ge*Z,Math.max(2,Ie/pe+.1|0))}E&&(Ie+=J),ie||(me=Math.min(se,Ie/(J*2)|0)),Q=Fe>=1?Fe:F*Fe,this._leds=[me,Q,J,Ie/me-J]}const G=Math.min(F-1,n*(n>0&&n<1?F:1));y&&(F-=Math.max(k?Q:0,G)),e.forEach((Z,Y)=>{let ie=Z.posX,se=F;y&&(n==0&&!k?(ie|=0,se|=0,Y>0&&ie>e[Y-1].posX+e[Y-1].width&&(ie--,se++)):ie+=Math.max(k?Q:0,G)/2,Z.posX=ie),Z.barCenter=ie+(F==1?0:se/2),Z.width=se});const de=[];for(const Z of[0,1]){const Y=o==wt?(p+S)*Z:0,ie=Y+p,se=Y+_-(!k||E?0:J);de.push({channelTop:Y,channelBottom:ie,analyzerBottom:se})}this._aux={analyzerHeight:_,analyzerWidth:f,centerX:g,centerY:m,channelCoords:de,channelHeight:p,channelGap:S,initialX:I,innerRadius:M,outerRadius:x,scaleMin:V,unitWidth:$},this._flg={isAlpha:R,isBands:y,isLeds:k,isLumi:A,isOctaves:C,isOutline:D,isRound:T,noLedGap:E},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,g=d.canvas,m=h.canvas,v=[],b=this._chLayout==cs,y=this._chLayout==wt,C=Math.min(r.width,r.height),k=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,R=g.height>>1,D=A>>1,T=R*(c?.7:1.5),E=D*(c?1:2),p=2**(1/12);if(!c&&(this._ansiBands||a!=xi))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==_n?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let x=Cu;for(let N=-1;N<11;N++)for(let O=0;O<12;O++){if(x>=this._minFreq&&x<=this._maxFreq){const F=k[O],V=F=="C";(F&&c&&!l&&!b||V)&&v.push(c?[x,F+(V?N:"")]:x)}x*=p}}m.width=m.height=Math.max(C*.15,(n<<1)+y*A);const _=m.width>>1,f=_-A*.7,S=(x,N)=>{const O=Ri*(x/r.width),F=O-kr,V=f*Math.cos(F),$=f*Math.sin(F);h.save(),h.translate(_+V,_+$),h.rotate(O),h.fillText(N,0,0),h.restore()};g.width|=0,d.fillStyle=h.strokeStyle=Ey,d.fillRect(0,0,g.width,g.height),h.arc(_,_,_-A/2,0,Ri),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=Bu,d.font=`${R}px ${us}`,h.font=`${D}px ${us}`,d.textAlign=h.textAlign="center";let I=-T/4,M=-E;for(const x of v){const[N,O]=Array.isArray(x)?x:[x,x<1e3?x|0:`${(x/100|0)/10}k`],F=o*(this._freqScaling(N)-s),V=g.height*.75,$=O[0]=="C",Q=R*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?Iy:Bu,c){const J=a==xi,G=a==_n;let de=["C"];if((J||N>2e3||!G&&N>250||(!u||y)&&(!G&&N>125||N>1e3))&&de.push("G"),(J||N>4e3||!G&&N>500||(!u||y)&&(!G&&N>250||N>2e3))&&de.push("E"),(G&&N>4e3||(!u||y)&&(J||N>2e3||!G&&N>500))&&de.push("D","F","A","B"),!de.includes(O[0]))continue}F>=I+T/2&&F<=e&&(d.fillText(O,b&&l==-1?e-F:i+F,V,Q),(b||l&&(F>T||l==1))&&d.fillText(O,b&&l!=1?e+F:(i||r.width)-F,V,Q),I=F+Math.min(Q,d.measureText(O).width)/2),F>=M+E&&F<e-E&&(S(b&&l==1?e-F:F,O),(b||l&&(F>E||l==1))&&S(b&&l!=-1?e+F:-F,O),M=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:g,centerX:m,centerY:v,channelCoords:b,channelHeight:y,channelGap:C,initialX:k,innerRadius:A,outerRadius:R}=this._aux,{_bars:D,canvas:T,_canvasGradients:E,_chLayout:p,_colorMode:_,_ctx:f,_energy:S,_fadePeaks:I,fillAlpha:M,_fps:x,_linearAmplitude:N,_lineWidth:O,maxDecibels:F,minDecibels:V,_mirror:$,_mode:Q,overlay:J,_radial:G,showBgColor:de,showPeaks:Z,useCanvas:Y,_weightingFilter:ie}=this,se=this._scaleX.canvas,ge=this._scaleR.canvas,Fe=x*this._peakFadeTime/1e3,me=x**2,Ie=this._gravity*1e3,pe=x*this._peakHoldTime/1e3,ne=p==Tu,oe=p==cs,Qe=p==wt,ft=p==Mt,xn=a&&this._trueLeds&&_==ds,Et=G?T.width:this._aux.analyzerWidth,ma=k+Et,Dn=Z&&this._peakLine&&Q==Ai,Gt=G?R-A:g,bS=Gt/this._pixelRatio,[wS,DS,Ln,va]=this._leds||[];S.val>0&&x>0&&(this._spinAngle+=this._spinSpeed*Ri/60/x);const SS=j=>{if(this._reflexRatio>0&&!l&&!G){let ue,It;this.reflexFit||Qe?(ue=Qe&&j==0?y+C:0,It=y-g):(ue=T.height-g*2,It=g),f.save(),f.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(f.filter=`brightness(${this.reflexBright})`),f.setTransform(1,0,0,-1,0,T.height),f.drawImage(T,0,b[j].channelTop,T.width,g,0,ue,T.width,It),f.restore()}},CS=()=>{this.showScaleX&&(G?(f.save(),f.translate(m,v),this._spinSpeed&&f.rotate(this._spinAngle+kr),f.drawImage(ge,-ge.width>>1,-ge.width>>1),f.restore()):f.drawImage(se,0,T.height-se.height))},TS=j=>{const ue=j**2,It=424.36,Be=11599.29,Bs=25122.25,qt=544496.41,Ft=148693636,di=ui=>20*Math.log10(ui);switch(ie){case Du:const ui=Ft*ue**2/((ue+It)*Math.sqrt((ue+Be)*(ue+qt))*(ue+Ft));return 2+di(ui);case Lu:const hi=Ft*ue*j/((ue+It)*Math.sqrt(ue+Bs)*(ue+Ft));return .17+di(hi);case Mu:const ba=Ft*ue/((ue+It)*(ue+Ft));return .06+di(ba);case Ou:const Us=((103791848e-2-ue)**2+108076816e-2*ue)/((9837328-ue)**2+11723776*ue),wa=j/68966888496476e-18*Math.sqrt(Us/((ue+79919.29)*(ue+1345600)));return di(wa);case Pu:const Vs=-4737338981378384e-39*j**6+2043828333606125e-30*j**4-1363894795463638e-22*ue+1,fi=1306612257412824e-34*j**5-2118150887518656e-26*j**3+.0005559488023498642*j,et=.0001246332637532143*j/Math.hypot(Vs,fi);return 18.2+di(et)}return 0},_a=(j,ue,It)=>{f.beginPath(),f.moveTo(j,ue),f.lineTo(j,It),f.stroke()},ya=j=>{if(j&&O){const ue=f.globalAlpha;f.globalAlpha=1,f.stroke(),f.globalAlpha=ue}},ci=j=>Math.max(0,(j*wS|0)*(va+Ln)-Ln),kS=j=>{S.val=j,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*Ie/me/T.height*this._pixelRatio)),j>=S.peak&&(S.peak=j,S.hold=pe)};J&&f.clearRect(0,0,T.width,T.height);let $f=0;const jf=D.length,Hf=ft?1:2;for(let j=0;j<Hf;j++){const{channelTop:ue,channelBottom:It,analyzerBottom:Be}=b[j],Bs=this._gradients[this._selectedGrads[j]],qt=Bs.colorStops,Ft=qt.length,di=!de||a&&!J?"#000":Bs.bgColor,ui=Qe&&G&&j?-1:1,hi=!j&&$==-1||j&&$==1,ba=!oe||j&&$!=1?0:Et>>(j||!hi),Us=oe&&hi?-1:1,wa=()=>{const q=se.height,X=q>>1,te=N?100:F,ye=N?0:V,Re=N?20:5,Ye=g/(te-ye),Rt=$!=-1&&(!oe||j==0||$==1),zt=$!=1&&(!oe||j!=$);f.save(),f.fillStyle=Uu,f.font=`${X}px ${us}`,f.textAlign="right",f.lineWidth=1;for(let Kt=te;Kt>ye;Kt-=Re){const Hi=ue+(te-Kt)*Ye,Me=Kt%2==0|0;if(Me){const Ge=Hi+X*(Hi==ue?.8:.35);Rt&&f.fillText(Kt,q*.85,Ge),zt&&f.fillText(Kt,(oe?Et:T.width)-q*.1,Ge),f.strokeStyle=Uu,f.setLineDash([2,4]),f.lineDashOffset=0}else f.strokeStyle=Ry,f.setLineDash([2,8]),f.lineDashOffset=1;f.beginPath(),f.moveTo(k+q*Me*Rt,~~Hi+.5),f.lineTo(ma-q*Me*zt,~~Hi+.5),f.stroke()}f.restore()},Vs=(q,X)=>{const te=pt[q]+(q<pt.length-1?(pt[q+1]-pt[q])*X:0);return isNaN(te)?-1/0:te},fi=(q,X=Us)=>X*Ri*((q+ba)/T.width)+this._spinAngle,et=(q,X,te)=>{const ye=A+X*ui,Re=fi(q,te);return[m+ye*Math.cos(Re),v+ye*Math.sin(Re)]},Sa=(q,X,te,ye,Re)=>{f.beginPath();for(const Ye of $&&!oe?[1,-1]:[Us]){const[Rt,zt]=d?[fi(q,Ye),fi(q+te,Ye)]:[];f.moveTo(...et(q,X,Ye)),f.lineTo(...et(q,X+ye,Ye)),d?f.arc(m,v,A+(X+ye)*ui,Rt,zt,Ye!=1):f.lineTo(...et(q+te,X+ye,Ye)),f.lineTo(...et(q+te,X,Ye)),d&&!Re&&f.arc(m,v,A+X*ui,zt,Rt,Ye==1)}ya(Re),f.fill()},Ca=(q=0,X=0)=>{let te;if(_==ds&&!xn||Q==Ai)te=E[j];else{const ye=_==ku?X%Ft:qt.findLastIndex(Re=>a?ci(q)<=ci(Re.level):q<=Re.level);te=qt[ye].color}f.fillStyle=f.strokeStyle=te};if(Y){if(oe&&!G){const q=Et*(j+hi),X=hi?-1:1;f.setTransform(X,0,0,1,q,0)}if((!J||de)&&(J&&(f.globalAlpha=this.bgAlpha),f.fillStyle=di,(j==0||!G&&!ne)&&f.fillRect(k,ue-C,Et,(J&&this.reflexAlpha==1?g:y)+C),f.globalAlpha=1),this.showScaleY&&!l&&!G&&(j==0||!ne)&&wa(),a?(f.setLineDash([va,Ln]),f.lineWidth=D[0].width):f.lineWidth=u?Math.min(O,D[0].width/2):O,f.save(),!G){const q=new Path2D;q.rect(0,ue,T.width,g),f.clip(q)}}let pt=this._fftData[j];this._analyzer[j].getFloatFrequencyData(pt),ie&&(pt=pt.map((q,X)=>q+TS(this._binToFreq(X)))),f.beginPath();let Mn=[];for(let q=0;q<jf;q++){const X=D[q],{posX:te,barCenter:ye,width:Re,freq:Ye,binLo:Rt,binHi:zt,ratioLo:Kt,ratioHi:Hi}=X;let Me=Math.max(Vs(Rt,Kt),Vs(zt,Hi));for(let ve=Rt+1;ve<zt;ve++)pt[ve]>Me&&(Me=pt[ve]);if(Me=this._normalizedB(Me),X.value[j]=Me,$f+=Me,X.peak[j]>0&&X.alpha[j]>0&&(X.hold[j]--,X.hold[j]<0)){if(I&&!Dn){const ve=!o||u&&O>0?1:o?X.peak[j]:M;X.alpha[j]=ve*(1+X.hold[j]/Fe)}else X.peak[j]+=X.hold[j]*Ie/me/bS;X.alpha[j]<=0&&(X.peak[j]=0)}if(Me>=X.peak[j]&&(X.peak[j]=Me,X.hold[j]=pe,X.alpha[j]=!o||u&&O>0?1:o?Me:M),!Y)continue;f.globalAlpha=l||o?Me:u?M:1,Ca(Me,q);const Ge=l?Gt:a?ci(Me):Me*Gt|0;if(Q==Ai){const ve=q?0:(this._normalizedB(pt[D[1].binLo])*Gt+Ge)/2;if(G){if(q==0&&(oe&&f.moveTo(...et(0,0)),f.lineTo(...et(0,te<0?ve:Ge))),te>=0){const ct=[te,Ge];f.lineTo(...et(...ct)),Mn.push(ct)}}else{if(q==0)if($==-1&&!oe)f.moveTo(k,Be-(te<k?ve:Ge));else{const ct=Rt?this._normalizedB(pt[Rt-1])*Gt:Ge;f.moveTo(k-O,Be-ct)}(oe||$!=-1||te>=k)&&f.lineTo(te,Be-Ge)}}else if(a){if(de&&!J&&(j==0||!ne)){const ve=f.globalAlpha;f.strokeStyle=Cy,f.globalAlpha=1,_a(ye,ue,Be),f.strokeStyle=f.fillStyle,f.globalAlpha=ve}if(xn){const ve=l?0:qt.findLastIndex(pi=>ci(Me)<=ci(pi.level));let ct=Be;for(let pi=Ft-1;pi>=ve;pi--){f.strokeStyle=qt[pi].color;let Gf=Be-(pi==ve?Ge:ci(qt[pi].level));_a(ye,ct,Gf),ct=Gf-Ln}}else _a(ye,Be,Be-Ge)}else if(te>=k)if(G)Sa(te,0,Re,Ge,u);else if(d){const ve=Re/2,ct=Be+ve;f.beginPath(),f.moveTo(te,ct),f.lineTo(te,ct-Ge),f.arc(ye,ct-Ge,ve,Tr,Ri),f.lineTo(te+Re,ct),ya(u),f.fill()}else{const ve=u?f.lineWidth:0;f.beginPath(),f.rect(te,Be+ve,Re,-Ge-ve),ya(u),f.fill()}const Wi=X.peak[j],Wf=X.alpha[j];if(Wi>0&&Wf>0&&Z&&!Dn&&!l&&te>=k&&te<ma){if(I?f.globalAlpha=Wf:u&&O>0?f.globalAlpha=1:o&&(f.globalAlpha=Wi),(_==Eu||xn)&&Ca(Wi),a){const ve=ci(Wi);ve>=Ln&&f.fillRect(te,Be-ve,Re,va)}else if(!G)f.fillRect(te,Be-Wi*Gt,Re,2);else if(Q!=Ai){const ve=Wi*Gt;Sa(te,ve,Re,!this._radialInvert||Qe||ve+A>=2?-2:2)}}}if(Y){if(f.globalAlpha=1,Q==Ai){if(Ca(),G&&!oe){if($){let q;for(;q=Mn.pop();)f.lineTo(...et(...q,-1))}f.closePath()}if(O>0&&f.stroke(),M>0){if(G){const q=oe?fi(Et>>1):0,X=oe?fi(Et):Ri;f.moveTo(...et(oe?Et>>1:0,0)),f.arc(m,v,A,q,X,oe?!hi:!0)}else f.lineTo(ma,Be),f.lineTo(k,Be);f.globalAlpha=M,f.fill(),f.globalAlpha=1}if((Dn||G&&Z)&&(Mn=[],f.beginPath(),D.forEach((q,X)=>{let te=q.posX,ye=q.peak[j],Re=X?"lineTo":"moveTo";if(G&&te<0){const Ye=D[X+1];ye=By(te,ye,Ye.posX,Ye.peak[j],0),te=0}ye*=Gt,Dn?(f[Re](...G?et(te,ye):[te,Be-ye]),G&&$&&!oe&&Mn.push([te,ye])):ye>0&&Sa(te,ye,1,-2)}),Dn)){let q;for(;q=Mn.pop();)f.lineTo(...et(...q,-1));f.lineWidth=1,f.stroke()}}f.restore(),oe&&!G&&f.setTransform(1,0,0,1,0,0),(!oe&&!ne||j)&&SS(j)}}if(kS($f/(jf<<Hf-1)),Y&&($&&!G&&!oe&&(f.setTransform(-1,0,0,1,T.width-k,0),f.drawImage(T,k,0,m,T.height,0,0,m,T.height),f.setTransform(1,0,0,1,0,0)),f.setLineDash([]),CS()),this.showFPS){const j=se.height;f.font=`bold ${j}px ${us}`,f.fillStyle=Sy,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 xi:return Math.log2(e);case Ir:return 26.81*e/(1960+e)-.53;case Rr:return Math.log2(1+e/700);case _n: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==wt,g=1-s,m=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],y=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,m]),y){const A=h&&!this._splitGradient&&(!C||n);for(let R=0;R<1+A;R++){const D=y.length-1;y.forEach((T,E)=>{let p=T.pos;if(A&&(p/=2),h&&!d&&!n&&!C&&(p*=g,!A&&p>.5*g&&(p+=.5*s)),R==1)if(n||d){const _=D-E;T=y[_],p=1-T.pos/2}else E==0&&p>0&&k.addColorStop(.5,T.color),p+=.5;k.addColorStop(p,T.color),h&&E==D&&p<.5&&k.addColorStop(.5,T.color)})}}this._canvasGradients[v]=k}}_normalizedB(e){const i=this._linearAmplitude,n=i?1/this._linearBoost:1,s=(l,c,u)=>l<=c?c:l>=u?u:l,o=l=>10**(l/20);let r=this.maxDecibels,a=this.minDecibels;return i&&(r=o(r),a=o(a),e=o(e)**n),s((e-a)/(r-a)**n,0,1)}_setCanvas(e){if(!this._ready)return;const{canvas:i,_ctx:n}=this,s=this._scaleX.canvas,o=window.devicePixelRatio/(this._loRes+1);let r=window.screen.width*o,a=window.screen.height*o;Math.abs(window.orientation)==90&&r<a&&([r,a]=[a,r]);const l=this.isFullscreen,c=l&&this._fsEl==i,u=c?r:(this._width||this._container.clientWidth||this._defaultWidth)*o|0,d=c?a:(this._height||this._container.clientHeight||this._defaultHeight)*o|0;this._pixelRatio=o,this._fsWidth=r,this._fsHeight=a,!(e!=Nu&&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=Fu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new rt(Dy,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(yn).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...yn,...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 Vy={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}]}},Wu=({stream:t,className:e,onClick:i})=>{var o;const n=he(null),s=ni();return xe(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Uy(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",Vy[((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]),L("div",{onClick:i,className:Lt("w-full",e),ref:n})},Gu=$n(null),qu=({className:t,debug:e=!1})=>{const i=co(Gu);return!e||!i||!(i.region||i.dc)?null:L("div",{className:`text-xs opacity-60 text-black dark:text-white ${t??""}`,"data-testid":"connection-info",children:[i.region&&L("span",{"data-testid":"connection-info-region",children:["region: ",i.region]}),i.region&&i.dc&&L("span",{children:" · "}),i.dc&&L("span",{"data-testid":"connection-info-dc",children:["dc: ",i.dc]})]})};/**
|
|
16
|
+
*/const Ay="4.5.1",Lr=Math.PI,Ni=2*Lr,Mr=Lr/2,xu=8.17579892,Du="dual-combined",_s="dual-horizontal",$t="single",Rt="dual-vertical",Lu="bar-index",Mu="bar-level",ys="gradient",Ou=60,Pu="click",Ry="fullscreenchange",Nu="resize",xy="#111",Fu="",Uu="A",Bu="B",Vu="C",$u="D",ju="468",bs="sans-serif",Dy="#0f0",Ly="#7f7f7f22",Fi=10,Hu="create",Wu="fschange",My="lores",Oy=Nu,Or="user",Py="#000c",Gu="#fff",Ny="#4f4",qu="#888",Fy="#555",Pr="bark",kn="linear",Ui="log",Nr="mel",zu=["#a35","#c66","#e94","#ed0","#9d5","#4d8","#2cb","#0bc","#09c","#36b"],Ku=[["classic",{colorStops:["red",{color:"yellow",level:.85,pos:.6},{color:"lime",level:.475}]}],["prism",{colorStops:zu}],["rainbow",{dir:"h",colorStops:["#817",...zu,"#639"]}],["orangered",{bgColor:"#3e2f29",colorStops:["OrangeRed"]}],["steelblue",{bgColor:"#222c35",colorStops:["SteelBlue"]}]],En={alphaBars:!1,ansiBands:!1,barSpace:.1,bgAlpha:.7,channelLayout:$t,colorMode:ys,fadePeaks:!1,fftSize:8192,fillAlpha:1,frequencyScale:Ui,gradient:Ku[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:Fu,width:void 0},Uy=["ERR_AUDIO_CONTEXT_FAIL","Could not create audio context. Web Audio API not supported?"],By=["ERR_INVALID_AUDIO_CONTEXT","Provided audio context is not valid"],Vy=["ERR_UNKNOWN_GRADIENT","Unknown gradient"],Fr=["ERR_FREQUENCY_TOO_LOW","Frequency values must be >= 1"],$y=["ERR_INVALID_MODE","Invalid mode"],jy=["ERR_REFLEX_OUT_OF_RANGE","Reflex ratio must be >= 0 and < 1"],Hy=["ERR_INVALID_AUDIO_SOURCE","Audio source must be an instance of HTMLMediaElement or AudioNode"],Wy=["ERR_GRADIENT_INVALID_NAME","Gradient name must be a non-empty string"],Gy=["ERR_GRADIENT_NOT_AN_OBJECT","Gradient options must be an object"],qy=["ERR_GRADIENT_MISSING_COLOR","Gradient colorStops must be a non-empty array"];class pt extends Error{constructor(e,i){const[n,s]=e;super(s+(i!==void 0?`: ${i}`:"")),this.name="AudioMotionError",this.code=n}}const Yu=(t,e)=>console.warn(`${t} is deprecated. Use ${e} instead.`),Xu=t=>{for(const e in t)return!1;return!0},ws=(t,e,i="toLowerCase")=>e[Math.max(0,e.indexOf((""+t)[i]()))],zy=(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 Ky{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||(Xu(i)&&!Xu(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 Ku)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 pt(Uy)}}if(!s.createGain)throw new pt(By);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(Oy),this._fsTimeout=0)},Ou))};window.ResizeObserver&&(this._observer=new ResizeObserver(l),this._observer.observe(this._container)),this._controller=new AbortController;const c=this._controller.signal;window.addEventListener(Nu,l,{signal:c}),n.addEventListener(Ry,()=>{this._fsChanging=!0,this._fsTimeout&&window.clearTimeout(this._fsTimeout),this._setCanvas(Wu),this._fsTimeout=window.setTimeout(()=>{this._fsChanging=!1,this._fsTimeout=0},Ou)},{signal:c});const u=()=>{s.state=="suspended"&&s.resume().then(()=>window.removeEventListener(Pu,u))};window.addEventListener(Pu,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(Hu)}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=ws(e,[$t,_s,Rt,Du]),this._input.disconnect(),this._input.connect(this._chLayout!=$t?this._splitter:this._analyzer[0]),this._analyzer[0].disconnect(),this._outNodes.length&&this._analyzer[0].connect(this._chLayout!=$t?this._merger:this._output),this._calcBars(),this._makeGrad()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=ws(e,[ys,Lu,Mu])}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=ws(e,[Ui,Pr,Nr,kn]),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||En.gravity}get height(){return this._height}set height(e){this._height=e,this._setCanvas(Or)}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(My)}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 pt(Fr);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 pt(Fr);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 pt($y,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||En.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 pt(jy);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=-Mr),this._spinSpeed=e}get splitGradient(){return this._splitGradient}set splitGradient(e){this._splitGradient=!!e,this._makeGrad()}get stereo(){return Yu("stereo","channelLayout"),this._chLayout!=$t}set stereo(e){Yu("stereo","channelLayout"),this.channelLayout=e?Rt:$t}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=ws(e,[Fu,Uu,Bu,Vu,$u,ju],"toUpperCase")}get width(){return this._width}set width(e){this._width=e,this._setCanvas(Or)}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 Ay}connectInput(e){const i=e instanceof HTMLMediaElement;if(!(i||e.connect))throw new pt(Hy);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==$t&&!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==$t?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(En))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 pt(Wy);if(typeof i!="object")throw new pt(Gy);const{colorStops:n}=i;if(!Array.isArray(n)||!n.length)throw new pt(qy);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||xy,dir:i.dir,colorStops:n},this._selectedGrads.includes(e)&&this._makeGrad()}setCanvasSize(e,i){this._width=e,this._height=i,this._setCanvas(Or)}setFreqRange(e,i){if(e<1||i<1)throw new pt(Fr);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,m=s.height>>1,v=o==Rt&&!u,b=o==_s,y=c%10!=0,C=y&&this._frequencyScale==Ui,T=this._showLeds&&y&&!u,A=this._lumiBars&&y&&!u,x=this._alphaBars&&!A&&c!=Fi,N=this._outlineBars&&y&&!A&&!T,E=this._roundBars&&y&&!A&&!T,k=o!=Rt||h>0&&!A,f=s.height-(v&&!T?.5:0)>>v,_=f*(A||u?1:1-h)|0,g=s.width-p*(b||l!=0),S=v?s.height-f*2:0,I=p*(l==-1&&!b&&!u);let M=Math.min(s.width,s.height)*.375*(o==Rt?1:this._radius)|0,R=Math.min(p,m);d&&o!=Rt&&([M,R]=[R,M]);const P=K=>e.push({...K,peak:[0,0],hold:[0],alpha:[0],value:[0]}),O=K=>{const Z=this._freqToBin(K,"floor"),Y=this._binToFreq(Z),te=this._binToFreq(Z+1),me=Math.log2(K/Y)/Math.log2(te/Y);return[Z,me]};let L,V,$;if(C){const K=(he,de,fe)=>+he.toPrecision(fe?Math.max(de,1+Math.log10(he)|0):de),Z=he=>{const de=[1,1.12,1.25,1.4,1.6,1.8,2,2.24,2.5,2.8,3.15,3.55,4,4.5,5,5.6,6.3,7.1,8,9,10],fe=Math.log10(he)|0,Je=he/10**fe;let Qe=1;for(;Qe<de.length&&Je>de[Qe];)Qe++;return Je-de[Qe-1]<de[Qe]-Je&&Qe--,(de[Qe]*10**(fe+5)|0)/1e5},Y=[0,24,12,8,6,4,3,2,1][c],te=i?10**(3/(Y*10)):2**(1/Y),me=te**.5;let Oe=i?7.94328235/(Y%2?1:me):xu;do{let he=Oe;const de=K(he/me,4,!0),fe=K(he*me,4,!0),[Je,Qe]=O(de),[Ot,Ze]=O(fe);i?he=Y<4?Z(he):K(he,he.toString()[0]<5?3:2):he=K(he,4,!0),he>=a&&P({posX:0,freq:he,freqLo:de,freqHi:fe,binLo:Je,binHi:Ot,ratioLo:Qe,ratioHi:Ze}),Oe*=te}while(Oe<=r);L=g/e.length,e.forEach((he,de)=>he.posX=I+de*L);const _e=e[0],xe=e[e.length-1];V=this._freqScaling(_e.freqLo),$=g/(this._freqScaling(xe.freqHi)-V),_e.freqLo<a&&(_e.freqLo=a,[_e.binLo,_e.ratioLo]=O(a)),xe.freqHi>r&&(xe.freqHi=r,[xe.binHi,xe.ratioHi]=O(r))}else if(y){const K=[0,24,12,8,6,4,3,2,1][c]*10,Z=Y=>{switch(this._frequencyScale){case Pr:return 1960/(26.81/(Y+.53)-1);case Nr:return 700*(2**Y-1);case kn:return Y}};L=g/K,V=this._freqScaling(a),$=g/(this._freqScaling(r)-V);for(let Y=0,te=0;Y<K;Y++,te+=L){const me=Z(V+te/$),Oe=Z(V+(te+L/2)/$),_e=Z(V+(te+L)/$),[xe,he]=O(me),[de,fe]=O(_e);P({posX:I+te,freq:Oe,freqLo:me,freqHi:_e,binLo:xe,binHi:de,ratioLo:he,ratioHi:fe})}}else{L=1,V=this._freqScaling(a),$=g/(this._freqScaling(r)-V);const K=this._freqToBin(a,"floor"),Z=this._freqToBin(r);let Y=-999;for(let te=K;te<=Z;te++){const me=this._binToFreq(te),Oe=I+Math.round($*(this._freqScaling(me)-V));if(Oe>Y)P({posX:Oe,freq:me,freqLo:me,freqHi:me,binLo:te,binHi:te,ratioLo:0,ratioHi:0}),Y=Oe;else if(e.length){const _e=e[e.length-1];_e.binHi=te,_e.freqHi=me,_e.freq=(_e.freqLo*me)**.5}}}let W=0,q=0;if(T){const K=this._pixelRatio/(window.devicePixelRatio>1&&window.screen.height<=540?2:1),Z=[[],[128,3,.45],[128,4,.225],[96,6,.225],[80,6,.225],[80,6,.125],[64,6,.125],[48,8,.125],[24,16,.125]],Y=this._ledParams,[te,me,Oe]=Y||Z[c];let _e,xe=_;if(Y){const he=2*K;let de;_e=te+1;do _e--,de=xe/_e/(1+me),q=de*me;while((de<he||q<he)&&_e>1)}else{const he=540/me;q=Math.min(me*K,Math.max(2,xe/he+.1|0))}k&&(xe+=q),Y||(_e=Math.min(te,xe/(q*2)|0)),W=Oe>=1?Oe:L*Oe,this._leds=[_e,W,q,xe/_e-q]}const G=Math.min(L-1,n*(n>0&&n<1?L:1));y&&(L-=Math.max(T?W:0,G)),e.forEach((K,Z)=>{let Y=K.posX,te=L;y&&(n==0&&!T?(Y|=0,te|=0,Z>0&&Y>e[Z-1].posX+e[Z-1].width&&(Y--,te++)):Y+=Math.max(T?W:0,G)/2,K.posX=Y),K.barCenter=Y+(L==1?0:te/2),K.width=te});const oe=[];for(const K of[0,1]){const Z=o==Rt?(f+S)*K:0,Y=Z+f,te=Z+_-(!T||k?0:q);oe.push({channelTop:Z,channelBottom:Y,analyzerBottom:te})}this._aux={analyzerHeight:_,analyzerWidth:g,centerX:p,centerY:m,channelCoords:oe,channelHeight:f,channelGap:S,initialX:I,innerRadius:M,outerRadius:R,scaleMin:V,unitWidth:$},this._flg={isAlpha:x,isBands:y,isLeds:T,isLumi:A,isOctaves:C,isOutline:N,isRound:E,noLedGap:k},this._createScales()}_createScales(){if(!this._ready)return;const{analyzerWidth:e,initialX:i,innerRadius:n,scaleMin:s,unitWidth:o}=this._aux,{canvas:r,_frequencyScale:a,_mirror:l,_noteLabels:c,_radial:u,_scaleX:d,_scaleR:h}=this,p=d.canvas,m=h.canvas,v=[],b=this._chLayout==_s,y=this._chLayout==Rt,C=Math.min(r.width,r.height),T=["C",,"D",,"E","F",,"G",,"A",,"B"],A=C/34|0,x=p.height>>1,N=A>>1,E=x*(c?.7:1.5),k=N*(c?1:2),f=2**(1/12);if(!c&&(this._ansiBands||a!=Ui))v.push(16,31.5,63,125,250,500,1e3,2e3,4e3),a==kn?v.push(6e3,8e3,1e4,12e3,14e3,16e3,18e3,2e4,22e3):v.push(8e3,16e3);else{let R=xu;for(let P=-1;P<11;P++)for(let O=0;O<12;O++){if(R>=this._minFreq&&R<=this._maxFreq){const L=T[O],V=L=="C";(L&&c&&!l&&!b||V)&&v.push(c?[R,L+(V?P:"")]:R)}R*=f}}m.width=m.height=Math.max(C*.15,(n<<1)+y*A);const _=m.width>>1,g=_-A*.7,S=(R,P)=>{const O=Ni*(R/r.width),L=O-Mr,V=g*Math.cos(L),$=g*Math.sin(L);h.save(),h.translate(_+V,_+$),h.rotate(O),h.fillText(P,0,0),h.restore()};p.width|=0,d.fillStyle=h.strokeStyle=Py,d.fillRect(0,0,p.width,p.height),h.arc(_,_,_-A/2,0,Ni),h.lineWidth=A,h.stroke(),d.fillStyle=h.fillStyle=Gu,d.font=`${x}px ${bs}`,h.font=`${N}px ${bs}`,d.textAlign=h.textAlign="center";let I=-E/4,M=-k;for(const R of v){const[P,O]=Array.isArray(R)?R:[R,R<1e3?R|0:`${(R/100|0)/10}k`],L=o*(this._freqScaling(P)-s),V=p.height*.75,$=O[0]=="C",W=x*(c&&!l&&!b?$?1.2:.6:3);if(d.fillStyle=h.fillStyle=$&&!l&&!b?Ny:Gu,c){const q=a==Ui,G=a==kn;let oe=["C"];if((q||P>2e3||!G&&P>250||(!u||y)&&(!G&&P>125||P>1e3))&&oe.push("G"),(q||P>4e3||!G&&P>500||(!u||y)&&(!G&&P>250||P>2e3))&&oe.push("E"),(G&&P>4e3||(!u||y)&&(q||P>2e3||!G&&P>500))&&oe.push("D","F","A","B"),!oe.includes(O[0]))continue}L>=I+E/2&&L<=e&&(d.fillText(O,b&&l==-1?e-L:i+L,V,W),(b||l&&(L>E||l==1))&&d.fillText(O,b&&l!=1?e+L:(i||r.width)-L,V,W),I=L+Math.min(W,d.measureText(O).width)/2),L>=M+k&&L<e-k&&(S(b&&l==1?e-L:L,O),(b||l&&(L>k||l==1))&&S(b&&l!=-1?e+L:-L,O),M=L)}}_draw(e){this._runId=requestAnimationFrame(H=>this._draw(H));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:m,centerY:v,channelCoords:b,channelHeight:y,channelGap:C,initialX:T,innerRadius:A,outerRadius:x}=this._aux,{_bars:N,canvas:E,_canvasGradients:k,_chLayout:f,_colorMode:_,_ctx:g,_energy:S,_fadePeaks:I,fillAlpha:M,_fps:R,_linearAmplitude:P,_lineWidth:O,maxDecibels:L,minDecibels:V,_mirror:$,_mode:W,overlay:q,_radial:G,showBgColor:oe,showPeaks:K,useCanvas:Z,_weightingFilter:Y}=this,te=this._scaleX.canvas,me=this._scaleR.canvas,Oe=R*this._peakFadeTime/1e3,_e=R**2,xe=this._gravity*1e3,he=R*this._peakHoldTime/1e3,de=f==Du,fe=f==_s,Je=f==Rt,Qe=f==$t,Ot=a&&this._trueLeds&&_==ys,Ze=G?E.width:this._aux.analyzerWidth,ne=T+Ze,ye=K&&this._peakLine&&W==Fi,Be=G?x-A:p,Ee=Be/this._pixelRatio,[at,Vn,St,vi]=this._leds||[];S.val>0&&R>0&&(this._spinAngle+=this._spinSpeed*Ni/60/R);const MS=H=>{if(this._reflexRatio>0&&!l&&!G){let ge,Pt;this.reflexFit||Je?(ge=Je&&H==0?y+C:0,Pt=y-p):(ge=E.height-p*2,Pt=p),g.save(),g.globalAlpha=this.reflexAlpha,this.reflexBright!=1&&(g.filter=`brightness(${this.reflexBright})`),g.setTransform(1,0,0,-1,0,E.height),g.drawImage(E,0,b[H].channelTop,E.width,p,0,ge,E.width,Pt),g.restore()}},OS=()=>{this.showScaleX&&(G?(g.save(),g.translate(m,v),this._spinSpeed&&g.rotate(this._spinAngle+Mr),g.drawImage(me,-me.width>>1,-me.width>>1),g.restore()):g.drawImage(te,0,E.height-te.height))},PS=H=>{const ge=H**2,Pt=424.36,We=11599.29,qs=25122.25,ei=544496.41,Wt=148693636,yi=bi=>20*Math.log10(bi);switch(Y){case Uu:const bi=Wt*ge**2/((ge+Pt)*Math.sqrt((ge+We)*(ge+ei))*(ge+Wt));return 2+yi(bi);case Bu:const wi=Wt*ge*H/((ge+Pt)*Math.sqrt(ge+qs)*(ge+Wt));return .17+yi(wi);case Vu:const ka=Wt*ge/((ge+Pt)*(ge+Wt));return .06+yi(ka);case $u:const zs=((103791848e-2-ge)**2+108076816e-2*ge)/((9837328-ge)**2+11723776*ge),Ea=H/68966888496476e-18*Math.sqrt(zs/((ge+79919.29)*(ge+1345600)));return yi(Ea);case ju:const Ks=-4737338981378384e-39*H**6+2043828333606125e-30*H**4-1363894795463638e-22*ge+1,Si=1306612257412824e-34*H**5-2118150887518656e-26*H**3+.0005559488023498642*H,lt=.0001246332637532143*H/Math.hypot(Ks,Si);return 18.2+yi(lt)}return 0},Ca=(H,ge,Pt)=>{g.beginPath(),g.moveTo(H,ge),g.lineTo(H,Pt),g.stroke()},Ta=H=>{if(H&&O){const ge=g.globalAlpha;g.globalAlpha=1,g.stroke(),g.globalAlpha=ge}},_i=H=>Math.max(0,(H*at|0)*(vi+St)-St),NS=H=>{S.val=H,S.peak>0&&(S.hold--,S.hold<0&&(S.peak+=S.hold*xe/_e/E.height*this._pixelRatio)),H>=S.peak&&(S.peak=H,S.hold=he)};q&&g.clearRect(0,0,E.width,E.height);let Zf=0;const ep=N.length,tp=Qe?1:2;for(let H=0;H<tp;H++){const{channelTop:ge,channelBottom:Pt,analyzerBottom:We}=b[H],qs=this._gradients[this._selectedGrads[H]],ei=qs.colorStops,Wt=ei.length,yi=!oe||a&&!q?"#000":qs.bgColor,bi=Je&&G&&H?-1:1,wi=!H&&$==-1||H&&$==1,ka=!fe||H&&$!=1?0:Ze>>(H||!wi),zs=fe&&wi?-1:1,Ea=()=>{const X=te.height,ee=X>>1,se=P?100:L,Se=P?0:V,Pe=P?20:5,st=p/(se-Se),Nt=$!=-1&&(!fe||H==0||$==1),ti=$!=1&&(!fe||H!=$);g.save(),g.fillStyle=qu,g.font=`${ee}px ${bs}`,g.textAlign="right",g.lineWidth=1;for(let ii=se;ii>Se;ii-=Pe){const Xi=ge+(se-ii)*st,Ve=ii%2==0|0;if(Ve){const et=Xi+ee*(Xi==ge?.8:.35);Nt&&g.fillText(ii,X*.85,et),ti&&g.fillText(ii,(fe?Ze:E.width)-X*.1,et),g.strokeStyle=qu,g.setLineDash([2,4]),g.lineDashOffset=0}else g.strokeStyle=Fy,g.setLineDash([2,8]),g.lineDashOffset=1;g.beginPath(),g.moveTo(T+X*Ve*Nt,~~Xi+.5),g.lineTo(ne-X*Ve*ti,~~Xi+.5),g.stroke()}g.restore()},Ks=(X,ee)=>{const se=Ct[X]+(X<Ct.length-1?(Ct[X+1]-Ct[X])*ee:0);return isNaN(se)?-1/0:se},Si=(X,ee=zs)=>ee*Ni*((X+ka)/E.width)+this._spinAngle,lt=(X,ee,se)=>{const Se=A+ee*bi,Pe=Si(X,se);return[m+Se*Math.cos(Pe),v+Se*Math.sin(Pe)]},Ia=(X,ee,se,Se,Pe)=>{g.beginPath();for(const st of $&&!fe?[1,-1]:[zs]){const[Nt,ti]=d?[Si(X,st),Si(X+se,st)]:[];g.moveTo(...lt(X,ee,st)),g.lineTo(...lt(X,ee+Se,st)),d?g.arc(m,v,A+(ee+Se)*bi,Nt,ti,st!=1):g.lineTo(...lt(X+se,ee+Se,st)),g.lineTo(...lt(X+se,ee,st)),d&&!Pe&&g.arc(m,v,A+ee*bi,ti,Nt,st==1)}Ta(Pe),g.fill()},Aa=(X=0,ee=0)=>{let se;if(_==ys&&!Ot||W==Fi)se=k[H];else{const Se=_==Lu?ee%Wt:ei.findLastIndex(Pe=>a?_i(X)<=_i(Pe.level):X<=Pe.level);se=ei[Se].color}g.fillStyle=g.strokeStyle=se};if(Z){if(fe&&!G){const X=Ze*(H+wi),ee=wi?-1:1;g.setTransform(ee,0,0,1,X,0)}if((!q||oe)&&(q&&(g.globalAlpha=this.bgAlpha),g.fillStyle=yi,(H==0||!G&&!de)&&g.fillRect(T,ge-C,Ze,(q&&this.reflexAlpha==1?p:y)+C),g.globalAlpha=1),this.showScaleY&&!l&&!G&&(H==0||!de)&&Ea(),a?(g.setLineDash([vi,St]),g.lineWidth=N[0].width):g.lineWidth=u?Math.min(O,N[0].width/2):O,g.save(),!G){const X=new Path2D;X.rect(0,ge,E.width,p),g.clip(X)}}let Ct=this._fftData[H];this._analyzer[H].getFloatFrequencyData(Ct),Y&&(Ct=Ct.map((X,ee)=>X+PS(this._binToFreq(ee)))),g.beginPath();let $n=[];for(let X=0;X<ep;X++){const ee=N[X],{posX:se,barCenter:Se,width:Pe,freq:st,binLo:Nt,binHi:ti,ratioLo:ii,ratioHi:Xi}=ee;let Ve=Math.max(Ks(Nt,ii),Ks(ti,Xi));for(let be=Nt+1;be<ti;be++)Ct[be]>Ve&&(Ve=Ct[be]);if(Ve=this._normalizedB(Ve),ee.value[H]=Ve,Zf+=Ve,ee.peak[H]>0&&ee.alpha[H]>0&&(ee.hold[H]--,ee.hold[H]<0)){if(I&&!ye){const be=!o||u&&O>0?1:o?ee.peak[H]:M;ee.alpha[H]=be*(1+ee.hold[H]/Oe)}else ee.peak[H]+=ee.hold[H]*xe/_e/Ee;ee.alpha[H]<=0&&(ee.peak[H]=0)}if(Ve>=ee.peak[H]&&(ee.peak[H]=Ve,ee.hold[H]=he,ee.alpha[H]=!o||u&&O>0?1:o?Ve:M),!Z)continue;g.globalAlpha=l||o?Ve:u?M:1,Aa(Ve,X);const et=l?Be:a?_i(Ve):Ve*Be|0;if(W==Fi){const be=X?0:(this._normalizedB(Ct[N[1].binLo])*Be+et)/2;if(G){if(X==0&&(fe&&g.moveTo(...lt(0,0)),g.lineTo(...lt(0,se<0?be:et))),se>=0){const vt=[se,et];g.lineTo(...lt(...vt)),$n.push(vt)}}else{if(X==0)if($==-1&&!fe)g.moveTo(T,We-(se<T?be:et));else{const vt=Nt?this._normalizedB(Ct[Nt-1])*Be:et;g.moveTo(T-O,We-vt)}(fe||$!=-1||se>=T)&&g.lineTo(se,We-et)}}else if(a){if(oe&&!q&&(H==0||!de)){const be=g.globalAlpha;g.strokeStyle=Ly,g.globalAlpha=1,Ca(Se,ge,We),g.strokeStyle=g.fillStyle,g.globalAlpha=be}if(Ot){const be=l?0:ei.findLastIndex(Ci=>_i(Ve)<=_i(Ci.level));let vt=We;for(let Ci=Wt-1;Ci>=be;Ci--){g.strokeStyle=ei[Ci].color;let np=We-(Ci==be?et:_i(ei[Ci].level));Ca(Se,vt,np),vt=np-St}}else Ca(Se,We,We-et)}else if(se>=T)if(G)Ia(se,0,Pe,et,u);else if(d){const be=Pe/2,vt=We+be;g.beginPath(),g.moveTo(se,vt),g.lineTo(se,vt-et),g.arc(Se,vt-et,be,Lr,Ni),g.lineTo(se+Pe,vt),Ta(u),g.fill()}else{const be=u?g.lineWidth:0;g.beginPath(),g.rect(se,We+be,Pe,-et-be),Ta(u),g.fill()}const Ji=ee.peak[H],ip=ee.alpha[H];if(Ji>0&&ip>0&&K&&!ye&&!l&&se>=T&&se<ne){if(I?g.globalAlpha=ip:u&&O>0?g.globalAlpha=1:o&&(g.globalAlpha=Ji),(_==Mu||Ot)&&Aa(Ji),a){const be=_i(Ji);be>=St&&g.fillRect(se,We-be,Pe,vi)}else if(!G)g.fillRect(se,We-Ji*Be,Pe,2);else if(W!=Fi){const be=Ji*Be;Ia(se,be,Pe,!this._radialInvert||Je||be+A>=2?-2:2)}}}if(Z){if(g.globalAlpha=1,W==Fi){if(Aa(),G&&!fe){if($){let X;for(;X=$n.pop();)g.lineTo(...lt(...X,-1))}g.closePath()}if(O>0&&g.stroke(),M>0){if(G){const X=fe?Si(Ze>>1):0,ee=fe?Si(Ze):Ni;g.moveTo(...lt(fe?Ze>>1:0,0)),g.arc(m,v,A,X,ee,fe?!wi:!0)}else g.lineTo(ne,We),g.lineTo(T,We);g.globalAlpha=M,g.fill(),g.globalAlpha=1}if((ye||G&&K)&&($n=[],g.beginPath(),N.forEach((X,ee)=>{let se=X.posX,Se=X.peak[H],Pe=ee?"lineTo":"moveTo";if(G&&se<0){const st=N[ee+1];Se=zy(se,Se,st.posX,st.peak[H],0),se=0}Se*=Be,ye?(g[Pe](...G?lt(se,Se):[se,We-Se]),G&&$&&!fe&&$n.push([se,Se])):Se>0&&Ia(se,Se,1,-2)}),ye)){let X;for(;X=$n.pop();)g.lineTo(...lt(...X,-1));g.lineWidth=1,g.stroke()}}g.restore(),fe&&!G&&g.setTransform(1,0,0,1,0,0),(!fe&&!de||H)&&MS(H)}}if(NS(Zf/(ep<<tp-1)),Z&&($&&!G&&!fe&&(g.setTransform(-1,0,0,1,E.width-T,0),g.drawImage(E,T,0,m,E.height,0,0,m,E.height),g.setTransform(1,0,0,1,0,0)),g.setLineDash([]),OS()),this.showFPS){const H=te.height;g.font=`bold ${H}px ${bs}`,g.fillStyle=Dy,g.textAlign="right",g.fillText(Math.round(R),E.width-H,H*2)}this.onCanvasDraw&&(g.save(),g.fillStyle=g.strokeStyle=k[0],this.onCanvasDraw(this,{timestamp:e,canvasGradients:k}),g.restore())}_freqScaling(e){switch(this._frequencyScale){case Ui:return Math.log2(e);case Pr:return 26.81*e/(1960+e)-.53;case Nr:return Math.log2(1+e/700);case kn: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==Rt,p=1-s,m=d?e.height:e.height*(1-s*!h)|0;for(const v of[0,1]){const b=this._gradients[this._selectedGrads[v]],y=b.colorStops,C=b.dir=="h";let T;if(n?T=i.createRadialGradient(r,a,u,r,a,c-(u-c)*h):T=i.createLinearGradient(...C?[l,0,l+o,0]:[0,0,0,m]),y){const A=h&&!this._splitGradient&&(!C||n);for(let x=0;x<1+A;x++){const N=y.length-1;y.forEach((E,k)=>{let f=E.pos;if(A&&(f/=2),h&&!d&&!n&&!C&&(f*=p,!A&&f>.5*p&&(f+=.5*s)),x==1)if(n||d){const _=N-k;E=y[_],f=1-E.pos/2}else k==0&&f>0&&T.addColorStop(.5,E.color),f+=.5;T.addColorStop(f,E.color),h&&k==N&&f<.5&&T.addColorStop(.5,E.color)})}}this._canvasGradients[v]=T}}_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!=Hu&&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=Wu),this._fsStatus=l,this.onCanvasResize&&this.onCanvasResize(e,this))}_setGradient(e,i){if(!this._gradients.hasOwnProperty(e))throw new pt(Vy,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(En).filter(r=>r!="start").concat(n,s);(i||e===void 0)&&(e={...En,...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 Yy={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}]}},Ju=({stream:t,className:e,onClick:i})=>{var o;const n=ce(null),s=ui();return Le(()=>{var c;if(!n.current||!t)return;const r=new AudioContext,a=r.createMediaStreamSource(t),l=new Ky(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",Yy[((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:Vt("w-full",e),ref:n})},Qu=Yn(null),Ur=({className:t,debug:e=!1})=>{const i=_o(Qu);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
|
|
21
|
+
*/const Zu=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Xy=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,i,n)=>n?n.toUpperCase():i.toLowerCase()),eh=t=>{const e=Xy(t);return e.charAt(0).toUpperCase()+e.slice(1)},Jy=(...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
|
|
26
|
+
*/var Qy={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
|
|
31
|
+
*/const Zy=({color:t="currentColor",size:e=24,strokeWidth:i=2,absoluteStrokeWidth:n,children:s,iconNode:o,class:r="",...a})=>ct("svg",{...Qy,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])=>ct(l,c)),...kt(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
|
|
36
|
+
*/const Ye=(t,e)=>{const i=({class:n="",children:s,...o})=>ct(Zy,{...o,iconNode:e,class:Jy(`lucide-${Zu(eh(t))}`,`lucide-${Zu(t)}`,n)},s);return i.displayName=eh(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
|
|
41
|
+
*/const th=Ye("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
|
|
46
|
+
*/const e0=Ye("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
|
|
51
|
+
*/const ih=Ye("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
|
|
56
|
+
*/const t0=Ye("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
|
|
61
|
+
*/const i0=Ye("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
|
|
66
|
+
*/const n0=Ye("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
|
|
71
|
+
*/const s0=Ye("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
|
|
76
|
+
*/const o0=Ye("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
|
|
81
|
+
*/const r0=Ye("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
|
|
86
|
+
*/const a0=Ye("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
|
|
91
|
+
*/const l0=Ye("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
|
|
96
|
+
*/const c0=Ye("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
|
|
101
|
+
*/const d0=Ye("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
|
|
106
|
+
*/const u0=Ye("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 xr=He("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ju=$n(!1),n0=()=>Il(Ju),Ot=({children:t,className:e,onClick:i,tooltip:n})=>L("button",{title:n,onClick:i,className:Lt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),Zu=({call:t,chatMode:e})=>{const[i,n]=n0(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return L("div",{className:"flex items-center justify-center gap-2",children:[!e&&L(Ot,{tooltip:i?"Unmute":"Mute",onClick:s,className:Lt(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?L(Ky,{className:"w-5 h-5 text-black dark:text-white"}):L(Yy,{className:"w-5 h-5 text-black dark:text-white"})}),L(Ot,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:L(Jy,{className:"w-4 h-4 text-black dark:text-white"})})]})},Qu=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>L(Ii.div,{layoutId:vn,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&&L(Wu,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),L(Su,{stream:t.remoteStream,chatMode:i}),L(wu,{size:"small"}),L(Zu,{call:t,chatMode:i}),L(qu,{debug:n})]});function s0(){const[t,e]=Ae(!1),i=ni();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 L("div",{children:[L(Ot,{tooltip:"More",onClick:()=>e(!t),children:L(Xu,{className:"text-black dark:text-white"})}),t&&L("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:[L(Ot,{tooltip:"More",onClick:()=>e(!t),children:L(Xu,{className:"text-black dark:text-white"})}),L("ul",{className:"text-sm font-semibold divide-y text-left divider-solid divide-[#3D3D46]",children:[i.give_feedback_url&&L("li",{onClick:s,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Give Feedback ",L(t0,{className:"w-4 h-4"})]}),i.report_issue_url&&L("li",{onClick:o,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["Report Issue ",L(i0,{className:"w-4 h-4"})]}),i.view_history_url&&L("li",{onClick:r,className:"flex items-center gap-2 px-4 py-3 border-solid cursor-pointer",children:["View History ",L(qy,{className:"w-4 h-4"})]})]})]})]})}function o0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var fs={exports:{}},r0=fs.exports,eh;function a0(){return eh||(eh=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(r0,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 y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function g(v,b){var y=this,C,k,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function D(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),M=S.indexOf(I+"=");M!==-1&&(f=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.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 p(f){var S=f;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??k??C},y.setLevel=function(f,S){return A=p(f),S!==!1&&D(A),u.call(y)},y.setDefaultLevel=function(f){k=p(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var _=T();_!=null&&(A=p(_)),u.call(y)}r=new g,r.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=o[b];return y||(y=o[b]=new g(b,r.methodFactory)),y};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(fs)),fs.exports}var l0=a0();const c0=o0(l0),d0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),u0="[ai-agent-widget]",re=c0.getLogger("telnyx-ai-agent-widget"),h0=re.methodFactory;re.methodFactory=(t,e,i)=>{const n=h0(t,e,i);return function(...s){n(d0(),u0,...s)}},re.setLevel("info");function f0({onCapture:t,onClose:e}){const i=he(null),n=he(null),s=he(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){re.error("Error accessing camera:",h),h instanceof Error?h.name==="NotAllowedError"||h.name==="PermissionDeniedError"?r("Camera permission denied. Please allow camera access to take photos."):h.name==="NotFoundError"||h.name==="DevicesNotFoundError"?r("No camera found on this device."):h.name==="NotReadableError"||h.name==="TrackStartError"?r("Camera is already in use by another application."):r("Unable to access camera. Please try again."):r("Unable to access camera. Please try again."),l(!1)}})(),()=>{s.current&&s.current.getTracks().forEach(h=>h.stop())}),[]);const c=()=>{if(!i.current||!n.current)return;const d=i.current,h=n.current,g=h.getContext("2d");if(!g)return;h.width=d.videoWidth,h.height=d.videoHeight,g.drawImage(d,0,0,h.width,h.height);const m=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(m),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return L("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:[L("div",{className:"absolute top-2 right-2 z-10",children:L(Ot,{tooltip:"Close",onClick:u,children:L(xr,{className:"text-white w-5 h-5"})})}),L("div",{className:"relative flex-1 flex flex-col items-center justify-center p-4",children:[a&&!o&&L("div",{className:"absolute text-white text-center",children:L("p",{className:"text-sm",children:"Loading camera..."})}),o&&L("div",{className:"text-white text-center max-w-xs",children:[L("p",{className:"text-sm font-semibold mb-2",children:"Camera Error"}),L("p",{className:"text-xs",children:o}),L("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&&L(mt,{children:[L("video",{ref:i,autoPlay:!0,playsInline:!0,className:Lt("w-full h-full object-cover rounded-lg",{"opacity-0":a})}),L("canvas",{ref:n,className:"hidden"})]})]}),!o&&!a&&L("div",{className:"p-3 flex justify-center",children:L("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:[L(Yu,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const Dr=["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"],p0=["audio","lang","mark","p","s","sub","w"],th=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ih(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function nh(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const sh=Dr.filter(t=>!p0.includes(t)),g0=ih(Dr,"gi"),oh=ih(sh,"gi"),m0=nh(Dr,"i"),v0=nh(sh,"i"),_0=new RegExp(`${oh.source}|${th.source}`,"i");function y0(t){const e=_0.test(t),i=e?g0:oh,n=e?m0:v0;return t.replace(i,"").replace(n,"").replace(th,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function b0({item:t,containerRef:e}){const i=he(null),n=t.role==="assistant"?y0(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]),L("li",{className:Lt("flex flex-col gap-1 text-left",{"items-end":t.role==="user"}),ref:i,children:[L("span",{className:"text-xs text-[#969696]",children:[t.timestamp.toLocaleTimeString(),t.role==="assistant"&&t.greetingLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:["Greeting: ",t.greetingLatencyMs," ms"]}),t.role==="assistant"&&t.userPerceivedLatencyMs!==void 0&&L("span",{className:"ml-2 text-[#969696]",children:[t.userPerceivedLatencyMs," ms"]})]}),L("div",{className:Lt("flex flex-col gap-2",{"items-end":t.role==="user"}),children:[t.attachments&&t.attachments.length>0&&L("div",{className:"flex flex-wrap gap-2",children:t.attachments.map((s,o)=>s.type==="image"&&L("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&&L("p",{className:Lt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const w0=({transcript:t,call:e})=>{const i=he(null),n=he(null),s=he(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(p=>p.filter(_=>_.timestamp>E.timestamp))}},[t,c]);const h=T=>new Promise((E,p)=>{const _=new FileReader;_.onload=()=>E(_.result),_.onerror=p,_.readAsDataURL(T)}),g=async T=>{if(T.type.startsWith("image/"))try{const E=await h(T),p=URL.createObjectURL(T),_={id:Date.now().toString(),file:T,base64:E,preview:p};r(f=>[...f,_])}catch(E){re.error("Error processing image:",E)}},m=T=>{r(E=>{const p=E.find(_=>_.id===T);return p&&URL.revokeObjectURL(p.preview),E.filter(_=>_.id!==T)})},v=T=>{const E=T.target,p=E.files;p&&p.length>0&&(Array.from(p).forEach(g),E.value="")},b=T=>{var p;const E=(p=T.clipboardData)==null?void 0:p.items;E&&Array.from(E).forEach(_=>{if(_.type.startsWith("image/")){const f=_.getAsFile();f&&g(f)}})},y=()=>{var T;(T=n.current)==null||T.click()},C=()=>{l(!0)},k=T=>{fetch(T).then(E=>E.blob()).then(E=>{const p=new File([E],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});g(p)}).catch(E=>{re.error("Error processing camera capture:",E)})},A=async()=>{var p;const T=i.current&&i.current.value.trim()!=="",E=o.length>0;if(T||E){const _=((p=i.current)==null?void 0:p.value)||"",f=new Date,S={id:`optimistic-${f.getTime()}`,role:"user",content:_,timestamp:f,attachments:o.map(I=>({type:"image",url:I.base64}))};u(I=>[...I,S]),E&&d("processing_image"),e.sendConversationMessage(_,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(),A())},D=[...t,...c];return L("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:[L("ul",{className:"flex flex-col flex-1 gap-4 p-4 overflow-y-auto",ref:s,children:D.map((T,E)=>L(b0,{item:T,containerRef:s},T.id+E))}),o.length>0&&L("div",{className:"flex flex-wrap gap-2 mb-2",children:o.map(T=>L("div",{className:"relative",children:[L("img",{src:T.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),L("button",{onClick:()=>m(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:L(xr,{className:"w-3 h-3"})})]},T.id))}),L("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:[L("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"}),L("input",{ref:n,type:"file",accept:"image/*",multiple:!0,onChange:v,className:"hidden"}),L(Ot,{tooltip:"Attach image",onClick:y,children:L(Xy,{className:"text-[#969696] w-4 h-4"})}),L(Ot,{tooltip:"Take photo",onClick:C,children:L(Yu,{className:"text-[#969696] w-4 h-4"})}),L(Ot,{tooltip:"Send",children:L(Qy,{onClick:A,className:"text-[#969696] w-4 h-4"})})]}),a&&L(f0,{onCapture:k,onClose:()=>l(!1)})]})};function S0({onCollapse:t}){return L("div",{className:"flex items-center justify-between w-full",children:[L(s0,{}),L(Ot,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:L(xr,{className:"text-black dark:text-white"})})]})}const C0=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>L(Om,{children:L(Ii.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:[L("div",{className:"p-4 text-center",children:[L(S0,{onCollapse:e}),!n&&L(Wu,{className:"h-[144px]",stream:t.remoteStream}),L(wu,{size:"large",className:"mb-4"}),L(Zu,{call:t,chatMode:n}),L(qu,{className:"mt-2",debug:s})]}),L(Su,{stream:t.remoteStream,chatMode:n}),L(w0,{call:t,transcript:i})]})});function rh(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 B(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 ah=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),T0=new Uint8Array(16);function k0(){if(!ah)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ah(T0)}for(var lh=[],ps=0;ps<256;++ps)lh[ps]=(ps+256).toString(16).substr(1);function Di(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||k0)();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=lh;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 E0={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},I0={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:R0,SDP_CREATE_ANSWER_FAILED:A0,SDP_SET_LOCAL_DESCRIPTION_FAILED:x0,SDP_SET_REMOTE_DESCRIPTION_FAILED:ch,SDP_SEND_FAILED:dh,MEDIA_MICROPHONE_PERMISSION_DENIED:uh,MEDIA_DEVICE_NOT_FOUND:hh,MEDIA_GET_USER_MEDIA_FAILED:Lr,HOLD_FAILED:D0,INVALID_CALL_PARAMETERS:L0,BYE_SEND_FAILED:M0,SUBSCRIBE_FAILED:O0,PEER_CLOSED_DURING_INIT:Mr,WEBSOCKET_CONNECTION_FAILED:P0,WEBSOCKET_ERROR:N0,RECONNECTION_EXHAUSTED:Or,GATEWAY_FAILED:F0,LOGIN_FAILED:fh,INVALID_CREDENTIALS:B0,AUTHENTICATION_REQUIRED:U0,ICE_RESTART_FAILED:V0,NETWORK_OFFLINE:$0,SESSION_NOT_REATTACHED:ph,UNEXPECTED_ERROR:gh}=E0,{HIGH_RTT:j0,HIGH_JITTER:H0,HIGH_PACKET_LOSS:W0,LOW_MOS:mh,LOW_LOCAL_AUDIO:gs,LOW_INBOUND_AUDIO:ms,LOW_BYTES_RECEIVED:Pr,LOW_BYTES_SENT:vh,RECORDING_UNAVAILABLE:G0,RECORDING_BUFFER_OVERFLOW:q0,ICE_CONNECTIVITY_LOST:z0,ICE_GATHERING_TIMEOUT:K0,ICE_GATHERING_EMPTY:Y0,PEER_CONNECTION_FAILED:X0,ONLY_HOST_ICE_CANDIDATES:J0,ANSWER_WHILE_PEER_ACTIVE:Z0,ICE_CANDIDATE_PAIR_CHANGED:Q0,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:eb,MULTIPLE_ACTIVE_CALLS_DETECTED:tb,DUPLICATE_INBOUND_ANSWER:ib,SHARED_REMOTE_ELEMENT_OVERWRITE:nb,TOKEN_EXPIRING_SOON:sb,UNKNOWN_REATTACHED_SESSION:ob,SIGNALING_RECOVERY_REQUIRED:rb,MEDIA_RECOVERY_REQUIRED:ab,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:lb}=I0,_h="wss://rtc.telnyx.com",yh={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},bh={urls:"stun:stun.l.google.com:19302"},cb={urls:"stun:stun.telnyx.com:3478"},db={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},ub={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},hb={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},fb={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},pb=[cb,bh,db,ub,hb,fb],gb=[{urls:"stun:stundev.telnyx.com:3478"},bh,{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 mb={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}},vb={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 with host (local network) candidates only. This is diagnostic evidence that no server-reflexive (srflx), peer-reflexive (prflx), or relay (TURN) candidates were found; connectivity may still succeed, but network traversal options can be limited.",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 Pe(t,e){const i=vb[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Ht 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,Ht.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 Li(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return uh;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return hh}return Lr}function ae(t,e,i,n){const s=mb[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Ht({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 _b 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 Nr 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 yb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function wh(t,e){return t(e={exports:{}},e.exports),e.exports}var bb=wh(function(t){var e,i;e=yb,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,y){var C=b[y];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,y){for(var C=0;C<r.length;C++){var k=r[C];this[k]=C<b?n:this.methodFactory(k,b,y)}this.log=this.debug}function u(b,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[b].apply(this,arguments))}}function d(b,y,C){return function(k){return k==="debug"&&(k="log"),typeof console!==s&&(k==="trace"&&o?l:console[k]!==void 0?a(console,k):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,y,C){var k,A=this;y=y??"WARN";var R="loglevel";function D(){var E;if(typeof window!==s&&R){try{E=window.localStorage[R]}catch{}if(typeof E===s)try{var p=window.document.cookie,_=p.indexOf(encodeURIComponent(R)+"=");_!==-1&&(E=/^([^;]+)/.exec(p.slice(_))[1])}catch{}return A.levels[E]===void 0&&(E=void 0),E}}typeof b=="string"?R+=":"+b:typeof b=="symbol"&&(R=void 0),A.name=b,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return k},A.setLevel=function(E,p){if(typeof E=="string"&&A.levels[E.toUpperCase()]!==void 0&&(E=A.levels[E.toUpperCase()]),!(typeof E=="number"&&E>=0&&E<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+E;if(k=E,p!==!1&&function(_){var f=(r[_]||"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(A,E,b),typeof console===s&&E<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(E){y=E,D()||A.setLevel(E,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&R){try{return void window.localStorage.removeItem(R)}catch{}try{window.document.cookie=encodeURIComponent(R)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(E){A.setLevel(A.levels.TRACE,E)},A.disableAll=function(E){A.setLevel(A.levels.SILENT,E)};var T=D();T==null&&(T=y),A.setLevel(T,!1)}var g=new h,m={};g.getLogger=function(b){if(typeof b!="symbol"&&typeof b!="string"||b==="")throw new TypeError("You must supply a name when creating a logger.");var y=m[b];return y||(y=m[b]=new h(b,g.getLevel(),g.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return g.noConflict=function(){return typeof window!==s&&window.log===g&&(window.log=v),g},g.getLoggers=function(){return m},g.default=g,g},t.exports?t.exports=i():e.log=i()});const Sh={debug:0,info:1,warn:2,error:3};class wb{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||Sh[e]<Sh[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 Ch=null;const w=bb.getLogger("telnyx"),vs={trace:0,debug:1,info:2,warn:3,error:4};let Th=vs.info;function kh(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 Sb=w.methodFactory;w.methodFactory=(t,e,i)=>{const n=Sb(t,e,i);return function(...s){if(vs[t]>=Th){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Ch;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?kh(a[0]):{args:a.map(kh)}),o.addEntry(t,l,c)}}},w.setLevel("debug",!1);const _s=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{w.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Eh=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},ys=t=>t instanceof Function||typeof t=="function",bn=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,Cb=/^(ws|wss):\/\//,Ih=(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?Ih(a,r):{result:s}},bs=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),wn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Fr=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 Rh({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?Tb(n,t):n,i=s}),resolve:e,reject:i}}const Tb=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},Br="telnyx-voice-sdk-id",ws="telnyx-voice-sdk-session-id",Ss="telnyx-voice-sdk-session-id-stored-at",Ur="telnyx-voice-sdk-active-calls",kb=9e4;function Ah(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(Ss));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=kb}function Sn(){return sessionStorage.getItem(Br)}function Vr(t,e=Date.now()){sessionStorage.setItem(ws,t),sessionStorage.setItem(Ss,String(e))}function xh(){sessionStorage.removeItem(Br),sessionStorage.removeItem(ws),sessionStorage.removeItem(Ss)}function si(){(function(t){try{sessionStorage.removeItem(t)}catch(e){w.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(Ur)}function Dh(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return w.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(Ur);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return w.debug("Active-calls recovery marker payload was malformed — discarded."),si(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(w.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),si(),null):i.calls.length===0?(w.debug("Active-calls recovery marker had no call records — discarded."),si(),null):i}catch(i){return w.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),si(),null}}function Lh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void si();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){w.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(Ur,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var Ne,St,ee;(function(t){t.Offer="offer",t.Answer="answer"})(Ne||(Ne={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(St||(St={})),function(t){t.Invite="telnyx_rtc.invite",t.Attach="telnyx_rtc.attach",t.Answer="telnyx_rtc.answer",t.Info="telnyx_rtc.info",t.Candidate="telnyx_rtc.candidate",t.EndOfCandidates="telnyx_rtc.endOfCandidates",t.Display="telnyx_rtc.display",t.Media="telnyx_rtc.media",t.Event="telnyx_rtc.event",t.Bye="telnyx_rtc.bye",t.Punt="telnyx_rtc.punt",t.Broadcast="telnyx_rtc.broadcast",t.Subscribe="telnyx_rtc.subscribe",t.Unsubscribe="telnyx_rtc.unsubscribe",t.ClientReady="telnyx_rtc.clientReady",t.Modify="telnyx_rtc.modify",t.Ringing="telnyx_rtc.ringing",t.GatewayState="telnyx_rtc.gatewayState",t.Ping="telnyx_rtc.ping",t.Pong="telnyx_rtc.pong"}(ee||(ee={}));const at={generic:"event",[ee.Display]:"participantData",[ee.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Eb={invalidCredentialsOptions:"InvalidCredentialsOptions"},Mh=8e6,Oh={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:!1};var W,$r,Xe,Ct,Le,Mi;(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"}($r||($r={})),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"}(Xe||(Xe={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Ct||(Ct={})),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"}(Le||(Le={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}(Mi||(Mi={}));const Oi="GLOBAL",Ke={},Cn=(t,e)=>`${t}|${e}`,Ph=(t,e=Oi)=>Cn(t,e)in Ke,Wt=(t,e,i=Oi)=>{const n=Cn(t,i);n in Ke||(Ke[n]=[]),Ke[n].push(e)},Nh=(t,e,i=Oi)=>{const n=function(s){Tt(t,n,i),e(s)};return n.prototype.targetRef=e,Wt(t,n,i)},Tt=(t,e,i=Oi)=>{if(!Ph(t,i))return!1;const n=Cn(t,i);if(ys(e))for(let s=Ke[n].length-1;s>=0;s--){const o=Ke[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&Ke[n].splice(s,1)}else Ke[n]=[];return Ke[n].length===0&&delete Ke[n],!0},U=(t,e,i=Oi,n=!0)=>{const s=n&&i!==Oi;if(!Ph(t,i))return s&&U(t,e),!1;const o=Cn(t,i),r=Ke[o].length;if(!r)return s&&U(t,e),!1;for(let a=r-1;a>=0;a--)Ke[o][a](e);return s&&U(t,e),!0},jr=t=>{const e=Cn(t,"");Object.keys(Ke).filter(i=>i.indexOf(e)===0).forEach(i=>delete Ke[i])};let Ib=typeof WebSocket<"u"?WebSocket:null;const Rb=0,Ab=1,xb=2,Fh=3;class Cs{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=_h,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;w.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":_h),i&&(this._host=(r=>`${Cb.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===Ab}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Rb}get closing(){return!!this._wsClient&&this._wsClient.readyState===xb}get closed(){return!!this._wsClient&&this._wsClient.readyState===Fh}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){w.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=Sn();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"),w.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 Ib(e.toString()),this.socketGeneration+=1,w.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){w.error("WebSocket connection failed:",n);const s=ae(P0,n);U(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=g=>{if(d!==null&&(clearTimeout(d),this._pendingRequestTimers.delete(s.id),d=null),this._pendingRequestIds.delete(s.id),this._pendingRequestRejecters.delete(s.id),this.session.onOutboundConfirmed(),u)return;const{result:m,error:v}=Ih(g);return v?c(v):l(m)};Nh(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),Tt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return w.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Nr(s.id,o,this.socketGeneration));c(new _b(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return w.debug(`SEND:
|
|
111
|
+
*/const In=Ye("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),nh=Yn(!1),h0=()=>Ll(nh),xt=({children:t,className:e,onClick:i,tooltip:n,disabled:s=!1})=>D("button",{title:n,"aria-label":n,disabled:s,onClick:i,className:Vt("w-8 h-8 rounded-full cursor-pointer text-white flex items-center justify-center",e),children:t}),sh=({call:t,chatMode:e})=>{const[i,n]=h0(),s=()=>{n(r=>{const a=!r;return a?t.muteAudio():t.unmuteAudio(),a})},o=()=>{t.hangup()};return D("div",{className:"flex items-center justify-center gap-2",children:[!e&&D(xt,{tooltip:i?"Unmute":"Mute",onClick:s,className:Vt(i?"bg-[#F36666] dark:bg-[#750000]":"bg-[#E6E3D3] dark:bg-[#3C3C3C]"),children:i?D(n0,{className:"w-5 h-5 text-black dark:text-white"}):D(s0,{className:"w-5 h-5 text-black dark:text-white"})}),D(xt,{tooltip:"End Call",onClick:o,className:"bg-[#F36666] text-black dark:text-black dark:bg-[#750000]",children:D(r0,{className:"w-4 h-4 text-black dark:text-white"})})]})},oh=({call:t,onExpand:e,chatMode:i,debug:n=!1})=>D(Xt.div,{layoutId:Tn,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(Ju,{onClick:e,className:"h-[72px] cursor-pointer",stream:t.remoteStream}),D(Ru,{stream:t.remoteStream,chatMode:i}),D(Dr,{size:"small"}),D(sh,{call:t,chatMode:i}),D(Ur,{debug:n})]});function rh(){const[t,e]=ve(!1),i=ui();if(!i.give_feedback_url&&!i.report_issue_url&&!i.view_history_url)return null;const n=a=>{a&&window.open(a,"_blank","noopener,noreferrer"),e(!1)},s=()=>{n(i.give_feedback_url)},o=()=>{n(i.report_issue_url)},r=()=>{n(i.view_history_url)};return D("div",{children:[D(xt,{tooltip:"More",onClick:()=>e(!t),children:D(ih,{className:"text-black dark:text-white"})}),t&&D("div",{className:"absolute p-4 w-[200px] min-h-[180px] top-0 left-0 bg-[#FEFDF599] dark:bg-[#38383C96] rounded-3xl backdrop-blur-xs z-10",children:[D(xt,{tooltip:"More",onClick:()=>e(!t),children:D(ih,{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(d0,{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(u0,{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(t0,{className:"w-4 h-4"})]})]})]})]})}function f0(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ss={exports:{}},p0=Ss.exports,ah;function g0(){return ah||(ah=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(p0,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 y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function E(){var g;if(!(typeof window===i||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===i)try{var S=window.document.cookie,I=encodeURIComponent(x),M=S.indexOf(I+"=");M!==-1&&(g=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function k(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),E()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=E();_!=null&&(A=f(_)),u.call(y)}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 y=o[b];return y||(y=o[b]=new p(b,r.methodFactory)),y};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(Ss)),Ss.exports}var m0=g0();const v0=f0(m0),_0=()=>new Date().toISOString().replace("T"," ").replace("Z",""),y0="[ai-agent-widget]",re=v0.getLogger("telnyx-ai-agent-widget"),b0=re.methodFactory;re.methodFactory=(t,e,i)=>{const n=b0(t,e,i);return function(...s){n(_0(),y0,...s)}},re.setLevel("info");function w0({onCapture:t,onClose:e}){const i=ce(null),n=ce(null),s=ce(null),[o,r]=ve(null),[a,l]=ve(!0);Le(()=>((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){re.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 m=h.toDataURL("image/jpeg",.9);s.current&&s.current.getTracks().forEach(v=>v.stop()),t(m),e()},u=()=>{s.current&&s.current.getTracks().forEach(d=>d.stop()),e()};return D("div",{className:"absolute inset-0 z-50 flex flex-col bg-black bg-opacity-40 backdrop-blur-lg rounded-t-3xl sm:rounded-3xl overflow-hidden",children:[D("div",{className:"absolute top-2 right-2 z-10",children:D(xt,{tooltip:"Close",onClick:u,children:D(In,{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(yt,{children:[D("video",{ref:i,autoPlay:!0,playsInline:!0,className:Vt("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(th,{className:"w-4 h-4"}),"Capture Photo"]})})]})}const Br=["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"],S0=["audio","lang","mark","p","s","sub","w"],lh=/\[(pause|long-pause|hum-tune|laugh|laughter|chuckle|giggle|cry|tsk|tongue-click|lip-smack|breath|inhale|exhale|sigh)\]/gi;function ch(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`</?(?:${i})(?:\\s+[^<>]*)?\\s*/?>`,e)}function dh(t,e){const i=[...t].sort((n,s)=>s.length-n.length).join("|");return new RegExp(`<\\/?(?:${i})(?:\\s+[^<>]*)?$`,e)}const uh=Br.filter(t=>!S0.includes(t)),C0=ch(Br,"gi"),hh=ch(uh,"gi"),T0=dh(Br,"i"),k0=dh(uh,"i"),E0=new RegExp(`${hh.source}|${lh.source}`,"i");function I0(t){const e=E0.test(t),i=e?C0:hh,n=e?T0:k0;return t.replace(i,"").replace(n,"").replace(lh,"").replace(/[ \t]{2,}/g," ").replace(/\s+([.,!?;:])/g,"$1").trim()}function A0({item:t,containerRef:e}){const i=ce(null),n=t.role==="assistant"?I0(t.content):t.content;return Le(()=>{var s;i.current&&((s=e==null?void 0:e.current)==null||s.scrollTo({top:i.current.offsetTop,behavior:"smooth"}))},[e]),D("li",{className:Vt("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:Vt("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:Vt("text-sm",{"bg-[#FEFDF5] dark:bg-[#222227] px-2.5 py-2 rounded-md":t.role==="user"}),children:n})]})]})}const fh=({transcript:t,onSendMessage:e,allowAttachments:i=!0,awaitAcceptance:n=!1,sendDisabled:s=!1})=>{const o=ce(!1),[r,a]=ve(!1),[l,c]=ve(null),u=ce(null),d=ce(null),h=ce(null),[p,m]=ve([]),[v,b]=ve(!1),[y,C]=ve([]),[,T]=ms();Le(()=>()=>{p.forEach(R=>URL.revokeObjectURL(R.preview))},[p]),Le(()=>{if(y.length===0)return;const R=t.filter(P=>P.role==="user"&&!P.id.startsWith("optimistic-"));if(R.length>0){const P=R[R.length-1];C(O=>O.filter(L=>L.timestamp>P.timestamp))}},[t,y]);const A=R=>new Promise((P,O)=>{const L=new FileReader;L.onload=()=>P(L.result),L.onerror=O,L.readAsDataURL(R)}),x=async R=>{if(i&&R.type.startsWith("image/"))try{const P=await A(R),O=URL.createObjectURL(R),L={id:Date.now().toString(),file:R,base64:P,preview:O};m(V=>[...V,L])}catch(P){re.error("Error processing image:",P)}},N=R=>{m(P=>{const O=P.find(L=>L.id===R);return O&&URL.revokeObjectURL(O.preview),P.filter(L=>L.id!==R)})},E=R=>{const P=R.target,O=P.files;O&&O.length>0&&(Array.from(O).forEach(x),P.value="")},k=R=>{var O;const P=(O=R.clipboardData)==null?void 0:O.items;P&&Array.from(P).forEach(L=>{if(L.type.startsWith("image/")){const V=L.getAsFile();V&&x(V)}})},f=()=>{var R;(R=d.current)==null||R.click()},_=()=>{b(!0)},g=R=>{fetch(R).then(P=>P.blob()).then(P=>{const O=new File([P],`camera-${Date.now()}.jpg`,{type:"image/jpeg"});x(O)}).catch(P=>{re.error("Error processing camera capture:",P)})},S=async()=>{var O;if(s||o.current)return;if(n){const L=u.current;if(!L||!L.value.trim())return;const V=L.value;o.current=!0,a(!0),c(null);try{await e(V,[]),L.value===V&&(L.value="")}catch($){c($ instanceof Error?$.message:"Message was not sent. Please try again.")}finally{o.current=!1,a(!1)}return}const R=u.current&&u.current.value.trim()!=="",P=i&&p.length>0;if(R||P){const L=((O=u.current)==null?void 0:O.value)||"",V=new Date,$={id:`optimistic-${V.getTime()}`,role:"user",content:L,timestamp:V,attachments:p.map(W=>({type:"image",url:W.base64}))};C(W=>[...W,$]),P&&T("processing_image"),e(L,p.map(W=>W.base64)),u.current&&(u.current.value=""),p.forEach(W=>URL.revokeObjectURL(W.preview)),m([])}},I=R=>{R.key==="Enter"&&(R.preventDefault(),S())},M=[...t,...y];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:h,children:M.map((R,P)=>D(A0,{item:R,containerRef:h},R.id+P))}),l&&D("p",{role:"alert",className:"text-sm mb-2",children:l}),p.length>0&&D("div",{className:"flex flex-wrap gap-2 mb-2",children:p.map(R=>D("div",{className:"relative",children:[D("img",{src:R.preview,alt:"Preview",className:"w-16 h-16 object-cover rounded-lg border border-[#969696] dark:border-[#3D3D46]"}),D("button",{onClick:()=>N(R.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(In,{className:"w-3 h-3"})})]},R.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:u,type:"text","aria-label":"Message",readOnly:r,onKeyDown:I,onPaste:k,placeholder:"Type something here",className:"w-full text-sm bg-transparent outline-none dark:text-white"}),i&&D(yt,{children:[D("input",{ref:d,type:"file",accept:"image/*",multiple:!0,onChange:E,className:"hidden"}),D(xt,{tooltip:"Attach image",onClick:f,children:D(o0,{className:"text-[#969696] w-4 h-4"})}),D(xt,{tooltip:"Take photo",onClick:_,children:D(th,{className:"text-[#969696] w-4 h-4"})})]}),D(xt,{tooltip:"Send",onClick:S,disabled:s||r,children:D(l0,{className:"text-[#969696] w-4 h-4"})})]}),i&&v&&D(w0,{onCapture:g,onClose:()=>b(!1)})]})};function R0({onCollapse:t}){return D("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D(xt,{tooltip:"Collapse",className:"ml-auto",onClick:t,children:D(In,{className:"text-black dark:text-white"})})]})}const x0=({call:t,onCollapse:e,transcript:i,chatMode:n,debug:s=!1})=>D(Gc,{children:D(Xt.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(R0,{onCollapse:e}),!n&&D(Ju,{className:"h-[144px]",stream:t.remoteStream}),D(Dr,{size:"large",className:"mb-4"}),D(sh,{call:t,chatMode:n}),D(Ur,{className:"mt-2",debug:s})]}),D(Ru,{stream:t.remoteStream,chatMode:n}),D(fh,{transcript:i,onSendMessage:(o,r)=>t.sendConversationMessage(o,r)})]})});function ph(t,e){var i={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function"){var s=0;for(n=Object.getOwnPropertySymbols(t);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(t,n[s])&&(i[n[s]]=t[n[s]])}return i}function U(t,e,i,n){return new(i||(i=Promise))(function(s,o){function r(c){try{l(n.next(c))}catch(u){o(u)}}function a(c){try{l(n.throw(c))}catch(u){o(u)}}function l(c){var u;c.done?s(c.value):(u=c.value,u instanceof i?u:new i(function(d){d(u)})).then(r,a)}l((n=n.apply(t,[])).next())})}var gh=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),D0=new Uint8Array(16);function L0(){if(!gh)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return gh(D0)}for(var mh=[],Cs=0;Cs<256;++Cs)mh[Cs]=(Cs+256).toString(16).substr(1);function Bi(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||L0)();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=mh;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 M0={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},O0={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:P0,SDP_CREATE_ANSWER_FAILED:N0,SDP_SET_LOCAL_DESCRIPTION_FAILED:F0,SDP_SET_REMOTE_DESCRIPTION_FAILED:vh,SDP_SEND_FAILED:_h,MEDIA_MICROPHONE_PERMISSION_DENIED:yh,MEDIA_DEVICE_NOT_FOUND:bh,MEDIA_GET_USER_MEDIA_FAILED:Vr,HOLD_FAILED:U0,INVALID_CALL_PARAMETERS:B0,BYE_SEND_FAILED:V0,SUBSCRIBE_FAILED:$0,PEER_CLOSED_DURING_INIT:$r,WEBSOCKET_CONNECTION_FAILED:j0,WEBSOCKET_ERROR:H0,RECONNECTION_EXHAUSTED:jr,GATEWAY_FAILED:W0,LOGIN_FAILED:wh,INVALID_CREDENTIALS:G0,AUTHENTICATION_REQUIRED:q0,ICE_RESTART_FAILED:z0,NETWORK_OFFLINE:K0,SESSION_NOT_REATTACHED:Sh,UNEXPECTED_ERROR:Ch}=M0,{HIGH_RTT:Y0,HIGH_JITTER:X0,HIGH_PACKET_LOSS:J0,LOW_MOS:Th,LOW_LOCAL_AUDIO:Ts,LOW_INBOUND_AUDIO:ks,LOW_BYTES_RECEIVED:Hr,LOW_BYTES_SENT:kh,RECORDING_UNAVAILABLE:Q0,RECORDING_BUFFER_OVERFLOW:Z0,ICE_CONNECTIVITY_LOST:eb,ICE_GATHERING_TIMEOUT:tb,ICE_GATHERING_EMPTY:ib,PEER_CONNECTION_FAILED:nb,ONLY_HOST_ICE_CANDIDATES:sb,ANSWER_WHILE_PEER_ACTIVE:ob,ICE_CANDIDATE_PAIR_CHANGED:rb,AUDIO_INPUT_DEVICE_CHANGE_SKIPPED:ab,MULTIPLE_ACTIVE_CALLS_DETECTED:lb,DUPLICATE_INBOUND_ANSWER:cb,SHARED_REMOTE_ELEMENT_OVERWRITE:db,TOKEN_EXPIRING_SOON:ub,UNKNOWN_REATTACHED_SESSION:hb,SIGNALING_RECOVERY_REQUIRED:fb,MEDIA_RECOVERY_REQUIRED:pb,RECONNECTION_FAILED_WITH_NO_AUTO_RECONNECT:gb}=O0,Eh="wss://rtc.telnyx.com",Ih={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},Ah={urls:"stun:stun.l.google.com:19302"},mb={urls:"stun:stun.telnyx.com:3478"},vb={urls:"turn:turn.telnyx.com:3478?transport=udp",username:"testuser",credential:"testpassword"},_b={urls:"turn:turn.telnyx.com:3478?transport=tcp",username:"testuser",credential:"testpassword"},yb={urls:"turns:turn.telnyx.com:443",username:"testuser",credential:"testpassword"},bb={urls:"turns:turn2.telnyx.com:443",username:"testuser",credential:"testpassword"},wb=[mb,Ah,vb,_b,yb,bb],Sb=[{urls:"stun:stundev.telnyx.com:3478"},Ah,{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 F;(function(t){t.SocketOpen="telnyx.socket.open",t.SocketClose="telnyx.socket.close",t.SocketError="telnyx.socket.error",t.SocketMessage="telnyx.socket.message",t.SpeedTest="telnyx.internal.speedtest",t.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"})(F||(F={}));const Cb={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}},Tb={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 with host (local network) candidates only. This is diagnostic evidence that no server-reflexive (srflx), peer-reflexive (prflx), or relay (TURN) candidates were found; connectivity may still succeed, but network traversal options can be limited.",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 je(t,e){const i=Tb[t];return{code:t,name:i.name,message:i.message,description:i.description,causes:[...i.causes],solutions:[...i.solutions]}}class Jt 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,Jt.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 Vi(t){if(t instanceof DOMException){if(t.name==="NotAllowedError")return yh;if(t.name==="NotFoundError"||t.name==="OverconstrainedError")return bh}return Vr}function ae(t,e,i,n){const s=Cb[t],o=e instanceof Error?e:e!==void 0?new Error(String(e)):void 0;return new Jt({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 kb 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 Wr 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 Eb=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Rh(t,e){return t(e={exports:{}},e.exports),e.exports}var Ib=Rh(function(t){var e,i;e=Eb,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,y){var C=b[y];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,y){for(var C=0;C<r.length;C++){var T=r[C];this[T]=C<b?n:this.methodFactory(T,b,y)}this.log=this.debug}function u(b,y,C){return function(){typeof console!==s&&(c.call(this,y,C),this[b].apply(this,arguments))}}function d(b,y,C){return function(T){return T==="debug"&&(T="log"),typeof console!==s&&(T==="trace"&&o?l:console[T]!==void 0?a(console,T):console.log!==void 0?a(console,"log"):n)}(b)||u.apply(this,arguments)}function h(b,y,C){var T,A=this;y=y??"WARN";var x="loglevel";function N(){var k;if(typeof window!==s&&x){try{k=window.localStorage[x]}catch{}if(typeof k===s)try{var f=window.document.cookie,_=f.indexOf(encodeURIComponent(x)+"=");_!==-1&&(k=/^([^;]+)/.exec(f.slice(_))[1])}catch{}return A.levels[k]===void 0&&(k=void 0),k}}typeof b=="string"?x+=":"+b:typeof b=="symbol"&&(x=void 0),A.name=b,A.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},A.methodFactory=C||d,A.getLevel=function(){return T},A.setLevel=function(k,f){if(typeof k=="string"&&A.levels[k.toUpperCase()]!==void 0&&(k=A.levels[k.toUpperCase()]),!(typeof k=="number"&&k>=0&&k<=A.levels.SILENT))throw"log.setLevel() called with invalid level: "+k;if(T=k,f!==!1&&function(_){var g=(r[_]||"silent").toUpperCase();if(typeof window!==s&&x){try{return void(window.localStorage[x]=g)}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+g+";"}catch{}}}(k),c.call(A,k,b),typeof console===s&&k<A.levels.SILENT)return"No console available for logging"},A.setDefaultLevel=function(k){y=k,N()||A.setLevel(k,!1)},A.resetLevel=function(){A.setLevel(y,!1),function(){if(typeof window!==s&&x){try{return void window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}()},A.enableAll=function(k){A.setLevel(A.levels.TRACE,k)},A.disableAll=function(k){A.setLevel(A.levels.SILENT,k)};var E=N();E==null&&(E=y),A.setLevel(E,!1)}var p=new h,m={};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 y=m[b];return y||(y=m[b]=new h(b,p.getLevel(),p.methodFactory)),y};var v=typeof window!==s?window.log:void 0;return p.noConflict=function(){return typeof window!==s&&window.log===p&&(window.log=v),p},p.getLoggers=function(){return m},p.default=p,p},t.exports?t.exports=i():e.log=i()});const xh={debug:0,info:1,warn:2,error:3};class Ab{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||xh[e]<xh[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 Dh=null;const w=Ib.getLogger("telnyx"),Es={trace:0,debug:1,info:2,warn:3,error:4};let Lh=Es.info;function Mh(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 Rb=w.methodFactory;w.methodFactory=(t,e,i)=>{const n=Rb(t,e,i);return function(...s){if(Es[t]>=Lh){const r=[new Date().toISOString().replace("T"," ").replace("Z",""),"-"];for(const a of s)r.push(a);n(...r)}const o=Dh;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?Mh(a[0]):{args:a.map(Mh)}),o.addEntry(t,l,c)}}},w.setLevel("debug",!1);const Is=t=>{const[e,i,n,s,o,r]=t;let a={};try{a=JSON.parse(o.replace(/ID"/g,'Id"'))}catch{w.warn("Verto LA invalid media JSON string:",o)}return{participantId:Number(e),participantNumber:i,participantName:n,codec:s,media:a,participantData:r}},Oh=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}},As=t=>t instanceof Function||typeof t=="function",An=t=>typeof document=="object"&&"getElementById"in document?typeof t=="string"?document.getElementById(t)||null:typeof t=="function"?t():t instanceof HTMLMediaElement?t:null:null,xb=/^(ws|wss):\/\//,Ph=(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?Ph(a,r):{result:s}},Rs=({login:t,passwd:e,password:i,login_token:n})=>!!(t&&(e||i)||n),Rn=({anonymous_login:t})=>!!t&&!!t.target_id&&!!t.target_type,Gr=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 Nh({debounceTime:t}){let e,i;return{promise:new Promise((n,s)=>{e=t?Db(n,t):n,i=s}),resolve:e,reject:i}}const Db=(t,e)=>{let i;return(...n)=>{clearTimeout(i),i=window.setTimeout(()=>{t(...n)},e)}},qr="telnyx-voice-sdk-id",xs="telnyx-voice-sdk-session-id",Ds="telnyx-voice-sdk-session-id-stored-at",zr="telnyx-voice-sdk-active-calls",Lb=9e4;function Fh(t=Date.now()){const e=function(){const i=Number(sessionStorage.getItem(Ds));return Number.isFinite(i)?i:null}();return e!==null&&t-e<=Lb}function xn(){return sessionStorage.getItem(qr)}function Kr(t,e=Date.now()){sessionStorage.setItem(xs,t),sessionStorage.setItem(Ds,String(e))}function Uh(){sessionStorage.removeItem(qr),sessionStorage.removeItem(xs),sessionStorage.removeItem(Ds)}function hi(){(function(t){try{sessionStorage.removeItem(t)}catch(e){w.debug(`safeRemoveItem('${t}') failed: ${e instanceof Error?e.message:String(e)}`)}})(zr)}function Bh(t=Date.now()){const e=function(i){try{return sessionStorage.getItem(i)}catch(n){return w.debug(`safeGetItem('${i}') failed: ${n instanceof Error?n.message:String(n)}`),null}}(zr);if(!e)return null;try{const i=JSON.parse(e);if(!i||typeof i!="object"||!Array.isArray(i.calls))return w.debug("Active-calls recovery marker payload was malformed — discarded."),hi(),null;const n=Number(i.storedAt);return!Number.isFinite(n)||t-n>9e5?(w.debug("Active-calls recovery marker was stale or had an invalid timestamp — discarded."),hi(),null):i.calls.length===0?(w.debug("Active-calls recovery marker had no call records — discarded."),hi(),null):i}catch(i){return w.debug(`Active-calls recovery marker JSON parse failed — discarded: ${i instanceof Error?i.message:String(i)}`),hi(),null}}function Vh(t,e,i=Date.now()){if(!Array.isArray(t)||t.length===0)return void hi();(function(n,s){try{sessionStorage.setItem(n,s)}catch(o){w.info(`safeSetItem('${n}') failed: ${o instanceof Error?o.message:String(o)}`)}})(zr,JSON.stringify({sessionId:e,calls:t,storedAt:i}))}var He,Dt,ie;(function(t){t.Offer="offer",t.Answer="answer"})(He||(He={})),function(t){t.Inbound="inbound",t.Outbound="outbound"}(Dt||(Dt={})),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"}(ie||(ie={}));const gt={generic:"event",[ie.Display]:"participantData",[ie.Attach]:"participantData",conferenceUpdate:"conferenceUpdate",callUpdate:"callUpdate",vertoClientReady:"vertoClientReady",userMediaError:"userMediaError",peerConnectionFailureError:"peerConnectionFailureError",signalingStateClosed:"signalingStateClosed"},Mb={invalidCredentialsOptions:"InvalidCredentialsOptions"},$h=8e6,jh={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:!1};var z,Yr,ot,Lt,Ue,$i;(function(t){t[t.New=0]="New",t[t.Requesting=1]="Requesting",t[t.Trying=2]="Trying",t[t.Recovering=3]="Recovering",t[t.Ringing=4]="Ringing",t[t.Answering=5]="Answering",t[t.Early=6]="Early",t[t.Active=7]="Active",t[t.Held=8]="Held",t[t.Hangup=9]="Hangup",t[t.Destroy=10]="Destroy",t[t.Purge=11]="Purge"})(z||(z={})),function(t){t.Participant="participant",t.Moderator="moderator"}(Yr||(Yr={})),function(t){t.Join="join",t.Leave="leave",t.Bootstrap="bootstrap",t.Add="add",t.Modify="modify",t.Delete="delete",t.Clear="clear",t.ChatMessage="chatMessage",t.LayerInfo="layerInfo",t.LogoInfo="logoInfo",t.LayoutInfo="layoutInfo",t.LayoutList="layoutList",t.ModCmdResponse="modCommandResponse"}(ot||(ot={})),function(t){t.Video="videoinput",t.AudioIn="audioinput",t.AudioOut="audiooutput"}(Lt||(Lt={})),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"}(Ue||(Ue={})),function(t){t.Hold="hold",t.Unhold="unhold",t.ToggleHold="toggleHold",t.UpdateMedia="updateMedia"}($i||($i={}));const ji="GLOBAL",it={},Dn=(t,e)=>`${t}|${e}`,Hh=(t,e=ji)=>Dn(t,e)in it,Qt=(t,e,i=ji)=>{const n=Dn(t,i);n in it||(it[n]=[]),it[n].push(e)},Wh=(t,e,i=ji)=>{const n=function(s){Mt(t,n,i),e(s)};return n.prototype.targetRef=e,Qt(t,n,i)},Mt=(t,e,i=ji)=>{if(!Hh(t,i))return!1;const n=Dn(t,i);if(As(e))for(let s=it[n].length-1;s>=0;s--){const o=it[n][s];(e===o||o.prototype&&e===o.prototype.targetRef)&&it[n].splice(s,1)}else it[n]=[];return it[n].length===0&&delete it[n],!0},j=(t,e,i=ji,n=!0)=>{const s=n&&i!==ji;if(!Hh(t,i))return s&&j(t,e),!1;const o=Dn(t,i),r=it[o].length;if(!r)return s&&j(t,e),!1;for(let a=r-1;a>=0;a--)it[o][a](e);return s&&j(t,e),!0},Xr=t=>{const e=Dn(t,"");Object.keys(it).filter(i=>i.indexOf(e)===0).forEach(i=>delete it[i])};let Ob=typeof WebSocket<"u"?WebSocket:null;const Pb=0,Nb=1,Fb=2,Gh=3;class Ls{constructor(e){this.session=e,this.previousGatewayState="",this.lastInboundAt=0,this.socketGeneration=0,this._wsClient=null,this._host=Eh,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;w.debug("Creating new Connection",{host:this._host,env:n,region:s,useCanaryRtcServer:o}),n&&(this._host=n==="development"?"wss://rtcdev.telnyx.com":Eh),i&&(this._host=(r=>`${xb.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===Nb}get connecting(){return!!this._wsClient&&this._wsClient.readyState===Pb}get closing(){return!!this._wsClient&&this._wsClient.readyState===Fb}get closed(){return!!this._wsClient&&this._wsClient.readyState===Gh}get isAlive(){return this.connecting||this.connected}get isDead(){return this.closing||this.closed}get host(){return this._host}connect(){w.debug("Connection.connect() called",{host:this._host,socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const e=new URL(this._host);let i=xn();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"),w.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 Ob(e.toString()),this.socketGeneration+=1,w.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){w.error("WebSocket connection failed:",n);const s=ae(j0,n);j(F.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),this.session.onOutboundConfirmed(),u)return;const{result:m,error:v}=Ph(p);return v?c(v):l(m)};Wh(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),Mt(s.id,h),this._pendingRequestIds.delete(s.id),this.socketGeneration!==o)return w.debug(`Stale request timeout for ${s.id} (gen ${o}, current ${this.socketGeneration}) — settling with StaleRequestError`),void c(new Wr(s.id,o,this.socketGeneration));c(new kb(s.id,i,r))},i),this._pendingRequestTimers.set(s.id,d))});return w.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(w.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;
|
|
113
|
+
`),(n=this._wsClient)===null||n===void 0||n.send(JSON.stringify(s)),a}close(){if(w.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;As(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=>(w.debug("WebSocket onopen",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid}),j(F.SocketOpen,n,this.session.uuid)),e.onclose=n=>(this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"close"),w.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}),j(F.SocketClose,{event:n,socketGeneration:i},this.session.uuid)),e.onerror=n=>{this._clearSafetyTimeout(),this._safetyCleanupSocket(e,"error"),w.debug("WebSocket onerror",{socketGeneration:this.socketGeneration,sessionId:this.session.sessionid});const s=ae(H0);return j(F.Error,{error:s,sessionId:this.session.sessionid},this.session.uuid),j(F.SocketError,{error:n,sessionId:this.session.sessionid,socketGeneration:i},this.session.uuid)},e.onmessage=n=>{var s,o;this.lastInboundAt=Date.now(),j(F.SocketActivity,{timestamp:this.lastInboundAt},this.session.uuid);const r=Oh(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(qr,a)),this._unsetTimer(r.id),w.debug(`RECV:
|
|
114
114
|
`,JSON.stringify(r,null,2),`
|
|
115
|
-
`),Le[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!U(r.id,r)){const l=Fr(r);U(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!==Fh?(w.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?w.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(w.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),U(P.SocketClose,{code:yh.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))):w.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(w.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(w.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):w.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{Tt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Nr(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)),U(P.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",e)}}Cs.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Pi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Di()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const Bh={id:"callID",destinationNumber:"destination_number",remoteCallerName:"remote_caller_id_name",remoteCallerNumber:"remote_caller_id_number",callerName:"caller_id_name",callerNumber:"caller_id_number",customHeaders:"custom_headers"};class Ve extends Pi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=rh(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in Bh)n&&i.hasOwnProperty(n)&&(i[Bh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class Uh extends Ve{constructor(e){super(),this.method=ee.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Db{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>B(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Fr(i))}),this.getIsRegistered=()=>B(this,void 0,void 0,function*(){const i=new Uh(Sn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Rh({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Le.REGISTER,Le.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Rh({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Hr extends Ve{constructor(e){super(),this.method=ee.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ni{constructor(e){this._session=e,this._lastInboundAt=0,this._lastOutboundConfirmedAt=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 Ni.CRITICAL_METHODS.has(e)}start(){this._intervalId||(w.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=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(),w.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}onOutboundConfirmed(){this._lastOutboundConfirmedAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),w.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void w.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(w.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?w.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(w.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&&(Ni.isCriticalMethod(n)?(w.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")):w.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){w.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){w.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&&(w.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,w.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ae($0);U(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){w.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,s=i-this._lastOutboundConfirmedAt,o=n>=2e4;if(!o&&!(s>=45e3))return;if(!this._probeInFlight)return w.info(o?`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`:`Signaling health: inbound WS activity is flowing but no outbound request has been answered for ${Math.round(s/1e3)}s, sending health probe`),void this._sendProbe();const r=i-this._lastProbeSentAt;r>=5e3&&(w.warn(`Signaling health: probe timed out after ${r}ms (inbound silent for ${Math.round(n/1e3)}s, no outbound request answered for ${Math.round(s/1e3)}s) — declaring signaling unhealthy`),this._triggerSignalingRecovery(o?"Signaling health probe timed out: no inbound WS activity after probe":"Signaling health probe timed out: inbound WS activity is flowing but no outbound request is being answered","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Hr(Sn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{w.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void w.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(w.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(w.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`)):(w.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,w.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=Pe(rb);U(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?(w.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):w.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){w.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void w.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=Pe(ab);U(P.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Ni.CRITICAL_METHODS=new Set([ee.Modify,ee.Bye,ee.Ping]);var Vh="2.27.10",Wr=Vh;class Lb extends Ve{constructor(e,i,n,s,o={},r,a=!1){super(),this.method="login";const l={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{early_sdp_answer:a},"User-Agent":{sdkVersion:Wr,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Mb extends Ve{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class $h extends Ve{toString(){return ee.Invite}}class jh extends Ve{toString(){return ee.Answer}}class Hh extends Ve{toString(){return ee.Attach}}class Ob extends Ve{toString(){return ee.Bye}}class Pb extends Ve{toString(){return ee.Candidate}}class Nb extends Ve{toString(){return ee.EndOfCandidates}}class Ts extends Ve{toString(){return ee.Modify}}class Wh extends Ve{toString(){return ee.Info}}class Fb extends Ve{toString(){return ee.Broadcast}}class Bb extends Ve{toString(){return ee.Subscribe}}class Ub extends Ve{toString(){return ee.Unsubscribe}}class Vb extends Ve{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:Wr,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 oi{constructor(e){if(this.options=e,this.uuid=Di(),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 Ni(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Th=(n=vs[i])!==null&&n!==void 0?n:vs.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 Cs(this),this.registerAgent=new Db(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return B(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 w.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}),w.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Ni.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?Cs.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>B(this,void 0,void 0,function*(){if(s instanceof Nr)throw w.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=ae(U0,s,void 0,!0);U(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 B(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()},oi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&w.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return bs(this.options)||wn(this.options)}broadcast(e){}disconnect(){return B(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(),w.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Wt(e,i,this.uuid),this}off(e,i){return Tt(e,i,this.uuid),this}connect(){return B(this,void 0,void 0,function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new Cs(this)),this._attachListeners(),this._autoReconnect||(w.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(w.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),w.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ae(fh,e);U(P.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){xh()}_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<=oi.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-oi.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{w.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=Pe(sb);U(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 B(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),bs(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(wn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";w.error(s);const o=ae(B0,void 0,s);return void U(P.Error,{error:o,type:Eb.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r,a;return B(this,void 0,void 0,function*(){let l;const c=!!Sn(),u=c&&(this.sessionid&&Ah()?this.sessionid:function(h=Date.now()){const g=sessionStorage.getItem(ws);return g?Ah(h)?g:(sessionStorage.removeItem(ws),sessionStorage.removeItem(Ss),null):null}())||"";if(e==="login"){const h=(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,g=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:h,pn_late_fanout:h}),m=(a=this.options.earlySdpAnswer)!==null&&a!==void 0&&a;l=new Lb(this.options.login,this.options.password||this.options.passwd,this.options.login_token,u,g,c,m)}else l=new Vb({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:u,userVariables:this.options.userVariables,reconnection:c});const d=yield this.execute(l).catch(h=>{this._handleLoginError(h),n&&n(h)});d&&(this.sessionid=d.sessid,this.sessionid&&Vr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return B(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){w.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(yh).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)w.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),w.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&&jr(this.relayProtocol);for(const l in this.subscriptions)jr(l);if(this.subscriptions={},this.contexts=[],clearTimeout(this._keepAliveTimeout),clearTimeout(this._reconnectTimeout),this.stopSignalingHealthMonitor(),this.sessionid&&this._autoReconnect&&Vr(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){w.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ae(Or);return void U(P.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;w.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{w.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(w.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=Pe(lb);U(P.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else w.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],Tt(e,null,i)):(delete this.subscriptions[e],jr(e)))}_addSubscription(e,i=null,n){this._existsSubscription(e,n)||(this._existsSubscription(e)||(this.subscriptions[e]={}),this.subscriptions[e][n]={},ys(i)&&Wt(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),w.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(){w.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(),w.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&&(w.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Hr(Sn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){w.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}onOutboundConfirmed(){this._signalingHealthMonitor.onOutboundConfirmed()}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){w.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 w.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 w.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||w.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){Wt(e,i)}static off(e){Tt(e)}static uuid(){return Di()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}oi.TOKEN_EXPIRY_WARNING_SECONDS=120,oi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const ks=t=>navigator.mediaDevices.getUserMedia(t),Tn=t=>t&&t instanceof MediaStream,Es=(t,e,i)=>{const n=bn(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(w.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=Pe(nb);U(P.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},Gh=(t,e)=>{const i=bn(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},qh=(t,e)=>B(void 0,void 0,void 0,function*(){const i=bn(t);if(i===null)return w.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return w.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),$b=t=>{t&&t.readyState==="live"&&t.stop()},kn=t=>{Tn(t)&&t.getTracks().forEach($b),t=null},Is=t=>B(void 0,void 0,void 0,function*(){w.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield ks(t)}catch(n){if(w.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){w.warn("Device not found or not readable, falling back to default device");try{return yield ks(s)}catch(o){throw w.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),En=(t=null,e=!1)=>B(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Ct.AudioIn||s===Ct.AudioOut,video:!s||s===Ct.Video}))(t)).catch(s=>(w.error(s),null));if(n){if(kn(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}),zh=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Rs=(t,e,i)=>B(void 0,void 0,void 0,function*(){const n=yield En(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}),jb=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Gr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,Kh=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=>Gr(a)):[]},qr=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=zr(t);return i.includes(e)||n.includes(e)},zr=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Fi=(t,e=null,i=null)=>{if(!Tn(t))return null;let n=[];switch(e){case"audio":n=t.getAudioTracks();break;case"video":n=t.getVideoTracks();break;default:n=t.getTracks()}n.forEach(s=>{switch(i){case"on":case!0:s.enabled=!0;break;case"off":case!1:s.enabled=!1;break;default:s.enabled=!s.enabled}})},Kr=t=>{Fi(t,"audio",!0)},As=t=>{Fi(t,"audio",!1)};function Hb(){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:!!Is}}catch(t){return t.message}}var Te;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 Xh(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{w.error("playAudio",e),t._playFulfilled=!0}))}function Jh(t){t&&(t._playFulfilled?(t.pause(),t.currentTime=0):t._promise&&t._promise.then?t._promise.then(()=>{t.pause(),t.currentTime=0}):setTimeout(()=>{t.pause(),t.currentTime=0},1e3))}(function(t){t.not_supported="not supported",t.full="full",t.partial="partial"})(Te||(Te={}));const Zh=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 Wb extends Pi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Di(),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 Gb extends Pi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ce{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 wb(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Ch=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,w.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ce.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 B(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(),w.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 w.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 g=(r=(o=this.logCollector)===null||o===void 0?void 0:o.drain())!==null&&r!==void 0?r:[],m=new Date;this._lastIntermediateFlushTime=m;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(m.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:m.toISOString()}),stats:h},g.length>0?{logs:g}:{}),{segment:d}),i?{flushReason:i}:{});return w.info("CallReportCollector: Flushed intermediate segment",{segment:d,intervals:h.length,logEntries:g.length,callId:e.callId,flushReason:i}),v}finally{this._flushing=!1}}postReport(e,i,n,s){var o,r;return B(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void w.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void w.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 B(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 B(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}`;w.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 g=JSON.stringify(e),m=(o||r)&&g.length<=ce.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=ce.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:g},m?{keepalive:!0}:{}));if(C.ok)return void w.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}`),w.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:k})}}catch(C){v=C,w.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const y=ce.RETRY_DELAYS_MS[b];if(y===void 0)break;w.info(`CallReportCollector: Retrying ${d} in ${y}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,y))}throw w.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,g,m,v,b;if(this.statsBuffer.length<2)return!1;const y=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],k=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((k==null?void 0:k.networkType)==="vpn"&&(k==null?void 0:k.candidateType)!=="relay"))return!1;const A=((i=y.ice)===null||i===void 0?void 0:i.writable)===!1,R=((n=y.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",D=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),T=this._positiveDelta((a=y.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),E=D>0&&T===0,p=this._positiveDelta((u=(c=y.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),_=this._positiveDelta((m=(g=y.audio)===null||g===void 0?void 0:g.inbound)===null||m===void 0?void 0:m.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return A||R||E||p>0&&_===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(ms,!1),this._trackBreach(Pr,!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(ce.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 B(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 g=null;s.forEach(p=>{switch(p.type){case"outbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(r=p);break;case"inbound-rtp":p.kind==="audio"&&p.mediaType==="audio"&&(a=p);break;case"media-playout":p.kind==="audio"&&(l=p);break;case"remote-inbound-rtp":p.kind==="audio"&&(c=p);break;case"remote-outbound-rtp":p.kind==="audio"&&(u=p);break;case"candidate-pair":(p.nominated||p.state==="succeeded")&&h.push(p);break;case"transport":g=p}});const m=g==null?void 0:g.selectedCandidatePairId,v=m?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,m):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),y=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:m?h.find(p=>p.id===m)||h[h.length-1]||null:h[h.length-1]||null,r){const p=this._getOutboundAudioLevel(s,r);if(p!==null&&this.intervalAudioLevels.outbound.push(p),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(r.bytesSent||0)-this.previousStats.outboundBytes,f=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*_*1e3/f;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const p=this._getInboundAudioLevel(s,a);if(p!==null&&this.intervalAudioLevels.inbound.push(p),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(a.bytesReceived||0)-this.previousStats.inboundBytes,f=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(f>0){const S=8*_*1e3/f;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,k,A,R,D;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),k=this._resolveCandidate(s,d.remoteCandidateId)),d&&(A=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),k?{remote:k}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(Q0)),this.previousCandidatePairSnapshot=A),r&&(R=this._getLocalAudioTrackSnapshot(),D=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(R,D),this.previousStats.timestamp=o.getTime();const T=o.getTime()-this.intervalStartTime.getTime(),E=this._collectionIntervalFor();if(e||T>=E){const p=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,k,g,R,D,l,c,u,b,y);this.statsBuffer.push(p),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(p,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){w.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ce.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 w.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>=ce.STATS_FLUSH_THRESHOLD||o>=ce.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){w.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){w.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,g,m,v,b,y;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,k=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(i){const R=(r=i.packetsReceived)!==null&&r!==void 0?r:0,D=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const T=R-this._prevPacketsReceived,E=D-this._prevPacketsLost,p=T+E;p>0&&(A=E/p*100)}this._prevPacketsReceived=R,this._prevPacketsLost=D}if(this._trackBreach(j0,C!==void 0&&C>ce.THRESHOLD_RTT_MS),this._trackBreach(H0,k!==void 0&&k>ce.THRESHOLD_JITTER_MS),this._trackBreach(W0,A!==void 0&&A>ce.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(ms,!1):this._trackLowInboundAudio(e),C!==void 0&&k!==void 0&&A!==void 0){const R=93.2-.11*k-2.5*A-.01*(1e3*C),D=Math.max(1,Math.min(4.5,1+.035*R+R*(R-60)*(100-R)*7e-6));this._trackBreach(mh,D<ce.THRESHOLD_MOS)}else this._trackBreach(mh,!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,D=e.audio.inbound.bytesReceived;this._trackBreach(Pr,!this._isHeld&&R!==void 0&&D-R==0)}if(((m=(g=e.audio)===null||g===void 0?void 0:g.outbound)===null||m===void 0?void 0:m.bytesSent)!==void 0){const R=(y=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||y===void 0?void 0:y.bytesSent,D=e.audio.outbound.bytesSent;this._trackBreach(vh,R!==void 0&&D-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<=ce.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(gs,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ce.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(gs)):this._trackBreach(gs,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(gs,!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(ms,!1);const o=s<=ce.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(ms,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]>=ce.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ce.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=Pe(e);w.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,g,m,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}:{}),m?{codec:this._buildCodecSnapshot(m,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({synthesizedSamplesEvents:d.synthesizedSamplesEvents,synthesizedSamplesDuration:d.synthesizedSamplesDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSamplesCount:d.totalSamplesCount,totalSamplesDuration:d.totalSamplesDuration})),h||g){const y={};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),y.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:k,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}g&&(y.outbound=this._withoutUndefined({packetsSent:g.packetsSent,bytesSent:g.bytesSent,reportsCount:g.reportsCount,roundTripTime:g.roundTripTime,totalPacketSendDelay:g.totalPacketSendDelay})),b.remoteRtcp=y}return b}_resolveCandidate(e,i){if(!i)return void w.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void w.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;w.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 w.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,w.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:[]}}}ce.INITIAL_COLLECTION_INTERVAL_MS=1e3,ce.STATS_FLUSH_THRESHOLD=300,ce.LOGS_FLUSH_THRESHOLD=800,ce.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ce.CONSECUTIVE_BREACHES_REQUIRED=3,ce.THRESHOLD_RTT_MS=.4,ce.THRESHOLD_JITTER_MS=30,ce.THRESHOLD_PACKET_LOSS_PCT=1,ce.THRESHOLD_MOS=3.5,ce.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ce.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ce.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,ce.WARNING_THROTTLE_MS=15e3,ce.RETRY_DELAYS_MS=[500,1e3,2e3],ce.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 w.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(G0),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 w.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(),w.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,w.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return B(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void w.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void w.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),B(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||w.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){w.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,w.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(q0))}}_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:Mh}_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=>{w.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 B(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void w.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=>{w.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 B(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 w.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}`),w.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,w.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;w.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw w.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=Pe(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.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 qb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return B(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,w.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){w.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return B(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){w.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 B(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)&&w.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){w.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var xs,Qh=wh(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(p){return p._maxListeners===void 0?s.defaultMaxListeners:p._maxListeners}function r(p,_,f,S){var I,M,x;if(typeof f!="function")throw new TypeError('"listener" argument must be a function');if((M=p._events)?(M.newListener&&(p.emit("newListener",_,f.listener?f.listener:f),M=p._events),x=M[_]):(M=p._events=new n,p._eventsCount=0),x){if(typeof x=="function"?x=M[_]=S?[f,x]:[x,f]:S?x.unshift(f):x.push(f),!x.warned&&(I=o(p))&&0<I&&x.length>I){x.warned=!0;var N=new Error("Possible EventEmitter memory leak detected. "+x.length+" "+_+" listeners added. Use emitter.setMaxListeners() to increase limit");N.name="MaxListenersExceededWarning",N.emitter=p,N.type=_,N.count=x.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(N)}}else x=M[_]=f,++p._eventsCount;return p}function a(p,_,f){function S(){p.removeListener(_,S),I||(I=!0,f.apply(p,arguments))}var I=!1;return S.listener=f,S}function l(p){var _=this._events;if(_){var f=_[p];if(typeof f=="function")return 1;if(f)return f.length}return 0}function c(p,_){for(var f=Array(_);_--;)f[_]=p[_];return f}Object.defineProperty(e,"__esModule",{value:!0}),n.prototype=Object.create(null),s.EventEmitter=s,s.usingDomains=!1,s.prototype.domain=void 0,s.prototype._events=void 0,s.prototype._maxListeners=void 0,s.defaultMaxListeners=10,s.init=function(){this.domain=null,s.usingDomains&&i.active&&!(this instanceof i.Domain)&&(this.domain=i.active),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new n,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(p){if(typeof p!="number"||0>p||isNaN(p))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=p,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(p){var _,f,S,I,M,x,N,O=p==="error";if(x=this._events)O=O&&x.error==null;else if(!O)return!1;if(N=this.domain,O){if(_=arguments[1],!N){if(_ instanceof Error)throw _;var F=new Error('Uncaught, unspecified "error" event. ('+_+")");throw F.context=_,F}return _||(_=new Error('Uncaught, unspecified "error" event')),_.domainEmitter=this,_.domain=N,_.domainThrown=!1,N.emit("error",_),!1}if(!(f=x[p]))return!1;var V=typeof f=="function";switch(S=arguments.length){case 1:(function($,Q,J){if(Q)$.call(J);else for(var G=$.length,de=c($,G),Z=0;Z<G;++Z)de[Z].call(J)})(f,V,this);break;case 2:(function($,Q,J,G){if(Q)$.call(J,G);else for(var de=$.length,Z=c($,de),Y=0;Y<de;++Y)Z[Y].call(J,G)})(f,V,this,arguments[1]);break;case 3:(function($,Q,J,G,de){if(Q)$.call(J,G,de);else for(var Z=$.length,Y=c($,Z),ie=0;ie<Z;++ie)Y[ie].call(J,G,de)})(f,V,this,arguments[1],arguments[2]);break;case 4:(function($,Q,J,G,de,Z){if(Q)$.call(J,G,de,Z);else for(var Y=$.length,ie=c($,Y),se=0;se<Y;++se)ie[se].call(J,G,de,Z)})(f,V,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),M=1;M<S;M++)I[M-1]=arguments[M];(function($,Q,J,G){if(Q)$.apply(J,G);else for(var de=$.length,Z=c($,de),Y=0;Y<de;++Y)Z[Y].apply(J,G)})(f,V,this,I)}return!0},s.prototype.addListener=function(p,_){return r(this,p,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(p,_){return r(this,p,_,!0)},s.prototype.once=function(p,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.on(p,a(this,p,_)),this},s.prototype.prependOnceListener=function(p,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(p,a(this,p,_)),this},s.prototype.removeListener=function(p,_){var f,S,I,M,x;if(typeof _!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(f=S[p]))return this;if(f===_||f.listener&&f.listener===_)--this._eventsCount==0?this._events=new n:(delete S[p],S.removeListener&&this.emit("removeListener",p,f.listener||_));else if(typeof f!="function"){for(I=-1,M=f.length;0<M--;)if(f[M]===_||f[M].listener&&f[M].listener===_){x=f[M].listener,I=M;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[p]}else(function(N,O){for(var F=O,V=F+1,$=N.length;V<$;F+=1,V+=1)N[F]=N[V];N.pop()})(f,I);S.removeListener&&this.emit("removeListener",p,x||_)}return this},s.prototype.removeAllListeners=function(p){var _,f;if(!(f=this._events))return this;if(!f.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):f[p]&&(--this._eventsCount==0?this._events=new n:delete f[p]),this;if(arguments.length===0){for(var S,I=Object.keys(f),M=0;M<I.length;++M)(S=I[M])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(_=f[p])=="function")this.removeListener(p,_);else if(_)do this.removeListener(p,_[_.length-1]);while(_[0]);return this},s.prototype.listeners=function(p){var _,f,S=this._events;return S?f=(_=S[p])?typeof _=="function"?[_.listener||_]:function(I){for(var M=Array(I.length),x=0;x<M.length;++x)M[x]=I[x].listener||I[x];return M}(_):[]:f=[],f},s.listenerCount=function(p,_){return typeof p.listenerCount=="function"?p.listenerCount(_):l.call(p,_)},s.prototype.listenerCount=l,s.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]};var u,d=new Uint8Array(16);function h(){if(!u&&!(u=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return u(d)}for(var g=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i,m=[],v=0;256>v;++v)m.push((v+256).toString(16).substr(1));function b(p){var _=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,f=(m[p[_+0]]+m[p[_+1]]+m[p[_+2]]+m[p[_+3]]+"-"+m[p[_+4]]+m[p[_+5]]+"-"+m[p[_+6]]+m[p[_+7]]+"-"+m[p[_+8]]+m[p[_+9]]+"-"+m[p[_+10]]+m[p[_+11]]+m[p[_+12]]+m[p[_+13]]+m[p[_+14]]+m[p[_+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&g.test(S)}(f))throw TypeError("Stringified UUID is invalid");return f}function y(p,_,f){var S=(p=p||{}).random||(p.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(p,_){if(!p||!_)return{};const f={...p};if(f.localCandidateId){const S=_.get(f.localCandidateId);f.local={...S}}if(f.remoteCandidateId){const S=_.get(f.remoteCandidateId);f.remote={...S}}return f}function k(p,_,f){return 8*function(S,I,M){const x=S[M],N=I?I[M]:null;return x===null||N===null?null:(x-N)/(S.timestamp-I.timestamp)*1e3}(p,_,f)}function A(p){if(!p.entries)return p;const _={};return p.forEach(function(f,S){_[S]=f}),_}function R(p,_,f={}){if(!p)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 p.values())switch(I.type){case"outbound-rtp":{const M=I.mediaType||I.kind,x={};let N={};if(!["audio","video"].includes(M))continue;if(I.codecId){const O=p.get(I.codecId);O&&(x.clockRate=O.clockRate,x.mimeType=O.mimeType,x.payloadType=O.payloadType)}N=p.get(I.mediaSourceId)||p.get(I.trackId)||{},S[M].outbound.push({...I,...x,track:{...N}});break}case"inbound-rtp":{let M=I.mediaType||I.kind,x={};const N={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const O=p.get(I.codecId);O&&(N.clockRate=O.clockRate,N.mimeType=O.mimeType,N.payloadType=O.payloadType)}if(!S.connection.id&&I.transportId){const O=p.get(I.transportId);if(O&&O.selectedCandidatePairId){const F=p.get(O.selectedCandidatePairId);S.connection=C(F,p)}}x=p.get(I.mediaSourceId)||p.get(I.trackId)||{},S[M].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 M=I.mediaType||I.kind;const x={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const N=p.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}if(!S.connection.id&&I.transportId){const N=p.get(I.transportId);if(N&&N.selectedCandidatePairId){const O=p.get(N.selectedCandidatePairId);S.connection=C(O,p)}}S.remote[M].inbound.push({...I,...x});break}case"remote-outbound-rtp":{if(!f.remote)break;const M=I.mediaType||I.kind,x={};if(!["audio","video"].includes(M))continue;if(I.codecId){const N=p.get(I.codecId);N&&(x.clockRate=N.clockRate,x.mimeType=N.mimeType,x.payloadType=N.payloadType)}S.remote[M].outbound.push({...I,...x});break}}if(!S.connection.id)for(const I of p.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,p));return S=function(I,M){return M&&(I.audio.inbound.map(x=>{let N=M.audio.inbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.audio.outbound.map(x=>{let N=M.audio.outbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")}),I.video.inbound.map(x=>{let N=M.video.inbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesReceived"),x.packetRate=k(x,N,"packetsReceived")}),I.video.outbound.map(x=>{let N=M.video.outbound.find(O=>O.id===x.id);x.bitrate=k(x,N,"bytesSent"),x.packetRate=k(x,N,"packetsSent")})),I}(S,_),S}let D,T={},E=[];e.WebRTCStats=class extends s{constructor(p){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const _={...p};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=_.getStatsInterval||1e3,this.rawStats=!!_.rawStats,this.statsObject=!!_.statsObject,this.filteredStats=!!_.filteredStats,this.shouldWrapGetUserMedia=!!_.wrapGetUserMedia,typeof _.remote=="boolean"&&(this.remote=_.remote),this.debug=!!_.debug,this.logLevel=_.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(p,_){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:p,pc:_})}async addConnection(p){const{pc:_,peerId:f}=p;let{connectionId:S,remote:I}=p;if(I=typeof I=="boolean"?I:this.remote,!(_&&_ 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===_)throw new Error(`We are already monitoring peer with id ${f}.`);N.pc.connectionState==="closed"&&this.removeConnection({pc:N.pc})}}const M=_.getConfiguration();return M.iceServers&&M.iceServers.forEach(function(x){delete x.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:f,connectionId:S,data:{options:p,peerConfiguration:M}}),this.monitorPeer({peerId:f,connectionId:S,pc:_,remote:I}),{connectionId:S}}getTimeline(p){return this.timeline=this.timeline.sort((_,f)=>_.timestamp.getTime()-f.timestamp.getTime()),p?this.timeline.filter(_=>_.tag===p):this.timeline}get logger(){const p=_=>{const f=["none","error","warn","info","debug"];return f.slice(0,f.indexOf(this.logLevel)+1).indexOf(_)>-1};return{error(..._){this.debug&&p("error")&&console.error("[webrtc-stats][error] ",..._)},warn(..._){this.debug&&p("warn")&&console.warn("[webrtc-stats][warn] ",..._)},info(..._){this.debug&&p("info")&&console.log("[webrtc-stats][info] ",..._)},debug(..._){this.debug&&p("debug")&&console.debug("[webrtc-stats][debug] ",..._)}}}removeConnection(p){let _,{connectionId:f,pc:S}=p;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,_=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 M in this.peersToMonitor[I])this.peersToMonitor[I][M].pc===S&&(f=M,_=I)}if(!S||!f)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(f,S),delete this.peersToMonitor[_][f],Object.values(this.peersToMonitor[_]).length===0&&delete this.peersToMonitor[_],{connectionId:f}}removeAllPeers(){for(let p in this.peersToMonitor)this.removePeer(p)}removePeer(p){if(this.logger.info(`Removing PeerConnection with id ${p}.`),this.peersToMonitor[p]){for(let _ in this.peersToMonitor[p]){let f=this.peersToMonitor[p][_].pc;this.removePeerConnectionEventListeners(_,f)}delete this.peersToMonitor[p]}}destroy(){this.removeAllPeers(),E.forEach(p=>{this.removeTrackEventListeners(p)}),E=[],this.shouldWrapGetUserMedia&&D&&(navigator.mediaDevices.getUserMedia=D)}monitorPeer(p){let{peerId:_,connectionId:f,pc:S,remote:I}=p;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const M={pc:S,connectionId:f,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[_]){if(f in this.peersToMonitor[_])return void this.logger.warn(`Already watching connection with ID ${f}`);this.peersToMonitor[_][f]=M}else this.peersToMonitor[_]={[f]:M};this.addPeerConnectionEventListeners(_,f,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(p=>{p.forEach(_=>{this.emitEvent(_)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(p=null){this.logger.info(p?`Getting stats from peer ${p}`:"Getting stats from all peers");let _={};if(p){if(!this.peersToMonitor[p])throw new Error(`Cannot get stats. Peer with id ${p} does not exist`);_[p]=this.peersToMonitor[p]}else _=this.peersToMonitor;let f=[];for(const S in _)for(const I in _[S]){const M=_[S][I],x=M.pc;if(x&&!this.checkIfConnectionIsClosed(S,I,x))try{const N=this.getTimestamp(),O=x.getStats(null);if(O){const F=await O,V=this.getTimestamp(),$=A(F),Q={remote:M.options.remote},J=R(F,M.stats.parsed,Q),G={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:V-N,data:J};this.rawStats===!0&&(G.rawStats=F),this.statsObject===!0&&(G.statsObject=$),this.filteredStats===!0&&(G.filteredStats=this.filteroutStats($)),f.push(G),M.stats.parsed=J}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(N){this.logger.error(N)}}return f}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const p in this.peersToMonitor)for(const _ in this.peersToMonitor[p]){const f=this.peersToMonitor[p][_].pc;this.checkIfConnectionIsClosed(p,_,f)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(p,_,f){const S=this.isConnectionClosed(f);if(S){this.removeConnection({pc:f});let I=f.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:p,connectionId:_,tag:"connection",data:"closed"})}return S}isConnectionClosed(p){return p.connectionState==="closed"||p.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),D=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const p=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return p({constraints:arguments[0]}),D.apply(navigator.mediaDevices,arguments).then(_=>(p({stream:_}),_),_=>(p({error:_}),Promise.reject(_)))}).bind(navigator.mediaDevices)}filteroutStats(p={}){const _={...p};for(const S in _){var f=_[S];this.statsToMonitor.includes(f.type)||delete _[S]}return _}get peerConnectionListeners(){return{icecandidate:(p,_,f,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:p,connectionId:_,data:S.candidate})},track:(p,_,f,S)=>{this.logger.debug(`[pc-event] track | peerId: ${p}`,S);const I=S.track,M=S.streams[0];p in this.peersToMonitor&&_ in this.peersToMonitor[p]&&(this.peersToMonitor[p][_].stream=M),this.addTrackEventListeners(I,_),this.emitEvent({event:"ontrack",tag:"track",peerId:p,connectionId:_,data:{stream:M?this.getStreamDetails(M):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(x){return"stream:"+x.id})}})},signalingstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${p}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:p,connectionId:_,data:{signalingState:f.signalingState,localDescription:f.localDescription,remoteDescription:f.remoteDescription}})},iceconnectionstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${p}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:p,connectionId:_,data:f.iceConnectionState})},icegatheringstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${p}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:p,connectionId:_,data:f.iceGatheringState})},icecandidateerror:(p,_,f,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${p}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:p,connectionId:_,error:{errorCode:S.errorCode}})},connectionstatechange:(p,_,f)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${p}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:p,connectionId:_,data:f.connectionState})},negotiationneeded:(p,_,f)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${p}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:p,connectionId:_})},datachannel:(p,_,f,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${p}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:p,connectionId:_,data:S.channel})}}}addPeerConnectionEventListeners(p,_,f){this.logger.debug(`Adding event listeners for peer ${p} and connection ${_}.`),T[_]={},Object.keys(this.peerConnectionListeners).forEach(S=>{T[_][S]=this.peerConnectionListeners[S].bind(this,p,_,f),f.addEventListener(S,T[_][S],!1)})}parseGetUserMedia(p){try{const _={event:"getUserMedia",tag:"getUserMedia",data:{...p}};p.stream&&(_.data.details=this.parseStream(p.stream),p.stream.getTracks().map(f=>{this.addTrackEventListeners(f),E.push(f)})),this.emitEvent(_)}catch{}}parseStream(p){const _={audio:[],video:[]};return p.getTracks().forEach(f=>{_[f.kind].push(this.getMediaTrackDetails(f))}),_}getMediaTrackDetails(p){return{enabled:p.enabled,id:p.id,contentHint:p.contentHint,kind:p.kind,label:p.label,muted:p.muted,readyState:p.readyState,constructorName:p.constructor.name,capabilities:p.getCapabilities?p.getCapabilities():{},constraints:p.getConstraints?p.getConstraints():{},settings:p.getSettings?p.getSettings():{},_track:p}}getStreamDetails(p){return{active:p.active,id:p.id,_stream:p}}getTrackEventObject(p){return{mute:_=>{this.emitEvent({event:"mute",tag:"track",connectionId:p,data:{event:_}})},unmute:_=>{this.emitEvent({event:"unmute",tag:"track",connectionId:p,data:{event:_}})},overconstrained:_=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:p,data:{event:_}})},ended:_=>{this.emitEvent({event:"ended",tag:"track",connectionId:p,data:{event:_}}),this.removeTrackEventListeners(_.target)}}}addTrackEventListeners(p,_){T[p.id]={};const f=this.getTrackEventObject(_);Object.keys(f).forEach(S=>{T[p.id][S]=f[S].bind(this),p.addEventListener(S,T[p.id][S])}),T[p.id].readyState=setInterval(()=>{if(p.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});p.dispatchEvent(S)}},1e3)}removeTrackEventListeners(p){if(p.id in T){const _=this.getTrackEventObject();Object.keys(_).forEach(f=>{p.removeEventListener(f,T[p.id][f])}),clearInterval(T[p.id].readyState),delete T[p.id]}}addToTimeline(p){this.timeline.push(p),this.emit("timeline",p)}emitEvent(p){const _={...p,timestamp:new Date};this.addToTimeline(_),_.tag&&this.emit(_.tag,_)}set getStatsInterval(p){if(!Number.isInteger(p))throw new Error(`getStatsInterval should be an integer, got: ${p}`);this._getStatsInterval=p,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(p,_){p in T&&(Object.keys(this.peerConnectionListeners).forEach(f=>{_.removeEventListener(f,T[p][f],!1)}),delete T[p]),_.getSenders().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)}),_.getReceivers().forEach(f=>{f.track&&this.removeTrackEventListeners(f.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const p=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const _=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),f=function(){return p.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),_.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return p.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=f.bind(navigator.mediaDevices)}}}});(xs=Qh)&&xs.__esModule&&Object.prototype.hasOwnProperty.call(xs,"default")&&xs.default;var zb=Qh.WebRTCStats;function Kb(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 Yb(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 Xb extends Pi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class Jb extends Pi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class Zb extends Pi{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 Qb(t,e){const i=Di();let n=!1;const s=new zb({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>B(this,void 0,void 0,function*(){r.event==="stats"&&U(P.StatsFrame,function({data:a}){var l,c,u,d,h,g,m,v;const{audio:b,remote:y}=a,{audio:C}=y,k=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,R=(g=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&g!==void 0?g:-1,D=(v=(m=b.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,T=Kb({jitter:1e3*k,rtt:1e3*A,packetsLost:D,packetsReceived:R});return{jitter:k,rtt:A,mos:T,quality:Yb(T),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new Zb(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>B(this,void 0,void 0,function*(){if(n)w.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new Xb(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){w.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>B(this,void 0,void 0,function*(){const a=s.getTimeline();U(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 Jb(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 ef=(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:at.conferenceUpdate,call:t.calls[s],canvasInfo:ew(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:Xe.LayerInfo},a);U(P.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:Xe.LayoutInfo},a);U(P.Notification,l,t.uuid);break}}},ew=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Eh(e)},tf=["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"],tw={"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 le(t,e){return`telnyx:call:${t}:${e}`}function nf(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function sf(t,e,i){const n=nf(le(t,"new-call-start"));if(n===void 0)return{mode:e,direction:i,steps:[]};const s=[];for(const a of tf){if(a==="new-call-start")continue;const l=nf(le(t,a));l!==void 0&&s.push({label:tw[a]||a,fromStart:l-n})}s.sort((a,l)=>a.fromStart-l.fromStart);const o=[];let r=0;for(const a of s)o.push({label:a.label,fromStart:a.fromStart,delta:a.fromStart-r}),r=a.fromStart;return{mode:e,direction:i,steps:o}}function Yr(t){for(const e of tf)try{performance.clearMarks(le(t,e))}catch{w.warn("Clearing performance marks is failed")}}class ri{constructor(e,i,n,s,o){this.type=e,this.options=i,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=()=>B(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void w.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(w.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return B(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const g=h[0].sender,m=g==null?void 0:g.transport;m&&(d.dtlsState=m.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const g=yield c.getStats();g.forEach(m=>{m.type==="candidate-pair"&&m.state==="succeeded"&&(d.candidatePairState=m.state,g.forEach(v=>{v.type==="local-candidate"&&v.id===m.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===m.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})})),m.type==="transport"&&(d.dtlsCipher=m.dtlsCipher,d.srtpCipher=m.srtpCipher,d.tlsVersion=m.tlsVersion,m.dtlsState&&(d.dtlsState=m.dtlsState))})}catch(g){w.error("Error gathering connection state details:",g)}return d})}(this.instance,this._prevConnectionState).then(c=>{this.statsReporter.reportConnectionStateChange(c)}),(a=(r=this._session).reportPeerFailure)===null||a===void 0||a.call(r,this.options.id,"connection_failed")),l==="disconnected"){const c=Pe(z0);U(P.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=Pe(X0);U(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(le(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(le(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(le(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void w.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;w.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(le(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;w.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)},w.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},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?(w.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&&(w.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},ri.ICE_RESTART_TIMEOUT_MS),w.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(w.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(w.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===Ne.Offer}get isAnswer(){return this.type===Ne.Answer}get isDebugEnabled(){return this.options.debug||this._session.options.debug}get debugOutput(){return this.options.debugOutput||this._session.options.debugOutput}get restartedIceOnConnectionStateFailed(){return this._restartedIceOnConnectionStateFailed}get callEstablishmentTimings(){return this._callEstablishmentTimings}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(le(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 B(this,void 0,void 0,function*(){performance.mark(le(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 Ht&&U(P.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(w.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{w.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),w.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):w.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(w.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":U(P.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(w.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){w.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?w.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(le(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&&Es(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(le(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=sf(this.options.id,e,i);this._callEstablishmentTimings=n,function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void w.info(`${l} No timing data collected`);const c=Math.max(...a.map(m=>m.label.length),4)+2,u=(m,v)=>{for(;m.length<v;)m+=" ";return m},d=(m,v)=>{for(;m.length<v;)m=" "+m;return m},h=u("Step",c)+d("Delta",14)+d("From Start",14);let g="";for(let m=0;m<h.length;m++)g+="-";w.info(`${l} Call establishment timing breakdown:`),w.info(`${l} ${h}`),w.info(`${l} ${g}`),w.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const m of a){const v=m.delta.toFixed(2)+"ms",b=m.fromStart.toFixed(2)+"ms";w.info(`${l} ${u(m.label,c)}${d(v,14)}${d(b,14)}`)}w.info(`${l} ${g}`)}(n),Yr(this.options.id)}createPeerConnection(){return B(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer}),performance.mark(le(this.options.id,"set-remote-description")),!this.instance))throw ae(Mr);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>B(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),U(P.Error,{error:ae(Li(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(()=>B(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 ae(Mr);if(!this.options.localStream&&!i)throw ae(n?Li(n):Lr,n??void 0);performance.mark(le(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Tn(this.options.localStream)&&(w.info("Muting local audio tracks on start"),As(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(le(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=Pe(Y0);U(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=Pe(K0);U(P.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},ri.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return B(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ae(Mr);this.isDebugEnabled&&(this.statsReporter=Qb(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(Tn(n)){const o=n.getAudioTracks();let r=[...o];if(w.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{w.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],w.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{w.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=Zh(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&&Es(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});w.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=Zh(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);w.info("Add transceiver",e,i)}}_createOffer(){return B(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,w.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(le(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createOffer error:",e),e instanceof Ht?e:ae(R0,e)}}})}_setRemoteDescription(e){return B(this,void 0,void 0,function*(){w.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw w.error("Peer _setRemoteDescription error:",i),ae(ch,i)}})}_createAnswer(){return B(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return w.debug("Skipping negotiation, state:",this.instance.signalingState),w.debug(" - But the signaling state isn't stable, so triggering rollback"),void(yield Promise.all([this.instance.setLocalDescription({type:"rollback"}),this.instance.setRemoteDescription({sdp:this.options.remoteSdp,type:Ne.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(le(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createAnswer error:",e),e instanceof Ht?e:ae(A0,e)}}})}_setLocalDescription(e){return B(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw w.error("Peer _setLocalDescription error:",i),ae(x0,i)}})}_retrieveLocalStream(){return B(this,void 0,void 0,function*(){if(Tn(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,B(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 Rs(s,a,Ct.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield Rs(r,l,Ct.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return Is(e)})}_isOffer(){return this.type===Ne.Offer}_isAnswer(){return this.type===Ne.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?1:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return w.info("RTC config",s),s}restartStatsReporter(){return B(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?w.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(w.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):w.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return B(this,void 0,void 0,function*(){Yr(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)})}}ri.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,ri.ICE_RESTART_TIMEOUT_MS=15e3;const Ds=Wr;class of{constructor(e,i){var n;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=$r.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=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(k=>{if(k.callback){if(k.constraints){for(const A in k.constraints)if(k.constraints.hasOwnProperty(A)&&k.constraints[A]!==C[A])return}k.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:u,remoteElement:d,options:h,mediaConstraints:{audio:g,video:m},ringtoneFile:v,ringbackFile:b}=e;this.options=Object.assign({},Oh,{audio:g,video:m,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:s,localElement:u,remoteElement:d,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:b,debug:h.debug,debugOutput:h.debugOutput,trickleIce:h.trickleIce,prefetchIceCandidates:(n=h.prefetchIceCandidates)!==null&&n!==void 0?n:Oh.prefetchIceCandidates,forceRelayCandidate:h.forceRelayCandidate,keepConnectionAliveOnSocketClose:h.keepConnectionAliveOnSocketClose,mutedMicOnStart:h.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 B(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=St.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(le(this.id,"new-peer")),this.peer=new ri(Ne.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){w.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Ht?e:ae(gh,e instanceof Error?e:void 0);return U(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 B(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&&w.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=Pe(Z0);return U(P.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void w.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(le(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=St.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(le(this.id,"new-peer")),this.peer=new ri(Ne.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){w.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Ht?d:ae(gh,d instanceof Error?d:void 0);return U(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(){Xh(this._ringtone)}stopRingtone(){Jh(this._ringtone)}playRingback(){Xh(this._ringback)}stopRingback(){Jh(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return B(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,g=this._captureHangupCallerStack(),m=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:[]],w.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:m,sipCode:this.sipCode,sipReason:this.sipReason,sipCallId:this.sipCallId,isRecovering:!!c.isRecovering,hasDialogCustomHeaders:!!(!((a=(r=c.dialogParams)===null||r===void 0?void 0:r.customHeaders)===null||a===void 0)&&a.length),callerStack:g}),c.isRecovering)return this._isRecovering=!0,this.setState(W.Recovering),void this._finalize();if(this.setState(W.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new Ob({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let y;try{yield Promise.race([this._execute(b),new Promise(C=>{y=setTimeout(()=>{w.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){w.error("telnyx_rtc.bye failed!",C);const k=ae(M0,C);U(P.Error,{error:k,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{y&&clearTimeout(y)}}w.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(W.Destroy)})}hold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Ts({sessid:this.session.sessionid,action:Mi.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new Wh({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 Wh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){w.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,As(this.options.localStream)}unmuteAudio(){w.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,Kr(this.options.localStream)}_applyDesiredAudioMuteState(){w.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?As(this.options.localStream):Kr(this.options.localStream)}toggleAudioMute(){w.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 B(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 w.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void U(P.Warning,{warning:Pe(eb),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;w.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Gr(l.track),localTracks:Kh(this.options.localStream)});try{c=yield ks({audio:{deviceId:{exact:e}}})}catch(h){const g=ae(Li(h),h);return void U(P.MediaError,g,((s=this.options)===null||s===void 0?void 0:s.id)||this.id)}const u=c.getAudioTracks()[0];u.enabled=!r;try{yield l.replaceTrack(u)}catch(h){const g=ae(Li(h),h);return U(P.MediaError,g,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(m=>m.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,w.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Gr(l.track),localTracks:Kh(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Fi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Fi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Fi(e,"video",null)}setVideoDevice(e){return B(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 ks({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Es(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(){As(this.options.remoteStream)}undeaf(){Kr(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Fi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return B(this,void 0,void 0,function*(){if(!this||!this.peer)return void w.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 w.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"}]),w.info("Parameters: ",r),w.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{w.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>w.error(a))}else w.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(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:at.callUpdate,call:this}),e){case W.Purge:w.info(`[${this.id}] Entering Purge state.`);break;case W.Active:if(performance.mark(le(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,w.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(w.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&&qh(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 qb,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 ee.Answer:if(performance.mark(le(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 ee.Media:if(performance.mark(le(this.id,"telnyx-rtc-media")),this._state>=W.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case ee.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===St.Inbound?St.Outbound:St.Inbound,c={type:at[i],call:this,displayName:o,displayNumber:r,displayDirection:l};U(P.Notification,c,this.id)||U(P.Notification,c,this.session.uuid);break}case ee.Candidate:this._addIceCandidate(n);break;case ee.Info:case ee.Event:{const o=Object.assign(Object.assign({},n),{type:at.generic,call:this});U(P.Notification,o,this.id)||U(P.Notification,o,this.session.uuid);break}case ee.Ringing:performance.mark(le(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 ee.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 B(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return w.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:Xe.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const g=[];for(const m in s)g.push(Object.assign({callId:s[m][0],index:Number(m)},_s(s[m][1])));this._dispatchConferenceUpdate({action:Xe.Bootstrap,participants:g});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:Xe.Add,callId:o,index:r},_s(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:Xe.Modify,callId:o,index:r},_s(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:Xe.Delete,callId:o,index:r},_s(s)));break;case"clear":this._dispatchConferenceUpdate({action:Xe.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 B(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:Xe.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfChat subscription error:",s)});qr(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 B(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,ef(this.session,o)):w.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfInfo subscription error:",s)});qr(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){w.error(`Failed to ${e.action} on call ${this.id}`);const i=ae(D0,e);return U(P.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Ts(Object.assign(Object.assign({sessid:this.session.sessionid,action:Mi.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));w.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>B(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(w.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;w.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ae(V0,i);U(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 B(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:Ne.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(le(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=>B(this,void 0,void 0,function*(){w.error("Call setRemoteDescription Error: ",n);const s=ae(ch,n);U(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){w.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_warnIfOnlyHostIceCandidates(e){if(!(n=>{if(!n)return!1;const s=n.split(/\r?\n/).filter(o=>/^a=candidate:/i.test(o));return s.length>0&&s.every(o=>/\styp\s+host(?:\s|$)/i.test(o))})(e))return;const i=Pe(J0);w.warn(`[${this.id}] Warning ${i.code}: ${i.message}`),U(P.Warning,{warning:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._isTerminatingOrTerminated())return;if(this.peer&&(this.peer.iceDone=!0),!e)return void w.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;(n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),this._warnIfOnlyHostIceCandidates(o),performance.mark(le(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Ds}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case Ne.Offer:this.setState(W.Requesting),a=new $h(l);break;case Ne.Answer:this._isRecovering||this.setState(W.Answering),a=this.options.attach===!0?new Hh(l):new jh(l);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===Ne.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(c=>B(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${r} error:`,c);const u=ae(dh,c);U(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){w.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(this._isTerminatingOrTerminated())return;if(!e)return w.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-${Ds}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case Ne.Offer:this.setState(W.Requesting),o=new $h(r);break;case Ne.Answer:this._isRecovering||this.setState(W.Answering),o=this.options.attach===!0?new Hh(r):new jh(r);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===Ne.Offer?this.setState(W.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(W.Held):this.setState(W.Active)}).catch(a=>B(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${s} error:`,a);const l=ae(dh,a);U(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){w.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;if(this._isTerminatingOrTerminated())return;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?(w.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,n,s,o;this._isTerminatingOrTerminated()||(e.candidate&&e.candidate.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):(e.candidate===null&&this._warnIfOnlyHostIceCandidates((o=(s=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||s===void 0?void 0:s.localDescription)===null||o===void 0?void 0:o.sdp),this._sendEndOfCandidates()))}_sendIceCandidate(e){const i=new Pb({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 w.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(()=>{w.debug("Successfully added ICE candidate:",e)}).catch(n=>{w.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new Nb({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(le(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(le(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=>{w.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(w.debug("Finished gathering candidates"),performance.mark(le(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(w.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&&Es(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:at.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),w.error(`Media error (${i}): ${n}`,e),U(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:at.peerConnectionFailureError,error:e.error}),w.error("Peer connection failure error"),e.warning&&U(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:at.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:at.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(U(P.Notification,e,this.id,!1)||U(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=Pe(ib);return U(P.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),w.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:g,onNotification:m,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var y;this.options.id=d?d.toString():Di(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(y=h,Object.keys(y).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),g||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Wt(P.MediaError,this._onMediaError,this.id),Wt(P.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Wt(P.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),ys(m)&&Wt(P.Notification,m.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,k=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,R=this.session.options.debugLogLevel||"debug",D=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new ce({enabled:!0,interval:k,intermediateReportInterval:A},{enabled:!0,level:R,maxEntries:D}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=T=>{var E,p,_,f;U(P.Warning,{warning:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),T.code===Pr&&this._state!==W.Held?(p=(E=this.session).reportNoRtp)===null||p===void 0||p.call(E,this.id,"inbound"):T.code===vh&&this._state!==W.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((f=(_=this.session).reportNoRtp)===null||f===void 0||f.call(_,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:Mh,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 p=(l=this.session.connection)===null||l===void 0?void 0:l.host;p&&this._callRecorder._setHost(p),this._callRecorder.onWarning=_=>{U(P.Warning,{warning:_,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(W.Recovering):this.setState(W.New),w.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)}getEstablishmentTimings(){var e,i,n;const s=(e=this.peer)===null||e===void 0?void 0:e.callEstablishmentTimings;if(s)return s;const o=!((i=this.options)===null||i===void 0)&&i.trickleIce&&!(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)?"trickle":"non-trickle";return sf(this.id,o,this.direction)}_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(),Yr(this.id),w.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;kn(s),kn(o),Gh(r,s),Gh(a,o),Tt(P.MediaError,null,this.id),Tt(P.PeerConnectionFailureError,null,this.id),Tt(P.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{w.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 g=this.session.options,m=g.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},m?{anonymousLogin:{targetType:m.target_type,targetId:m.target_id,targetVersionId:m.target_version_id,targetParams:this._sanitizeClientOption(m.target_params)}}:{}),connection:{env:g.env,host:g.host,project:g.project,region:(e=this.session.region)!==null&&e!==void 0?e:g.region,dc:this.session.dc,rtcIp:g.rtcIp,rtcPort:g.rtcPort,autoReconnect:(i=g.autoReconnect)===null||i===void 0||i,maxReconnectAttempts:(n=g.maxReconnectAttempts)!==null&&n!==void 0?n:10,keepConnectionAliveOnSocketClose:(s=g.keepConnectionAliveOnSocketClose)!==null&&s!==void 0&&s,hangupOnBeforeUnload:g.hangupOnBeforeUnload!==!1,useCanaryRtcServer:(o=g.useCanaryRtcServer)!==null&&o!==void 0&&o,skipLastVoiceSdkId:(r=g.skipLastVoiceSdkId)!==null&&r!==void 0&&r,skipTrailing:(a=g.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:g.enableCallReports!==!1,intervalMs:g.callReportInterval||5e3,flushIntervalMs:(h=g.callReportFlushInterval)!==null&&h!==void 0?h:18e4,debugLogLevel:g.debugLogLevel||"debug",debugLogMaxEntries:g.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 w.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 w.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===St.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ds,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;w.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=>{w.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return B(this,void 0,void 0,function*(){if(!this._callReportCollector)return void w.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=>{w.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 w.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===St.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Ds,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void w.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 w.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),w.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),w.debug("Stats stopped")}}of.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 ai extends of{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Wb(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 Gb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return B(this,void 0,void 0,function*(){this.screenShare instanceof ai&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return B(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",()=>B(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 ai(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return B(this,void 0,void 0,function*(){this.screenShare instanceof ai&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return B(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&qh(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>B(this,void 0,void 0,function*(){const 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
|
+
`),Ue[`${(o=(s=r==null?void 0:r.result)===null||s===void 0?void 0:s.params)===null||o===void 0?void 0:o.state}`]||!j(r.id,r)){const l=Gr(r);j(F.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!==Gh?(w.warn("Socket stuck in CLOSING after 5s — forcefully cleaning up"),this._deregisterSocketEvents(e),this._safetyCleanupSocket(e,"timeout"),this._wsClient&&this._wsClient!==e?w.debug("Safety timeout: socket was replaced, not emitting SocketClose",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}):(w.debug("Safety timeout: emitting SocketClose for stuck socket",{hasWsClient:!!this._wsClient,isSameSocket:this._wsClient===e}),j(F.SocketClose,{code:Ih.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))):w.warn("Safety timeout fired but socket is already closed or cleaned up")}_clearSafetyTimeout(){this._safetyTimeoutId&&(w.debug("Clearing safety timeout"),clearTimeout(this._safetyTimeoutId),this._safetyTimeoutId=null)}_safetyCleanupSocket(e,i){this._wsClient===e?(w.debug(`Nulling socket reference (reason: ${i})`),this._wsClient=null):w.debug(`Skipping socket cleanup - old socket already replaced (reason: ${i})`)}_cleanupPendingRequests(){Array.from(this._pendingRequestIds).forEach(e=>{Mt(e);const i=this._pendingRequestTimers.get(e),n=this._pendingRequestRejecters.get(e);i&&(clearTimeout(i),this._pendingRequestTimers.delete(e),n&&n.reject(new Wr(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)),j(F.SpeedTest,{upDur:this.upDur,downDur:this.downDur},this.session.uuid)}else w.warn("Unknown message from socket",e)}}Ls.DEFAULT_REQUEST_TIMEOUT_MS=1e4;class Hi{buildRequest(e){this.request=Object.assign({jsonrpc:"2.0",id:Bi()},e)}buildNotification(e){this.request=Object.assign({jsonrpc:"2.0"},e)}}const qh={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 qe extends Hi{constructor(e={}){if(super(),e.hasOwnProperty("dialogParams")){const i=ph(e.dialogParams,["remoteSdp","localStream","remoteStream","localElement","remoteElement","onNotification","camId","micId","speakerId"]);for(const n in qh)n&&i.hasOwnProperty(n)&&(i[qh[n]]=i[n],delete i[n]);e.dialogParams=i}this.buildRequest({method:this.toString(),params:e})}}class zh extends qe{constructor(e){super(),this.method=ie.GatewayState,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Ub{constructor(e){this.pendingRequestId=null,this.onSocketMessage=i=>U(this,void 0,void 0,function*(){i.id===this.pendingRequestId&&this.gatewayStateTask.resolve(Gr(i))}),this.getIsRegistered=()=>U(this,void 0,void 0,function*(){const i=new zh(xn());this.pendingRequestId=i.request.id,this.gatewayStateTask=Nh({}),this.session.execute(i);const n=yield this.gatewayStateTask.promise;return!!n&&[Ue.REGISTER,Ue.REGED].includes(n)}),this.session=e,this.gatewayStateTask=Nh({}),this.session.on("telnyx.socket.message",this.onSocketMessage)}}class Jr extends qe{constructor(e){super(),this.method=ie.Ping,this.buildRequest({method:this.method,voice_sdk_id:e,params:{}})}}class Wi{constructor(e){this._session=e,this._lastInboundAt=0,this._lastOutboundConfirmedAt=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 Wi.CRITICAL_METHODS.has(e)}start(){this._intervalId||(w.debug("Signaling health: monitor started"),this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=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(),w.debug("Signaling health: monitor stopped")}get isRunning(){return this._intervalId!==null}get isProbeInFlight(){return this._probeInFlight}onSocketActivity(){this._lastInboundAt=Date.now()}onOutboundConfirmed(){this._lastOutboundConfirmedAt=Date.now()}_resolveProbe(){if(!this._probeInFlight)return;if(this._probeInFlight=!1,this._lastProbeSentAt=0,this._lastInboundAt=Date.now(),this._lastOutboundConfirmedAt=Date.now(),w.debug("Signaling health: probe resolved by matching Ping response"),!this._pendingMediaRecovery)return void w.debug("Signaling health: probe resolved but no pending media recovery");const e=this._pendingMediaRecovery;this._pendingMediaRecovery=null,this._getSignalingHealthState()==="healthy"&&(w.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?w.debug(`Signaling health: probe already in flight, skipping duplicate probe (${e})`):(w.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&&(Wi.isCriticalMethod(n)?(w.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")):w.warn(`Non-critical signaling request timed out (id=${e}, method=${n||"unknown"}, timeout=${i}ms) — logging but not triggering signaling recovery`))}onPeerFailure(e,i){w.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){w.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&&(w.debug(`Signaling health: browser online — clearing browser offline state for session ${this._session.sessionid}`),this._browserWasOffline=!1)},this._offlineHandler=()=>{this._browserWasOffline=!0,w.debug(`Signaling health: browser offline signal received for session ${this._session.sessionid}`);const e=ae(K0);j(F.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){w.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,s=i-this._lastOutboundConfirmedAt,o=n>=2e4;if(!o&&!(s>=45e3))return;if(!this._probeInFlight)return w.info(o?`Signaling health: no inbound WS activity for ${Math.round(n/1e3)}s during active call, sending health probe`:`Signaling health: inbound WS activity is flowing but no outbound request has been answered for ${Math.round(s/1e3)}s, sending health probe`),void this._sendProbe();const r=i-this._lastProbeSentAt;r>=5e3&&(w.warn(`Signaling health: probe timed out after ${r}ms (inbound silent for ${Math.round(n/1e3)}s, no outbound request answered for ${Math.round(s/1e3)}s) — declaring signaling unhealthy`),this._triggerSignalingRecovery(o?"Signaling health probe timed out: no inbound WS activity after probe":"Signaling health probe timed out: inbound WS activity is flowing but no outbound request is being answered","probe"))}_sendProbe(){var e;this._probeInFlight=!0,this._lastProbeSentAt=Date.now();const i=new Jr(xn());(e=this._session.connection)===null||e===void 0||e.send(i).then(()=>this._resolveProbe()).catch(n=>{w.warn("Signaling health: probe Ping failed to send",n)})}_recoverMediaOrSignaling(e,i,n,s){if(!this._session.hasActiveCall())return void w.debug(`Signaling health: ignoring ${s} recovery without an active call`);const o=this._getSignalingHealthState();return o==="healthy"?(w.info(`Signaling health: signaling is healthy, triggering ICE restart for call ${e}`),void this._triggerIceRestart(e,i)):o==="unknown"?(w.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`)):(w.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,w.debug(`Signaling recovery triggered (source=${i}, reason=${e})`);const r=je(fb);j(F.Warning,{warning:r,reason:e,source:i,sessionId:this._session.sessionid},this._session.uuid),!((n=this._session.connection)===null||n===void 0)&&n.connected?(w.info("Signaling health: force-closing WebSocket to trigger reconnect"),this._session.socketDisconnect()):w.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){w.info(`Signaling health: triggering ICE restart for call ${e}`);const n=this._session.triggerIceRestart(e);if(!n.started)return void w.info(`Signaling health: ICE restart not started for call ${e}: ${n.reason}`);const s=je(pb);j(F.Warning,{warning:s,reason:i,callId:e,sessionId:this._session.sessionid},this._session.uuid)}}Wi.CRITICAL_METHODS=new Set([ie.Modify,ie.Bye,ie.Ping]);var Kh="2.27.10",Qr=Kh;class Bb extends qe{constructor(e,i,n,s,o={},r,a=!1){super(),this.method="login";const l={login:e,passwd:i,login_token:n,userVariables:o,reconnection:r,loginParams:{early_sdp_answer:a},"User-Agent":{sdkVersion:Qr,data:navigator.userAgent}};s&&(l.sessid=s),this.buildRequest({method:this.method,params:l})}}class Vb extends qe{constructor(e,i){super(),this.buildRequest({id:e,result:{method:i}})}}class Yh extends qe{toString(){return ie.Invite}}class Xh extends qe{toString(){return ie.Answer}}class Jh extends qe{toString(){return ie.Attach}}class $b extends qe{toString(){return ie.Bye}}class jb extends qe{toString(){return ie.Candidate}}class Hb extends qe{toString(){return ie.EndOfCandidates}}class Ms extends qe{toString(){return ie.Modify}}class Qh extends qe{toString(){return ie.Info}}class Wb extends qe{toString(){return ie.Broadcast}}class Gb extends qe{toString(){return ie.Subscribe}}class qb extends qe{toString(){return ie.Unsubscribe}}class zb extends qe{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:Qr,data:navigator.userAgent}};a&&(c.sessid=a),s&&(c.target_version_id=s),o&&(c.target_params=o),this.buildRequest({method:this.method,params:c})}}class fi{constructor(e){if(this.options=e,this.uuid=Bi(),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 Wi(this),this._executeQueue=[],!this.validateOptions())throw new Error("Invalid init options");var i,n;i=e.debug?"debug":"info",Lh=(n=Es[i])!==null&&n!==void 0?n:Es.info,this._onSocketOpen=this._onSocketOpen.bind(this),this.onNetworkClose=this.onNetworkClose.bind(this),this._onSocketMessage=this._onSocketMessage.bind(this),this._handleLoginError=this._handleLoginError.bind(this),this._onSocketActivity=this._onSocketActivity.bind(this),this._attachListeners(),this.connection=new Ls(this),this.registerAgent=new Ub(this)}get __logger(){return w}get connected(){return this.connection&&this.connection.connected}getIsRegistered(){return U(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 w.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}),w.debug("Calling connect from execute since not currently connected."),this.connect()});const n=Wi.isCriticalMethod(((i=e.request)===null||i===void 0?void 0:i.method)||"")?Ls.DEFAULT_REQUEST_TIMEOUT_MS:void 0;return(n!=null?this.connection.send(e,n):this.connection.send(e)).catch(s=>U(this,void 0,void 0,function*(){if(s instanceof Wr)throw w.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=ae(q0,s,void 0,!0);j(F.Error,{error:o,sessionId:this.sessionid},this.uuid)}yield this.login()}throw s}))}executeRaw(e){this._idle?this._executeQueue.push({msg:e}):this.connection.sendRawText(e)}trackCallReportUpload(e){this._pendingCallReportUploads.add(e),e.then(()=>this._pendingCallReportUploads.delete(e),()=>this._pendingCallReportUploads.delete(e))}_drainCallReportUploads(){return U(this,void 0,void 0,function*(){if(this._pendingCallReportUploads.size===0)return;const e=Array.from(this._pendingCallReportUploads);let i=!1;yield Promise.race([Promise.all(e.map(n=>n.catch(()=>{}))),new Promise(n=>setTimeout(()=>{i=!0,n()},fi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS))]),i&&w.warn("Timed out waiting for pending call report uploads",{pendingCount:this._pendingCallReportUploads.size})})}validateOptions(){return Rs(this.options)||Rn(this.options)}broadcast(e){}disconnect(){return U(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(),w.debug("Session disconnected. Cleaned up all listeners and subscriptions, closed connection, disabled auto-reconnect.")})}on(e,i){return Qt(e,i,this.uuid),this}off(e,i){return Mt(e,i,this.uuid),this}connect(){return U(this,void 0,void 0,function*(){this.connection||(w.debug("No existing connection found, creating a new one."),this.connection=new Ls(this)),this._attachListeners(),this._autoReconnect||(w.debug("autoReconnect was disabled, resetting reconnect attempts"),this._reconnectAttempts=0),this._autoReconnect=!0,this.connection.isAlive||(w.debug("Connection wasn't alive, initiating connection to the server..."),this.connection.connect()),w.debug("Connect method called. Connection initiated.")})}resetReconnectAttempts(){this._reconnectAttempts=0,this._reconnectCountedGeneration=-1}_handleLoginError(e){const i=ae(wh,e);j(F.Error,{error:i,sessionId:this.sessionid},this.uuid)}clearReconnectToken(){Uh()}_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<=fi.TOKEN_EXPIRY_WARNING_SECONDS)this._emitTokenExpiryWarning();else{const o=1e3*(s-fi.TOKEN_EXPIRY_WARNING_SECONDS);this._tokenExpiryTimeout=setTimeout(()=>{this._emitTokenExpiryWarning()},o)}}catch{w.debug("login_token is not a decodable JWT, skipping expiry check")}}_emitTokenExpiryWarning(){const e=je(ub);j(F.Warning,{warning:e,sessionId:this.sessionid},this.uuid)}_clearTokenExpiryTimeout(){this._tokenExpiryTimeout!==null&&(clearTimeout(this._tokenExpiryTimeout),this._tokenExpiryTimeout=null)}login({creds:e,onSuccess:i,onError:n}={}){return U(this,void 0,void 0,function*(){if(this.connection&&this.connection.isAlive){if(e&&(e.login!==void 0&&(this.options.login=e.login),e.password!==void 0&&(this.options.password=e.password),e.passwd!==void 0&&(this.options.passwd=e.passwd),e.login_token!==void 0&&(this.options.login_token=e.login_token),e.userVariables!==void 0&&(this.options.userVariables=e.userVariables),e.anonymous_login!==void 0&&(this.options.anonymous_login=e.anonymous_login)),Rs(this.options))return this._login({type:"login",onSuccess:i,onError:n});if(Rn(this.options))return this._login({type:"anonymous_login",onSuccess:i,onError:n});{const s="Invalid login options provided for authentication.";w.error(s);const o=ae(G0,void 0,s);return void j(F.Error,{error:o,type:Mb.invalidCredentialsOptions,sessionId:this.sessionid},this.uuid)}}})}_login({type:e,onSuccess:i,onError:n}){var s,o,r,a;return U(this,void 0,void 0,function*(){let l;const c=!!xn(),u=c&&(this.sessionid&&Fh()?this.sessionid:function(h=Date.now()){const p=sessionStorage.getItem(xs);return p?Fh(h)?p:(sessionStorage.removeItem(xs),sessionStorage.removeItem(Ds),null):null}())||"";if(e==="login"){const h=(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,p=Object.assign(Object.assign({},this.options.userVariables),{push_when_active:h,pn_late_fanout:h}),m=(a=this.options.earlySdpAnswer)!==null&&a!==void 0&&a;l=new Bb(this.options.login,this.options.password||this.options.passwd,this.options.login_token,u,p,c,m)}else l=new zb({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:u,userVariables:this.options.userVariables,reconnection:c});const d=yield this.execute(l).catch(h=>{this._handleLoginError(h),n&&n(h)});d&&(this.sessionid=d.sessid,this.sessionid&&Kr(this.sessionid),this._checkTokenExpiry(),i&&i())})}_onSocketOpen(){return U(this,void 0,void 0,function*(){this.startSignalingHealthMonitor()})}_flushIntermediateCallReports(e){const i=this.calls;i&&Object.values(i).forEach(n=>{if(n!=null&&n.flushIntermediateCallReport)try{n.flushIntermediateCallReport(e)}catch(s){w.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(Ih).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)w.debug(`Skipping stale onNetworkClose for socket generation ${a} (current generation is ${r})`);else if(a!==this._reconnectCountedGeneration){this._flushIntermediateCallReports(this._createSocketCloseFlushReason(e)),w.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&&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){w.info(`Reconnection exhausted after ${l} attempts. Stopping automatic reconnect.`),this._reconnectAttempts=0,this._autoReconnect=!1,this._terminateActiveCallsLocally();const u=ae(jr);return void j(F.Error,{error:u,sessionId:this.sessionid},this.uuid)}const c=this.reconnectDelay;w.debug(`Reconnect attempt ${this._reconnectAttempts}${l>0?` of ${l}`:""} (delay=${c}ms)`),this._reconnectTimeout=setTimeout(()=>{w.debug("Calling connect due to network close and auto-reconnect enabled."),this.connect()},c)}else if(w.debug("auto_reconnect disabled, not reconnecting",{voiceSdkId:this.callReportVoiceSdkId,sessid:this.sessionid||void 0,intentionalClose:this._intentionalClose}),!this._intentionalClose){const l=je(gb);j(F.Warning,{warning:l,reason:"auto_reconnect_disabled",sessionId:this.sessionid},this.uuid)}this._intentionalClose=!1}else w.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],Mt(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]={},As(i)&&Qt(e,i,n))}_existsSubscription(e,i){return!(!this.subscriptions.hasOwnProperty(e)||!(!i||i&&this.subscriptions[e].hasOwnProperty(i)))}_attachListeners(){this._detachListeners(),w.debug("Attaching socket event listeners"),this.on(F.SocketOpen,this._onSocketOpen),this.on(F.SocketClose,this.onNetworkClose),this.on(F.SocketError,this.onNetworkClose),this.on(F.SocketMessage,this._onSocketMessage),this.on(F.SocketActivity,this._onSocketActivity)}_detachListeners(){w.debug("Detaching socket event listeners"),this.off(F.SocketOpen,this._onSocketOpen),this.off(F.SocketClose,this.onNetworkClose),this.off(F.SocketError,this.onNetworkClose),this.off(F.SocketMessage,this._onSocketMessage),this.off(F.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(),w.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&&(w.warn("No ping/pong received, forcing PING ACK to keep alive"),this.execute(new Jr(xn()))),clearTimeout(this._keepAliveTimeout),this._triggerKeepAliveTimeoutCheck()}_triggerKeepAliveTimeoutCheck(){this._pong=!1,this._keepAliveTimeout=setTimeout(()=>this._resetKeepAlive(),35e3)}setPingReceived(){w.debug("Ping received"),this._pong=!0}_onSocketActivity(){this._signalingHealthMonitor.onSocketActivity()}onOutboundConfirmed(){this._signalingHealthMonitor.onOutboundConfirmed()}hasActiveCall(){const e=this.calls;if(!e)return!1;const i=new Set([z.Early,z.Active,z.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){w.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 w.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 w.warn(`Signaling health: cannot trigger ICE restart — no peer for call ${e}`),{started:!1,reason:"no peer"};const o=s.restartIce();return o.started||w.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){Qt(e,i)}static off(e){Mt(e)}static uuid(){return Bi()}clearConnection(){this.connection=null}hasAutoReconnect(){return this._autoReconnect}}fi.TOKEN_EXPIRY_WARNING_SECONDS=120,fi.CALL_REPORT_UPLOAD_DRAIN_TIMEOUT_MS=1e4;const Os=t=>navigator.mediaDevices.getUserMedia(t),Ln=t=>t&&t instanceof MediaStream,Ps=(t,e,i)=>{const n=An(t);if(n!==null){if(n.getAttribute("autoplay")||n.setAttribute("autoplay","autoplay"),n.getAttribute("playsinline")||n.setAttribute("playsinline","playsinline"),n.srcObject&&n.srcObject!==e&&(w.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=je(db);j(F.Warning,{warning:s,callId:i.callId,sessionId:i.sessionId},i.eventTarget)}n.srcObject=e}},Zh=(t,e)=>{const i=An(t);if(i){if(e&&i.srcObject!==e)return;i.srcObject=null}},ef=(t,e)=>U(void 0,void 0,void 0,function*(){const i=An(t);if(i===null)return w.info("No HTMLMediaElement to attach the speakerId"),!1;if(typeof e!="string")return w.info(`Invalid speaker deviceId: '${e}'`),!1;try{return yield i.setSinkId(e),!0}catch{return!1}}),Kb=t=>{t&&t.readyState==="live"&&t.stop()},Mn=t=>{Ln(t)&&t.getTracks().forEach(Kb),t=null},Ns=t=>U(void 0,void 0,void 0,function*(){w.info("RTCService.getUserMedia",t);const{audio:e,video:i}=t;if(!e&&!i)return null;try{return yield Os(t)}catch(n){if(w.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){w.warn("Device not found or not readable, falling back to default device");try{return yield Os(s)}catch(o){throw w.error("Fallback getUserMedia also failed: ",o),n}}}throw n}}),On=(t=null,e=!1)=>U(void 0,void 0,void 0,function*(){let i=[];const n=yield navigator.mediaDevices.getUserMedia(((s=null)=>({audio:!s||s===Lt.AudioIn||s===Lt.AudioOut,video:!s||s===Lt.Video}))(t)).catch(s=>(w.error(s),null));if(n){if(Mn(n),i=yield navigator.mediaDevices.enumerateDevices(),t&&(i=i.filter(o=>o.kind===t)),e===!0)return i;const s=[];i=i.filter(o=>{if(!o.groupId)return!0;const r=`${o.kind}-${o.groupId}`;return!s.includes(r)&&(s.push(r),!0)})}return i}),tf=[[320,240],[640,360],[640,480],[1280,720],[1920,1080]],Fs=(t,e,i)=>U(void 0,void 0,void 0,function*(){const n=yield On(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}),Yb=t=>{const e=navigator.mediaDevices.getSupportedConstraints();Object.keys(t).map(i=>{e.hasOwnProperty(i)&&t[i]!==null&&t[i]!==void 0||delete t[i]})},Zr=t=>t?{id:t.id,kind:t.kind,enabled:t.enabled,muted:t.muted,readyState:t.readyState}:null,nf=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=>Zr(a)):[]},ea=(t,e)=>{if(!t)return!1;const{subscribed:i,alreadySubscribed:n}=ta(t);return i.includes(e)||n.includes(e)},ta=t=>{const e={subscribed:[],alreadySubscribed:[],unauthorized:[],unsubscribed:[],notSubscribed:[]};return Object.keys(e).forEach(i=>{e[i]=t[`${i}Channels`]||[]}),e},Gi=(t,e=null,i=null)=>{if(!Ln(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}})},ia=t=>{Gi(t,"audio",!0)},Us=t=>{Gi(t,"audio",!1)};function Xb(){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:!!Ns}}catch(t){return t.message}}var Ae;function sf(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 of(t){t&&(t._playFulfilled=!1,t._promise=t.play(),t._promise.then(()=>{t._playFulfilled=!0}).catch(e=>{w.error("playAudio",e),t._playFulfilled=!0}))}function rf(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"})(Ae||(Ae={}));const af=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 Jb extends Hi{constructor(e,i){super(),this.method="ai_conversation",this.buildRequest({method:this.method,params:{type:"conversation.item.create",previous_item_id:null,item:{id:Bi(),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 Qb extends Hi{constructor(e){super(),this.method="ai_conversation",this.buildNotification({method:this.method,params:{type:"conversation.item.create",item:e}})}}class ue{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 Ab(s)}(this.logCollectorOptions),this.logCollector.start(),n=this.logCollector,Dh=n)}start(e){var i,n;this.options.enabled&&(this.peerConnection=e,this.intervalStartTime=new Date,this._lastIntermediateFlushTime=this.intervalStartTime,this._stopped=!1,w.info("CallReportCollector: Starting stats collection",{interval:this.options.interval,initialInterval:ue.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 U(this,void 0,void 0,function*(){this._stopped=!0,this.intervalId&&(clearTimeout(this.intervalId),this.intervalId=null),this.callEndTime=new Date,this.peerConnection&&this.intervalStartTime&&(yield this._collectStats(!0));const n=(i=(e=this.logCollector)===null||e===void 0?void 0:e.getLogCount())!==null&&i!==void 0?i:0;this.logCollector&&this.logCollector.stop(),w.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 w.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:[],m=new Date;this._lastIntermediateFlushTime=m;const v=Object.assign(Object.assign(Object.assign({summary:Object.assign(Object.assign({},e),{durationSeconds:(m.getTime()-this.callStartTime.getTime())/1e3,startTimestamp:this.callStartTime.toISOString(),endTimestamp:m.toISOString()}),stats:h},p.length>0?{logs:p}:{}),{segment:d}),i?{flushReason:i}:{});return w.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 U(this,void 0,void 0,function*(){const a=(o=this.logCollector)===null||o===void 0?void 0:o.getLogs(),l=a&&a.length>0;if(!this.options.enabled)return void w.info("CallReportCollector: Skipping report — call reports disabled");if(this.statsBuffer.length===0&&!l)return void w.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 U(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 U(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}`;w.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),m=(o||r)&&p.length<=ue.KEEPALIVE_BODY_LIMIT_BYTES;let v;for(let b=0;b<=ue.RETRY_DELAYS_MS.length;b++){try{const C=yield fetch(u,Object.assign({method:"POST",headers:h,body:p},m?{keepalive:!0}:{}));if(C.ok)return void w.info(`CallReportCollector: Successfully posted ${d}`,{attempt:b+1,status:C.status});{const T=yield C.text();v=new Error(`Call report POST failed with status ${C.status}`),w.error(`CallReportCollector: Failed to post ${d}`,{attempt:b+1,status:C.status,error:T})}}catch(C){v=C,w.warn(`CallReportCollector: Network error posting ${d}`,{attempt:b+1,error:C})}const y=ue.RETRY_DELAYS_MS[b];if(y===void 0)break;w.info(`CallReportCollector: Retrying ${d} in ${y}ms`,{attempt:b+2}),yield new Promise(C=>setTimeout(C,y))}throw w.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,m,v,b;if(this.statsBuffer.length<2)return!1;const y=this.statsBuffer[this.statsBuffer.length-1],C=this.statsBuffer[this.statsBuffer.length-2],T=(e=y.ice)===null||e===void 0?void 0:e.local;if(!((T==null?void 0:T.networkType)==="vpn"&&(T==null?void 0:T.candidateType)!=="relay"))return!1;const A=((i=y.ice)===null||i===void 0?void 0:i.writable)===!1,x=((n=y.transport)===null||n===void 0?void 0:n.iceState)==="disconnected"||((s=y.transport)===null||s===void 0?void 0:s.iceState)==="failed",N=this._positiveDelta((o=y.ice)===null||o===void 0?void 0:o.requestsSent,(r=C.ice)===null||r===void 0?void 0:r.requestsSent),E=this._positiveDelta((a=y.ice)===null||a===void 0?void 0:a.responsesReceived,(l=C.ice)===null||l===void 0?void 0:l.responsesReceived),k=N>0&&E===0,f=this._positiveDelta((u=(c=y.audio)===null||c===void 0?void 0:c.outbound)===null||u===void 0?void 0:u.bytesSent,(h=(d=C.audio)===null||d===void 0?void 0:d.outbound)===null||h===void 0?void 0:h.bytesSent),_=this._positiveDelta((m=(p=y.audio)===null||p===void 0?void 0:p.inbound)===null||m===void 0?void 0:m.bytesReceived,(b=(v=C.audio)===null||v===void 0?void 0:v.inbound)===null||b===void 0?void 0:b.bytesReceived);return A||x||k||f>0&&_===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(ks,!1),this._trackBreach(Hr,!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(ue.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 U(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(f=>{switch(f.type){case"outbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(r=f);break;case"inbound-rtp":f.kind==="audio"&&f.mediaType==="audio"&&(a=f);break;case"media-playout":f.kind==="audio"&&(l=f);break;case"remote-inbound-rtp":f.kind==="audio"&&(c=f);break;case"remote-outbound-rtp":f.kind==="audio"&&(u=f);break;case"candidate-pair":(f.nominated||f.state==="succeeded")&&h.push(f);break;case"transport":p=f}});const m=p==null?void 0:p.selectedCandidatePairId,v=m?(n=(i=s).get)===null||n===void 0?void 0:n.call(i,m):void 0,b=this._getCodec(s,r==null?void 0:r.codecId),y=this._getCodec(s,a==null?void 0:a.codecId);if(d=(v==null?void 0:v.type)==="candidate-pair"?v:m?h.find(f=>f.id===m)||h[h.length-1]||null:h[h.length-1]||null,r){const f=this._getOutboundAudioLevel(s,r);if(f!==null&&this.intervalAudioLevels.outbound.push(f),this.previousStats.outboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(r.bytesSent||0)-this.previousStats.outboundBytes,g=(r.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.outbound.push(S)}}this.previousStats.outboundBytes=r.bytesSent}if(a){const f=this._getInboundAudioLevel(s,a);if(f!==null&&this.intervalAudioLevels.inbound.push(f),a.jitter!==void 0&&this.intervalJitters.push(1e3*a.jitter),this.previousStats.inboundBytes!==void 0&&this.previousStats.timestamp!==void 0){const _=(a.bytesReceived||0)-this.previousStats.inboundBytes,g=(a.timestamp||o.getTime())-this.previousStats.timestamp;if(g>0){const S=8*_*1e3/g;this.intervalBitrates.inbound.push(S)}}this.previousStats.inboundBytes=a.bytesReceived}let C,T,A,x,N;d&&d.currentRoundTripTime!==void 0&&this.intervalRTTs.push(d.currentRoundTripTime),d&&(C=this._resolveCandidate(s,d.localCandidateId),T=this._resolveCandidate(s,d.remoteCandidateId)),d&&(A=Object.assign(Object.assign({id:d.id,localCandidateId:d.localCandidateId,remoteCandidateId:d.remoteCandidateId,state:d.state,nominated:d.nominated,writable:d.writable,currentRoundTripTime:d.currentRoundTripTime,requestsSent:d.requestsSent,responsesReceived:d.responsesReceived},C?{local:C}:{}),T?{remote:T}:{}),this.previousCandidatePairSnapshot!==null&&d.id!==this.previousCandidatePairSnapshot.id&&(w.debug("CallReportCollector: ICE candidate pair changed mid-call",{previous:this.previousCandidatePairSnapshot,current:A}),this._emitWarning(rb)),this.previousCandidatePairSnapshot=A),r&&(x=this._getLocalAudioTrackSnapshot(),N=this._getOutboundAudioSourceStats(s,r)),this._logLocalAudioTrackSnapshot(x,N),this.previousStats.timestamp=o.getTime();const E=o.getTime()-this.intervalStartTime.getTime(),k=this._collectionIntervalFor();if(e||E>=k){const f=this._createStatsEntry(this.intervalStartTime,o,r,a,d,C,T,p,x,N,l,c,u,b,y);this.statsBuffer.push(f),this.statsBuffer.length>this.MAX_BUFFER_SIZE&&(this.statsBuffer.shift(),w.warn("CallReportCollector: Buffer size limit reached, removing oldest entry")),this._checkQualityWarnings(f,a),this._requestIntermediateFlushIfNeeded(o),this.intervalStartTime=o,this._resetIntervalAccumulators()}}catch(s){w.error("CallReportCollector: Error collecting stats",{error:s})}})}_getIntermediateReportInterval(){var e;return(e=this.options.intermediateReportInterval)!==null&&e!==void 0?e:ue.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 w.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>=ue.STATS_FLUSH_THRESHOLD||o>=ue.LOGS_FLUSH_THRESHOLD?l="buffer-limit":r>0&&a>=r&&(l="safety-interval"),l){w.info("CallReportCollector: Requesting intermediate report flush",{reason:l,statsIntervals:s,logEntries:o,msSinceLastFlush:a}),this._lastIntermediateFlushTime=e;try{this.onFlushNeeded()}catch(c){w.error("CallReportCollector: onFlushNeeded callback error",{error:c})}}}_checkQualityWarnings(e,i){var n,s,o,r,a,l,c,u,d,h,p,m,v,b,y;if(!this.onWarning)return;const C=(n=e.connection)===null||n===void 0?void 0:n.roundTripTimeAvg,T=(o=(s=e.audio)===null||s===void 0?void 0:s.inbound)===null||o===void 0?void 0:o.jitterAvg;let A;if(i){const x=(r=i.packetsReceived)!==null&&r!==void 0?r:0,N=(a=i.packetsLost)!==null&&a!==void 0?a:0;if(this._prevPacketsReceived!==null&&this._prevPacketsLost!==null){const E=x-this._prevPacketsReceived,k=N-this._prevPacketsLost,f=E+k;f>0&&(A=k/f*100)}this._prevPacketsReceived=x,this._prevPacketsLost=N}if(this._trackBreach(Y0,C!==void 0&&C>ue.THRESHOLD_RTT_MS),this._trackBreach(X0,T!==void 0&&T>ue.THRESHOLD_JITTER_MS),this._trackBreach(J0,A!==void 0&&A>ue.THRESHOLD_PACKET_LOSS_PCT),this._trackLowLocalAudio(e),this._isHeld?this._trackBreach(ks,!1):this._trackLowInboundAudio(e),C!==void 0&&T!==void 0&&A!==void 0){const x=93.2-.11*T-2.5*A-.01*(1e3*C),N=Math.max(1,Math.min(4.5,1+.035*x+x*(x-60)*(100-x)*7e-6));this._trackBreach(Th,N<ue.THRESHOLD_MOS)}else this._trackBreach(Th,!1);if(((c=(l=e.audio)===null||l===void 0?void 0:l.inbound)===null||c===void 0?void 0:c.bytesReceived)!==void 0){const x=(h=(d=(u=this._previousStatsEntryForWarnings)===null||u===void 0?void 0:u.audio)===null||d===void 0?void 0:d.inbound)===null||h===void 0?void 0:h.bytesReceived,N=e.audio.inbound.bytesReceived;this._trackBreach(Hr,!this._isHeld&&x!==void 0&&N-x==0)}if(((m=(p=e.audio)===null||p===void 0?void 0:p.outbound)===null||m===void 0?void 0:m.bytesSent)!==void 0){const x=(y=(b=(v=this._previousStatsEntryForWarnings)===null||v===void 0?void 0:v.audio)===null||b===void 0?void 0:b.outbound)===null||y===void 0?void 0:y.bytesSent,N=e.audio.outbound.bytesSent;this._trackBreach(kh,x!==void 0&&N-x==0)}this._previousStatsEntryForWarnings=e}_trackLowLocalAudio(e){var i;const n=(i=e.audio)===null||i===void 0?void 0:i.outbound,s=n==null?void 0:n.audioLevelAvg,o=n==null?void 0:n.localTrack;if(s===void 0||(o==null?void 0:o.enabled)===!1||(o==null?void 0:o.muted)===!0)return void this._resetLowLocalAudioWarning();if(!(s<=ue.THRESHOLD_LOCAL_AUDIO_LEVEL))return this._hasConfirmedLocalAudio=!0,this._confirmedLocalAudioSilenceMs=0,void this._trackBreach(Ts,!1);this._hasConfirmedLocalAudio?(this._confirmedLocalAudioSilenceMs+=this._getStatsIntervalDurationMs(e),this._confirmedLocalAudioSilenceMs>=ue.CONFIRMED_LOCAL_AUDIO_SILENCE_MS&&this._emitWarningOncePerEpisode(Ts)):this._trackBreach(Ts,!0)}_resetLowLocalAudioWarning(){this._confirmedLocalAudioSilenceMs=0,this._trackBreach(Ts,!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(ks,!1);const o=s<=ue.THRESHOLD_INBOUND_AUDIO_LEVEL;this._trackBreach(ks,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]>=ue.CONSECUTIVE_BREACHES_REQUIRED){this._activeWarnings.add(e);const o=Date.now();o-((s=this._lastWarningEmitted[e])!==null&&s!==void 0?s:0)>=ue.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=je(e);w.warn(`CallReportCollector: warning ${n.code}: ${n.message}`),(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.error(`CallReportCollector: Failed to emit warning ${e}`,{error:n})}}_createStatsEntry(e,i,n,s,o,r,a,l,c,u,d,h,p,m,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}:{}),m?{codec:this._buildCodecSnapshot(m,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({synthesizedSamplesEvents:d.synthesizedSamplesEvents,synthesizedSamplesDuration:d.synthesizedSamplesDuration,totalPlayoutDelay:d.totalPlayoutDelay,totalSamplesCount:d.totalSamplesCount,totalSamplesDuration:d.totalSamplesDuration})),h||p){const y={};if(h){const C=h.jitter!==void 0?1e3*h.jitter:void 0;let T;typeof h.totalRoundTripTime=="number"&&typeof h.roundTripTimeMeasurements=="number"&&h.roundTripTimeMeasurements>0&&(T=h.totalRoundTripTime/h.roundTripTimeMeasurements),y.inbound=this._withoutUndefined({packetsReceived:h.packetsReceived,packetsLost:h.packetsLost,fractionLost:h.fractionLost,jitter:C,roundTripTime:h.roundTripTime,totalRoundTripTime:h.totalRoundTripTime,roundTripTimeMeasurements:h.roundTripTimeMeasurements,roundTripTimeAvg:T,nackCount:h.nackCount,reportsReceived:h.reportsReceived,packetsDiscarded:h.packetsDiscarded})}p&&(y.outbound=this._withoutUndefined({packetsSent:p.packetsSent,bytesSent:p.bytesSent,reportsCount:p.reportsCount,roundTripTime:p.roundTripTime,totalPacketSendDelay:p.totalPacketSendDelay})),b.remoteRtcp=y}return b}_resolveCandidate(e,i){if(!i)return void w.debug("CallReportCollector: candidateId is empty, skipping resolve");const n=e.get(i);if(!n)return void w.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;w.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 w.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,w.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:[]}}}ue.INITIAL_COLLECTION_INTERVAL_MS=1e3,ue.STATS_FLUSH_THRESHOLD=300,ue.LOGS_FLUSH_THRESHOLD=800,ue.DEFAULT_INTERMEDIATE_REPORT_INTERVAL_MS=18e4,ue.CONSECUTIVE_BREACHES_REQUIRED=3,ue.THRESHOLD_RTT_MS=.4,ue.THRESHOLD_JITTER_MS=30,ue.THRESHOLD_PACKET_LOSS_PCT=1,ue.THRESHOLD_MOS=3.5,ue.THRESHOLD_LOCAL_AUDIO_LEVEL=.001,ue.CONFIRMED_LOCAL_AUDIO_SILENCE_MS=3e4,ue.THRESHOLD_INBOUND_AUDIO_LEVEL=.001,ue.WARNING_THROTTLE_MS=15e3,ue.RETRY_DELAYS_MS=[500,1e3,2e3],ue.KEEPALIVE_BODY_LIMIT_BYTES=61440;class ze{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 w.warn("CallRecorder: MediaStreamTrackProcessor unavailable — recording disabled for this call"),this._emitWarning(Q0),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 w.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(),w.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,w.info("CallRecorder: stopped",{callId:this.callContext.callId,packetsBuffered:this._buffers.local.length+this._buffers.remote.length}))}postFinalReport(){return U(this,void 0,void 0,function*(){if(!this.options.enabled)return;if(this.stop(),!this._startedAt)return void w.debug("CallRecorder: postFinalReport skipped — never started");const e=this._resolveEndpointFromContext();if(!e)return void w.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)<=ze.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),U(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||w.warn("CallRecorder: reader loop error",{track:i,error:a})}})}catch(n){w.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+ze.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+ze.PACKET_OVERHEAD_BYTES)}this._overflowWarnedThisWindow[i]||(this._overflowWarnedThisWindow[i]=!0,w.warn("CallRecorder: buffer overflow — oldest packets dropped",{track:i}),this._emitWarning(Z0))}}_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()*ze.BYTES_PER_SAMPLE+ze.FRAMES_PER_SECOND*ze.PACKET_OVERHEAD_BYTES;return Math.max(1e3,this._maxBufferBytes()/e*500)}_maxBufferBytes(){var e;return(e=this.options.maxBufferBytes)!==null&&e!==void 0?e:$h}_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=>{w.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 U(this,void 0,void 0,function*(){if(!this._flushing&&!this._stopped){this._flushing=!0;try{const e=this._resolveEndpointFromContext();if(!e)return void w.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=>{w.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 U(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<=ze.KEEPALIVE_BODY_LIMIT_BYTES,a=this.options.fetchImpl||fetch;let l;for(let c=0;c<=ze.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 w.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}`),w.error("CallRecorder: failed to post",{track:i.track,segment:i.segment,attempt:c+1,status:d.status,error:h})}}catch(d){l=d,w.warn("CallRecorder: network error posting",{track:i.track,segment:i.segment,attempt:c+1,error:d})}const u=ze.RETRY_DELAYS_MS[c];if(u===void 0)break;w.info("CallRecorder: retrying",{track:i.track,segment:i.segment,inMs:u,attempt:c+2}),yield new Promise(d=>setTimeout(d,u))}throw w.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=je(e);(i=this.onWarning)===null||i===void 0||i.call(this,n)}catch(n){w.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)}}ze.RETRY_DELAYS_MS=[500,1e3,2e3],ze.KEEPALIVE_BODY_LIMIT_BYTES=61440,ze.PACKET_OVERHEAD_BYTES=160,ze.BYTES_PER_SAMPLE=4,ze.FRAMES_PER_SECOND=100;class Zb{constructor(){this._rawDeviceCache=[],this._deviceChangeHandler=null,this._stopped=!1}logDevicesAtStart(){return U(this,void 0,void 0,function*(){try{const e=yield this._enumerateAudioDevices();this._rawDeviceCache=e,w.debug("MediaDeviceCollector: devices at call start",{devices:e}),this._startDeviceChangeListener()}catch(e){w.debug("MediaDeviceCollector: failed to log devices at start",{error:e})}})}stop(){this._stopped=!0,this._removeDeviceChangeListener()}_enumerateAudioDevices(){return U(this,void 0,void 0,function*(){try{if(typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.enumerateDevices=="function")return(yield navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind==="audioinput"||e.kind==="audiooutput")}catch(e){w.debug("MediaDeviceCollector: enumerateDevices failed",{error:e})}return[]})}_startDeviceChangeListener(){typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.addEventListener=="function"&&(this._deviceChangeHandler=()=>{this._onDeviceChange()},navigator.mediaDevices.addEventListener("devicechange",this._deviceChangeHandler))}_removeDeviceChangeListener(){this._deviceChangeHandler&&typeof navigator<"u"&&navigator.mediaDevices&&typeof navigator.mediaDevices.removeEventListener=="function"&&navigator.mediaDevices.removeEventListener("devicechange",this._deviceChangeHandler),this._deviceChangeHandler=null}_onDeviceChange(){return U(this,void 0,void 0,function*(){if(!this._stopped)try{const e=yield this._enumerateAudioDevices(),i=new Set(this._rawDeviceCache.map(r=>r.deviceId)),n=new Set(e.map(r=>r.deviceId)),s=e.filter(r=>!i.has(r.deviceId)),o=this._rawDeviceCache.filter(r=>!n.has(r.deviceId));(s.length>0||o.length>0)&&w.debug("MediaDeviceCollector: devices changed during call",{connected:s,disconnected:o}),this._rawDeviceCache=e}catch(e){w.debug("MediaDeviceCollector: error handling devicechange",{error:e})}})}}var Bs,lf=Rh(function(t,e){var i;function n(){}function s(){s.init.call(this)}function o(f){return f._maxListeners===void 0?s.defaultMaxListeners:f._maxListeners}function r(f,_,g,S){var I,M,R;if(typeof g!="function")throw new TypeError('"listener" argument must be a function');if((M=f._events)?(M.newListener&&(f.emit("newListener",_,g.listener?g.listener:g),M=f._events),R=M[_]):(M=f._events=new n,f._eventsCount=0),R){if(typeof R=="function"?R=M[_]=S?[g,R]:[R,g]:S?R.unshift(g):R.push(g),!R.warned&&(I=o(f))&&0<I&&R.length>I){R.warned=!0;var P=new Error("Possible EventEmitter memory leak detected. "+R.length+" "+_+" listeners added. Use emitter.setMaxListeners() to increase limit");P.name="MaxListenersExceededWarning",P.emitter=f,P.type=_,P.count=R.length,function(O){typeof console.warn=="function"?console.warn(O):console.log(O)}(P)}}else R=M[_]=g,++f._eventsCount;return f}function a(f,_,g){function S(){f.removeListener(_,S),I||(I=!0,g.apply(f,arguments))}var I=!1;return S.listener=g,S}function l(f){var _=this._events;if(_){var g=_[f];if(typeof g=="function")return 1;if(g)return g.length}return 0}function c(f,_){for(var g=Array(_);_--;)g[_]=f[_];return g}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(f){if(typeof f!="number"||0>f||isNaN(f))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=f,this},s.prototype.getMaxListeners=function(){return o(this)},s.prototype.emit=function(f){var _,g,S,I,M,R,P,O=f==="error";if(R=this._events)O=O&&R.error==null;else if(!O)return!1;if(P=this.domain,O){if(_=arguments[1],!P){if(_ instanceof Error)throw _;var L=new Error('Uncaught, unspecified "error" event. ('+_+")");throw L.context=_,L}return _||(_=new Error('Uncaught, unspecified "error" event')),_.domainEmitter=this,_.domain=P,_.domainThrown=!1,P.emit("error",_),!1}if(!(g=R[f]))return!1;var V=typeof g=="function";switch(S=arguments.length){case 1:(function($,W,q){if(W)$.call(q);else for(var G=$.length,oe=c($,G),K=0;K<G;++K)oe[K].call(q)})(g,V,this);break;case 2:(function($,W,q,G){if(W)$.call(q,G);else for(var oe=$.length,K=c($,oe),Z=0;Z<oe;++Z)K[Z].call(q,G)})(g,V,this,arguments[1]);break;case 3:(function($,W,q,G,oe){if(W)$.call(q,G,oe);else for(var K=$.length,Z=c($,K),Y=0;Y<K;++Y)Z[Y].call(q,G,oe)})(g,V,this,arguments[1],arguments[2]);break;case 4:(function($,W,q,G,oe,K){if(W)$.call(q,G,oe,K);else for(var Z=$.length,Y=c($,Z),te=0;te<Z;++te)Y[te].call(q,G,oe,K)})(g,V,this,arguments[1],arguments[2],arguments[3]);break;default:for(I=Array(S-1),M=1;M<S;M++)I[M-1]=arguments[M];(function($,W,q,G){if(W)$.apply(q,G);else for(var oe=$.length,K=c($,oe),Z=0;Z<oe;++Z)K[Z].apply(q,G)})(g,V,this,I)}return!0},s.prototype.addListener=function(f,_){return r(this,f,_,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(f,_){return r(this,f,_,!0)},s.prototype.once=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.on(f,a(this,f,_)),this},s.prototype.prependOnceListener=function(f,_){if(typeof _!="function")throw new TypeError('"listener" argument must be a function');return this.prependListener(f,a(this,f,_)),this},s.prototype.removeListener=function(f,_){var g,S,I,M,R;if(typeof _!="function")throw new TypeError('"listener" argument must be a function');if(!(S=this._events))return this;if(!(g=S[f]))return this;if(g===_||g.listener&&g.listener===_)--this._eventsCount==0?this._events=new n:(delete S[f],S.removeListener&&this.emit("removeListener",f,g.listener||_));else if(typeof g!="function"){for(I=-1,M=g.length;0<M--;)if(g[M]===_||g[M].listener&&g[M].listener===_){R=g[M].listener,I=M;break}if(0>I)return this;if(g.length===1){if(g[0]=void 0,--this._eventsCount==0)return this._events=new n,this;delete S[f]}else(function(P,O){for(var L=O,V=L+1,$=P.length;V<$;L+=1,V+=1)P[L]=P[V];P.pop()})(g,I);S.removeListener&&this.emit("removeListener",f,R||_)}return this},s.prototype.removeAllListeners=function(f){var _,g;if(!(g=this._events))return this;if(!g.removeListener)return arguments.length===0?(this._events=new n,this._eventsCount=0):g[f]&&(--this._eventsCount==0?this._events=new n:delete g[f]),this;if(arguments.length===0){for(var S,I=Object.keys(g),M=0;M<I.length;++M)(S=I[M])!=="removeListener"&&this.removeAllListeners(S);return this.removeAllListeners("removeListener"),this._events=new n,this._eventsCount=0,this}if(typeof(_=g[f])=="function")this.removeListener(f,_);else if(_)do this.removeListener(f,_[_.length-1]);while(_[0]);return this},s.prototype.listeners=function(f){var _,g,S=this._events;return S?g=(_=S[f])?typeof _=="function"?[_.listener||_]:function(I){for(var M=Array(I.length),R=0;R<M.length;++R)M[R]=I[R].listener||I[R];return M}(_):[]:g=[],g},s.listenerCount=function(f,_){return typeof f.listenerCount=="function"?f.listenerCount(_):l.call(f,_)},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,m=[],v=0;256>v;++v)m.push((v+256).toString(16).substr(1));function b(f){var _=1<arguments.length&&arguments[1]!==void 0?arguments[1]:0,g=(m[f[_+0]]+m[f[_+1]]+m[f[_+2]]+m[f[_+3]]+"-"+m[f[_+4]]+m[f[_+5]]+"-"+m[f[_+6]]+m[f[_+7]]+"-"+m[f[_+8]]+m[f[_+9]]+"-"+m[f[_+10]]+m[f[_+11]]+m[f[_+12]]+m[f[_+13]]+m[f[_+14]]+m[f[_+15]]).toLowerCase();if(!function(S){return typeof S=="string"&&p.test(S)}(g))throw TypeError("Stringified UUID is invalid");return g}function y(f,_,g){var S=(f=f||{}).random||(f.rng||h)();return S[6]=64|15&S[6],S[8]=128|63&S[8],b(S)}function C(f,_){if(!f||!_)return{};const g={...f};if(g.localCandidateId){const S=_.get(g.localCandidateId);g.local={...S}}if(g.remoteCandidateId){const S=_.get(g.remoteCandidateId);g.remote={...S}}return g}function T(f,_,g){return 8*function(S,I,M){const R=S[M],P=I?I[M]:null;return R===null||P===null?null:(R-P)/(S.timestamp-I.timestamp)*1e3}(f,_,g)}function A(f){if(!f.entries)return f;const _={};return f.forEach(function(g,S){_[S]=g}),_}function x(f,_,g={}){if(!f)return null;let S={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{inbound:[],outbound:[]}};g.remote&&(S.remote={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]}});for(const I of f.values())switch(I.type){case"outbound-rtp":{const M=I.mediaType||I.kind,R={};let P={};if(!["audio","video"].includes(M))continue;if(I.codecId){const O=f.get(I.codecId);O&&(R.clockRate=O.clockRate,R.mimeType=O.mimeType,R.payloadType=O.payloadType)}P=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[M].outbound.push({...I,...R,track:{...P}});break}case"inbound-rtp":{let M=I.mediaType||I.kind,R={};const P={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const O=f.get(I.codecId);O&&(P.clockRate=O.clockRate,P.mimeType=O.mimeType,P.payloadType=O.payloadType)}if(!S.connection.id&&I.transportId){const O=f.get(I.transportId);if(O&&O.selectedCandidatePairId){const L=f.get(O.selectedCandidatePairId);S.connection=C(L,f)}}R=f.get(I.mediaSourceId)||f.get(I.trackId)||{},S[M].inbound.push({...I,...P,track:{...R}});break}case"peer-connection":S.connection.dataChannelsClosed=I.dataChannelsClosed,S.connection.dataChannelsOpened=I.dataChannelsOpened;break;case"remote-inbound-rtp":{if(!g.remote)break;let M=I.mediaType||I.kind;const R={};if(!["audio","video"].includes(M))if(I.id.includes("Video"))M="video";else{if(!I.id.includes("Audio"))continue;M="audio"}if(I.codecId){const P=f.get(I.codecId);P&&(R.clockRate=P.clockRate,R.mimeType=P.mimeType,R.payloadType=P.payloadType)}if(!S.connection.id&&I.transportId){const P=f.get(I.transportId);if(P&&P.selectedCandidatePairId){const O=f.get(P.selectedCandidatePairId);S.connection=C(O,f)}}S.remote[M].inbound.push({...I,...R});break}case"remote-outbound-rtp":{if(!g.remote)break;const M=I.mediaType||I.kind,R={};if(!["audio","video"].includes(M))continue;if(I.codecId){const P=f.get(I.codecId);P&&(R.clockRate=P.clockRate,R.mimeType=P.mimeType,R.payloadType=P.payloadType)}S.remote[M].outbound.push({...I,...R});break}}if(!S.connection.id)for(const I of f.values())I.type==="candidate-pair"&&I.nominated&&I.state==="succeeded"&&(S.connection=C(I,f));return S=function(I,M){return M&&(I.audio.inbound.map(R=>{let P=M.audio.inbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesReceived"),R.packetRate=T(R,P,"packetsReceived")}),I.audio.outbound.map(R=>{let P=M.audio.outbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesSent"),R.packetRate=T(R,P,"packetsSent")}),I.video.inbound.map(R=>{let P=M.video.inbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesReceived"),R.packetRate=T(R,P,"packetsReceived")}),I.video.outbound.map(R=>{let P=M.video.outbound.find(O=>O.id===R.id);R.bitrate=T(R,P,"bytesSent"),R.packetRate=T(R,P,"packetsSent")})),I}(S,_),S}let N,E={},k=[];e.WebRTCStats=class extends s{constructor(f){if(super(),this.monitoringSetInterval=0,this.connectionMonitoringSetInterval=0,this.connectionMonitoringInterval=1e3,this.remote=!0,this.peersToMonitor={},this.timeline=[],this.statsToMonitor=["inbound-rtp","outbound-rtp","remote-inbound-rtp","remote-outbound-rtp","peer-connection","data-channel","stream","track","sender","receiver","transport","candidate-pair","local-candidate","remote-candidate"],typeof window>"u")throw new Error("WebRTCStats only works in browser");const _={...f};this.isEdge=!!window.RTCIceGatherer,this.getStatsInterval=_.getStatsInterval||1e3,this.rawStats=!!_.rawStats,this.statsObject=!!_.statsObject,this.filteredStats=!!_.filteredStats,this.shouldWrapGetUserMedia=!!_.wrapGetUserMedia,typeof _.remote=="boolean"&&(this.remote=_.remote),this.debug=!!_.debug,this.logLevel=_.logLevel||"none",this.shouldWrapGetUserMedia&&this.wrapGetUserMedia()}async addPeer(f,_){return console.warn("The addPeer() method has been deprecated, please use addConnection()"),this.addConnection({peerId:f,pc:_})}async addConnection(f){const{pc:_,peerId:g}=f;let{connectionId:S,remote:I}=f;if(I=typeof I=="boolean"?I:this.remote,!(_&&_ instanceof RTCPeerConnection))throw new Error("Missing argument 'pc' or is not of instance RTCPeerConnection");if(!g)throw new Error("Missing argument peerId");if(this.isEdge)throw new Error("Can't monitor peers in Edge at this time.");if(this.peersToMonitor[g]){if(S&&S in this.peersToMonitor[g])throw new Error(`We are already monitoring connection with id ${S}.`);for(let R in this.peersToMonitor[g]){const P=this.peersToMonitor[g][R];if(P.pc===_)throw new Error(`We are already monitoring peer with id ${g}.`);P.pc.connectionState==="closed"&&this.removeConnection({pc:P.pc})}}const M=_.getConfiguration();return M.iceServers&&M.iceServers.forEach(function(R){delete R.credential}),S||(S=y()),this.emitEvent({event:"addConnection",tag:"peer",peerId:g,connectionId:S,data:{options:f,peerConfiguration:M}}),this.monitorPeer({peerId:g,connectionId:S,pc:_,remote:I}),{connectionId:S}}getTimeline(f){return this.timeline=this.timeline.sort((_,g)=>_.timestamp.getTime()-g.timestamp.getTime()),f?this.timeline.filter(_=>_.tag===f):this.timeline}get logger(){const f=_=>{const g=["none","error","warn","info","debug"];return g.slice(0,g.indexOf(this.logLevel)+1).indexOf(_)>-1};return{error(..._){this.debug&&f("error")&&console.error("[webrtc-stats][error] ",..._)},warn(..._){this.debug&&f("warn")&&console.warn("[webrtc-stats][warn] ",..._)},info(..._){this.debug&&f("info")&&console.log("[webrtc-stats][info] ",..._)},debug(..._){this.debug&&f("debug")&&console.debug("[webrtc-stats][debug] ",..._)}}}removeConnection(f){let _,{connectionId:g,pc:S}=f;if(!S&&!g)throw new Error("Missing arguments. You need to either send pc or a connectionId.");if(g){if(typeof g!="string")throw new Error("connectionId must be a string.");for(let I in this.peersToMonitor)g in this.peersToMonitor[I]&&(S=this.peersToMonitor[I][g].pc,_=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 M in this.peersToMonitor[I])this.peersToMonitor[I][M].pc===S&&(g=M,_=I)}if(!S||!g)throw new Error("Could not find the desired connection.");return this.removePeerConnectionEventListeners(g,S),delete this.peersToMonitor[_][g],Object.values(this.peersToMonitor[_]).length===0&&delete this.peersToMonitor[_],{connectionId:g}}removeAllPeers(){for(let f in this.peersToMonitor)this.removePeer(f)}removePeer(f){if(this.logger.info(`Removing PeerConnection with id ${f}.`),this.peersToMonitor[f]){for(let _ in this.peersToMonitor[f]){let g=this.peersToMonitor[f][_].pc;this.removePeerConnectionEventListeners(_,g)}delete this.peersToMonitor[f]}}destroy(){this.removeAllPeers(),k.forEach(f=>{this.removeTrackEventListeners(f)}),k=[],this.shouldWrapGetUserMedia&&N&&(navigator.mediaDevices.getUserMedia=N)}monitorPeer(f){let{peerId:_,connectionId:g,pc:S,remote:I}=f;if(!S)return void this.logger.warn("Did not receive pc argument when calling monitorPeer()");const M={pc:S,connectionId:g,stream:null,stats:{parsed:null,raw:null},options:{remote:I}};if(this.peersToMonitor[_]){if(g in this.peersToMonitor[_])return void this.logger.warn(`Already watching connection with ID ${g}`);this.peersToMonitor[_][g]=M}else this.peersToMonitor[_]={[g]:M};this.addPeerConnectionEventListeners(_,g,S),this.numberOfMonitoredPeers===1&&(this.startStatsMonitoring(),this.startConnectionStateMonitoring())}startStatsMonitoring(){this.monitoringSetInterval||(this.monitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopStatsMonitoring(),this.getStats().then(f=>{f.forEach(_=>{this.emitEvent(_)})})},this._getStatsInterval))}stopStatsMonitoring(){this.monitoringSetInterval&&(window.clearInterval(this.monitoringSetInterval),this.monitoringSetInterval=0)}async getStats(f=null){this.logger.info(f?`Getting stats from peer ${f}`:"Getting stats from all peers");let _={};if(f){if(!this.peersToMonitor[f])throw new Error(`Cannot get stats. Peer with id ${f} does not exist`);_[f]=this.peersToMonitor[f]}else _=this.peersToMonitor;let g=[];for(const S in _)for(const I in _[S]){const M=_[S][I],R=M.pc;if(R&&!this.checkIfConnectionIsClosed(S,I,R))try{const P=this.getTimestamp(),O=R.getStats(null);if(O){const L=await O,V=this.getTimestamp(),$=A(L),W={remote:M.options.remote},q=x(L,M.stats.parsed,W),G={event:"stats",tag:"stats",peerId:S,connectionId:I,timeTaken:V-P,data:q};this.rawStats===!0&&(G.rawStats=L),this.statsObject===!0&&(G.statsObject=$),this.filteredStats===!0&&(G.filteredStats=this.filteroutStats($)),g.push(G),M.stats.parsed=q}else this.logger.error(`PeerConnection from peer ${S} did not return any stats data`)}catch(P){this.logger.error(P)}}return g}startConnectionStateMonitoring(){this.connectionMonitoringSetInterval=window.setInterval(()=>{this.numberOfMonitoredPeers||this.stopConnectionStateMonitoring();for(const f in this.peersToMonitor)for(const _ in this.peersToMonitor[f]){const g=this.peersToMonitor[f][_].pc;this.checkIfConnectionIsClosed(f,_,g)}},this.connectionMonitoringInterval)}checkIfConnectionIsClosed(f,_,g){const S=this.isConnectionClosed(g);if(S){this.removeConnection({pc:g});let I=g.connectionState==="closed"?"onconnectionstatechange":"oniceconnectionstatechange";this.emitEvent({event:I,peerId:f,connectionId:_,tag:"connection",data:"closed"})}return S}isConnectionClosed(f){return f.connectionState==="closed"||f.iceConnectionState==="closed"}stopConnectionStateMonitoring(){this.connectionMonitoringSetInterval&&(window.clearInterval(this.connectionMonitoringSetInterval),this.connectionMonitoringSetInterval=0)}wrapGetUserMedia(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)return void this.logger.warn("'navigator.mediaDevices.getUserMedia' is not available in browser. Will not wrap getUserMedia.");this.logger.info("Wrapping getUsermedia functions."),N=navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);const f=this.parseGetUserMedia.bind(this);navigator.mediaDevices.getUserMedia=(function(){return f({constraints:arguments[0]}),N.apply(navigator.mediaDevices,arguments).then(_=>(f({stream:_}),_),_=>(f({error:_}),Promise.reject(_)))}).bind(navigator.mediaDevices)}filteroutStats(f={}){const _={...f};for(const S in _){var g=_[S];this.statsToMonitor.includes(g.type)||delete _[S]}return _}get peerConnectionListeners(){return{icecandidate:(f,_,g,S)=>{this.logger.debug("[pc-event] icecandidate | peerId: ${peerId}",S),this.emitEvent({event:"onicecandidate",tag:"connection",peerId:f,connectionId:_,data:S.candidate})},track:(f,_,g,S)=>{this.logger.debug(`[pc-event] track | peerId: ${f}`,S);const I=S.track,M=S.streams[0];f in this.peersToMonitor&&_ in this.peersToMonitor[f]&&(this.peersToMonitor[f][_].stream=M),this.addTrackEventListeners(I,_),this.emitEvent({event:"ontrack",tag:"track",peerId:f,connectionId:_,data:{stream:M?this.getStreamDetails(M):null,track:I?this.getMediaTrackDetails(I):null,title:S.track.kind+":"+S.track.id+" "+S.streams.map(function(R){return"stream:"+R.id})}})},signalingstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] signalingstatechange | peerId: ${f}`),this.emitEvent({event:"onsignalingstatechange",tag:"connection",peerId:f,connectionId:_,data:{signalingState:g.signalingState,localDescription:g.localDescription,remoteDescription:g.remoteDescription}})},iceconnectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] iceconnectionstatechange | peerId: ${f}`),this.emitEvent({event:"oniceconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceConnectionState})},icegatheringstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] icegatheringstatechange | peerId: ${f}`),this.emitEvent({event:"onicegatheringstatechange",tag:"connection",peerId:f,connectionId:_,data:g.iceGatheringState})},icecandidateerror:(f,_,g,S)=>{this.logger.debug(`[pc-event] icecandidateerror | peerId: ${f}`),this.emitEvent({event:"onicecandidateerror",tag:"connection",peerId:f,connectionId:_,error:{errorCode:S.errorCode}})},connectionstatechange:(f,_,g)=>{this.logger.debug(`[pc-event] connectionstatechange | peerId: ${f}`),this.emitEvent({event:"onconnectionstatechange",tag:"connection",peerId:f,connectionId:_,data:g.connectionState})},negotiationneeded:(f,_,g)=>{this.logger.debug(`[pc-event] negotiationneeded | peerId: ${f}`),this.emitEvent({event:"onnegotiationneeded",tag:"connection",peerId:f,connectionId:_})},datachannel:(f,_,g,S)=>{this.logger.debug(`[pc-event] datachannel | peerId: ${f}`,S),this.emitEvent({event:"ondatachannel",tag:"datachannel",peerId:f,connectionId:_,data:S.channel})}}}addPeerConnectionEventListeners(f,_,g){this.logger.debug(`Adding event listeners for peer ${f} and connection ${_}.`),E[_]={},Object.keys(this.peerConnectionListeners).forEach(S=>{E[_][S]=this.peerConnectionListeners[S].bind(this,f,_,g),g.addEventListener(S,E[_][S],!1)})}parseGetUserMedia(f){try{const _={event:"getUserMedia",tag:"getUserMedia",data:{...f}};f.stream&&(_.data.details=this.parseStream(f.stream),f.stream.getTracks().map(g=>{this.addTrackEventListeners(g),k.push(g)})),this.emitEvent(_)}catch{}}parseStream(f){const _={audio:[],video:[]};return f.getTracks().forEach(g=>{_[g.kind].push(this.getMediaTrackDetails(g))}),_}getMediaTrackDetails(f){return{enabled:f.enabled,id:f.id,contentHint:f.contentHint,kind:f.kind,label:f.label,muted:f.muted,readyState:f.readyState,constructorName:f.constructor.name,capabilities:f.getCapabilities?f.getCapabilities():{},constraints:f.getConstraints?f.getConstraints():{},settings:f.getSettings?f.getSettings():{},_track:f}}getStreamDetails(f){return{active:f.active,id:f.id,_stream:f}}getTrackEventObject(f){return{mute:_=>{this.emitEvent({event:"mute",tag:"track",connectionId:f,data:{event:_}})},unmute:_=>{this.emitEvent({event:"unmute",tag:"track",connectionId:f,data:{event:_}})},overconstrained:_=>{this.emitEvent({event:"overconstrained",tag:"track",connectionId:f,data:{event:_}})},ended:_=>{this.emitEvent({event:"ended",tag:"track",connectionId:f,data:{event:_}}),this.removeTrackEventListeners(_.target)}}}addTrackEventListeners(f,_){E[f.id]={};const g=this.getTrackEventObject(_);Object.keys(g).forEach(S=>{E[f.id][S]=g[S].bind(this),f.addEventListener(S,E[f.id][S])}),E[f.id].readyState=setInterval(()=>{if(f.readyState==="ended"){let S=new CustomEvent("ended",{detail:{check:"readyState"}});f.dispatchEvent(S)}},1e3)}removeTrackEventListeners(f){if(f.id in E){const _=this.getTrackEventObject();Object.keys(_).forEach(g=>{f.removeEventListener(g,E[f.id][g])}),clearInterval(E[f.id].readyState),delete E[f.id]}}addToTimeline(f){this.timeline.push(f),this.emit("timeline",f)}emitEvent(f){const _={...f,timestamp:new Date};this.addToTimeline(_),_.tag&&this.emit(_.tag,_)}set getStatsInterval(f){if(!Number.isInteger(f))throw new Error(`getStatsInterval should be an integer, got: ${f}`);this._getStatsInterval=f,this.monitoringSetInterval&&(this.stopStatsMonitoring(),this.startStatsMonitoring())}get numberOfMonitoredPeers(){return Object.keys(this.peersToMonitor).length}removePeerConnectionEventListeners(f,_){f in E&&(Object.keys(this.peerConnectionListeners).forEach(g=>{_.removeEventListener(g,E[f][g],!1)}),delete E[f]),_.getSenders().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)}),_.getReceivers().forEach(g=>{g.track&&this.removeTrackEventListeners(g.track)})}getTimestamp(){return Date.now()}wrapGetDisplayMedia(){const f=this;if(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia){const _=navigator.mediaDevices.getDisplayMedia.bind(navigator.mediaDevices),g=function(){return f.debug("navigator.mediaDevices.getDisplayMedia",null,arguments[0]),_.apply(navigator.mediaDevices,arguments).then(function(S){return S},function(S){return f.debug("navigator.mediaDevices.getDisplayMediaOnFailure",null,S.name),Promise.reject(S)})};navigator.mediaDevices.getDisplayMedia=g.bind(navigator.mediaDevices)}}}});(Bs=lf)&&Bs.__esModule&&Object.prototype.hasOwnProperty.call(Bs,"default")&&Bs.default;var ew=lf.WebRTCStats;function tw(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 iw(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 nw extends Hi{constructor(e,i){super(),this.buildRequest({type:"debug_report_start",debug_report_id:e,debug_report_version:1,call_id:i})}}class sw extends Hi{constructor(e,i){super(),this.buildRequest({type:"debug_report_stop",debug_report_id:e,debug_report_version:1,call_id:i})}}class ow extends Hi{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 rw(t,e){const i=Bi();let n=!1;const s=new ew({getStatsInterval:1e3,rawStats:!1,statsObject:!0,filteredStats:!1,remote:!0,debug:!1,logLevel:"warn"}),o=r=>U(this,void 0,void 0,function*(){r.event==="stats"&&j(F.StatsFrame,function({data:a}){var l,c,u,d,h,p,m,v;const{audio:b,remote:y}=a,{audio:C}=y,T=(c=(l=C.inbound[0])===null||l===void 0?void 0:l.jitter)!==null&&c!==void 0?c:1/0,A=(d=(u=C.inbound[0])===null||u===void 0?void 0:u.roundTripTime)!==null&&d!==void 0?d:1/0,x=(p=(h=b.inbound[0])===null||h===void 0?void 0:h.packetsReceived)!==null&&p!==void 0?p:-1,N=(v=(m=b.inbound[0])===null||m===void 0?void 0:m.packetsLost)!==null&&v!==void 0?v:-1,E=tw({jitter:1e3*T,rtt:1e3*A,packetsLost:N,packetsReceived:x});return{jitter:T,rtt:A,mos:E,quality:iw(E),inboundAudio:b.inbound[0],outboundAudio:b.outbound[0],remoteInboundAudio:C.inbound[0],remoteOutboundAudio:C.outbound[0]}}(r),t.uuid),yield t.execute(new ow(i,e,r))});return{get isRunning(){return n},start:(r,a,l)=>U(this,void 0,void 0,function*(){if(n)w.debug(`[${e}] Stats reporter already running, skipping start`);else{yield t.execute(new nw(i,e)),s.on("timeline",o);try{yield s.addConnection({pc:r,peerId:a,connectionId:l}),n=!0}catch(c){w.error(`[${e}] Failed to start stats reporter:`,c),s.removeAllPeers(),s.destroy()}}}),stop:r=>U(this,void 0,void 0,function*(){const a=s.getTimeline();j(F.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 sw(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 cf=(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:gt.conferenceUpdate,call:t.calls[s],canvasInfo:aw(o),currentLayerIdx:r};switch(i){case"layer-info":{const l=Object.assign({action:ot.LayerInfo},a);j(F.Notification,l,t.uuid);break}case"layout-info":{const l=Object.assign({action:ot.LayoutInfo},a);j(F.Notification,l,t.uuid);break}}},aw=t=>{const e=JSON.stringify(t).replace(/memberID/g,"participantId").replace(/ID"/g,'Id"').replace(/POS"/g,'Pos"');return Oh(e)},df=["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"],lw={"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 le(t,e){return`telnyx:call:${t}:${e}`}function uf(t){try{const e=performance.getEntriesByName(t,"mark");return e.length>0?e[0].startTime:void 0}catch{return}}function hf(t,e,i){const n=uf(le(t,"new-call-start"));if(n===void 0)return{mode:e,direction:i,steps:[]};const s=[];for(const a of df){if(a==="new-call-start")continue;const l=uf(le(t,a));l!==void 0&&s.push({label:lw[a]||a,fromStart:l-n})}s.sort((a,l)=>a.fromStart-l.fromStart);const o=[];let r=0;for(const a of s)o.push({label:a.label,fromStart:a.fromStart,delta:a.fromStart-r}),r=a.fromStart;return{mode:e,direction:i,steps:o}}function na(t){for(const e of df)try{performance.clearMarks(le(t,e))}catch{w.warn("Clearing performance marks is failed")}}class pi{constructor(e,i,n,s,o){this.type=e,this.options=i,this.statsReporter=null,this.isIceRestarting=!1,this.iceDone=!1,this._negotiating=!1,this._prevConnectionState=null,this._restartedIceOnConnectionStateFailed=!1,this._sleepWakeupIntervalId=null,this._iceGatheringSafetyTimeout=null,this._gatheredCandidatesCount=0,this._firstMediaTrackMarked=!1,this._timingsCollected=!1,this._iceRestartTimeoutId=null,this.handleConnectionStateChange=()=>U(this,void 0,void 0,function*(){var r,a;if(!this.instance)return void w.debug("Connection state change ignored: instance is null");const{connectionState:l}=this.instance;if(w.info(`[${new Date().toISOString()}] Connection State changed: ${this._prevConnectionState} -> ${l}`),l!=="failed"&&l!=="disconnected"||(this.isDebugEnabled&&this.statsReporter&&function(c,u){return U(this,void 0,void 0,function*(){const d={connectionState:c.connectionState,previousConnectionState:u,iceConnectionState:c.iceConnectionState,iceGatheringState:c.iceGatheringState,signalingState:c.signalingState},h=c.getTransceivers();if(h.length>0){const p=h[0].sender,m=p==null?void 0:p.transport;m&&(d.dtlsState=m.state)}c.sctp&&(d.sctpState=c.sctp.state);try{const p=yield c.getStats();p.forEach(m=>{m.type==="candidate-pair"&&m.state==="succeeded"&&(d.candidatePairState=m.state,p.forEach(v=>{v.type==="local-candidate"&&v.id===m.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===m.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})})),m.type==="transport"&&(d.dtlsCipher=m.dtlsCipher,d.srtpCipher=m.srtpCipher,d.tlsVersion=m.tlsVersion,m.dtlsState&&(d.dtlsState=m.dtlsState))})}catch(p){w.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=je(eb);j(F.Warning,{warning:c,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}if(l==="failed"){const c=je(nb);j(F.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(le(this.options.id,"dtls-connected")),this.tryCollectTimings(),this._restartedIceOnConnectionStateFailed=!1),this._isTrickleIce()&&(l==="connecting"&&performance.mark(le(this.options.id,"peer-connection-connecting")),l==="connected"&&(this._clearIceGatheringSafetyTimeout(),performance.mark(le(this.options.id,"peer-connection-connected"))))}),this._handleIceConnectionStateChange=()=>{var r,a;if(!this.instance)return void w.debug("ICE connection state change ignored: instance is null");const l=this.instance.iceConnectionState;w.debug(`[${new Date().toISOString()}] ICE Connection State`,l),l==="connected"&&performance.mark(le(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;w.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)},w.debug("New Peer with type:",this.type,"Options:",this.options),this._constraints={offerToReceiveAudio:!0,offerToReceiveVideo:!!i.video},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?(w.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&&(w.warn("ICE restart: Modify exchange timed out, clearing isIceRestarting flag"),this.isIceRestarting=!1),this._iceRestartTimeoutId=null},pi.ICE_RESTART_TIMEOUT_MS),w.info("ICE restart: initiated by signaling health monitor"),{started:!0}):(w.debug("ICE restart: session not connected, skipping"),{started:!1,reason:"session not connected"}):(w.warn("ICE restart: no RTCPeerConnection instance"),{started:!1,reason:"no RTCPeerConnection instance"})}get isOffer(){return this.type===He.Offer}get isAnswer(){return this.type===He.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}get callEstablishmentTimings(){return this._callEstablishmentTimings}isConnectionHealthy(){return this.instance.connectionState==="connected"&&this.instance.iceConnectionState==="connected"&&this.instance.signalingState!=="closed"}startNegotiation(){performance.mark(le(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 U(this,void 0,void 0,function*(){performance.mark(le(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 Jt&&j(F.Error,{error:e,sessionId:this._session.sessionid},this.options.id)}_logTransceivers(){this.instance?(w.info("Number of transceivers:",this.instance.getTransceivers().length),this.instance.getTransceivers().forEach((e,i)=>{w.info(`>> Transceiver [${i}]:`,e.mid,e.direction,e.stopped),w.info(`>> Sender Params [${i}]:`,JSON.stringify(e.sender.getParameters(),null,2))})):w.warn("Cannot log transceivers: peer connection is null")}handleSignalingStateChangeEvent(){switch(w.info("signalingState:",this.instance.signalingState),this.instance.signalingState){case"stable":this._negotiating=!1;break;case"closed":j(F.PeerConnectionSignalingStateClosed,{sessionId:this._session.sessionid},this.options.id),this.instance&&(w.debug(`[${this.options.id}] Closing peer due to signalingState closed`),this.close());break;default:this._negotiating=!0}}handleNegotiationNeededEvent(){w.info("Negotiation needed event"),this.instance.signalingState!=="stable"||this._negotiating?w.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(le(this.options.id,"first-remote-media-track")),this._firstMediaTrackMarked=!0);const{streams:[i]}=e,{remoteElement:n,screenShare:s}=this.options;this.options.remoteStream=i,s===!1&&Ps(n,this.options.remoteStream,{callId:this.options.id,sessionId:this._session.sessionid,eventTarget:this._session.uuid})}tryCollectTimings(){if(this._timingsCollected||!(performance.getEntriesByName(le(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=hf(this.options.id,e,i);this._callEstablishmentTimings=n,function(s){const{mode:o,direction:r,steps:a}=s,l=`[CallTimings][${r}][${o}]`;if(a.length===0)return void w.info(`${l} No timing data collected`);const c=Math.max(...a.map(m=>m.label.length),4)+2,u=(m,v)=>{for(;m.length<v;)m+=" ";return m},d=(m,v)=>{for(;m.length<v;)m=" "+m;return m},h=u("Step",c)+d("Delta",14)+d("From Start",14);let p="";for(let m=0;m<h.length;m++)p+="-";w.info(`${l} Call establishment timing breakdown:`),w.info(`${l} ${h}`),w.info(`${l} ${p}`),w.info(`${l} ${u("Call Start",c)}${d("-",14)}${d("0.00ms",14)}`);for(const m of a){const v=m.delta.toFixed(2)+"ms",b=m.fromStart.toFixed(2)+"ms";w.info(`${l} ${u(m.label,c)}${d(v,14)}${d(b,14)}`)}w.info(`${l} ${p}`)}(n),na(this.options.id)}createPeerConnection(){return U(this,void 0,void 0,function*(){var e;if(this.instance=(e=this._config(),new window.RTCPeerConnection(e)),this.instance.onsignalingstatechange=this.handleSignalingStateChangeEvent,this.instance.onnegotiationneeded=this.handleNegotiationNeededEvent,this.instance.ontrack=this.handleTrackEvent,this.instance.addEventListener("connectionstatechange",this.handleConnectionStateChange),this.instance.addEventListener("iceconnectionstatechange",this._handleIceConnectionStateChange),this.instance.addEventListener("icegatheringstatechange",this._handleIceGatheringStateChange),this.instance.addEventListener("addstream",s=>{this.options.remoteStream=s.stream}),this._registerPeerEvents(this.instance),this._prevConnectionState=this.instance.connectionState,this.isAnswer&&(yield this._setRemoteDescription({sdp:this.options.remoteSdp,type:He.Offer}),performance.mark(le(this.options.id,"set-remote-description")),!this.instance))throw ae($r);const i=!!this.options.receiveOnlyAudio&&!this.options.audio;let n=null;if(this.options.localStream=yield this._retrieveLocalStream().catch(s=>U(this,void 0,void 0,function*(){const o=this._session.options.mediaPermissionsRecovery;if(o!=null&&o.enabled&&this._isAnswer()){let r=null,a=null;return yield new Promise((l,c)=>{a=setTimeout(()=>c(new Error("Media recovery flow timed out!")),o.timeout),j(F.Error,{error:ae(Vi(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(()=>U(this,void 0,void 0,function*(){var l;a&&(clearTimeout(a),a=null),r=yield this._retrieveLocalStream(),(l=o.onSuccess)===null||l===void 0||l.call(o)})).catch(l=>{var c;a&&(clearTimeout(a),a=null),n=l,(c=o.onError)===null||c===void 0||c.call(o,l)}),r}return n=s,null})),!this.instance)throw ae($r);if(!this.options.localStream&&!i)throw ae(n?Vi(n):Vr,n??void 0);performance.mark(le(this.options.id,"get-user-media")),this.options.mutedMicOnStart&&Ln(this.options.localStream)&&(w.info("Muting local audio tracks on start"),Us(this.options.localStream)),this.options.applyDesiredAudioMuteState&&this.options.applyDesiredAudioMuteState(),performance.mark(le(this.options.id,"peer-creation-end"))})}incrementGatheredCandidates(){this._gatheredCandidatesCount++}_startIceGatheringSafetyTimeout(){this._clearIceGatheringSafetyTimeout(),this._iceGatheringSafetyTimeout=setTimeout(()=>{if(this.instance){if(this._gatheredCandidatesCount===0){const e=je(ib);j(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}else if(this.instance.iceGatheringState!=="complete"){const e=je(tb);j(F.Warning,{warning:e,callId:this.options.id,sessionId:this._session.sessionid},this.options.id)}}},pi.ICE_GATHERING_SAFETY_TIMEOUT_MS)}_clearIceGatheringSafetyTimeout(){this._iceGatheringSafetyTimeout!==null&&(clearTimeout(this._iceGatheringSafetyTimeout),this._iceGatheringSafetyTimeout=null)}init(){var e;return U(this,void 0,void 0,function*(){if(yield this.createPeerConnection(),!this.instance)throw ae($r);this.isDebugEnabled&&(this.statsReporter=rw(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(Ln(n)){const o=n.getAudioTracks();let r=[...o];if(w.info("Local audio tracks: ",o),typeof this.options.audio=="object"&&o.forEach(c=>{w.info("Local audio tracks constraints: ",c.getConstraints())}),this.options.video){const c=n.getVideoTracks();r=[...o,...c],w.info("Local video tracks: ",c),typeof this.options.video=="object"&&c.forEach(u=>{w.info("Local video tracks constraints: ",u.getConstraints())})}const{audioCodecs:a,videoCodecs:l}=af(this.options.preferred_codecs);if(this.isOffer&&typeof this.instance.addTransceiver=="function"){const c={direction:"sendrecv",streams:[n]};r.forEach(u=>{u.kind==="audio"&&(this.options.userVariables.microphoneLabel=u.label),u.kind==="video"&&(this.options.userVariables.cameraLabel=u.label);const d=this.instance.addTransceiver(u,c);u.kind==="audio"&&a.length>0&&this._setCodecs(d,a),u.kind==="video"&&l.length>0&&this._setCodecs(d,l)})}else typeof this.instance.addTrack=="function"?(r.forEach(c=>{c.kind==="audio"&&(this.options.userVariables.microphoneLabel=c.label),c.kind==="video"&&(this.options.userVariables.cameraLabel=c.label),this.instance.addTrack(c,n)}),this.instance.getTransceivers().forEach(c=>{c.receiver.track.kind==="audio"&&a.length>0&&this._setCodecs(c,a),c.receiver.track.kind==="video"&&l.length>0&&this._setCodecs(c,l)})):this.instance.addStream(n);s===!1&&Ps(i,n)}else if(this.options.receiveOnlyAudio&&typeof this.instance.addTransceiver=="function"){const o=this.instance.addTransceiver("audio",{direction:"recvonly"});w.info("Added recvonly audio transceiver for receive-only mode",o);const{audioCodecs:r}=af(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);w.info("Add transceiver",e,i)}}_createOffer(){return U(this,void 0,void 0,function*(){if(this._isOffer()||this.isIceRestarting){this._constraints.offerToReceiveAudio=this.options.audio!==!1||!!this.options.receiveOnlyAudio,this._constraints.offerToReceiveVideo=!!this.options.video,w.info("_createOffer - this._constraints",this._constraints);try{const e=yield this.instance.createOffer(this._constraints);return performance.mark(le(this.options.id,"create-offer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createOffer error:",e),e instanceof Jt?e:ae(P0,e)}}})}_setRemoteDescription(e){return U(this,void 0,void 0,function*(){w.debug("Setting remote description",e);try{yield this.instance.setRemoteDescription(e)}catch(i){throw w.error("Peer _setRemoteDescription error:",i),ae(vh,i)}})}_createAnswer(){return U(this,void 0,void 0,function*(){if(this._isAnswer()){if(this.instance.signalingState!=="stable"&&this.instance.signalingState!=="have-remote-offer")return w.debug("Skipping negotiation, state:",this.instance.signalingState),w.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:He.Offer})]));this._logTransceivers();try{const e=yield this.instance.createAnswer();return performance.mark(le(this.options.id,"create-answer")),yield this._setLocalDescription(e),performance.mark(le(this.options.id,"set-local-description")),performance.mark(le(this.options.id,"ice-gathering-started")),e}catch(e){throw w.error("Peer _createAnswer error:",e),e instanceof Jt?e:ae(N0,e)}}})}_setLocalDescription(e){return U(this,void 0,void 0,function*(){try{yield this.instance.setLocalDescription(e)}catch(i){throw w.error("Peer _setLocalDescription error:",i),ae(F0,i)}})}_retrieveLocalStream(){return U(this,void 0,void 0,function*(){if(Ln(this.options.localStream))return this.options.localStream;const e=yield(i=this.options,U(void 0,void 0,void 0,function*(){let{audio:n=!0,micId:s,video:o=!1,camId:r}=i;const{micLabel:a="",camLabel:l=""}=i;return s&&(s=yield Fs(s,a,Lt.AudioIn).catch(()=>null),s&&(typeof n=="boolean"&&(n={}),n.deviceId={exact:s})),r&&(r=yield Fs(r,l,Lt.Video).catch(()=>null),r&&(typeof o=="boolean"&&(o={}),o.deviceId={exact:r})),{audio:n,video:o}}));var i;return Ns(e)})}_isOffer(){return this.type===He.Offer}_isAnswer(){return this.type===He.Answer}_isTrickleIce(){return this.options.trickleIce===!0}_config(){const{prefetchIceCandidates:e,forceRelayCandidate:i,iceServers:n}=this.options,s={bundlePolicy:"balanced",iceCandidatePoolSize:e?1:0,iceServers:n,iceTransportPolicy:i?"relay":"all"};return w.info("RTC config",s),s}restartStatsReporter(){return U(this,void 0,void 0,function*(){this.isDebugEnabled&&this.statsReporter&&(this.instance?this.statsReporter.isRunning?w.debug(`[${this.options.id}] Stats reporter already running, skipping restart`):(w.debug(`[${this.options.id}] Restarting stats reporter after reconnect`),yield this.statsReporter.start(this.instance,this._session.sessionid,this._session.sessionid)):w.debug(`[${this.options.id}] Cannot restart stats reporter - no peer connection instance`))})}close(){return U(this,void 0,void 0,function*(){na(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)})}}pi.ICE_GATHERING_SAFETY_TIMEOUT_MS=15e3,pi.ICE_RESTART_TIMEOUT_MS=15e3;const Vs=Qr;class ff{constructor(e,i){var n;this.session=e,this._callReportCollector=null,this._callRecorder=null,this._mediaDeviceCollector=null,this.id="",this.recoveredCallId="",this.state=z[z.New],this.prevState="",this.channels=[],this.role=Yr.Participant,this.extension=null,this._state=z.New,this._prevState=z.New,this.gotAnswer=!1,this.gotEarly=!1,this._lastSerno=0,this._targetNodeId=null,this._iceTimeout=null,this._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=y=>{const C=y<0||!this._lastSerno||this._lastSerno&&y===this._lastSerno+1;return C&&y>=0&&(this._lastSerno=y),C},this._doStats=()=>{this.peer&&this.peer.instance&&this._statsBindings.length!==0&&this.peer.instance.getStats().then(y=>{y.forEach(C=>{this._statsBindings.forEach(T=>{if(T.callback){if(T.constraints){for(const A in T.constraints)if(T.constraints.hasOwnProperty(A)&&T.constraints[A]!==C[A])return}T.callback(C)}})})})};const{iceServers:s,speaker:o,micId:r,micLabel:a,camId:l,camLabel:c,localElement:u,remoteElement:d,options:h,mediaConstraints:{audio:p,video:m},ringtoneFile:v,ringbackFile:b}=e;this.options=Object.assign({},jh,{audio:p,video:m,iceServers:i!=null&&i.iceServers&&Array.isArray(i.iceServers)?i.iceServers:s,localElement:u,remoteElement:d,micId:r,micLabel:a,camId:l,camLabel:c,speakerId:o,ringtoneFile:v,ringbackFile:b,debug:h.debug,debugOutput:h.debugOutput,trickleIce:h.trickleIce,prefetchIceCandidates:(n=h.prefetchIceCandidates)!==null&&n!==void 0?n:jh.prefetchIceCandidates,forceRelayCandidate:h.forceRelayCandidate,keepConnectionAliveOnSocketClose:h.keepConnectionAliveOnSocketClose,mutedMicOnStart:h.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=sf(this.options.ringtoneFile,"_ringtone"),this._ringback=sf(this.options.ringbackFile,"_ringback"))}get creatingPeer(){return this._creatingPeer}get signalingStateClosed(){return this._signalingStateClosed}_captureHangupCallerStack(){const e=new Error("Call.hangup caller").stack;return e?e.split(`
|
|
116
|
+
`).map(i=>i.trim()).filter(Boolean).slice(1,11):[]}get nodeId(){return this._targetNodeId}set nodeId(e){this._targetNodeId=e}get isVideoCall(){return!!this.options.video}get telnyxIDs(){return{telnyxCallControlId:this.options.telnyxCallControlId,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId}}get localStream(){return this.options.localStream}get remoteStream(){return this.options.remoteStream}get memberChannel(){return`conference-member.${this.id}`}get isAudioMuted(){return this._desiredAudioMuted}_getLocalAudioTrackId(){var e,i;return(i=(e=this.options.localStream)===null||e===void 0?void 0:e.getAudioTracks()[0])===null||i===void 0?void 0:i.id}_hasActiveUnmutedLocalAudioTrack(){const e=this.options.localStream;return!!(e!=null&&e.getAudioTracks)&&e.getAudioTracks().some(i=>i.enabled===!0&&i.muted!==!0&&i.readyState==="live")}shouldForceRelayCandidateForRecovery(){var e,i;return!!this.options.forceRelayCandidate||!!this.recoveredCallId&&(i=(e=this._callReportCollector)===null||e===void 0?void 0:e.shouldForceRelayCandidateForRecovery())!==null&&i!==void 0&&i}invite(){return U(this,void 0,void 0,function*(){this._creatingPeer=!0,this.direction=Dt.Outbound,this.options.trickleIce&&this._resetTrickleIceCandidateState(),performance.mark(le(this.id,"new-peer")),this.peer=new pi(He.Offer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(e){w.error("Peer init failed, aborting call",e),this._creatingPeer=!1;const i=e instanceof Jt?e:ae(Ch,e instanceof Error?e:void 0);return j(F.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 U(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&&w.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=je(ob);return j(F.Warning,{warning:d,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),void w.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(le(this.id,"answer-called")),this._creatingPeer=!0,this.stopRingtone(),this.direction=Dt.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(le(this.id,"new-peer")),this.peer=new pi(He.Answer,this.options,this.session,this._onTrickleIceSdp,this._registerPeerEvents);try{yield this.peer.init()}catch(d){w.error("Peer init failed, aborting call",d),this._creatingPeer=!1;const h=d instanceof Jt?d:ae(Ch,d instanceof Error?d:void 0);return j(F.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(){of(this._ringtone)}stopRingtone(){rf(this._ringtone)}playRingback(){of(this._ringback)}stopRingback(){rf(this._ringback)}hangup(e,i){var n,s,o,r,a,l;return U(this,void 0,void 0,function*(){const c=e||{},u=i!==!1,d=this.state,h=this.prevState,p=this._captureHangupCallerStack(),m=c.initiator||"app:call.hangup",v=this._state<z.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:[]],w.debug(`[${this.id}] hangup() invoked`,{callId:this.id,execute:u,state:d,prevState:h,cause:this.cause,causeCode:this.causeCode,initiator:m,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(z.Recovering),void this._finalize();if(this.setState(z.Hangup),this.stopRingtone(),this.stopRingback(),u){const b=new $b({sipCode:this.sipCode,sip_call_id:this.sipCallId,sessid:this.session.sessionid,dialogParams:this.options,cause:this.cause,causeCode:this.causeCode});let y;try{yield Promise.race([this._execute(b),new Promise(C=>{y=setTimeout(()=>{w.warn(`[${this.id}] BYE execution timed out after 5000ms — proceeding to destroy.`),C()},5e3)})])}catch(C){w.error("telnyx_rtc.bye failed!",C);const T=ae(V0,C);j(F.Error,{error:T,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}finally{y&&clearTimeout(y)}}w.debug(`[${this.id}] Closing peer from hangup`),(l=this.peer)===null||l===void 0||l.close(),this.setState(z.Destroy)})}hold(){const e=new Ms({sessid:this.session.sessionid,action:$i.Hold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}unhold(){const e=new Ms({sessid:this.session.sessionid,action:$i.Unhold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}toggleHold(){const e=new Ms({sessid:this.session.sessionid,action:$i.ToggleHold,dialogParams:this.options});return this._execute(e).then(this._handleChangeHoldStateSuccess.bind(this)).catch(this._handleChangeHoldStateError.bind(this))}dtmf(e){const i=new Qh({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 Qh({sessid:this.session.sessionid,msg:n,dialogParams:this.options});this._execute(s)}muteAudio(){w.debug("muteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!0,Us(this.options.localStream)}unmuteAudio(){w.debug("unmuteAudio called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!1,ia(this.options.localStream)}_applyDesiredAudioMuteState(){w.debug("applyDesiredAudioMuteState called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted?Us(this.options.localStream):ia(this.options.localStream)}toggleAudioMute(){w.debug("toggleAudioMute called",{callId:this.id,previousAudioState:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),this._desiredAudioMuted=!this._desiredAudioMuted,this._applyDesiredAudioMuteState()}setAudioInDevice(e,i=this._desiredAudioMuted){var n,s,o;return U(this,void 0,void 0,function*(){const r=!!i,{instance:a}=this.peer,l=a.getSenders().find(({track:{kind:h}})=>h==="audio");if(!l)return w.warn("Skipping audio input device change: no audio sender found",{callId:this.id,deviceId:e,audioMuted:this._desiredAudioMuted,audioTrackId:this._getLocalAudioTrackId()}),void j(F.Warning,{warning:je(ab),callId:this.id,deviceId:e,sessionId:this.session.sessionid},((n=this.options)===null||n===void 0?void 0:n.id)||this.id);let c;w.debug("Starting audio input device change",{callId:this.id,state:this.state,deviceId:e,previousDesiredAudioMuted:this._desiredAudioMuted,newDesiredMuted:r,currentSenderTrack:Zr(l.track),localTracks:nf(this.options.localStream)});try{c=yield Os({audio:{deviceId:{exact:e}}})}catch(h){const p=ae(Vi(h),h);return void j(F.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=ae(Vi(h),h);return j(F.MediaError,p,((o=this.options)===null||o===void 0?void 0:o.id)||this.id),void c.getTracks().forEach(m=>m.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,w.debug("Finished audio input device change",{callId:this.id,state:this.state,deviceId:e,desiredAudioMuted:this._desiredAudioMuted,senderTrack:Zr(l.track),localTracks:nf(this.options.localStream)})})}muteVideo(){var e;e=this.options.localStream,Gi(e,"video",!1)}unmuteVideo(){var e;e=this.options.localStream,Gi(e,"video",!0)}toggleVideoMute(){var e;e=this.options.localStream,Gi(e,"video",null)}setVideoDevice(e){return U(this,void 0,void 0,function*(){const{instance:i}=this.peer,n=i.getSenders().find(({track:{kind:s}})=>s==="video");if(n){const s=yield Os({video:{deviceId:{exact:e}}}),o=s.getVideoTracks()[0];n.replaceTrack(o);const{localElement:r,localStream:a}=this.options;Ps(r,s),this.options.camId=e,a.getAudioTracks().forEach(l=>s.addTrack(l)),a.getVideoTracks().forEach(l=>l.stop()),this.options.localStream=s,this._applyDesiredAudioMuteState()}})}deaf(){Us(this.options.remoteStream)}undeaf(){ia(this.options.remoteStream)}toggleDeaf(){var e;e=this.options.remoteStream,Gi(e,"audio",null)}setBandwidthEncodingsMaxBps(e,i){return U(this,void 0,void 0,function*(){if(!this||!this.peer)return void w.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 w.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"}]),w.info("Parameters: ",r),w.info("Setting max ",i==="audio"?"audio":"video"," bandwidth to: ",e," [bps]"),r.encodings[0].maxBitrate=e,yield o.setParameters(r).then(()=>{w.info(i==="audio"?"New audio":"New video"," bandwidth settings in use: ",o.getParameters())}).catch(a=>w.error(a))}else w.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[z.Hangup,z.Destroy,z.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=z[this._state].toLowerCase(),this.prevState=z[this._prevState].toLowerCase(),w.debug(`Call ${this.id} state change from ${this.prevState} to ${this.state}`),this._dispatchNotification({type:gt.callUpdate,call:this}),e){case z.Purge:w.info(`[${this.id}] Entering Purge state.`);break;case z.Active:if(performance.mark(le(this.id,"call-active")),(i=this.peer)===null||i===void 0||i.tryCollectTimings(),this._isRecovering&&(this._isRecovering=!1,w.debug(`[${this.id}] Recovery complete, call is active`)),this._wasHeldBeforeRecovery&&(w.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&&ef(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 Zb,this._mediaDeviceCollector.logDevicesAtStart();break;case z.Held:(l=this._callReportCollector)===null||l===void 0||l.setHeld(!0);break;case z.Destroy:this._finalize()}}handleMessage(e){const{method:i,params:n}=e;switch(i){case ie.Answer:if(performance.mark(le(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>=z.Active)return;this._state>=z.Early&&this.setState(z.Active),this.gotEarly||this._onRemoteSdp(n.sdp),this.stopRingback(),this.stopRingtone();break;case ie.Media:if(performance.mark(le(this.id,"telnyx-rtc-media")),this._state>=z.Early)return;this.gotEarly=!0,this._onRemoteSdp(n.sdp);break;case ie.Display:{const{display_name:o,display_number:r,display_direction:a}=n;this.extension=r;const l=a===Dt.Inbound?Dt.Outbound:Dt.Inbound,c={type:gt[i],call:this,displayName:o,displayNumber:r,displayDirection:l};j(F.Notification,c,this.id)||j(F.Notification,c,this.session.uuid);break}case ie.Candidate:this._addIceCandidate(n);break;case ie.Info:case ie.Event:{const o=Object.assign(Object.assign({},n),{type:gt.generic,call:this});j(F.Notification,o,this.id)||j(F.Notification,o,this.session.uuid);break}case ie.Ringing:performance.mark(le(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 ie.Bye:const s=n.client_state||n.clientState;s&&(this.options.clientState=s),this.stopRingback(),this.stopRingtone(),this.hangup(Object.assign(Object.assign({},n),{initiator:"remote:telnyx_rtc.bye"}),!1)}}handleConferenceUpdate(e,i){return U(this,void 0,void 0,function*(){if(!this._checkConferenceSerno(e.wireSerno)&&e.name!==i.laName)return w.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:ot.Join,conferenceName:u,participantId:Number(d),role:h}),a&&(yield this._subscribeConferenceChat(a)),l&&(yield this._subscribeConferenceInfo(l));const p=[];for(const m in s)p.push(Object.assign({callId:s[m][0],index:Number(m)},Is(s[m][1])));this._dispatchConferenceUpdate({action:ot.Bootstrap,participants:p});break}case"add":this._dispatchConferenceUpdate(Object.assign({action:ot.Add,callId:o,index:r},Is(s)));break;case"modify":this._dispatchConferenceUpdate(Object.assign({action:ot.Modify,callId:o,index:r},Is(s)));break;case"del":this._dispatchConferenceUpdate(Object.assign({action:ot.Delete,callId:o,index:r},Is(s)));break;case"clear":this._dispatchConferenceUpdate({action:ot.Clear});break;default:this._dispatchConferenceUpdate({action:n,data:s,callId:o,index:r})}})}_addChannel(e){this.channels.includes(e)||this.channels.push(e);const i=this.session.relayProtocol;this.session._existsSubscription(i,e)&&(this.session.subscriptions[i][e]=Object.assign(Object.assign({},this.session.subscriptions[i][e]),{callId:this.id}))}_subscribeConferenceChat(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{direction:o,from:r,fromDisplay:a,message:l,type:c}=s.data;this._dispatchConferenceUpdate({action:ot.ChatMessage,direction:o,participantNumber:r,participantName:a,messageText:l,messageType:c,messageId:s.eventSerno})}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfChat subscription error:",s)});ea(n,e)&&(this._addChannel(e),Object.defineProperties(this,{sendChatMessage:{configurable:!0,value:(s,o)=>{this.session.vertoBroadcast({nodeId:this.nodeId,channel:e,data:{action:"send",message:s,type:o}})}}}))})}_subscribeConferenceInfo(e){return U(this,void 0,void 0,function*(){const i={nodeId:this.nodeId,channels:[e],handler:s=>{const{eventData:o}=s;o.contentType==="layout-info"?(o.callID=this.id,cf(this.session,o)):w.error("Conference-Info unknown contentType",s)}},n=yield this.session.vertoSubscribe(i).catch(s=>{w.error("ConfInfo subscription error:",s)});ea(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(z.Active):this.setState(z.Held),!0}_handleChangeHoldStateError(e){w.error(`Failed to ${e.action} on call ${this.id}`);const i=ae(U0,e);return j(F.Error,{error:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),!1}_sendIceRestartModify(e,i={}){const n=new Ms(Object.assign(Object.assign({sessid:this.session.sessionid,action:$i.UpdateMedia,callID:this.options.id,sdp:e},i.trickle?{trickle:!0}:{}),{dialogParams:this.options}));w.info(`ICE restart: sending ${i.trickle?"trickle ":""}Modify with new offer SDP`),this._execute(n).then(s=>U(this,void 0,void 0,function*(){var o;s!=null&&s.sdp?(w.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;w.error(e,i),(n=this.peer)===null||n===void 0||n.finishIceRestart();const r=ae(z0,i);j(F.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 U(this,void 0,void 0,function*(){const i=new RTCSessionDescription({sdp:e,type:He.Answer});yield this.peer.instance.setRemoteDescription(i).then(()=>{performance.mark(le(this.id,"set-remote-description")),this.options.trickleIce&&(this._isRemoteDescriptionSet=!0,this._flushPendingTrickleIceCandidates()),this.gotEarly&&this.setState(z.Early),this.gotAnswer&&this._state!==z.Held&&this.setState(z.Active)}).catch(n=>U(this,void 0,void 0,function*(){w.error("Call setRemoteDescription Error: ",n);const s=ae(vh,n);j(F.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){w.error("Error during hangup after setRemoteDescription failure:",o)}}))})}_warnIfOnlyHostIceCandidates(e){if(!(n=>{if(!n)return!1;const s=n.split(/\r?\n/).filter(o=>/^a=candidate:/i.test(o));return s.length>0&&s.every(o=>/\styp\s+host(?:\s|$)/i.test(o))})(e))return;const i=je(sb);w.warn(`[${this.id}] Warning ${i.code}: ${i.message}`),j(F.Warning,{warning:i,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onIceSdp(e){var i,n,s;if(this._iceTimeout&&clearTimeout(this._iceTimeout),this._iceTimeout=null,this._isTerminatingOrTerminated())return;if(this.peer&&(this.peer.iceDone=!0),!e)return void w.warn("localDescription is null — PeerConnection may have been closed during ICE gathering");const{sdp:o,type:r}=e;(n=(i=this.peer)===null||i===void 0?void 0:i.instance)===null||n===void 0||n.removeEventListener("icecandidate",this._onIce),this._warnIfOnlyHostIceCandidates(o),performance.mark(le(this.id,"ice-gathering-end"));let a=null;const l={sessid:this.session.sessionid,sdp:o,dialogParams:this.options,"User-Agent":`Web-${Vs}`};if(!((s=this.peer)===null||s===void 0)&&s.isIceRestarting)this._sendIceRestartModify(o);else{switch(r){case He.Offer:this.setState(z.Requesting),a=new Yh(l);break;case He.Answer:this._isRecovering||this.setState(z.Answering),a=this.options.attach===!0?new Jh(l):new Xh(l);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(a).then(c=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${r} response because call is ${this.state}`);const{node_id:u=null}=c;this._targetNodeId=u,r===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(c=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${r} error:`,c);const u=ae(_h,c);j(F.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){w.error("Error during hangup after SDP send failure:",d)}}))}}_onTrickleIceSdp(e){var i;if(this._isTerminatingOrTerminated())return;if(!e)return w.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-${Vs}`};if(!((i=this.peer)===null||i===void 0)&&i.isIceRestarting)this._sendIceRestartModify(n,{trickle:!0});else{switch(s){case He.Offer:this.setState(z.Requesting),o=new Yh(r);break;case He.Answer:this._isRecovering||this.setState(z.Answering),o=this.options.attach===!0?new Jh(r):new Xh(r);break;default:return w.error(`${this.id} - Unknown local SDP type:`,e),void this.hangup({initiator:"sdk:unknown-local-sdp-type"},!1)}performance.mark(le(this.id,"send-sdp")),this._execute(o).then(a=>{if(this._isTerminatingOrTerminated())return void w.debug(`[${this.id}] Ignoring ${s} response because call is ${this.state}`);const{node_id:l=null}=a;this._targetNodeId=l,s===He.Offer?this.setState(z.Trying):this._wasHeldBeforeRecovery&&this._isRecovering?this.setState(z.Held):this.setState(z.Active)}).catch(a=>U(this,void 0,void 0,function*(){w.error(`${this.id} - Sending ${s} error:`,a);const l=ae(_h,a);j(F.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){w.error("Error during hangup after SDP send failure:",c)}}))}}_onIce(e){var i;if(this._isTerminatingOrTerminated())return;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?(w.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,n,s,o;this._isTerminatingOrTerminated()||(e.candidate&&e.candidate.candidate?(w.debug("RTCPeer Candidate:",e.candidate),(i=this.peer)===null||i===void 0||i.incrementGatheredCandidates(),this._trackCandidateMarks(e.candidate),this._sendIceCandidate(e.candidate)):(e.candidate===null&&this._warnIfOnlyHostIceCandidates((o=(s=(n=this.peer)===null||n===void 0?void 0:n.instance)===null||s===void 0?void 0:s.localDescription)===null||o===void 0?void 0:o.sdp),this._sendEndOfCandidates()))}_sendIceCandidate(e){const i=new jb({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 w.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(()=>{w.debug("Successfully added ICE candidate:",e)}).catch(n=>{w.error("Failed to add ICE candidate:",n,e)})}_sendEndOfCandidates(){const e=new Hb({sessid:this.session.sessionid,endOfCandidates:!0,dialogParams:this.options});this._execute(e)}_trackCandidateMarks(e){var i;if(this._firstCandidateSent||(performance.mark(le(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(le(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=>{w.debug("ICE gathering state changed:",e.iceGatheringState,i),e.iceGatheringState==="complete"&&(w.debug("Finished gathering candidates"),performance.mark(le(this.id,"ice-gathering-completed")))},e.onicecandidateerror=i=>{var n;if(w.debug("ICE candidate error:",i),(n=this.peer)===null||n===void 0?void 0:n.statsReporter){const s=function(o,r){var a,l;return{errorCode:o.errorCode,errorText:o.errorText,url:o.url,address:o.address,port:o.port,connectionState:r.connectionState,iceConnectionState:r.iceConnectionState,iceGatheringState:r.iceGatheringState,signalingState:r.signalingState,localDescriptionType:(a=r.localDescription)===null||a===void 0?void 0:a.type,remoteDescriptionType:(l=r.remoteDescription)===null||l===void 0?void 0:l.type}}(i,e);this.peer.statsReporter.reportIceCandidateError(s)}},e.addEventListener("addstream",i=>{this.options.remoteStream=i.stream}),e.addEventListener("track",i=>{this.options.remoteStream=i.streams[0];const{remoteElement:n,remoteStream:s,screenShare:o}=this.options;o===!1&&Ps(n,s,{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:gt.userMediaError,error:s,call:this,errorName:i,errorMessage:n}),w.error(`Media error (${i}): ${n}`,e),j(F.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:gt.peerConnectionFailureError,error:e.error}),w.error("Peer connection failure error"),e.warning&&j(F.Warning,{warning:e.warning,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}_onPeerConnectionSignalingStateClosed(e){this._signalingStateClosed=!0,this._dispatchNotification(Object.assign({type:gt.signalingStateClosed},e)),w.debug("Peer connection signaling state closed, call is not recoverable")}_dispatchConferenceUpdate(e){this._dispatchNotification(Object.assign({type:gt.conferenceUpdate,call:this},e))}_dispatchNotification(e){this.options.screenShare!==!0&&(j(F.Notification,e,this.id,!1)||j(F.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=je(cb);return j(F.Warning,{warning:n,callId:this.id,activeCallId:i.id,sessionId:this.session.sessionid},this.session.uuid),w.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:m,recoveredCallId:v,wasHeldBeforeRecovery:b}=this.options;var y;this.options.id=d?d.toString():Bi(),this.id=this.options.id,v&&(this.recoveredCallId=v,this._isRecovering=!0,this._wasHeldBeforeRecovery=!!b),h&&(y=h,Object.keys(y).length!==0)||(this.options.userVariables=this.session.options.userVariables||{}),p||(this.options.remoteCallerNumber=this.options.destinationNumber),this.session.calls[this.id]=this,Qt(F.MediaError,this._onMediaError,this.id),Qt(F.PeerConnectionFailureError,this._onPeerConnectionFailureError,this.id),Qt(F.PeerConnectionSignalingStateClosed,this._onPeerConnectionSignalingStateClosed,this.id),As(m)&&Qt(F.Notification,m.bind(this),this.id);const C=this.session.options.enableCallReports!==!1,T=this.session.options.callReportInterval||5e3,A=(e=this.session.options.callReportFlushInterval)!==null&&e!==void 0?e:18e4,x=this.session.options.debugLogLevel||"debug",N=this.session.options.debugLogMaxEntries||1e3;if(C&&(this._callReportCollector=new ue({enabled:!0,interval:T,intermediateReportInterval:A},{enabled:!0,level:x,maxEntries:N}),this._callReportCollector.onFlushNeeded=()=>{this._flushIntermediateReport()},this._callReportCollector.onWarning=E=>{var k,f,_,g;j(F.Warning,{warning:E,callId:this.id,sessionId:this.session.sessionid},this.session.uuid),E.code===Hr&&this._state!==z.Held?(f=(k=this.session).reportNoRtp)===null||f===void 0||f.call(k,this.id,"inbound"):E.code===kh&&this._state!==z.Held&&this._hasActiveUnmutedLocalAudioTrack()&&((g=(_=this.session).reportNoRtp)===null||g===void 0||g.call(_,this.id,"outbound"))}),this.session.options.enableCallRecording===!0){const E={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:$h,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"},k={callId:this.id,callReportId:(a=this.session.callReportId)!==null&&a!==void 0?a:"",voiceSdkId:this._getCallReportVoiceSdkId()};this._callRecorder=new ze(E,k);const f=(l=this.session.connection)===null||l===void 0?void 0:l.host;f&&this._callRecorder._setHost(f),this._callRecorder.onWarning=_=>{j(F.Warning,{warning:_,callId:this.id,sessionId:this.session.sessionid},this.session.uuid)}}this._isRecovering?this.setState(z.Recovering):this.setState(z.New),w.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)}getEstablishmentTimings(){var e,i,n;const s=(e=this.peer)===null||e===void 0?void 0:e.callEstablishmentTimings;if(s)return s;const o=!((i=this.options)===null||i===void 0)&&i.trickleIce&&!(!((n=this.peer)===null||n===void 0)&&n.isIceRestarting)?"trickle":"non-trickle";return hf(this.id,o,this.direction)}_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(),na(this.id),w.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;Mn(s),Mn(o),Zh(r,s),Zh(a,o),Mt(F.MediaError,null,this.id),Mt(F.PeerConnectionFailureError,null,this.id),Mt(F.PeerConnectionSignalingStateClosed,null,this.id),this.session.calls[this.id]=null,delete this.session.calls[this.id];const l=this._postCallReport().catch(c=>{w.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,m=p.anonymous_login;return{authentication:Object.assign({type:this._getAuthenticationType()},m?{anonymousLogin:{targetType:m.target_type,targetId:m.target_id,targetVersionId:m.target_version_id,targetParams:this._sanitizeClientOption(m.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 w.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 w.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===Dt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Vs,clientSummary:this._getClientSummary()},r=this._callReportCollector.flush(o,e);if(!r)return;w.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=>{w.error("Failed to post intermediate call report segment",{error:u})});this.session.trackCallReportUpload(c)}_postCallReport(){var e,i,n,s;return U(this,void 0,void 0,function*(){if(!this._callReportCollector)return void w.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=>{w.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 w.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===Dt.Inbound?"inbound":"outbound",state:this.state,telnyxSessionId:this.options.telnyxSessionId,telnyxLegId:this.options.telnyxLegId,sdkVersion:Vs,clientSummary:this._getClientSummary()},a=(i=this.session.connection)===null||i===void 0?void 0:i.host;if(!a)return void w.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 w.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),w.info("Stats started")}_stopStats(){this._statsIntervalId&&(clearInterval(this._statsIntervalId),this._statsIntervalId=null),w.debug("Stats stopped")}}ff.setStateTelnyx=t=>{if(t){switch(t._state){case z.Recovering:t.state="recovering";break;case z.Requesting:case z.Trying:case z.Early:t.state="connecting";break;case z.Active:t.state="active";break;case z.Held:t.state="held";break;case z.Hangup:case z.Destroy:t.state="done";break;case z.Answering:t.state="ringing";break;case z.New:t.state="new"}return t}};class gi extends ff{constructor(){super(...arguments),this._statsInterval=null,this.sendConversationMessage=(e,i)=>this.session.execute(new Jb(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 Qb(e);this.session.connection.sendRawText(JSON.stringify(i.request))}}hangup(e={},i=!0){const n=Object.create(null,{hangup:{get:()=>super.hangup}});return U(this,void 0,void 0,function*(){this.screenShare instanceof gi&&(yield this.screenShare.hangup(e,i)),yield n.hangup.call(this,e,i)})}startScreenShare(e){return U(this,void 0,void 0,function*(){const i=yield(n={video:!0},navigator.mediaDevices.getDisplayMedia(n));var n;i.getTracks().forEach(c=>{c.addEventListener("ended",()=>U(this,void 0,void 0,function*(){this.screenShare&&(yield this.screenShare.hangup({initiator:"sdk:screenshare-track-ended"}))}))});const{remoteCallerName:s,remoteCallerNumber:o,callerName:r,callerNumber:a}=this.options,l=Object.assign({screenShare:!0,localStream:i,destinationNumber:`${this.extension}-screen`,remoteCallerName:s,remoteCallerNumber:`${o}-screen`,callerName:`${r} (Screen)`,callerNumber:`${a} (Screen)`},e);return this.screenShare=new gi(this.session,l),this.screenShare.invite(),this.screenShare})}stopScreenShare(){return U(this,void 0,void 0,function*(){this.screenShare instanceof gi&&(yield this.screenShare.hangup({initiator:"app:stopScreenShare"}))})}setAudioOutDevice(e){return U(this,void 0,void 0,function*(){this.options.speakerId=e;const{remoteElement:i,speakerId:n}=this.options;return!(!i||!n)&&ef(i,n)})}_finalize(){this._stats(!1),super._finalize()}_stats(e=!0){if(e===!1)return clearInterval(this._statsInterval);this._statsInterval=window.setInterval(()=>U(this,void 0,void 0,function*(){const i=yield this.peer.instance.getStats(null);let n="";const s=["certificate","codec","peer-connection","stream","local-candidate","remote-candidate"],o=["id","type","timestamp"];i.forEach(r=>{s.includes(r.type)||(n+=`
|
|
117
117
|
${r.type}
|
|
118
118
|
`,Object.keys(r).forEach(a=>{o.includes(a)||(n+=` ${a}: ${r[a]}
|
|
119
|
-
`)}))}),w.info(n)}),2e3)}}class Ls extends oi{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=>Ls.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=Pe(tb),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};U(P.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),w.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 B(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return B(this,void 0,void 0,function*(){w.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return B(this,void 0,void 0,function*(){try{const n=yield Is({audio:e,video:i});return kn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return B(this,void 0,void 0,function*(){w.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),w.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 B(this,void 0,void 0,function*(){w.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(Nh(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 En().catch(e=>{const i=ae(Li(e),e);return U(P.MediaError,i,this.uuid),[]})}getVideoDevices(){return En(Ct.Video).catch(e=>(U(P.MediaError,e,this.uuid),[]))}getAudioInDevices(){return En(Ct.AudioIn).catch(e=>{const i=ae(Li(e),e);return U(P.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return En(Ct.AudioOut).catch(e=>(w.error("getAudioOutDevices",e),U(P.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return Rs(e,i,n)}getDeviceResolutions(e){return B(this,void 0,void 0,function*(){try{return yield(i=>B(void 0,void 0,void 0,function*(){const n=[],s=yield Is({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<zh.length;r++){const[a,l]=zh[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 kn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return B(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=rh(e,["micId","micLabel"]);return jb(s),this._audioConstraints=yield((o,r,a,l)=>B(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield Rs(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?gb:pb}}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=bn(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=bn(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 Fb({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 B(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Bb({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=zr(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 B(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new Ub({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=zr(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return ai.setStateTelnyx(e)}}Ls.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class rf{constructor(e,i){this.code=i,this.message=e}}class iw{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new Mb(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;const{session:d}=this;d.setPingReceived();const{id:h,method:g,params:m={},voice_sdk_id:v}=e,b=m==null?void 0:m.callID,y=m==null?void 0:m.eventChannel,C=m==null?void 0:m.eventType,k=d.calls[b],A=(i=k==null?void 0:k.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),R=new Set(Object.keys(d.calls));if(Array.isArray(m==null?void 0:m.reattached_sessions)&&R.size){w.debug(`Reattach: active call IDs before cleanup check: [${Array.from(R).join(", ")}].`);const p=m.reattached_sessions.length===0,_=m.reattached_sessions.some(f=>R.has(f));if(p||!_)for(const f of Object.keys(d.calls)){const S=d.calls[f];w.debug(`Session not reattached — terminating active call ${f} `);const I=ae(ph);U(P.Error,{error:I,callId:f,sessionId:d.sessionid},d.uuid),S.hangup({},!1)}}if(Array.isArray(m==null?void 0:m.reattached_sessions)&&d.sessionid){const p=Dh();if(p&&p.calls.length>0)if(p.sessionId!==d.sessionid)w.debug(`Recovery markers were saved for a different sessid (saved=${p.sessionId}, current=${d.sessionid}) — ignoring all.`),si();else{const _=new Set(m.reattached_sessions),f=[];for(const S of p.calls)try{if(_.has(S.id)){w.debug(`Recovery marker for call ${S.id} was reattached — keeping for Attach element restore.`),f.push(S);continue}w.info(`Recovery marker for call ${S.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=ae(ph);U(P.Error,{error:I,callId:S.id,sessionId:d.sessionid,customHeaders:S.customHeaders},d.uuid)}catch(I){w.debug(`Recovery marker for a saved call failed to process (callId=${S==null?void 0:S.id}) — skipping: ${I instanceof Error?I.message:String(I)}`),f.push(S)}Lh(f,p.sessionId,p.storedAt)}}if(C==="channelPvtData")return this._handlePvtEvent(m.pvtData);const D=({recoveredCallId:p,forceRelayCandidateForRecovery:_,mutedMicOnStart:f,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M}={})=>{var x,N,O,F,V,$;const Q={audio:!0,video:d.options.video,remoteSdp:m.sdp,destinationNumber:m.callee_id_number,remoteCallerName:m.caller_id_name,remoteCallerNumber:m.caller_id_number,callerName:m.callee_id_name,callerNumber:m.callee_id_number,attach:g===ee.Attach,mediaSettings:m.mediaSettings,debug:(x=d.options.debug)!==null&&x!==void 0&&x,debugOutput:(N=d.options.debugOutput)!==null&&N!==void 0?N:"socket",trickleIce:(O=d.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(F=d.options.prefetchIceCandidates)!==null&&F!==void 0&&F,forceRelayCandidate:typeof _=="boolean"?_:(V=d.options.forceRelayCandidate)!==null&&V!==void 0&&V,keepConnectionAliveOnSocketClose:($=d.options.keepConnectionAliveOnSocketClose)!==null&&$!==void 0&&$,mutedMicOnStart:f??d.options.mutedMicOnStart};b&&(Q.id=b),m.telnyx_call_control_id&&(Q.telnyxCallControlId=m.telnyx_call_control_id),m.telnyx_session_id&&(Q.telnyxSessionId=m.telnyx_session_id),m.telnyx_leg_id&&(Q.telnyxLegId=m.telnyx_leg_id),m.client_state&&(Q.clientState=m.client_state),m.dialogParams&&m.dialogParams.custom_headers&&m.dialogParams.custom_headers.length&&(Q.customHeaders=m.dialogParams.custom_headers),p&&(Q.recoveredCallId=p),M&&(Q.wasHeldBeforeRecovery=M),S!==void 0&&(Q.remoteElement=S),I!==void 0&&(Q.localElement=I),performance.mark(le(Q.id,"new-call-start"));const J=new ai(d,Q);return J.nodeId=this.nodeId,J},T=new Uh(v),E=new Hr(v);switch(g){case ee.Answer:case ee.Display:case ee.Candidate:case ee.Ringing:case ee.Bye:case ee.Media:if(!b||!k)return void w.error(`Received ${g} for non existing call:`,m);k.handleMessage(e),this._ack(h,g);break;case ee.Ping:this.session.setPingReceived(),this.session.execute(E);break;case ee.Punt:d.options.keepConnectionAliveOnSocketClose&&A?(w.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(h,g)):(w.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case ee.Invite:{const f=D();f.direction=St.Inbound,f.playRingtone(),f.setState(W.Ringing),this.session.emitMultipleActiveCallsWarning(f.id),this._ack(h,g);break}case ee.Attach:{const f=k||null;if(Object.keys(d.calls).length===0){let S,I;w.warn(`[${new Date().toISOString()}][${b}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${b}`);let M=!1,x=!1;const N=Dh();if(N&&N.sessionId===d.sessionid){const F=N.calls.find(V=>V!==null&&typeof V=="object"&&V.id===b);F&&(S=F.remoteElement,I=F.localElement,M=F.wasHeld===!0,typeof F.forceRelayCandidate=="boolean"&&(x=F.forceRelayCandidate),(S||I)&&w.info(`[${b}] Attach: restoring per-call media elements from recovery marker (remoteElement=${S??"<none>"}, localElement=${I??"<none>"}).`),typeof F.forceRelayCandidate=="boolean"&&w.info(`[${b}] Attach: restoring forceRelayCandidate=${F.forceRelayCandidate} from recovery marker.`))}const O=D({recoveredCallId:b,forceRelayCandidateForRecovery:x,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,g);break}if(f){const S=f.id,I=f.state==="held",M=f.shouldForceRelayCandidateForRecovery();M&&w.warn(`[${new Date().toISOString()}][${b}] Attach: forcing relay candidate for recovery`),w.info(`[${new Date().toISOString()}][${b}] Attach: recovering active call ${S}.`),f.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const x=D({recoveredCallId:S,forceRelayCandidateForRecovery:M,mutedMicOnStart:f.isAudioMuted,remoteElement:f.options.remoteElement,localElement:f.options.localElement,wasHeldBeforeRecovery:I});x.answer(),this.session.emitMultipleActiveCallsWarning(x.id),this._ack(h,g);break}w.warn(`Attach: callID ${b} does not match any active calls. `),U(P.Warning,{warning:Pe(ob),callId:b,params:m,sessionId:d.sessionid},d.uuid),this._ack(h,g);break}case ee.Event:case"webrtc.event":if(!y)return void w.error("Verto received an unknown event:",m);const p=d.relayProtocol,_=y.split(".")[0];d._existsSubscription(p,y)?U(p,m,y):y===d.sessionid?this._handleSessionEvent(m.eventData):d._existsSubscription(p,_)?U(p,m,_):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):U(P.Notification,m,d.uuid);break;case ee.Info:m.type=at.generic,U(P.Notification,m,d.uuid);break;case ee.ClientReady:this.session.execute(T);break;case"ai_conversation":U(P.AIConversationMessage,{method:"ai_conversation",params:m,voice_sdk_id:v},d.uuid);break;default:{const f=Fr(e);if(f){switch(f){case Le.REGISTER:case Le.REGED:if(!this.isDuplicateGatewayState(f,[Le.REGED,Le.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,f===Le.REGED&&this.session.resetReconnectAttempts();const S=(s=(n=e==null?void 0:e.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.call_report_id;S&&(d.callReportId=S,w.debug("Captured call_report_id from REGED:",S));const I=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.dc;I&&(d.dc=I);const M=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;M&&(d.region=M),w.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),m.type=at.vertoClientReady,U(P.Ready,m,d.uuid)}break;case Le.UNREGED:case Le.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const S=new rf("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=ae(fh,S);U(P.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(T)},this.reconnectDelay());break;case Le.FAILED:case Le.FAIL_WAIT:case Le.TIMEOUT:if(!this.isDuplicateGatewayState(f,[Le.FAILED,Le.FAIL_WAIT,Le.TIMEOUT])){const S=ae(F0,new Error(`Gateway state: ${f}`));if(U(P.Error,{error:S,sessionId:d.sessionid},d.uuid),d.options.skipLastVoiceSdkId=!0,w.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${d.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const I=new rf("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const M=ae(Or,I);U(P.Error,{error:M,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const I=ae(Or,new Error("Connection Retry Failed"));U(P.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(w.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(I=>{var M;return((M=I.peer)===null||M===void 0?void 0:M.instance)&&!I.signalingStateClosed}))return w.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();w.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:w.warn("GatewayState message unknown method:",e)}break}w.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&w.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 B(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const g=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},m={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=h||this._retrieveCallId(b,o);if(y&&i.calls.hasOwnProperty(y)){const C=i.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(k=>{k==="INVALID_PACKET"&&g()})}}},v=yield i.vertoSubscribe(m).catch(b=>{w.error("liveArray subscription error:",b);const y=ae(O0,b);U(P.Error,{error:y,sessionId:i.sessionid},i.uuid)});qr(v,o)&&g();break}case"conference-liveArray-part":{let g=null;if(o&&i._existsSubscription(n,o)){const{callId:v=null}=i.subscriptions[n][o];if(g=i.calls[v]||null,v!==null){const b={type:at.conferenceUpdate,action:Xe.Leave,conferenceName:r,participantId:Number(u),role:d};U(P.Notification,b,v,!1)||U(P.Notification,b,i.uuid),g===null&&Tt(P.Notification,null,v)}}const m=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:m}).then(({unsubscribedChannels:v=[]})=>{g&&(g.channels=g.channels.filter(b=>!v.includes(b)))}).catch(v=>{w.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":ef(this.session,e);break;case"logo-info":{const i={type:at.conferenceUpdate,action:Xe.LogoInfo,logo:e.logoURL};U(P.Notification,i,this.session.uuid);break}}}}class nw extends Ls{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>B(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new iw(this),window.addEventListener("beforeunload",i=>{if(w.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return xh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(w.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));try{const n=this.getActiveCalls().map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders,forceRelayCandidate:s.shouldForceRelayCandidateForRecovery()};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.getActiveCalls().forEach(s=>{if(s.flushIntermediateCallReport)try{w.debug(`beforeunload: flushing call report for ${s.id}.`),s.flushIntermediateCallReport({type:"page-unload"})}catch(o){w.debug(`beforeunload: failed to flush call report for ${s.id}: ${o instanceof Error?o.message:String(o)}`)}}),!this.sessionid||n.length===0)return w.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void si();w.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),Lh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];w.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()&&(w.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Vr(this.sessionid))})}validateOptions(){return bs(this.options)||wn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(L0,void 0,"Error: destinationNumber is required");const i=new ai(this,e);return e.id||w.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(le(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!!wn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return B(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),bs(this.options)?this.handleLoginOnSocketOpen():wn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}function af(t){return{options:t,statsSamples:[]}}function sw(t){var e,i;const n=(i=(e=t.call)===null||e===void 0?void 0:e.peer)===null||i===void 0?void 0:i.instance,s=t.statsSamples[t.statsSamples.length-1];if(!n||!s)return;const o=function(a,l){var c;const u=[],d=new Set,h=new Map,g=new Map,m={host:0,srflx:0,prflx:0,relay:0};a.forEach(E=>{switch(E.type){case"local-candidate":{const p=E;m[p.candidateType]++,g.set(p.id,p);break}case"remote-candidate":{const p=E;h.set(p.id,p);break}case"candidate-pair":{const p=E;u.push(p);break}case"transport":{const p=E;typeof p.selectedCandidatePairId=="string"&&d.add(p.selectedCandidatePairId);break}}});const v=function(E,p,_,f){var S,I;const M=E.find(V=>p.has(V.id)),x=E.find(V=>V.selected===!0),N=E.find(V=>V.nominated===!0&&V.state==="succeeded"),O=E.filter(V=>V.state==="succeeded"),F=(I=(S=M??x)!==null&&S!==void 0?S:N)!==null&&I!==void 0?I:O.length===1?O[0]:void 0;return F?Object.assign(Object.assign({},F),{localCandidate:_.get(F.localCandidateId),remoteCandidate:f.get(F.remoteCandidateId)}):null}(u,d,g,h),b=m.relay>0,y=m.srflx===0&&m.relay===0&&m.prflx===0,C=l.iceGatheringState,k=l.iceConnectionState,A=C==="complete",R=((c=v==null?void 0:v.localCandidate)===null||c===void 0?void 0:c.candidateType)==="relay",{hasMultipleNetworkInterfaces:D,vpnDetected:T}=function(E){if(E.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const p=Array.from(E.values());return{hasMultipleNetworkInterfaces:new Set(p.filter(_=>_.candidateType==="host").map(_=>_.address)).size>=2,vpnDetected:p.some(_=>_.networkType==="vpn")}}(g);return{candidateGatheringCompleted:A,gatheringComplete:A,candidateCounts:m,candidates:Array.from(g.values()),hasRelayCandidate:b,onlyHostCandidates:y,isTurnRequired:R,hasMultipleNetworkInterfaces:D,vpnDetected:T,hasSelectedPair:!!v,selectedPair:v??void 0,iceGatheringState:C,iceConnectionState:k}}(s,n),r=n.getConfiguration().iceServers;return r&&(o.serverCandidateComparison=function(a,l){var c,u;if(!a||a.length===0)return;const d=[];for(const h of a){const g=Array.isArray(h.urls)?h.urls:[h.urls],m=l.filter(y=>g.some(C=>ow(y.url,C,y.protocol))),v=(u=(c=m[0])===null||c===void 0?void 0:c.candidateType)!==null&&u!==void 0?u:null,b=m.length>0;d.push({urls:h.urls,hasCandidates:b,candidateType:v,candidates:m,candidateCount:m.length})}return d}(r,o.candidates)),o}function lf(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(e=>/^turns?:/i.test(e))}function cf(t){var e;let i=t;const n=i.match(/^([a-z]+:)(\/\/)?([^@]*@)(.+)$/i);n&&(i=n[1]+((e=n[2])!==null&&e!==void 0?e:"")+n[4]);const s=i.indexOf("?transport=");return s!==-1&&(i=i.substring(0,s)),i}function df(t){const e=t.indexOf("?transport=");if(e===-1)return;const i=t.substring(e+11).toLowerCase(),n=i.indexOf("&");return n===-1?i:i.substring(0,n)}function ow(t,e,i){var n;if(!t||!e||cf(t)!==cf(e))return!1;const s=df(e);if(s===void 0)return!0;const o=(n=df(t))!==null&&n!==void 0?n:i==null?void 0:i.toLowerCase();return o===void 0||o===s}const Xr=2e3,rw=100,uf=.01,aw="To check your microphone, we will be recorded your voice for a few seconds and played back to you so you can hear how it sounds.";function lw(){var t;return B(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((t=navigator.mediaDevices)===null||t===void 0?void 0:t.getUserMedia)!="function")return{report:{activeCapturePerformed:!1,captureError:"not_supported",captureErrorMessage:"getUserMedia is not available in this environment"},stream:void 0};try{return{report:{deviceAvailable:!0},stream:yield navigator.mediaDevices.getUserMedia({audio:!0})}}catch(e){const{captureError:i,captureErrorMessage:n}=function(s){const o=s&&typeof s=="object"&&"name"in s?String(s.name):"",r=s instanceof Error?s.message:String(s);return o==="NotAllowedError"||o==="PermissionDeniedError"||o==="SecurityError"?{captureError:"permission_denied",captureErrorMessage:`Microphone permission denied: ${r}`}:o==="NotFoundError"||o==="DevicesNotFoundError"||o==="OverconstrainedError"||o==="ConstraintNotSatisfiedError"?{captureError:"no_device",captureErrorMessage:`No microphone device found: ${r}`}:o==="TypeError"?{captureError:"not_supported",captureErrorMessage:`Microphone capture is not supported: ${r}`}:{captureError:"unknown",captureErrorMessage:r}}(e);return{report:{activeCapturePerformed:!1,captureError:i,captureErrorMessage:n,deviceAvailable:!1},stream:void 0}}})}function cw(t,e,i){return B(this,void 0,void 0,function*(){if(typeof AudioContext>"u")return null;let n,s,o;try{n=new AudioContext,s=n.createAnalyser(),o=n.createMediaStreamSource(t),s.fftSize=2048,o.connect(s);const r=new Float32Array(s.fftSize),a=Date.now()+e;let l=0,c=0,u=0;for(;Date.now()<a;){s.getFloatTimeDomainData(r);let d=0;for(const m of r)d+=m*m;const h=Math.sqrt(d/r.length);l=Math.max(l,h),c+=h,u+=1;const g=a-Date.now();g>0&&(yield new Promise(m=>setTimeout(m,Math.min(rw,g))))}return{audioLevel:l,audioDetected:l>=i,audioLevelStats:{peak:l,average:u>0?c/u:0,samples:u}}}catch{return null}finally{try{o==null||o.disconnect(),s==null||s.disconnect(),yield n==null?void 0:n.close()}catch{}}})}function dw(t,e){return B(this,void 0,void 0,function*(){if(typeof MediaRecorder<"u")try{const i=["audio/webm;codecs=opus","audio/webm"].find(r=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(r)),n=i?new MediaRecorder(t,{mimeType:i}):new MediaRecorder(t),s=[],o=Date.now();return yield new Promise(r=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(c),clearTimeout(u),r(d))};n.ondataavailable=({data:d})=>{d.size>0&&s.push(d)},n.onerror=()=>l(),n.onstop=()=>B(this,void 0,void 0,function*(){const d=n.mimeType||i||"audio/webm",h=yield(g=new Blob(s,{type:d}),new Promise(m=>{try{const v=new FileReader;v.onloadend=()=>m(typeof v.result=="string"?v.result:void 0),v.onerror=()=>m(void 0),v.readAsDataURL(g)}catch{m(void 0)}}));var g;l(h?{recordingDataUrl:h,recordingMimeType:d,recordingDurationMs:Date.now()-o}:void 0)});const c=setTimeout(()=>{try{n.state!=="inactive"&&n.stop()}catch{l()}},e),u=setTimeout(()=>l(),e+1e3);n.start()})}catch{return}})}function hf(t){var e,i;return B(this,void 0,void 0,function*(){const n=function(g){var m,v;const b=g&&typeof g=="object"?g:void 0;return{sampleDurationMs:Math.max(0,(m=b==null?void 0:b.sampleDurationMs)!==null&&m!==void 0?m:Xr),silenceThreshold:Math.min(1,Math.max(0,(v=b==null?void 0:b.silenceThreshold)!==null&&v!==void 0?v:uf)),record:(b==null?void 0:b.record)===!0,warnOnRecording:b==null?void 0:b.warnOnRecording}}(t.options.microphone),s=yield function(){var g;return B(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((g=navigator.permissions)===null||g===void 0?void 0:g.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}})}(),{report:o,stream:r}=yield lw(),a=yield function(){var g;return B(this,void 0,void 0,function*(){if(typeof navigator<"u"&&typeof((g=navigator.mediaDevices)===null||g===void 0?void 0:g.enumerateDevices)=="function")try{const m=(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:v})=>v==="audioinput").map(({deviceId:v,label:b})=>({deviceId:v||"",label:b||"",kind:"audioinput"}));return{devices:m,deviceCount:m.length,deviceAvailable:m.length>0,labelsAccessible:m.some(({label:v})=>v.length>0)}}catch{return}})}(),l=r?"granted":o.captureError==="permission_denied"?"denied":s,c={currentPermissionState:l,isPermissionGrantedCurrently:l==="granted",isGetUserMediaFailed:!r,deviceAvailable:(a==null?void 0:a.deviceAvailable)||o.deviceAvailable||!1,deviceCount:(e=a==null?void 0:a.deviceCount)!==null&&e!==void 0?e:0,devices:(i=a==null?void 0:a.devices)!==null&&i!==void 0?i:[],labelsAccessible:a==null?void 0:a.labelsAccessible,captureError:o.captureError,captureErrorMessage:o.captureErrorMessage,activeCapturePerformed:o.activeCapturePerformed};if(r)try{const g=yield function(m,v,b){var y,C,k;return B(this,void 0,void 0,function*(){m.activeCapturePerformed=!0,m.recordingPerformed=b.record,b.record&&b.warnOnRecording&&b.warnOnRecording(aw);const[A,R]=yield Promise.all([cw(v,(y=b.sampleDurationMs)!==null&&y!==void 0?y:Xr,(C=b.silenceThreshold)!==null&&C!==void 0?C:uf),b.record?dw(v,(k=b.sampleDurationMs)!==null&&k!==void 0?k:Xr):Promise.resolve(void 0)]);return A&&(m.audioLevel=A.audioLevel,m.audioDetected=A.audioDetected,m.audioLevelStats=A.audioLevelStats),R&&(m.recordingDataUrl=R.recordingDataUrl,m.recordingMimeType=R.recordingMimeType,m.recordingDurationMs=R.recordingDurationMs,m.recordingPerformed=!0),R})}(c,r,n);g&&(c.playbackPerformed=yield(u=g.recordingDataUrl,d=g.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise(m=>{let v,b=!1;const y=setTimeout(()=>C(!1),d),C=k=>{b||(b=!0,clearTimeout(y),v&&(v.onended=null,v.onerror=null,v.paused||v.pause(),v.src=""),m(k))};try{v=new Audio(u),v.onended=()=>C(!0),v.onerror=()=>C(!1),v.play().catch(()=>C(!1))}catch{C(!1)}})))}finally{try{r.getTracks().forEach(g=>g.stop())}catch{}}var u,d;const h=function(g){const m=[],v=(y,C)=>m.push({code:y,message:C,source:"microphone"});g.currentPermissionState==="denied"&&v("microphone_permission_denied","Microphone permission has been denied by the user."),g.deviceAvailable===!1&&v("microphone_no_device","No audio input device is available.");const b=g.captureError?{permission_denied:["microphone_capture_permission_denied","Active microphone capture was denied permission."],no_device:["microphone_capture_no_device","No microphone device was found for active capture."],not_supported:["microphone_capture_not_supported","Active microphone capture is not supported."],unknown:["microphone_capture_failed","Active microphone capture failed."]}[g.captureError]:void 0;return b&&v(...b),g.activeCapturePerformed&&g.audioDetected===!1&&v("microphone_silent","No audio was detected above the silence threshold during active capture."),m}(c);return h.length>0&&(c.reasons=h),Object.keys(c).length>0?c:void 0})}const Jr=300,Zr=500,Qr=30,ea=100,ta=.02,ia=.05,Ms=8e3;function lt(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function na(t){const e=t.filter(o=>lt(o)!==void 0);if(e.length===0)return;let i=1/0,n=-1/0,s=0;for(const o of e)o<i&&(i=o),o>n&&(n=o),s+=o;return{min:i,max:n,average:s/e.length}}function sa(t){var e,i;const n=[],s=new Set;t.forEach(r=>{const a=r;n.push(a),a.type==="transport"&&typeof a.selectedCandidatePairId=="string"&&s.add(a.selectedCandidatePairId)});const o=n.filter(r=>r.type==="candidate-pair");return(i=(e=o.find(r=>s.has(r.id)))!==null&&e!==void 0?e:o.find(r=>r.selected===!0||r.nominated===!0&&r.state==="succeeded"))!==null&&i!==void 0?i:o.find(r=>r.state==="succeeded")}function Bi(t,e){let i=0,n=!1;for(const s of t){const o=lt(s[e]);o!==void 0&&(i+=o,n=!0)}return n?i:void 0}function Ui(t,e,i=!1){const n=[];return t.forEach(s=>{const o=s;o.type!==e||i&&!function(r){var a;const l=(a=r.kind)!==null&&a!==void 0?a:r.mediaType;return l===void 0||l==="audio"}(o)||n.push(o)}),n}function uw(t,e){const i=t.packets===void 0?e.packets!==void 0:e.packets!==void 0&&e.packets>t.packets,n=t.bytes===void 0?e.bytes!==void 0:e.bytes!==void 0&&e.bytes>t.bytes;return i||n}function ff(t,e){if(t!==void 0&&e!==void 0)return lt(e-t)}function pf(t,e){var i,n;if(!t.some(c=>Ui(c,`${e}-rtp`,!0).length>0))return;const s=t.map(c=>function(u,d){const h=Ui(u,`${d}-rtp`,!0);return d==="outbound"?{packets:Bi(h,"packetsSent"),bytes:Bi(h,"bytesSent")}:{packets:Bi(h,"packetsReceived"),bytes:Bi(h,"bytesReceived")}}(c,e)).filter(({packets:c,bytes:u})=>c!==void 0||u!==void 0),o=(i=s[0])!==null&&i!==void 0?i:{},r=(n=s[s.length-1])!==null&&n!==void 0?n:{},a=ff(o.packets,r.packets),l=ff(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&uw(o,r)},r.packets!==void 0?{packets:r.packets}:{}),r.bytes!==void 0?{bytes:r.bytes}:{}),a!==void 0?{packetsDelta:a}:{}),l!==void 0?{bytesDelta:l}:{})}function gf(t,e){const i=[];for(const n of t)for(const s of Ui(n,e,!0)){const o=lt(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&i.push(r)}}return i}function mf(t){const e=Bi(t,"packetsReceived"),i=Bi(t,"packetsLost"),n=t.map(r=>lt(r.fractionLost)).filter(r=>r!==void 0&&r>=0&&r<=1),s=n.length>0?Math.max(...n):void 0,o=e!==void 0&&i!==void 0?e+i:void 0;return{packetsReceived:e,packetsLost:i,packetLossFraction:s??(i!==void 0&&o!==void 0&&o>0?i/o:void 0)}}function vf(t){let e;return t.forEach(i=>{e===void 0&&(e=lt(i.timestamp))}),e}function hw(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,i=pf(e,"inbound"),n=pf(e,"outbound"),s=na(function(g){var m;const v=[];for(const b of g){let y=!1;const C=Ui(b,"remote-inbound-rtp",!0);for(const k of C){const A=lt(k.roundTripTime);if(A!==void 0){const R=1e3*A;R>=0&&(v.push(R),y=!0)}}if(!y){const k=lt((m=sa(b))===null||m===void 0?void 0:m.currentRoundTripTime);if(k!==void 0){const A=1e3*k;A>=0&&v.push(A)}}}return v}(e)),o=(r=na(gf(e,"inbound-rtp")),a=na(gf(e,"remote-inbound-rtp")),(r==null?void 0:r.average)===void 0?a:(a==null?void 0:a.average)===void 0?r:a.average>r.average?a:r);var r,a;const l=function(g,m,v){var b;if(g.length===0)return;const y=g[g.length-1],C=Ui(y,"inbound-rtp",!0),k=Ui(y,"remote-inbound-rtp",!0),A=function(_,f){return _.packetLossFraction===void 0?f:f.packetLossFraction===void 0?_:f.packetLossFraction>_.packetLossFraction?f:_}(mf(C),mf(k));let R=v==null?void 0:v.packets,D=(b=A.packetsReceived)!==null&&b!==void 0?b:m==null?void 0:m.packets;const T=A.packetsLost,E=A.packetLossFraction,p=sa(y);return R===void 0&&(R=lt(p==null?void 0:p.packetsSent)),D===void 0&&(D=lt(p==null?void 0:p.packetsReceived)),R!==void 0||D!==void 0||T!==void 0?{packetsSent:R,packetsReceived:D,packetsLost:T,packetLossFraction:E}:void 0}(e,i,n),c=function(g,m,v){if(g.length===0)return;const b=g[g.length-1];let y=v==null?void 0:v.bytes,C=m==null?void 0:m.bytes;const k=sa(b);return y===void 0&&(y=lt(k==null?void 0:k.bytesSent)),C===void 0&&(C=lt(k==null?void 0:k.bytesReceived)),y!==void 0||C!==void 0?{bytesSent:y,bytesReceived:C}:void 0}(e,i,n),u=function(g,m,v){if(g.length<2)return;const b=g[0],y=g[g.length-1],C=vf(b),k=vf(y);if(C===void 0||k===void 0)return;const A=(k-C)/1e3;if(A<=0)return;const R=(v==null?void 0:v.bytesDelta)!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/A:void 0,D=(m==null?void 0:m.bytesDelta)!==void 0&&m.bytesDelta>=0?8*m.bytesDelta/A:void 0;return R!==void 0||D!==void 0?{outbound:R,inbound:D}:void 0}(e,i,n),d=function(g,m,v){let b=!1,y="good";return(g==null?void 0:g.average)!==void 0&&(b=!0,g.average>=Zr?y="poor":g.average>=Jr&&y==="good"&&(y="fair")),(m==null?void 0:m.average)!==void 0&&(b=!0,m.average>=ea?y="poor":m.average>=Qr&&y==="good"&&(y="fair")),(v==null?void 0:v.packetLossFraction)!==void 0&&(b=!0,v.packetLossFraction>=ia?y="poor":v.packetLossFraction>=ta&&y==="good"&&(y="fair")),b?y:"unknown"}(s,o,l),h=function(g,m,v,b){const y=[];return(g==null?void 0:g.average)!==void 0&&(g.average>=Zr?y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (poor: ≥${Zr}ms threshold)`,source:"network"}):g.average>=Jr&&y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(g.average)}ms (degraded: ≥${Jr}ms threshold)`,source:"network"})),(m==null?void 0:m.average)!==void 0&&(m.average>=ea?y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (poor: ≥${ea}ms threshold)`,source:"network"}):m.average>=Qr&&y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (degraded: ≥${Qr}ms threshold)`,source:"network"})),(v==null?void 0:v.packetLossFraction)!==void 0&&(v.packetLossFraction>=ia?y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (poor: ≥${100*ia}% threshold)`,source:"network"}):v.packetLossFraction>=ta&&y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (degraded: ≥${100*ta}% threshold)`,source:"network"})),b&&(b.outbound!==void 0&&b.outbound<Ms&&y.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(b.outbound)} bps (<${Ms} bps threshold)`,source:"network"}),b.inbound!==void 0&&b.inbound<Ms&&y.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(b.inbound)} bps (<${Ms} bps threshold)`,source:"network"})),y}(s,o,l,t.options.mode==="network-only"?void 0:u);return{quality:d,rtt:s,jitter:o,packets:l,bytes:c,bitrate:u,inbound:i,outbound:n,reasons:h.length>0?h:void 0}}function _f(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function oa(t,e){return t.find(i=>i.label===e)}class fw{constructor(){this.startedAtMonoMs=yf()}build(e={}){var i,n;const s={};try{const o=(n=(i=e.call)===null||i===void 0?void 0:i.getEstablishmentTimings)===null||n===void 0?void 0:n.call(i);if(o){s.callEstablishment={mode:o.mode,direction:o.direction,steps:o.steps.map(d=>Object.assign({},d))};const r=oa(o.steps,"ICE candidate gathering started"),a=oa(o.steps,"All ICE candidates gathered"),l=_f(r&&a?a.fromStart-r.fromStart:void 0);l!==void 0&&(s.iceGatheringMs=l);const c=oa(o.steps,"First server-reflexive/relay candidate found"),u=_f(r&&c?c.fromStart-r.fromStart:void 0);u!==void 0&&(s.firstNonHostCandidateMs=u)}}catch{}return s}complete(e){const i=yf()-this.startedAtMonoMs;Number.isFinite(i)&&i>=0&&(e.totalMs=i)}}function yf(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function ra(){return new fw}const Pt={NoCandidates:"ice_no_candidates",OnlyHostCandidates:"ice_only_host_candidates",GatheringTimeout:"ice_gathering_timeout",NoSelectedPair:"ice_no_selected_pair",TurnRequired:"ice_turn_required",ServerNoCandidates:"ice_server_no_candidates",MultipleInterfaces:"ice_multiple_interfaces",VpnDetected:"ice_vpn_detected"},In={LowBitrate:"network_low_bitrate",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},aa={CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureFailed:"microphone_capture_failed"},li=()=>({reasons:[],warnings:[]}),bf={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function We(t,e){return t?e?bf[t]>=bf[e]?t:e:t:e}function Je(t,e,i){return{code:t,message:e,source:i}}function Rn(t,e,i){return{code:t,message:e,source:i}}function wf(t,e=!1){var i;if(!t)return li();const n=li(),{reasons:s,warnings:o}=n,r=t.candidates.length>0;r||(s.push(Je(Pt.NoCandidates,"No ICE candidates were gathered.","ice")),n.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(Rn(Pt.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(Je(Pt.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),n.verdict=We(n.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(Je(Pt.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),n.verdict=We(n.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(Je(Pt.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),n.verdict=We(n.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(Je(Pt.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),n.verdict=We(n.verdict,"degraded"));const l=((i=t.serverCandidateComparison)!==null&&i!==void 0?i:[]).filter(({hasCandidates:c})=>!c);return l.length>0&&o.push(Rn(Pt.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(Rn(Pt.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(Rn(Pt.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!n.verdict&&r&&(n.verdict="ready"),n}function pw(t){if(t.established&&!t.error)return li();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[Je("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function Sf(t,e=!0){var i;if(!t)return li();const n=li(),{reasons:s,warnings:o}=n,r=e?t.reasons:(i=t.reasons)===null||i===void 0?void 0:i.filter(({code:l})=>l!==In.LowBitrate);switch(r!=null&&r.length&&(s.push(...r),n.verdict="degraded"),t.quality){case"poor":s.push(Je(In.PoorQuality,"Network quality is poor.","network")),n.verdict=We(n.verdict,"blocked");break;case"fair":o.push(Rn(In.FairQuality,"Network quality is fair.","network")),n.verdict=We(n.verdict,"degraded");break;case"good":n.verdict=We(n.verdict,"ready")}const a=[t.inbound,t.outbound].filter(l=>!!l);if(e&&a.length>0){const l=a.filter(({flowing:c})=>c).length;a.length===2&&l===2?n.verdict=We(n.verdict,"ready"):l>0?(s.push(Je(In.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),n.verdict=We(n.verdict,"blocked")):(s.push(Je(In.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),n.verdict=We(n.verdict,"blocked"))}return n}function gw(t){var e;if(!t)return li();const i=li();!((e=t.reasons)===null||e===void 0)&&e.length&&i.reasons.push(...t.reasons);const n=t.currentPermissionState==="denied"||t.isPermissionGrantedCurrently===!1||t.captureError==="permission_denied",s=t.deviceAvailable===!1||t.captureError!==void 0,o=t.activeCapturePerformed===!0&&t.audioDetected===!1;return n?i.verdict="permission_denied":s?i.verdict="blocked":o?i.verdict="degraded":(t.activeCapturePerformed===!0&&t.audioDetected===!0||t.activeCapturePerformed!==!0&&t.isPermissionGrantedCurrently===!0&&t.deviceAvailable!==!1)&&(i.verdict="ready"),i}class la{constructor(e){this.options=e}run(){return B(this,void 0,void 0,function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(af(this.options));default:return this.runFull()}})}runFull(){return B(this,void 0,void 0,function*(){const e=yield this.runTest({diagnosticOptions:this.options,modules:{ice:!!this.options.ice,network:!!this.options.network,microphone:!!this.options.microphone},autoHangup:this.options.autoHangup!==!1});return e.setupFailed?e.error?Vi({callId:e.callId,timings:e.timings},e.error):{version:1,verdict:"inconclusive",reasons:[{code:"call_setup_timeout",message:"The diagnostic call did not reach the established state",source:"diagnostic"}],callId:e.callId,timings:e.timings}:Vi({ice:e.ice,network:e.network,microphone:e.microphone,timings:e.timings,callId:e.callId,raw:e.raw},e.error)})}runNetworkOnly(){var e,i,n;return B(this,void 0,void 0,function*(){const s=this.options.client.iceServers,o=function(c){const u=[];for(const d of c)(Array.isArray(d.urls)?d.urls:[d.urls]).forEach(h=>{u.push(Object.assign(Object.assign({},d),{urls:h}))});return u}((n=(i=(e=this.options.rtcConfig)===null||e===void 0?void 0:e.iceServers)!==null&&i!==void 0?i:s)!==null&&n!==void 0?n:[]);let r=[];const a=ra();let l;try{return r=yield Promise.all(o.map(c=>B(this,void 0,void 0,function*(){const u=yield this.runTest({diagnosticOptions:Object.assign(Object.assign({},this.options),{durationMs:3e3,statsSampleIntervalMs:500,rtcConfig:Object.assign(Object.assign({},this.options.rtcConfig),{iceServers:[c]})}),iceServers:[c],forceRelayCandidate:lf(c),modules:{ice:!0,network:!!this.options.network,microphone:!1},autoHangup:!0}),d=function(h){if(h.error)return h.error.message;if(h.setupFailed)return"The diagnostic call did not reach the established state";if(!h.ice)return"No ICE report was produced";if(h.ice.candidates.length===0)return"No ICE candidates were gathered";if(!h.ice.hasSelectedPair)return"No ICE candidate pair was selected"}(u);return{server:c,established:d===void 0,callId:u.callId,ice:u.ice,network:u.network,timings:u.timings,error:d}}))),l=Vi({serverTests:r,timings:a.build()},void 0,{networkOnly:!0}),l}catch(c){return l=Vi({timings:a.build()},Os(c),{networkOnly:!0}),l}finally{l!=null&&l.timings&&a.complete(l.timings)}})}runTest(e){return B(this,void 0,void 0,function*(){const i=af(e.diagnosticOptions),n=ra();let s,o,r,a=!1;const l=c=>{c.callId===(s==null?void 0:s.id)&&(o=Os(c.error))};e.diagnosticOptions.client.on("telnyx.error",l);try{if(s=this.createDiagnosticCall(e.diagnosticOptions,e.iceServers,e.forceRelayCandidate),i.call=s,a=yield this.waitForCallEstablishment(s),!a)return r={established:!1,setupFailed:!0,callId:s.id,timings:n.build({call:s}),error:o},r;yield this.collectSamples(s,i);const c=e.modules.ice?sw(i):void 0,u=e.modules.network?hw(i):void 0,d=e.modules.microphone?yield hf(i):void 0;return r={established:!0,setupFailed:!1,callId:s.id,ice:c,network:u,microphone:d,timings:n.build({call:s}),raw:{samples:i.statsSamples.length?i.statsSamples:void 0}},r}catch(c){return i.error=Os(c),r={established:a,setupFailed:!1,callId:s==null?void 0:s.id,timings:n.build({call:s}),error:i.error},r}finally{if(e.diagnosticOptions.client.off("telnyx.error",l),s&&e.autoHangup)try{yield s.hangup()}catch{}r!=null&&r.timings&&n.complete(r.timings)}})}runMicrophoneOnly(e){return B(this,void 0,void 0,function*(){const i=ra();let n;try{return n=Vi({microphone:this.options.microphone?yield hf(e):void 0,timings:i.build()},e.error),n}catch(s){return e.error=Os(s),n=Vi({timings:i.build()},e.error),n}finally{n!=null&&n.timings&&i.complete(n.timings)}})}waitForCallEstablishment(e){return B(this,void 0,void 0,function*(){const i=Date.now()+3e4,n=()=>{var s,o;return e.state==="active"&&((o=(s=e.peer)===null||s===void 0?void 0:s.instance)===null||o===void 0?void 0:o.connectionState)==="connected"};for(;Date.now()<i;){if(n())return!0;if(["done","hangup","destroy"].includes(e.state))return!1;yield Cf(500)}return n()})}createDiagnosticCall(e,i,n=!1){const{client:s,destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c,rtcConfig:u}=e;return s.newCall({destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c===!0,iceServers:i??(u==null?void 0:u.iceServers),forceRelayCandidate:n})}collectSamples(e,i){var n,s,o;return B(this,void 0,void 0,function*(){const r=(n=i.options.durationMs)!==null&&n!==void 0?n:5e3,a=(s=i.options.statsSampleIntervalMs)!==null&&s!==void 0?s:1e3,l=Date.now()+r;for(;Date.now()<l;){try{const c=yield(o=e.peer.instance)===null||o===void 0?void 0:o.getStats();c&&i.statsSamples.push(c)}catch{}yield Cf(Math.min(a,Math.max(0,l-Date.now())))}})}}function Vi(t,e,i){const{verdict:n,reasons:s,warnings:o}=function(r,a,l={}){var c,u;const d=[wf(r.ice),Sf(r.network),gw(r.microphone),...((c=r.serverTests)!==null&&c!==void 0?c:[]).flatMap(v=>[wf(v.ice,l.networkOnly&&lf(v.server)),Sf(v.network,!l.networkOnly),pw(v)])],h=d.flatMap(v=>v.reasons),g=d.flatMap(v=>v.warnings);let m=d.reduce((v,b)=>We(v,b.verdict),void 0);if(l.networkOnly&&!((u=r.serverTests)===null||u===void 0)&&u.length){const v=r.serverTests.filter(b=>b.established&&!b.error).length;v===0?m="blocked":v<r.serverTests.length&&(m="degraded")}if(a)switch(a.code){case uh:h.push(Je(aa.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),m=We(m,"permission_denied");break;case hh:h.push(Je(aa.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),m=We(m,"blocked");break;case Lr:h.push(Je(aa.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),m=We(m,"blocked");break;default:h.push(Je("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),m=We(m,"blocked")}return{verdict:m??"inconclusive",reasons:h,warnings:g}}(t,e,i);return Object.assign(Object.assign({},t),{version:1,verdict:n??"inconclusive",reasons:s.length?s:void 0,warnings:o.length?o:void 0})}function Os(t){return t instanceof Error?t:new Error(String(t))}function Cf(t){return new Promise(e=>setTimeout(e,t))}const Tf="+1-872-231-5806";class mw extends nw{constructor(e){super(e),w.info(`SDK version: ${Vh}`)}newCall(e){return super.newCall(e)}runPreCall(e={}){var i,n;return B(this,void 0,void 0,function*(){const s={client:this,destinationNumber:(i=e.destinationNumber)!==null&&i!==void 0?i:Tf,durationMs:e.durationMs,ice:!0,network:!0,microphone:!0,mode:"full",rtcConfig:{iceServers:(n=e.iceServers)!==null&&n!==void 0?n:this.iceServers}};return new la(s).run()})}runNetworkCheck(e={}){var i;return B(this,void 0,void 0,function*(){const n={client:this,destinationNumber:Tf,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(i=e.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new la(n).run()})}runMicrophoneCheck(e={}){var i;return B(this,void 0,void 0,function*(){const n={client:this,ice:!1,network:!1,microphone:{sampleDurationMs:e.durationMs,silenceThreshold:e.silenceThreshold,record:(i=e.record)!==null&&i!==void 0&&i,warnOnRecording:e.warnOnRecording},mode:"microphone-only"};return new la(n).run()})}static webRTCInfo(){return Hb()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Te.not_supported},{browserName:"Firefox",supported:Te.not_supported},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",supported:Te.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",features:["video","audio"],supported:Te.full},{browserName:"Edge",features:["audio"],supported:Te.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Te.full},{browserName:"Firefox",features:["audio"],supported:Te.partial},{browserName:"Safari",supported:Te.not_supported},{browserName:"Edge",features:["audio"],supported:Te.partial}]}]}}function vw(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 kf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ef={exports:{}},If;function _w(){return If||(If=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(i=!1));function s(l,c,u){this.fn=l,this.context=c,this.once=u||!1}function o(l,c,u,d,h){if(typeof u!="function")throw new TypeError("The listener must be a function");var g=new s(u,d||l,h),m=i?i+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],g]:l._events[m].push(g):(l._events[m]=g,l._eventsCount++),l}function r(l,c){--l._eventsCount===0?l._events=new n:delete l._events[c]}function a(){this._events=new n,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,u;if(this._eventsCount===0)return l;for(u in c=this._events)e.call(c,u)&&l.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=i?i+l:l,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,g=new Array(h);d<h;d++)g[d]=u[d].fn;return g},a.prototype.listenerCount=function(l){var c=i?i+l:l,u=this._events[c];return u?u.fn?1:u.length:0},a.prototype.emit=function(l,c,u,d,h,g){var m=i?i+l:l;if(!this._events[m])return!1;var v=this._events[m],b=arguments.length,y,C;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),b){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,u),!0;case 4:return v.fn.call(v.context,c,u,d),!0;case 5:return v.fn.call(v.context,c,u,d,h),!0;case 6:return v.fn.call(v.context,c,u,d,h,g),!0}for(C=1,y=new Array(b-1);C<b;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var k=v.length,A;for(C=0;C<k;C++)switch(v[C].once&&this.removeListener(l,v[C].fn,void 0,!0),b){case 1:v[C].fn.call(v[C].context);break;case 2:v[C].fn.call(v[C].context,c);break;case 3:v[C].fn.call(v[C].context,c,u);break;case 4:v[C].fn.call(v[C].context,c,u,d);break;default:if(!y)for(A=1,y=new Array(b-1);A<b;A++)y[A-1]=arguments[A];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var g=this._events[h];if(g.fn)g.fn===c&&(!d||g.once)&&(!u||g.context===u)&&r(this,h);else{for(var m=0,v=[],b=g.length;m<b;m++)(g[m].fn!==c||d&&!g[m].once||u&&g[m].context!==u)&&v.push(g[m]);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}(Ef)),Ef.exports}var yw=_w();const ca=kf(yw),da=new ca;var ua={exports:{}},bw=ua.exports,Rf;function ww(){return Rf||(Rf=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(bw,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 y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function g(v,b){var y=this,C,k,A,R="loglevel";typeof v=="string"?R+=":"+v:typeof v=="symbol"&&(R=void 0);function D(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),M=S.indexOf(I+"=");M!==-1&&(f=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.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 p(f){var S=f;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+f)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??k??C},y.setLevel=function(f,S){return A=p(f),S!==!1&&D(A),u.call(y)},y.setDefaultLevel=function(f){k=p(f),T()||y.setLevel(f,!1)},y.resetLevel=function(){A=null,E(),u.call(y)},y.enableAll=function(f){y.setLevel(y.levels.TRACE,f)},y.disableAll=function(f){y.setLevel(y.levels.SILENT,f)},y.rebuild=function(){if(r!==y&&(C=p(r.getLevel())),u.call(y),r===y)for(var f in o)o[f].rebuild()},C=p(r?r.getLevel():"WARN");var _=T();_!=null&&(A=p(_)),u.call(y)}r=new g,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new g(v,r.methodFactory)),b};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(ua)),ua.exports}var Sw=ww();const Cw=kf(Sw),Tw=()=>new Date().toISOString().replace("T"," ").replace("Z",""),fe=Cw.getLogger("telnyx-ai-agent"),kw=fe.methodFactory;fe.methodFactory=(t,e,i)=>{const n=kw(t,e,i);return function(...s){n(Tw(),"-",...s)}},fe.setLevel("info");function Ew(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Iw=10,Rw=500,Aw=100,xw=300,Af=20;class Dw{constructor(e){H(this,"remoteIntervalId",null);H(this,"localIntervalId",null);H(this,"remoteStream",null);H(this,"localStream",null);H(this,"remoteAudioContext",null);H(this,"remoteSource",null);H(this,"remoteAnalyser",null);H(this,"localAudioContext",null);H(this,"localSource",null);H(this,"localAnalyser",null);H(this,"thinkingStartTime",null);H(this,"lastState",null);H(this,"userIsSpeaking",!1);H(this,"lastUserAudioTime",null);H(this,"userSpeechStartTime",null);H(this,"remoteSilenceStartTime",null);H(this,"remoteSilenceThresholdMs");H(this,"userSilenceStartTime",null);H(this,"isFirstAgentSpeech",!0);H(this,"monitorStartTime",null);H(this,"volumeThreshold");H(this,"silenceDurationMs");H(this,"minSpeechDurationMs");H(this,"maxLatencyMs");H(this,"updateAgentState",Ew(e=>{fe.debug("AudioStreamMonitor updateAgentState",e),fe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,da.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Iw,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Rw,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Aw,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??xw}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,Af)}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,Af)}destroy(){this.stopAudioStreamMonitor()}}function Lw(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Mw(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function Ow(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Ps(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function Pw(t){if(!Ps(t))return null;const e=t.params;return vw(e)?e.item:null}function Nw(t){if(!Ps(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 Fw(t){if(!Ps(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 Bw(t){var e;return Ps(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function Uw(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 Vw=3e4;function $w(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 ha(t){return JSON.stringify({error:t})}class jw{constructor(e){H(this,"registry",new Map);H(this,"toolTimeouts",new Map);H(this,"inFlight",new Set);H(this,"completed",new Set);H(this,"generation",0);H(this,"getActiveCall");H(this,"timeoutMs");H(this,"events");H(this,"handleEvent",e=>{const i=Nw(e);if(i){this.ingestToolSettings(i);return}const n=Pw(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:Vw,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,ha("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,ha("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,$w(u),!1,s,o)}catch(u){const d=u instanceof xf?"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,ha(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 xf(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 xf extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Fs=class Fs{constructor(e){H(this,"enabled");H(this,"getActiveCall");H(this,"events");H(this,"subscriptionConfirmed",!1);H(this,"subscribeAttempts",0);H(this,"handleEvent",e=>{if(!this.enabled)return;if(Bw(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Fw(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Hw(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>=Fs.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"}`)}}};H(Fs,"MAX_SUBSCRIBE_ATTEMPTS",10);let fa=Fs;function Hw(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Ww(t){return Mw(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Gw(t){if(!Ow(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 qw extends ca{constructor(i){super();H(this,"telnyxRTC");H(this,"transcript",[]);H(this,"onSocketMessage",i=>{if(Lw(i))switch(i.params.type){case"response.text.delta":{const n=Ww(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"conversation.item.deleted":{if(Uw(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=Gw(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 Nt=t=>typeof t=="object"&&t!==null,Df=t=>{const e=Nt(t)&&Nt(t.result)?t.result:t;if(!(!Nt(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},zw=t=>Nt(t)&&Nt(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Kw=(t,e)=>{if(!e||!Nt(t)||!Nt(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Nt(i.params))return;const n=i.params;Nt(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class Yw extends ca{constructor(i){super();H(this,"telnyxRTC");H(this,"transcription");H(this,"removeLoginSuccessHook",null);H(this,"authenticated",!1);H(this,"authenticating",!1);H(this,"agentId");H(this,"versionId");H(this,"widgetVersion");H(this,"conversationId");H(this,"debug");H(this,"audioStreamMonitor");H(this,"clientTools");H(this,"streamingAudio");H(this,"activeCall");H(this,"chatMode");H(this,"dc",null);H(this,"region",null);H(this,"callReportId",null);H(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)});H(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});H(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});H(this,"onSocketMessage",i=>{const n=Df(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});H(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()))});H(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});H(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 mw({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,prefetchIceCandidates:i.prefetchIceCandidates,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 qw(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),da.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Dw(i.vad),this.clientTools=new jw({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 fa({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(),da.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=g=>{c===g&&(this.authenticating=!1)},d=function(g){const m=zw(g),v=c;return m&&Kw(g,a),n.call(this,g).then(b=>{const y=m?Df(b):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),b})},h=function(g){const m=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,g).finally(()=>{l&&i.login===h&&u(m)})};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 Lf={exports:{}},An={},Mf;function Xw(){if(Mf)return An;Mf=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 An.Fragment=e,An.jsx=i,An.jsxs=i,An}var Of;function Jw(){return Of||(Of=1,Lf.exports=Xw()),Lf.exports}Jw(),At(void 0),At(null);const Zw=(t,e,i,n,s,o,r,a,l,c,u)=>new Yw({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,prefetchIceCandidates:o,vad:r,conversationId:a,chatMode:l,region:c,skipLastVoiceSdkId:u??!0}),Ns=10,Pf=5e3,Qw=[46001,46003],eS=["login incorrect","authentication required","authentication failed"];function Nf(t){var n;const e=t.code;if(e&&Qw.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return eS.some(s=>i.includes(s))}const tS=(t,e,i,n,s,o,r,a,l,c,u)=>{const d=u??!0,[h,g]=Ae(null),[m,v]=Ae(!1),[b,y]=Ae(null),[C,k]=Ae(!1),A=he(0),R=he(null),D=he(null),T=he(!1),E=he(!1),p=he(0),_=he(0),f=qe(()=>{R.current&&(clearTimeout(R.current),R.current=null)},[]),S=qe(()=>{f(),A.current=0,E.current=!0,k(!1),y(null)},[f]),I=qe(()=>{f(),k(!1)},[f]),M=qe(x=>{if(f(),A.current>=Ns){re.error(`Max login retry attempts (${Ns}) exceeded`),k(!1);return}A.current+=1;const N=p.current,O=_.current;re.info(`Scheduling login retry attempt ${A.current}/${Ns} in ${Pf}ms due to: ${x}`),k(!0),R.current=window.setTimeout(()=>{var $;R.current=null;const F=D.current,V=F==null?void 0:F.telnyxRTC;if(p.current!==N||_.current!==O||F!=null&&F.isAuthenticating){re.info("Skipping login retry because a newer socket/login is already in progress"),I();return}if(T.current||E.current||F!=null&&F.isAuthenticated){re.info("Skipping login retry because login already succeeded before retry timeout fired"),S();return}D.current&&(re.info(`Executing reconnect attempt ${A.current} (socket disconnect)`),($=V==null?void 0:V.socketDisconnect)==null||$.call(V))},Pf)},[f,I,S]);return xe(()=>{if(!t)return;const x=Zw(t,e,i,n,s,o,r,a,l,c,d);T.current=!1,E.current=!1,v(!1),y(null),k(!1),D.current=x;const N=()=>{re.info("Agent connected successfully"),T.current=!0,v(!0),S()},O=()=>{re.info("Agent disconnected"),T.current=!1,E.current=!1,v(!1)},F=de=>{if(re.error("AI Agent error:",de),Nf(de)){if(T.current||E.current){re.debug("Ignoring retryable error — login already succeeded");return}A.current<Ns?(y(null),M(de.message)):(y(de),k(!1))}else y(de),k(!1)},V=x.telnyxRTC??null,$=()=>{_.current+=1,E.current=!1},Q=()=>{re.info("Login succeeded; clearing pending login retry flow"),S()},J=()=>{p.current+=1,E.current=!1},G=()=>{E.current=!1};return x.on("agent.connected",N),x.on("agent.disconnected",O),x.on("agent.error",F),x.on("agent.login.started",$),x.on("agent.login.success",Q),V&&typeof V=="object"&&(V.on(P.SocketOpen,J),V.on(P.SocketClose,G)),x.connect(),g(x),()=>{f(),x.off("agent.connected",N),x.off("agent.disconnected",O),x.off("agent.error",F),x.off("agent.login.started",$),x.off("agent.login.success",Q),V&&typeof V=="object"&&(V.off(P.SocketOpen,J),V.off(P.SocketClose,G)),x.disconnect(),T.current=!1,D.current=null}},[t,e,i,n,s,o,r,a,l,c,u,d,f,S,M]),{client:h,isConnected:m,error:b,isReconnecting:C}},iS="telnyx-ai-agent",Ze={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 nS(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 Ff(){const t=document.querySelector(iS);return t instanceof HTMLElement?t:null}function kt(t,e,i){const n=i||Ff();if(!n){re.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),re.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const sS=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=he(null),l=Hn(Gu);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??Ff()},[i]),xe(()=>{if(!t)return;const c=a.current,u=()=>{n();const D=t.telnyxRTC,T={dc:(D==null?void 0:D.dc)??null,region:(D==null?void 0:D.region)??null,callReportId:(D==null?void 0:D.callReportId)??null};l(T),kt(Ze.AGENT_CONNECTED,T,c)},d=()=>{l(null),kt(Ze.AGENT_DISCONNECTED,void 0,c)},h=R=>{const D={message:R.message,name:R.name};if(Nf(R)){re.debug("Ignoring retryable agent.error in widget event layer"),kt(Ze.AGENT_ERROR,D,c);return}o(R),kt(Ze.AGENT_ERROR,D,c)},g=R=>{var D;s(R),kt(Ze.CONVERSATION_UPDATE,{type:R.type,callState:(D=R.call)==null?void 0:D.state},c)},m=R=>{kt(Ze.TRANSCRIPT_ITEM,R,c)},v=R=>{kt(Ze.CONVERSATION_AGENT_STATE,R,c)},b=R=>{kt(Ze.AGENT_AUDIO_MUTE,{muted:R},c)},C=t.telnyxRTC,k=R=>{r(R);const D=nS(R);D&&kt(Ze.CLIENT_TOOLS_CONFIGURED,{tools:D},c)},A=R=>{const D=R,T={code:D==null?void 0:D.code,reason:D==null?void 0:D.reason,wasClean:D==null?void 0:D.wasClean,timestamp:new Date().toISOString()};re.info("[socket.close]",T),kt(Ze.SOCKET_CLOSE,T,c)};return C&&typeof C=="object"&&(C.on(P.SocketMessage,k),C.on(P.SocketClose,A)),t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",g),t.on("transcript.item",m),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",g),t.off("transcript.item",m),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,A))}},[t,n,s,o,r,l])},oS=2e3;async function rS(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Bf(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 aS=(t,e)=>{const[i,n]=Ae([]),[,s]=Cr(),o=he(e);xe(()=>{o.current=e},[e]);const r=he(void 0),a=he(void 0);return xe(()=>{if(!t)return;const c=h=>{n(g=>{const m=g[g.length-1];if(h.role==="assistant"&&m&&Bf(m.id)===Bf(h.id)&&m.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&m.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&m.greetingLatencyMs===void 0,y={...m,content:m.content+h.content,timestamp:h.timestamp,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return v&&(r.current=void 0),b&&(a.current=void 0),[...g.slice(0,-1),y]}if(h.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...g,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=g.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...g];return y[v]={...g[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(m&&m.role==="user"&&h.timestamp.getTime()-m.timestamp.getTime()<oS){const C={...m,id:h.id,content:m.content+" "+h.content,timestamp:h.timestamp,attachments:[...m.attachments||[],...h.attachments||[]]};return[...g.slice(0,-1),C]}const b=h.attachments&&h.attachments.length>0;s(b?"processing_image":"thinking")}return[...g,h]})},u=({state:h,userPerceivedLatencyMs:g,greetingLatencyMs:m,thinkingStartedAt:v})=>{(g!==void 0||m!==void 0)&&re.info(`[AgentState] state=${h} userPerceivedLatencyMs=${g} greetingLatencyMs=${m} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),g!==void 0&&(r.current=g),m!==void 0&&(a.current=m)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var m;const g=(m=h.call)==null?void 0:m.state;(g==="destroy"||g==="done")&&n([])};return t.on("transcript.item",c),t.on("conversation.agent.state",u),t.on("conversation.update",d),()=>{t.off("transcript.item",c),t.off("conversation.agent.state",u),t.off("conversation.update",d)}},[t,s]),{transcript:i,sendMessage:async(c,u)=>{if(!t)return;const d=[];if(u&&u.length>0)for(const h of u)try{const g=await rS(h);d.push(g)}catch(g){throw re.error("Failed to convert file to base64:",g),g}t.sendConversationMessage(c,d)}}},$i={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class lS{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),re.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&&(re.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($i.INVOKED,this.boundInvoked),e.on($i.COMPLETED,this.boundCompleted),e.on($i.ERROR,this.boundError),this.handlers.size>0&&re.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off($i.INVOKED,this.boundInvoked),this.boundCompleted&&e.off($i.COMPLETED,this.boundCompleted),this.boundError&&e.off($i.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function pa(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const cS=(t,e)=>{const i=he(null);i.current===null&&(i.current=new lS),Js(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){re.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=>{pa(s(),Ze.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{pa(s(),Ze.CLIENT_TOOL_COMPLETED,o)},onError:o=>{pa(s(),Ze.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},dS=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=ni(),[r,a]=Ae(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=aS(e,i),d=he(!1);switch(xe(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(g=>{g.enabled=!1,re.info(`[ChatMode] Disabled remote audio track: ${g.label}`)}))}},[n,t]),r){case"collapsed":return L(Qu,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return L(C0,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return L(Qu,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},ga=()=>L(Ii.div,{layoutId:vn,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:L("div",{className:"rounded-full animate-spin",children:L(zy,{})})}),uS=({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 L(ga,{});case"done":case"purged":case"destroy":return null;case"active":return L(dS,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return L(ga,{})}},hS=({className:t})=>L("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:[L("g",{clipPath:"url(#:R5lfm:)",children:[L("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"}),L("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"}),L("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"}),L("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"}),L("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"})]}),L("defs",{children:L("clipPath",{id:":R5lfm:",children:L("rect",{width:"236",height:"211",fill:"currentColor"})})})]});function Uf(){const t=ni();return t.logo_icon_url?L("div",{className:"object-center w-8 h-8 mr-2 overflow-hidden rounded-full",children:L("img",{src:t.logo_icon_url,className:"object-cover w-full h-full",alt:"Logo"})}):L(hS,{className:"w-8 h-8 mr-2"})}const fS=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=ni(),o=he(!1),r=qe(async()=>{if(!t){re.error("Client is not initialized.");return}if(!n){re.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){re.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return xe(()=>{i&&t&&n&&!o.current&&(o.current=!0,re.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?L(Ii.div,{layoutId:vn,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:[L(Uf,{}),"Connecting..."]}):L(Ii.button,{layoutId:vn,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:[L(Uf,{}),s.start_call_text]})},pS='@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)}}',gS=({children:t})=>L("main",{className:"fixed inset-0 z-[9999] pointer-events-none",children:L("div",{className:"absolute bottom-0 right-0 pointer-events-auto md:bottom-10 md:right-10",children:t})}),mS={duration:.1,ease:"circOut"},vS=({children:t,position:e="fixed",rootRef:i})=>{const n=ni(),o=(e??n.position??"fixed")==="fixed"?L(gS,{children:t}):t;return L("div",{ref:i,className:Lt(n.theme==="dark"&&"dark"),children:L(Bm,{transition:mS,children:[L("style",{children:pS}),o]})})},_S=t=>L(Ii.div,{layoutId:vn,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:[L(Gy,{className:"w-8 h-8 text-red-400"}),L("h1",{className:"mt-2 mb-4 text-2xl font-medium",children:"An error occurred"}),L("ul",{className:"gap-4 ml-4 text-sm list-disc mb-4",children:[L("li",{children:"Failed to initialize the Telnyx AI Agent client. Please check your agent ID and ensure that you are connected to the internet."}),L("li",{children:["Make sure that the"," ",L("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"," ",L(e0,{className:"w-4 h-4"})]})," ","option is enabled in your Telnyx agent settings."]})]}),t.onRetry&&L("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:[L(Zy,{className:"w-4 h-4"}),"Retry"]})]});function ji(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Vf(t,e){return t===void 0?e:ji(t)}function yS({"agent-id":t,debug:e,"trickle-ice":i,"prefetch-ice-candidates":n,"call-destination-number":s,"call-caller-number":o,"call-caller-name":r,"call-custom-headers":a,"call-audio":l,vad:c,"show-user-perceived-latency":u,"show-greeting-latency":d,"conversation-id":h,"chat-mode":g,region:m,"skip-last-voice-sdk-id":v,environment:b,position:y="fixed","version-id":C}){const k=ji(e),A=Vf(i,!0),R=Vf(n,!0),D=ji(g),T=v===void 0?!0:ji(v),E=it(()=>{if(c)try{return JSON.parse(c)}catch(ne){re.error("Invalid JSON for vad attribute:",c,ne);return}},[c]),p=it(()=>({showUserPerceivedLatency:ji(u),showGreetingLatency:ji(d)}),[u,d]),{client:_,error:f,isConnected:S,isReconnecting:I}=tS(t,b,C,k,A,R,E,h,D,m,T),[M,x]=Ae(null),[N,O]=Ae(!1),[F,V]=Ae(!1),[$,Q]=Ae(!1),[J,G]=Ae(!1),de=Hn(Ju),Z=_y(),Y={};if(s&&(Y.destinationNumber=s),o&&(Y.callerNumber=o),r&&(Y.callerName=r),a)try{Y.customHeaders=JSON.parse(a)}catch(ne){re.error("Invalid JSON for call-custom-headers attribute:",a,ne)}if(l)try{Y.audio=JSON.parse(l);const ne=Y.audio;if(typeof ne=="object"){const oe=navigator.mediaDevices.getSupportedConstraints();Object.keys(ne).forEach(Qe=>{oe[Qe]||re.warn(`Audio constraint not supported by browser: ${Qe}`)})}}catch(ne){re.error("Invalid JSON for call-audio attribute:",l,ne)}const ie=qe(()=>{O(!1)},[]),se=qe(ne=>{var oe;if(((oe=ne.call)==null?void 0:oe.state)==="destroy")return de(!1),G(!0),x(null);x(ne)},[de]),ge=qe(()=>{O(!1),I||V(!0)},[I]),Fe=qe(()=>{re.info("User triggered retry"),V(!1),O(!0),_&&_.connect()},[_]),me=qe(ne=>{if(vy(ne)){const oe=ne.params.widget_settings;oe&&Object.keys(oe).length>0&&(Z(oe),Q(!0))}},[Z]),Ie=he(null);return sS(_,{onReady:ie,onConversationUpdate:se,onError:ge,onConfigMessage:me},Ie),cS(_,Ie),L(vS,{position:y,rootRef:Ie,children:t?F||f?L(_S,{agentId:t,onRetry:Fe}):N||I?L(ga,{message:I?"Retrying...":void 0}):M!=null&&M.call?L(uS,{call:M.call,client:_,latencySettings:p,chatMode:D,debug:k}):$?L(fS,{client:_,callProps:Y,chatMode:D&&!J,isReady:S&&!!_}):null:L("div",{children:"Please provide an assistant ID."})})}np(yS,"telnyx-ai-agent",gy,{shadow:!0})})();
|
|
119
|
+
`)}))}),w.info(n)}),2e3)}}class $s extends fi{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=>$s.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=je(lb),s=this.calls[e],o=s?this._extractSafeCallIdentifiers(s):{callId:e};j(F.Warning,{warning:n,callId:e,sessionId:this.sessionid,newCall:o,activeCalls:i.map(r=>this._extractSafeCallIdentifiers(r))},this.uuid),w.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 U(this,void 0,void 0,function*(){return e.getIsRegistered.call(this)})}connect(){const e=Object.create(null,{connect:{get:()=>super.connect}});return U(this,void 0,void 0,function*(){w.debug("BrowserSession.connect() called"),e.connect.call(this)})}checkPermissions(e=!0,i=!0){return U(this,void 0,void 0,function*(){try{const n=yield Ns({audio:e,video:i});return Mn(n),!0}catch{return!1}})}logout(){this.disconnect()}disconnect(){const e=Object.create(null,{disconnect:{get:()=>super.disconnect}});return U(this,void 0,void 0,function*(){w.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(z.Purge),w.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 U(this,void 0,void 0,function*(){w.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(z.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(Wh(F.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 On().catch(e=>{const i=ae(Vi(e),e);return j(F.MediaError,i,this.uuid),[]})}getVideoDevices(){return On(Lt.Video).catch(e=>(j(F.MediaError,e,this.uuid),[]))}getAudioInDevices(){return On(Lt.AudioIn).catch(e=>{const i=ae(Vi(e),e);return j(F.MediaError,i,this.uuid),[]})}getAudioOutDevices(){return On(Lt.AudioOut).catch(e=>(w.error("getAudioOutDevices",e),j(F.MediaError,e,this.uuid),[]))}validateDeviceId(e,i,n){return Fs(e,i,n)}getDeviceResolutions(e){return U(this,void 0,void 0,function*(){try{return yield(i=>U(void 0,void 0,void 0,function*(){const n=[],s=yield Ns({video:{deviceId:{exact:i}}}),o=s.getVideoTracks()[0];for(let r=0;r<tf.length;r++){const[a,l]=tf[r];(yield o.applyConstraints({width:{exact:a},height:{exact:l}}).then(()=>!0).catch(()=>!1))&&n.push({resolution:`${a}x${l}`,width:a,height:l})}return Mn(s),n}))(e)}catch(i){throw i}})}get mediaConstraints(){return{audio:this._audioConstraints,video:this._videoConstraints}}setAudioSettings(e){return U(this,void 0,void 0,function*(){if(!e)throw new Error("You need to provide the settings object");const{micId:i,micLabel:n}=e,s=ph(e,["micId","micLabel"]);return Yb(s),this._audioConstraints=yield((o,r,a,l)=>U(void 0,void 0,void 0,function*(){const{deviceId:c}=l;if(c===void 0&&(o||r)){const u=yield Fs(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?Sb:wb}}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=An(e)}get localElement(){return this._localElement}get localElementId(){return this._localElementId}set remoteElement(e){this._remoteElementId=typeof e=="string"?e:null,this._remoteElement=An(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 Wb({sessid:this.sessionid,eventChannel:i,data:n});e&&(s.targetNodeId=e),this.execute(s).catch(o=>o)}vertoSubscribe({nodeId:e,channels:i=[],handler:n}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(l=>l&&!this._existsSubscription(this.relayProtocol,l))).length)return{};const s=new Gb({sessid:this.sessionid,eventChannel:i});e&&(s.targetNodeId=e);const o=yield this.execute(s),{unauthorized:r=[],subscribed:a=[]}=ta(o);return r.length&&r.forEach(l=>this._removeSubscription(this.relayProtocol,l)),a.forEach(l=>this._addSubscription(this.relayProtocol,n,l)),o})}vertoUnsubscribe({nodeId:e,channels:i=[]}){return U(this,void 0,void 0,function*(){if(!(i=i.filter(a=>a&&this._existsSubscription(this.relayProtocol,a))).length)return{};const n=new qb({sessid:this.sessionid,eventChannel:i});e&&(n.targetNodeId=e);const s=yield this.execute(n),{unsubscribed:o=[],notSubscribed:r=[]}=ta(s);return o.forEach(a=>this._removeSubscription(this.relayProtocol,a)),r.forEach(a=>this._removeSubscription(this.relayProtocol,a)),s})}static telnyxStateCall(e){return gi.setStateTelnyx(e)}}$s.ACTIVE_CALL_STATE_NAMES=new Set(["new","requesting","trying","recovering","ringing","answering","early","active","held"]);class pf{constructor(e,i){this.code=i,this.message=e}}class cw{constructor(e){this.session=e,this.retriedConnect=0,this.retriedRegister=0}_ack(e,i){const n=new Vb(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;const{session:d}=this;d.setPingReceived();const{id:h,method:p,params:m={},voice_sdk_id:v}=e,b=m==null?void 0:m.callID,y=m==null?void 0:m.eventChannel,C=m==null?void 0:m.eventType,T=d.calls[b],A=(i=T==null?void 0:T.peer)===null||i===void 0?void 0:i.isConnectionHealthy(),x=new Set(Object.keys(d.calls));if(Array.isArray(m==null?void 0:m.reattached_sessions)&&x.size){w.debug(`Reattach: active call IDs before cleanup check: [${Array.from(x).join(", ")}].`);const f=m.reattached_sessions.length===0,_=m.reattached_sessions.some(g=>x.has(g));if(f||!_)for(const g of Object.keys(d.calls)){const S=d.calls[g];w.debug(`Session not reattached — terminating active call ${g} `);const I=ae(Sh);j(F.Error,{error:I,callId:g,sessionId:d.sessionid},d.uuid),S.hangup({},!1)}}if(Array.isArray(m==null?void 0:m.reattached_sessions)&&d.sessionid){const f=Bh();if(f&&f.calls.length>0)if(f.sessionId!==d.sessionid)w.debug(`Recovery markers were saved for a different sessid (saved=${f.sessionId}, current=${d.sessionid}) — ignoring all.`),hi();else{const _=new Set(m.reattached_sessions),g=[];for(const S of f.calls)try{if(_.has(S.id)){w.debug(`Recovery marker for call ${S.id} was reattached — keeping for Attach element restore.`),g.push(S);continue}w.info(`Recovery marker for call ${S.id} (sessid=${d.sessionid}) was not reattached — emitting SESSION_NOT_REATTACHED.`);const I=ae(Sh);j(F.Error,{error:I,callId:S.id,sessionId:d.sessionid,customHeaders:S.customHeaders},d.uuid)}catch(I){w.debug(`Recovery marker for a saved call failed to process (callId=${S==null?void 0:S.id}) — skipping: ${I instanceof Error?I.message:String(I)}`),g.push(S)}Vh(g,f.sessionId,f.storedAt)}}if(C==="channelPvtData")return this._handlePvtEvent(m.pvtData);const N=({recoveredCallId:f,forceRelayCandidateForRecovery:_,mutedMicOnStart:g,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M}={})=>{var R,P,O,L,V,$;const W={audio:!0,video:d.options.video,remoteSdp:m.sdp,destinationNumber:m.callee_id_number,remoteCallerName:m.caller_id_name,remoteCallerNumber:m.caller_id_number,callerName:m.callee_id_name,callerNumber:m.callee_id_number,attach:p===ie.Attach,mediaSettings:m.mediaSettings,debug:(R=d.options.debug)!==null&&R!==void 0&&R,debugOutput:(P=d.options.debugOutput)!==null&&P!==void 0?P:"socket",trickleIce:(O=d.options.trickleIce)!==null&&O!==void 0&&O,prefetchIceCandidates:(L=d.options.prefetchIceCandidates)!==null&&L!==void 0&&L,forceRelayCandidate:typeof _=="boolean"?_:(V=d.options.forceRelayCandidate)!==null&&V!==void 0&&V,keepConnectionAliveOnSocketClose:($=d.options.keepConnectionAliveOnSocketClose)!==null&&$!==void 0&&$,mutedMicOnStart:g??d.options.mutedMicOnStart};b&&(W.id=b),m.telnyx_call_control_id&&(W.telnyxCallControlId=m.telnyx_call_control_id),m.telnyx_session_id&&(W.telnyxSessionId=m.telnyx_session_id),m.telnyx_leg_id&&(W.telnyxLegId=m.telnyx_leg_id),m.client_state&&(W.clientState=m.client_state),m.dialogParams&&m.dialogParams.custom_headers&&m.dialogParams.custom_headers.length&&(W.customHeaders=m.dialogParams.custom_headers),f&&(W.recoveredCallId=f),M&&(W.wasHeldBeforeRecovery=M),S!==void 0&&(W.remoteElement=S),I!==void 0&&(W.localElement=I),performance.mark(le(W.id,"new-call-start"));const q=new gi(d,W);return q.nodeId=this.nodeId,q},E=new zh(v),k=new Jr(v);switch(p){case ie.Answer:case ie.Display:case ie.Candidate:case ie.Ringing:case ie.Bye:case ie.Media:if(!b||!T)return void w.error(`Received ${p} for non existing call:`,m);T.handleMessage(e),this._ack(h,p);break;case ie.Ping:this.session.setPingReceived(),this.session.execute(k);break;case ie.Punt:d.options.keepConnectionAliveOnSocketClose&&A?(w.info("[punt] Received PUNT from server. keepConnectionAliveOnSocketClose=true — disconnecting socket only, keeping calls alive."),d.socketDisconnect(),this._ack(h,p)):(w.info("[punt] Received PUNT from server — calling serverDisconnect() to purge all calls without BYE."),d.serverDisconnect());break;case ie.Invite:{const g=N();g.direction=Dt.Inbound,g.playRingtone(),g.setState(z.Ringing),this.session.emitMultipleActiveCallsWarning(g.id),this._ack(h,p);break}case ie.Attach:{const g=T||null;if(Object.keys(d.calls).length===0){let S,I;w.warn(`[${new Date().toISOString()}][${b}] Attach: SDK doens't have any active call therefore we recover first arrived attach session ${b}`);let M=!1,R=!1;const P=Bh();if(P&&P.sessionId===d.sessionid){const L=P.calls.find(V=>V!==null&&typeof V=="object"&&V.id===b);L&&(S=L.remoteElement,I=L.localElement,M=L.wasHeld===!0,typeof L.forceRelayCandidate=="boolean"&&(R=L.forceRelayCandidate),(S||I)&&w.info(`[${b}] Attach: restoring per-call media elements from recovery marker (remoteElement=${S??"<none>"}, localElement=${I??"<none>"}).`),typeof L.forceRelayCandidate=="boolean"&&w.info(`[${b}] Attach: restoring forceRelayCandidate=${L.forceRelayCandidate} from recovery marker.`))}const O=N({recoveredCallId:b,forceRelayCandidateForRecovery:R,remoteElement:S,localElement:I,wasHeldBeforeRecovery:M});O.answer(),this.session.emitMultipleActiveCallsWarning(O.id),this._ack(h,p);break}if(g){const S=g.id,I=g.state==="held",M=g.shouldForceRelayCandidateForRecovery();M&&w.warn(`[${new Date().toISOString()}][${b}] Attach: forcing relay candidate for recovery`),w.info(`[${new Date().toISOString()}][${b}] Attach: recovering active call ${S}.`),g.hangup({isRecovering:!0,initiator:"sdk:attach-recovery"},!1);const R=N({recoveredCallId:S,forceRelayCandidateForRecovery:M,mutedMicOnStart:g.isAudioMuted,remoteElement:g.options.remoteElement,localElement:g.options.localElement,wasHeldBeforeRecovery:I});R.answer(),this.session.emitMultipleActiveCallsWarning(R.id),this._ack(h,p);break}w.warn(`Attach: callID ${b} does not match any active calls. `),j(F.Warning,{warning:je(hb),callId:b,params:m,sessionId:d.sessionid},d.uuid),this._ack(h,p);break}case ie.Event:case"webrtc.event":if(!y)return void w.error("Verto received an unknown event:",m);const f=d.relayProtocol,_=y.split(".")[0];d._existsSubscription(f,y)?j(f,m,y):y===d.sessionid?this._handleSessionEvent(m.eventData):d._existsSubscription(f,_)?j(f,m,_):d.calls.hasOwnProperty(y)?d.calls[y].handleMessage(e):j(F.Notification,m,d.uuid);break;case ie.Info:m.type=gt.generic,j(F.Notification,m,d.uuid);break;case ie.ClientReady:this.session.execute(E);break;case"ai_conversation":j(F.AIConversationMessage,{method:"ai_conversation",params:m,voice_sdk_id:v},d.uuid);break;default:{const g=Gr(e);if(g){switch(g){case Ue.REGISTER:case Ue.REGED:if(!this.isDuplicateGatewayState(g,[Ue.REGED,Ue.REGISTER])){this.session._triggerKeepAliveTimeoutCheck(),this.retriedRegister=0,g===Ue.REGED&&this.session.resetReconnectAttempts();const S=(s=(n=e==null?void 0:e.result)===null||n===void 0?void 0:n.params)===null||s===void 0?void 0:s.call_report_id;S&&(d.callReportId=S,w.debug("Captured call_report_id from REGED:",S));const I=(r=(o=e==null?void 0:e.result)===null||o===void 0?void 0:o.params)===null||r===void 0?void 0:r.dc;I&&(d.dc=I);const M=(l=(a=e==null?void 0:e.result)===null||a===void 0?void 0:a.params)===null||l===void 0?void 0:l.region;M&&(d.region=M),w.info(`Connected to Telnyx — region: ${(c=d.region)!==null&&c!==void 0?c:"unknown"}, dc: ${(u=d.dc)!==null&&u!==void 0?u:"unknown"}`),m.type=gt.vertoClientReady,j(F.Ready,m,d.uuid)}break;case Ue.UNREGED:case Ue.NOREG:if(this.retriedRegister+=1,this.retriedRegister===5){this.retriedRegister=0;const S=new pf("Fail to register the user, the server tried 5 times","UNREGED|NOREG"),I=ae(wh,S);j(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{this.session.execute(E)},this.reconnectDelay());break;case Ue.FAILED:case Ue.FAIL_WAIT:case Ue.TIMEOUT:if(!this.isDuplicateGatewayState(g,[Ue.FAILED,Ue.FAIL_WAIT,Ue.TIMEOUT])){const S=ae(W0,new Error(`Gateway state: ${g}`));if(j(F.Error,{error:S,sessionId:d.sessionid},d.uuid),d.options.skipLastVoiceSdkId=!0,w.debug(`Set skipLastVoiceSdkId=true on session options to avoid sticky reconnect to same b2bua-rtc instance (sessionId=${d.sessionid})`),!this.session.hasAutoReconnect()){this.retriedConnect=0;const I=new pf("Fail to connect the server, the server tried 5 times","FAILED|FAIL_WAIT|TIMEOUT");this.session._terminateActiveCallsLocally();const M=ae(jr,I);j(F.Error,{error:M,sessionId:d.sessionid},d.uuid);break}if(this.retriedConnect+=1,this.retriedConnect===5){this.retriedConnect=0,this.session._terminateActiveCallsLocally();const I=ae(jr,new Error("Connection Retry Failed"));j(F.Error,{error:I,sessionId:d.sessionid},d.uuid);break}setTimeout(()=>{if(w.debug(`Reconnecting... Retry ${this.retriedConnect} of 5`),this.session.options.keepConnectionAliveOnSocketClose){if(Object.values(d.calls).some(I=>{var M;return((M=I.peer)===null||M===void 0?void 0:M.instance)&&!I.signalingStateClosed}))return w.debug("Reconnecting by keeping the existing session due to keepConnectionAliveOnSocketClose option being set."),void this.session.socketDisconnect();w.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:w.warn("GatewayState message unknown method:",e)}break}w.debug("Verto message unknown method:",e);break}}}isDuplicateGatewayState(e,i){const{previousGatewayState:n}=this.session.connection,s=i.includes(n);return s&&w.debug(`Gateway state '${e}' received but previous state was '${n}' — guard condition met, skipping re-emission (sessionId=${this.session.sessionid})`),s}_retrieveCallId(e,i){const n=Object.keys(this.session.calls);if(e.action!=="bootObj")return n.find(s=>this.session.calls[s].channels.includes(i));{const s=e.data.find(o=>n.includes(o[0]));if(s instanceof Array)return s[0]}}_handlePvtEvent(e){return U(this,void 0,void 0,function*(){const{session:i}=this,n=i.relayProtocol,{action:s,laChannel:o,laName:r,chatChannel:a,infoChannel:l,modChannel:c,conferenceMemberID:u,role:d,callID:h}=e;switch(s){case"conference-liveArray-join":{const p=()=>{i.vertoBroadcast({nodeId:this.nodeId,channel:o,data:{liveArray:{command:"bootstrap",context:o,name:r}}})},m={nodeId:this.nodeId,channels:[o],handler:({data:b})=>{const y=h||this._retrieveCallId(b,o);if(y&&i.calls.hasOwnProperty(y)){const C=i.calls[y];C._addChannel(o),C.extension=r,C.handleConferenceUpdate(b,e).then(T=>{T==="INVALID_PACKET"&&p()})}}},v=yield i.vertoSubscribe(m).catch(b=>{w.error("liveArray subscription error:",b);const y=ae($0,b);j(F.Error,{error:y,sessionId:i.sessionid},i.uuid)});ea(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:gt.conferenceUpdate,action:ot.Leave,conferenceName:r,participantId:Number(u),role:d};j(F.Notification,b,v,!1)||j(F.Notification,b,i.uuid),p===null&&Mt(F.Notification,null,v)}}const m=[o,a,l,c];i.vertoUnsubscribe({nodeId:this.nodeId,channels:m}).then(({unsubscribedChannels:v=[]})=>{p&&(p.channels=p.channels.filter(b=>!v.includes(b)))}).catch(v=>{w.error("liveArray unsubscribe error:",v)});break}}})}_handleSessionEvent(e){switch(e.contentType){case"layout-info":case"layer-info":cf(this.session,e);break;case"logo-info":{const i={type:gt.conferenceUpdate,action:ot.LogoInfo,logo:e.logoURL};j(F.Notification,i,this.session.uuid);break}}}}class dw extends $s{constructor(e){super(e),this.relayProtocol="verto-protocol",this.timeoutErrorCode=-329990,this.handleLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1;const{autoReconnect:i=!0}=this.options;yield this.login({onSuccess:()=>{this._autoReconnect=i}})}),this.handleAnonymousLoginOnSocketOpen=()=>U(this,void 0,void 0,function*(){this._idle=!1,yield this.login()}),this._vertoHandler=new cw(this),window.addEventListener("beforeunload",i=>{if(w.debug("Window beforeunload triggered."),e.hangupOnBeforeUnload!==!1)return Uh(),void(this.calls&&Object.keys(this.calls).forEach(n=>{this.calls[n]&&(w.info(`Hanging up call due to window unload: ${n}`),this.calls[n].hangup({initiator:"sdk:beforeunload"},!0))}));try{const n=this.getActiveCalls().map(s=>{const o={id:s.id,customHeaders:s.options.customHeaders,forceRelayCandidate:s.shouldForceRelayCandidateForRecovery()};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.getActiveCalls().forEach(s=>{if(s.flushIntermediateCallReport)try{w.debug(`beforeunload: flushing call report for ${s.id}.`),s.flushIntermediateCallReport({type:"page-unload"})}catch(o){w.debug(`beforeunload: failed to flush call report for ${s.id}: ${o instanceof Error?o.message:String(o)}`)}}),!this.sessionid||n.length===0)return w.debug(`No sessionID ${this.sessionid} or activeCalls ${n.length} during saving calls recover marker!`),void hi();w.info(`Saving recovery marker for ${n.length} active call(s) before unload (sessid=${this.sessionid}): [${n.map(s=>s.id).join(", ")}].`),Vh(n,this.sessionid)}catch(n){const s=this.calls?Object.keys(this.calls):[];w.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()&&(w.debug("visibilitychange → hidden: re-stamping reconnect session-id freshness."),Kr(this.sessionid))})}validateOptions(){return Rs(this.options)||Rn(this.options)}newCall(e){if(!this.validateCallOptions(e))throw ae(B0,void 0,"Error: destinationNumber is required");const i=new gi(this,e);return e.id||w.debug(`newCall: callId was not provided in options, SDK-generated ID: ${i.id}`),this.emitMultipleActiveCallsWarning(i.id),performance.mark(le(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!!Rn(this.options)||!!e.destinationNumber}_onSocketOpen(){const e=Object.create(null,{_onSocketOpen:{get:()=>super._onSocketOpen}});return U(this,void 0,void 0,function*(){return e._onSocketOpen.call(this),Rs(this.options)?this.handleLoginOnSocketOpen():Rn(this.options)?this.handleAnonymousLoginOnSocketOpen():void 0})}_onSocketMessage(e){this._vertoHandler.handleMessage(e)}}function gf(t){return{options:t,statsSamples:[]}}function uw(t){var e,i;const n=(i=(e=t.call)===null||e===void 0?void 0:e.peer)===null||i===void 0?void 0:i.instance,s=t.statsSamples[t.statsSamples.length-1];if(!n||!s)return;const o=function(a,l){var c;const u=[],d=new Set,h=new Map,p=new Map,m={host:0,srflx:0,prflx:0,relay:0};a.forEach(k=>{switch(k.type){case"local-candidate":{const f=k;m[f.candidateType]++,p.set(f.id,f);break}case"remote-candidate":{const f=k;h.set(f.id,f);break}case"candidate-pair":{const f=k;u.push(f);break}case"transport":{const f=k;typeof f.selectedCandidatePairId=="string"&&d.add(f.selectedCandidatePairId);break}}});const v=function(k,f,_,g){var S,I;const M=k.find(V=>f.has(V.id)),R=k.find(V=>V.selected===!0),P=k.find(V=>V.nominated===!0&&V.state==="succeeded"),O=k.filter(V=>V.state==="succeeded"),L=(I=(S=M??R)!==null&&S!==void 0?S:P)!==null&&I!==void 0?I:O.length===1?O[0]:void 0;return L?Object.assign(Object.assign({},L),{localCandidate:_.get(L.localCandidateId),remoteCandidate:g.get(L.remoteCandidateId)}):null}(u,d,p,h),b=m.relay>0,y=m.srflx===0&&m.relay===0&&m.prflx===0,C=l.iceGatheringState,T=l.iceConnectionState,A=C==="complete",x=((c=v==null?void 0:v.localCandidate)===null||c===void 0?void 0:c.candidateType)==="relay",{hasMultipleNetworkInterfaces:N,vpnDetected:E}=function(k){if(k.size===0)return{hasMultipleNetworkInterfaces:void 0,vpnDetected:void 0};const f=Array.from(k.values());return{hasMultipleNetworkInterfaces:new Set(f.filter(_=>_.candidateType==="host").map(_=>_.address)).size>=2,vpnDetected:f.some(_=>_.networkType==="vpn")}}(p);return{candidateGatheringCompleted:A,gatheringComplete:A,candidateCounts:m,candidates:Array.from(p.values()),hasRelayCandidate:b,onlyHostCandidates:y,isTurnRequired:x,hasMultipleNetworkInterfaces:N,vpnDetected:E,hasSelectedPair:!!v,selectedPair:v??void 0,iceGatheringState:C,iceConnectionState:T}}(s,n),r=n.getConfiguration().iceServers;return r&&(o.serverCandidateComparison=function(a,l){var c,u;if(!a||a.length===0)return;const d=[];for(const h of a){const p=Array.isArray(h.urls)?h.urls:[h.urls],m=l.filter(y=>p.some(C=>hw(y.url,C,y.protocol))),v=(u=(c=m[0])===null||c===void 0?void 0:c.candidateType)!==null&&u!==void 0?u:null,b=m.length>0;d.push({urls:h.urls,hasCandidates:b,candidateType:v,candidates:m,candidateCount:m.length})}return d}(r,o.candidates)),o}function mf(t){return(Array.isArray(t.urls)?t.urls:[t.urls]).some(e=>/^turns?:/i.test(e))}function vf(t){var e;let i=t;const n=i.match(/^([a-z]+:)(\/\/)?([^@]*@)(.+)$/i);n&&(i=n[1]+((e=n[2])!==null&&e!==void 0?e:"")+n[4]);const s=i.indexOf("?transport=");return s!==-1&&(i=i.substring(0,s)),i}function _f(t){const e=t.indexOf("?transport=");if(e===-1)return;const i=t.substring(e+11).toLowerCase(),n=i.indexOf("&");return n===-1?i:i.substring(0,n)}function hw(t,e,i){var n;if(!t||!e||vf(t)!==vf(e))return!1;const s=_f(e);if(s===void 0)return!0;const o=(n=_f(t))!==null&&n!==void 0?n:i==null?void 0:i.toLowerCase();return o===void 0||o===s}const sa=2e3,fw=100,yf=.01,pw="To check your microphone, we will be recorded your voice for a few seconds and played back to you so you can hear how it sounds.";function gw(){var t;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((t=navigator.mediaDevices)===null||t===void 0?void 0:t.getUserMedia)!="function")return{report:{activeCapturePerformed:!1,captureError:"not_supported",captureErrorMessage:"getUserMedia is not available in this environment"},stream:void 0};try{return{report:{deviceAvailable:!0},stream:yield navigator.mediaDevices.getUserMedia({audio:!0})}}catch(e){const{captureError:i,captureErrorMessage:n}=function(s){const o=s&&typeof s=="object"&&"name"in s?String(s.name):"",r=s instanceof Error?s.message:String(s);return o==="NotAllowedError"||o==="PermissionDeniedError"||o==="SecurityError"?{captureError:"permission_denied",captureErrorMessage:`Microphone permission denied: ${r}`}:o==="NotFoundError"||o==="DevicesNotFoundError"||o==="OverconstrainedError"||o==="ConstraintNotSatisfiedError"?{captureError:"no_device",captureErrorMessage:`No microphone device found: ${r}`}:o==="TypeError"?{captureError:"not_supported",captureErrorMessage:`Microphone capture is not supported: ${r}`}:{captureError:"unknown",captureErrorMessage:r}}(e);return{report:{activeCapturePerformed:!1,captureError:i,captureErrorMessage:n,deviceAvailable:!1},stream:void 0}}})}function mw(t,e,i){return U(this,void 0,void 0,function*(){if(typeof AudioContext>"u")return null;let n,s,o;try{n=new AudioContext,s=n.createAnalyser(),o=n.createMediaStreamSource(t),s.fftSize=2048,o.connect(s);const r=new Float32Array(s.fftSize),a=Date.now()+e;let l=0,c=0,u=0;for(;Date.now()<a;){s.getFloatTimeDomainData(r);let d=0;for(const m of r)d+=m*m;const h=Math.sqrt(d/r.length);l=Math.max(l,h),c+=h,u+=1;const p=a-Date.now();p>0&&(yield new Promise(m=>setTimeout(m,Math.min(fw,p))))}return{audioLevel:l,audioDetected:l>=i,audioLevelStats:{peak:l,average:u>0?c/u:0,samples:u}}}catch{return null}finally{try{o==null||o.disconnect(),s==null||s.disconnect(),yield n==null?void 0:n.close()}catch{}}})}function vw(t,e){return U(this,void 0,void 0,function*(){if(typeof MediaRecorder<"u")try{const i=["audio/webm;codecs=opus","audio/webm"].find(r=>typeof MediaRecorder.isTypeSupported!="function"||MediaRecorder.isTypeSupported(r)),n=i?new MediaRecorder(t,{mimeType:i}):new MediaRecorder(t),s=[],o=Date.now();return yield new Promise(r=>{let a=!1;const l=d=>{a||(a=!0,clearTimeout(c),clearTimeout(u),r(d))};n.ondataavailable=({data:d})=>{d.size>0&&s.push(d)},n.onerror=()=>l(),n.onstop=()=>U(this,void 0,void 0,function*(){const d=n.mimeType||i||"audio/webm",h=yield(p=new Blob(s,{type:d}),new Promise(m=>{try{const v=new FileReader;v.onloadend=()=>m(typeof v.result=="string"?v.result:void 0),v.onerror=()=>m(void 0),v.readAsDataURL(p)}catch{m(void 0)}}));var p;l(h?{recordingDataUrl:h,recordingMimeType:d,recordingDurationMs:Date.now()-o}:void 0)});const c=setTimeout(()=>{try{n.state!=="inactive"&&n.stop()}catch{l()}},e),u=setTimeout(()=>l(),e+1e3);n.start()})}catch{return}})}function bf(t){var e,i;return U(this,void 0,void 0,function*(){const n=function(p){var m,v;const b=p&&typeof p=="object"?p:void 0;return{sampleDurationMs:Math.max(0,(m=b==null?void 0:b.sampleDurationMs)!==null&&m!==void 0?m:sa),silenceThreshold:Math.min(1,Math.max(0,(v=b==null?void 0:b.silenceThreshold)!==null&&v!==void 0?v:yf)),record:(b==null?void 0:b.record)===!0,warnOnRecording:b==null?void 0:b.warnOnRecording}}(t.options.microphone),s=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator>"u"||typeof((p=navigator.permissions)===null||p===void 0?void 0:p.query)!="function")return"unknown";try{return(yield navigator.permissions.query({name:"microphone"})).state}catch{return"unknown"}})}(),{report:o,stream:r}=yield gw(),a=yield function(){var p;return U(this,void 0,void 0,function*(){if(typeof navigator<"u"&&typeof((p=navigator.mediaDevices)===null||p===void 0?void 0:p.enumerateDevices)=="function")try{const m=(yield navigator.mediaDevices.enumerateDevices()).filter(({kind:v})=>v==="audioinput").map(({deviceId:v,label:b})=>({deviceId:v||"",label:b||"",kind:"audioinput"}));return{devices:m,deviceCount:m.length,deviceAvailable:m.length>0,labelsAccessible:m.some(({label:v})=>v.length>0)}}catch{return}})}(),l=r?"granted":o.captureError==="permission_denied"?"denied":s,c={currentPermissionState:l,isPermissionGrantedCurrently:l==="granted",isGetUserMediaFailed:!r,deviceAvailable:(a==null?void 0:a.deviceAvailable)||o.deviceAvailable||!1,deviceCount:(e=a==null?void 0:a.deviceCount)!==null&&e!==void 0?e:0,devices:(i=a==null?void 0:a.devices)!==null&&i!==void 0?i:[],labelsAccessible:a==null?void 0:a.labelsAccessible,captureError:o.captureError,captureErrorMessage:o.captureErrorMessage,activeCapturePerformed:o.activeCapturePerformed};if(r)try{const p=yield function(m,v,b){var y,C,T;return U(this,void 0,void 0,function*(){m.activeCapturePerformed=!0,m.recordingPerformed=b.record,b.record&&b.warnOnRecording&&b.warnOnRecording(pw);const[A,x]=yield Promise.all([mw(v,(y=b.sampleDurationMs)!==null&&y!==void 0?y:sa,(C=b.silenceThreshold)!==null&&C!==void 0?C:yf),b.record?vw(v,(T=b.sampleDurationMs)!==null&&T!==void 0?T:sa):Promise.resolve(void 0)]);return A&&(m.audioLevel=A.audioLevel,m.audioDetected=A.audioDetected,m.audioLevelStats=A.audioLevelStats),x&&(m.recordingDataUrl=x.recordingDataUrl,m.recordingMimeType=x.recordingMimeType,m.recordingDurationMs=x.recordingDurationMs,m.recordingPerformed=!0),x})}(c,r,n);p&&(c.playbackPerformed=yield(u=p.recordingDataUrl,d=p.recordingDurationMs+5e3,typeof Audio>"u"?Promise.resolve(!1):new Promise(m=>{let v,b=!1;const y=setTimeout(()=>C(!1),d),C=T=>{b||(b=!0,clearTimeout(y),v&&(v.onended=null,v.onerror=null,v.paused||v.pause(),v.src=""),m(T))};try{v=new Audio(u),v.onended=()=>C(!0),v.onerror=()=>C(!1),v.play().catch(()=>C(!1))}catch{C(!1)}})))}finally{try{r.getTracks().forEach(p=>p.stop())}catch{}}var u,d;const h=function(p){const m=[],v=(y,C)=>m.push({code:y,message:C,source:"microphone"});p.currentPermissionState==="denied"&&v("microphone_permission_denied","Microphone permission has been denied by the user."),p.deviceAvailable===!1&&v("microphone_no_device","No audio input device is available.");const b=p.captureError?{permission_denied:["microphone_capture_permission_denied","Active microphone capture was denied permission."],no_device:["microphone_capture_no_device","No microphone device was found for active capture."],not_supported:["microphone_capture_not_supported","Active microphone capture is not supported."],unknown:["microphone_capture_failed","Active microphone capture failed."]}[p.captureError]:void 0;return b&&v(...b),p.activeCapturePerformed&&p.audioDetected===!1&&v("microphone_silent","No audio was detected above the silence threshold during active capture."),m}(c);return h.length>0&&(c.reasons=h),Object.keys(c).length>0?c:void 0})}const oa=300,ra=500,aa=30,la=100,ca=.02,da=.05,js=8e3;function mt(t){if(typeof t=="number"&&!Number.isNaN(t)&&Number.isFinite(t))return t}function ua(t){const e=t.filter(o=>mt(o)!==void 0);if(e.length===0)return;let i=1/0,n=-1/0,s=0;for(const o of e)o<i&&(i=o),o>n&&(n=o),s+=o;return{min:i,max:n,average:s/e.length}}function ha(t){var e,i;const n=[],s=new Set;t.forEach(r=>{const a=r;n.push(a),a.type==="transport"&&typeof a.selectedCandidatePairId=="string"&&s.add(a.selectedCandidatePairId)});const o=n.filter(r=>r.type==="candidate-pair");return(i=(e=o.find(r=>s.has(r.id)))!==null&&e!==void 0?e:o.find(r=>r.selected===!0||r.nominated===!0&&r.state==="succeeded"))!==null&&i!==void 0?i:o.find(r=>r.state==="succeeded")}function qi(t,e){let i=0,n=!1;for(const s of t){const o=mt(s[e]);o!==void 0&&(i+=o,n=!0)}return n?i:void 0}function zi(t,e,i=!1){const n=[];return t.forEach(s=>{const o=s;o.type!==e||i&&!function(r){var a;const l=(a=r.kind)!==null&&a!==void 0?a:r.mediaType;return l===void 0||l==="audio"}(o)||n.push(o)}),n}function _w(t,e){const i=t.packets===void 0?e.packets!==void 0:e.packets!==void 0&&e.packets>t.packets,n=t.bytes===void 0?e.bytes!==void 0:e.bytes!==void 0&&e.bytes>t.bytes;return i||n}function wf(t,e){if(t!==void 0&&e!==void 0)return mt(e-t)}function Sf(t,e){var i,n;if(!t.some(c=>zi(c,`${e}-rtp`,!0).length>0))return;const s=t.map(c=>function(u,d){const h=zi(u,`${d}-rtp`,!0);return d==="outbound"?{packets:qi(h,"packetsSent"),bytes:qi(h,"bytesSent")}:{packets:qi(h,"packetsReceived"),bytes:qi(h,"bytesReceived")}}(c,e)).filter(({packets:c,bytes:u})=>c!==void 0||u!==void 0),o=(i=s[0])!==null&&i!==void 0?i:{},r=(n=s[s.length-1])!==null&&n!==void 0?n:{},a=wf(o.packets,r.packets),l=wf(o.bytes,r.bytes);return Object.assign(Object.assign(Object.assign(Object.assign({flowing:s.length>1&&_w(o,r)},r.packets!==void 0?{packets:r.packets}:{}),r.bytes!==void 0?{bytes:r.bytes}:{}),a!==void 0?{packetsDelta:a}:{}),l!==void 0?{bytesDelta:l}:{})}function Cf(t,e){const i=[];for(const n of t)for(const s of zi(n,e,!0)){const o=mt(s.jitter);if(o!==void 0){const r=1e3*o;r>=0&&i.push(r)}}return i}function Tf(t){const e=qi(t,"packetsReceived"),i=qi(t,"packetsLost"),n=t.map(r=>mt(r.fractionLost)).filter(r=>r!==void 0&&r>=0&&r<=1),s=n.length>0?Math.max(...n):void 0,o=e!==void 0&&i!==void 0?e+i:void 0;return{packetsReceived:e,packetsLost:i,packetLossFraction:s??(i!==void 0&&o!==void 0&&o>0?i/o:void 0)}}function kf(t){let e;return t.forEach(i=>{e===void 0&&(e=mt(i.timestamp))}),e}function yw(t){if(t.statsSamples.length===0)return{quality:"unknown",reasons:[]};const e=t.statsSamples,i=Sf(e,"inbound"),n=Sf(e,"outbound"),s=ua(function(p){var m;const v=[];for(const b of p){let y=!1;const C=zi(b,"remote-inbound-rtp",!0);for(const T of C){const A=mt(T.roundTripTime);if(A!==void 0){const x=1e3*A;x>=0&&(v.push(x),y=!0)}}if(!y){const T=mt((m=ha(b))===null||m===void 0?void 0:m.currentRoundTripTime);if(T!==void 0){const A=1e3*T;A>=0&&v.push(A)}}}return v}(e)),o=(r=ua(Cf(e,"inbound-rtp")),a=ua(Cf(e,"remote-inbound-rtp")),(r==null?void 0:r.average)===void 0?a:(a==null?void 0:a.average)===void 0?r:a.average>r.average?a:r);var r,a;const l=function(p,m,v){var b;if(p.length===0)return;const y=p[p.length-1],C=zi(y,"inbound-rtp",!0),T=zi(y,"remote-inbound-rtp",!0),A=function(_,g){return _.packetLossFraction===void 0?g:g.packetLossFraction===void 0?_:g.packetLossFraction>_.packetLossFraction?g:_}(Tf(C),Tf(T));let x=v==null?void 0:v.packets,N=(b=A.packetsReceived)!==null&&b!==void 0?b:m==null?void 0:m.packets;const E=A.packetsLost,k=A.packetLossFraction,f=ha(y);return x===void 0&&(x=mt(f==null?void 0:f.packetsSent)),N===void 0&&(N=mt(f==null?void 0:f.packetsReceived)),x!==void 0||N!==void 0||E!==void 0?{packetsSent:x,packetsReceived:N,packetsLost:E,packetLossFraction:k}:void 0}(e,i,n),c=function(p,m,v){if(p.length===0)return;const b=p[p.length-1];let y=v==null?void 0:v.bytes,C=m==null?void 0:m.bytes;const T=ha(b);return y===void 0&&(y=mt(T==null?void 0:T.bytesSent)),C===void 0&&(C=mt(T==null?void 0:T.bytesReceived)),y!==void 0||C!==void 0?{bytesSent:y,bytesReceived:C}:void 0}(e,i,n),u=function(p,m,v){if(p.length<2)return;const b=p[0],y=p[p.length-1],C=kf(b),T=kf(y);if(C===void 0||T===void 0)return;const A=(T-C)/1e3;if(A<=0)return;const x=(v==null?void 0:v.bytesDelta)!==void 0&&v.bytesDelta>=0?8*v.bytesDelta/A:void 0,N=(m==null?void 0:m.bytesDelta)!==void 0&&m.bytesDelta>=0?8*m.bytesDelta/A:void 0;return x!==void 0||N!==void 0?{outbound:x,inbound:N}:void 0}(e,i,n),d=function(p,m,v){let b=!1,y="good";return(p==null?void 0:p.average)!==void 0&&(b=!0,p.average>=ra?y="poor":p.average>=oa&&y==="good"&&(y="fair")),(m==null?void 0:m.average)!==void 0&&(b=!0,m.average>=la?y="poor":m.average>=aa&&y==="good"&&(y="fair")),(v==null?void 0:v.packetLossFraction)!==void 0&&(b=!0,v.packetLossFraction>=da?y="poor":v.packetLossFraction>=ca&&y==="good"&&(y="fair")),b?y:"unknown"}(s,o,l),h=function(p,m,v,b){const y=[];return(p==null?void 0:p.average)!==void 0&&(p.average>=ra?y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (poor: ≥${ra}ms threshold)`,source:"network"}):p.average>=oa&&y.push({code:"network_high_rtt",message:`Average RTT is ${Math.round(p.average)}ms (degraded: ≥${oa}ms threshold)`,source:"network"})),(m==null?void 0:m.average)!==void 0&&(m.average>=la?y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (poor: ≥${la}ms threshold)`,source:"network"}):m.average>=aa&&y.push({code:"network_high_jitter",message:`Average jitter is ${Math.round(m.average)}ms (degraded: ≥${aa}ms threshold)`,source:"network"})),(v==null?void 0:v.packetLossFraction)!==void 0&&(v.packetLossFraction>=da?y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (poor: ≥${100*da}% threshold)`,source:"network"}):v.packetLossFraction>=ca&&y.push({code:"network_packet_loss",message:`Packet loss is ${(100*v.packetLossFraction).toFixed(1)}% (degraded: ≥${100*ca}% threshold)`,source:"network"})),b&&(b.outbound!==void 0&&b.outbound<js&&y.push({code:"network_low_bitrate",message:`Outbound audio bitrate is ${Math.round(b.outbound)} bps (<${js} bps threshold)`,source:"network"}),b.inbound!==void 0&&b.inbound<js&&y.push({code:"network_low_bitrate",message:`Inbound audio bitrate is ${Math.round(b.inbound)} bps (<${js} bps threshold)`,source:"network"})),y}(s,o,l,t.options.mode==="network-only"?void 0:u);return{quality:d,rtt:s,jitter:o,packets:l,bytes:c,bitrate:u,inbound:i,outbound:n,reasons:h.length>0?h:void 0}}function Ef(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function fa(t,e){return t.find(i=>i.label===e)}class bw{constructor(){this.startedAtMonoMs=If()}build(e={}){var i,n;const s={};try{const o=(n=(i=e.call)===null||i===void 0?void 0:i.getEstablishmentTimings)===null||n===void 0?void 0:n.call(i);if(o){s.callEstablishment={mode:o.mode,direction:o.direction,steps:o.steps.map(d=>Object.assign({},d))};const r=fa(o.steps,"ICE candidate gathering started"),a=fa(o.steps,"All ICE candidates gathered"),l=Ef(r&&a?a.fromStart-r.fromStart:void 0);l!==void 0&&(s.iceGatheringMs=l);const c=fa(o.steps,"First server-reflexive/relay candidate found"),u=Ef(r&&c?c.fromStart-r.fromStart:void 0);u!==void 0&&(s.firstNonHostCandidateMs=u)}}catch{}return s}complete(e){const i=If()-this.startedAtMonoMs;Number.isFinite(i)&&i>=0&&(e.totalMs=i)}}function If(){try{if(typeof performance<"u"&&typeof performance.now=="function")return performance.now()}catch{}return Date.now()}function pa(){return new bw}const jt={NoCandidates:"ice_no_candidates",OnlyHostCandidates:"ice_only_host_candidates",GatheringTimeout:"ice_gathering_timeout",NoSelectedPair:"ice_no_selected_pair",TurnRequired:"ice_turn_required",ServerNoCandidates:"ice_server_no_candidates",MultipleInterfaces:"ice_multiple_interfaces",VpnDetected:"ice_vpn_detected"},Pn={LowBitrate:"network_low_bitrate",PoorQuality:"network_poor_quality",FairQuality:"network_fair_quality",NoAudioFlow:"network_no_audio_flow",OneWayAudio:"network_one_way_audio"},ga={CapturePermissionDenied:"microphone_capture_permission_denied",CaptureNoDevice:"microphone_capture_no_device",CaptureFailed:"microphone_capture_failed"},mi=()=>({reasons:[],warnings:[]}),Af={inconclusive:0,ready:1,degraded:2,blocked:3,permission_denied:4};function Xe(t,e){return t?e?Af[t]>=Af[e]?t:e:t:e}function rt(t,e,i){return{code:t,message:e,source:i}}function Nn(t,e,i){return{code:t,message:e,source:i}}function Rf(t,e=!1){var i;if(!t)return mi();const n=mi(),{reasons:s,warnings:o}=n,r=t.candidates.length>0;r||(s.push(rt(jt.NoCandidates,"No ICE candidates were gathered.","ice")),n.verdict="inconclusive"),r&&t.onlyHostCandidates&&(t.hasSelectedPair?o.push(Nn(jt.OnlyHostCandidates,"Only host ICE candidates were found. Connectivity succeeded, but NAT traversal may not be possible.","ice")):(s.push(rt(jt.OnlyHostCandidates,"Only host ICE candidates were found. NAT traversal may not be possible.","ice")),n.verdict=Xe(n.verdict,"degraded"))),t.isTurnRequired&&!e&&(s.push(rt(jt.TurnRequired,"The selected ICE candidate pair requires a TURN relay.","ice")),n.verdict=Xe(n.verdict,"degraded"));const a=t.iceConnectionState!==void 0&&t.iceConnectionState!=="new";r&&!t.hasSelectedPair&&a&&(s.push(rt(jt.NoSelectedPair,"No ICE candidate pair was selected. Connectivity failed.","ice")),n.verdict=Xe(n.verdict,"blocked")),t.candidateGatheringCompleted===!1&&(s.push(rt(jt.GatheringTimeout,"ICE gathering did not complete within the timeout.","ice")),n.verdict=Xe(n.verdict,"degraded"));const l=((i=t.serverCandidateComparison)!==null&&i!==void 0?i:[]).filter(({hasCandidates:c})=>!c);return l.length>0&&o.push(Nn(jt.ServerNoCandidates,`${l.length} configured ICE server${l.length===1?"":"s"} produced no candidates.`,"ice")),t.hasMultipleNetworkInterfaces&&o.push(Nn(jt.MultipleInterfaces,"Multiple network interfaces were detected on the host.","ice")),t.vpnDetected&&o.push(Nn(jt.VpnDetected,"A VPN appears to be active and may affect media routing.","ice")),!n.verdict&&r&&(n.verdict="ready"),n}function ww(t){if(t.established&&!t.error)return mi();const e=Array.isArray(t.server.urls)?t.server.urls.join(", "):t.server.urls;return{verdict:"degraded",reasons:[rt("ice_server_failed",t.error?`ICE server [${e}] failed: ${t.error}`:`ICE server [${e}] did not establish a diagnostic call.`,"ice")],warnings:[]}}function xf(t,e=!0){var i;if(!t)return mi();const n=mi(),{reasons:s,warnings:o}=n,r=e?t.reasons:(i=t.reasons)===null||i===void 0?void 0:i.filter(({code:l})=>l!==Pn.LowBitrate);switch(r!=null&&r.length&&(s.push(...r),n.verdict="degraded"),t.quality){case"poor":s.push(rt(Pn.PoorQuality,"Network quality is poor.","network")),n.verdict=Xe(n.verdict,"blocked");break;case"fair":o.push(Nn(Pn.FairQuality,"Network quality is fair.","network")),n.verdict=Xe(n.verdict,"degraded");break;case"good":n.verdict=Xe(n.verdict,"ready")}const a=[t.inbound,t.outbound].filter(l=>!!l);if(e&&a.length>0){const l=a.filter(({flowing:c})=>c).length;a.length===2&&l===2?n.verdict=Xe(n.verdict,"ready"):l>0?(s.push(rt(Pn.OneWayAudio,"Audio RTP is flowing in only one direction.","network")),n.verdict=Xe(n.verdict,"blocked")):(s.push(rt(Pn.NoAudioFlow,"No inbound or outbound audio RTP is flowing.","network")),n.verdict=Xe(n.verdict,"blocked"))}return n}function Sw(t){var e;if(!t)return mi();const i=mi();!((e=t.reasons)===null||e===void 0)&&e.length&&i.reasons.push(...t.reasons);const n=t.currentPermissionState==="denied"||t.isPermissionGrantedCurrently===!1||t.captureError==="permission_denied",s=t.deviceAvailable===!1||t.captureError!==void 0,o=t.activeCapturePerformed===!0&&t.audioDetected===!1;return n?i.verdict="permission_denied":s?i.verdict="blocked":o?i.verdict="degraded":(t.activeCapturePerformed===!0&&t.audioDetected===!0||t.activeCapturePerformed!==!0&&t.isPermissionGrantedCurrently===!0&&t.deviceAvailable!==!1)&&(i.verdict="ready"),i}class ma{constructor(e){this.options=e}run(){return U(this,void 0,void 0,function*(){switch(this.options.mode){case"network-only":return this.runNetworkOnly();case"microphone-only":return this.runMicrophoneOnly(gf(this.options));default:return this.runFull()}})}runFull(){return U(this,void 0,void 0,function*(){const e=yield this.runTest({diagnosticOptions:this.options,modules:{ice:!!this.options.ice,network:!!this.options.network,microphone:!!this.options.microphone},autoHangup:this.options.autoHangup!==!1});return e.setupFailed?e.error?Ki({callId:e.callId,timings:e.timings},e.error):{version:1,verdict:"inconclusive",reasons:[{code:"call_setup_timeout",message:"The diagnostic call did not reach the established state",source:"diagnostic"}],callId:e.callId,timings:e.timings}:Ki({ice:e.ice,network:e.network,microphone:e.microphone,timings:e.timings,callId:e.callId,raw:e.raw},e.error)})}runNetworkOnly(){var e,i,n;return U(this,void 0,void 0,function*(){const s=this.options.client.iceServers,o=function(c){const u=[];for(const d of c)(Array.isArray(d.urls)?d.urls:[d.urls]).forEach(h=>{u.push(Object.assign(Object.assign({},d),{urls:h}))});return u}((n=(i=(e=this.options.rtcConfig)===null||e===void 0?void 0:e.iceServers)!==null&&i!==void 0?i:s)!==null&&n!==void 0?n:[]);let r=[];const a=pa();let l;try{return r=yield Promise.all(o.map(c=>U(this,void 0,void 0,function*(){const u=yield this.runTest({diagnosticOptions:Object.assign(Object.assign({},this.options),{durationMs:3e3,statsSampleIntervalMs:500,rtcConfig:Object.assign(Object.assign({},this.options.rtcConfig),{iceServers:[c]})}),iceServers:[c],forceRelayCandidate:mf(c),modules:{ice:!0,network:!!this.options.network,microphone:!1},autoHangup:!0}),d=function(h){if(h.error)return h.error.message;if(h.setupFailed)return"The diagnostic call did not reach the established state";if(!h.ice)return"No ICE report was produced";if(h.ice.candidates.length===0)return"No ICE candidates were gathered";if(!h.ice.hasSelectedPair)return"No ICE candidate pair was selected"}(u);return{server:c,established:d===void 0,callId:u.callId,ice:u.ice,network:u.network,timings:u.timings,error:d}}))),l=Ki({serverTests:r,timings:a.build()},void 0,{networkOnly:!0}),l}catch(c){return l=Ki({timings:a.build()},Hs(c),{networkOnly:!0}),l}finally{l!=null&&l.timings&&a.complete(l.timings)}})}runTest(e){return U(this,void 0,void 0,function*(){const i=gf(e.diagnosticOptions),n=pa();let s,o,r,a=!1;const l=c=>{c.callId===(s==null?void 0:s.id)&&(o=Hs(c.error))};e.diagnosticOptions.client.on("telnyx.error",l);try{if(s=this.createDiagnosticCall(e.diagnosticOptions,e.iceServers,e.forceRelayCandidate),i.call=s,a=yield this.waitForCallEstablishment(s),!a)return r={established:!1,setupFailed:!0,callId:s.id,timings:n.build({call:s}),error:o},r;yield this.collectSamples(s,i);const c=e.modules.ice?uw(i):void 0,u=e.modules.network?yw(i):void 0,d=e.modules.microphone?yield bf(i):void 0;return r={established:!0,setupFailed:!1,callId:s.id,ice:c,network:u,microphone:d,timings:n.build({call:s}),raw:{samples:i.statsSamples.length?i.statsSamples:void 0}},r}catch(c){return i.error=Hs(c),r={established:a,setupFailed:!1,callId:s==null?void 0:s.id,timings:n.build({call:s}),error:i.error},r}finally{if(e.diagnosticOptions.client.off("telnyx.error",l),s&&e.autoHangup)try{yield s.hangup()}catch{}r!=null&&r.timings&&n.complete(r.timings)}})}runMicrophoneOnly(e){return U(this,void 0,void 0,function*(){const i=pa();let n;try{return n=Ki({microphone:this.options.microphone?yield bf(e):void 0,timings:i.build()},e.error),n}catch(s){return e.error=Hs(s),n=Ki({timings:i.build()},e.error),n}finally{n!=null&&n.timings&&i.complete(n.timings)}})}waitForCallEstablishment(e){return U(this,void 0,void 0,function*(){const i=Date.now()+3e4,n=()=>{var s,o;return e.state==="active"&&((o=(s=e.peer)===null||s===void 0?void 0:s.instance)===null||o===void 0?void 0:o.connectionState)==="connected"};for(;Date.now()<i;){if(n())return!0;if(["done","hangup","destroy"].includes(e.state))return!1;yield Df(500)}return n()})}createDiagnosticCall(e,i,n=!1){const{client:s,destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c,rtcConfig:u}=e;return s.newCall({destinationNumber:o,callerName:r,callerNumber:a,audio:l,debug:c===!0,iceServers:i??(u==null?void 0:u.iceServers),forceRelayCandidate:n})}collectSamples(e,i){var n,s,o;return U(this,void 0,void 0,function*(){const r=(n=i.options.durationMs)!==null&&n!==void 0?n:5e3,a=(s=i.options.statsSampleIntervalMs)!==null&&s!==void 0?s:1e3,l=Date.now()+r;for(;Date.now()<l;){try{const c=yield(o=e.peer.instance)===null||o===void 0?void 0:o.getStats();c&&i.statsSamples.push(c)}catch{}yield Df(Math.min(a,Math.max(0,l-Date.now())))}})}}function Ki(t,e,i){const{verdict:n,reasons:s,warnings:o}=function(r,a,l={}){var c,u;const d=[Rf(r.ice),xf(r.network),Sw(r.microphone),...((c=r.serverTests)!==null&&c!==void 0?c:[]).flatMap(v=>[Rf(v.ice,l.networkOnly&&mf(v.server)),xf(v.network,!l.networkOnly),ww(v)])],h=d.flatMap(v=>v.reasons),p=d.flatMap(v=>v.warnings);let m=d.reduce((v,b)=>Xe(v,b.verdict),void 0);if(l.networkOnly&&!((u=r.serverTests)===null||u===void 0)&&u.length){const v=r.serverTests.filter(b=>b.established&&!b.error).length;v===0?m="blocked":v<r.serverTests.length&&(m="degraded")}if(a)switch(a.code){case yh:h.push(rt(ga.CapturePermissionDenied,"Microphone access was denied while establishing the diagnostic call.","microphone")),m=Xe(m,"permission_denied");break;case bh:h.push(rt(ga.CaptureNoDevice,"No microphone device was available while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;case Vr:h.push(rt(ga.CaptureFailed,"Microphone capture failed while establishing the diagnostic call.","microphone")),m=Xe(m,"blocked");break;default:h.push(rt("diagnostic_run_error",`Diagnostic run encountered an error: ${a.message}`,"diagnostic")),m=Xe(m,"blocked")}return{verdict:m??"inconclusive",reasons:h,warnings:p}}(t,e,i);return Object.assign(Object.assign({},t),{version:1,verdict:n??"inconclusive",reasons:s.length?s:void 0,warnings:o.length?o:void 0})}function Hs(t){return t instanceof Error?t:new Error(String(t))}function Df(t){return new Promise(e=>setTimeout(e,t))}const Lf="+1-872-231-5806";class Cw extends dw{constructor(e){super(e),w.info(`SDK version: ${Kh}`)}newCall(e){return super.newCall(e)}runPreCall(e={}){var i,n;return U(this,void 0,void 0,function*(){const s={client:this,destinationNumber:(i=e.destinationNumber)!==null&&i!==void 0?i:Lf,durationMs:e.durationMs,ice:!0,network:!0,microphone:!0,mode:"full",rtcConfig:{iceServers:(n=e.iceServers)!==null&&n!==void 0?n:this.iceServers}};return new ma(s).run()})}runNetworkCheck(e={}){var i;return U(this,void 0,void 0,function*(){const n={client:this,destinationNumber:Lf,ice:!0,network:!0,microphone:!1,mode:"network-only",rtcConfig:{iceServers:(i=e.iceServers)!==null&&i!==void 0?i:this.iceServers}};return new ma(n).run()})}runMicrophoneCheck(e={}){var i;return U(this,void 0,void 0,function*(){const n={client:this,ice:!1,network:!1,microphone:{sampleDurationMs:e.durationMs,silenceThreshold:e.silenceThreshold,record:(i=e.record)!==null&&i!==void 0&&i,warnOnRecording:e.warnOnRecording},mode:"microphone-only"};return new ma(n).run()})}static webRTCInfo(){return Xb()}static webRTCSupportedBrowserList(){return[{operationSystem:"Android",supported:[{browserName:"Chrome",features:["audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"iOS",supported:[{browserName:"Chrome",supported:Ae.not_supported},{browserName:"Firefox",supported:Ae.not_supported},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"Linux",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",supported:Ae.not_supported}]},{operationSystem:"MacOS",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",features:["video","audio"],supported:Ae.full},{browserName:"Edge",features:["audio"],supported:Ae.partial}]},{operationSystem:"Windows",supported:[{browserName:"Chrome",features:["video","audio"],supported:Ae.full},{browserName:"Firefox",features:["audio"],supported:Ae.partial},{browserName:"Safari",supported:Ae.not_supported},{browserName:"Edge",features:["audio"],supported:Ae.partial}]}]}}function Tw(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 Mf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Of={exports:{}},Pf;function kw(){return Pf||(Pf=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),m=i?i+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],p]:l._events[m].push(p):(l._events[m]=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 m=i?i+l:l;if(!this._events[m])return!1;var v=this._events[m],b=arguments.length,y,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,y=new Array(b-1);C<b;C++)y[C-1]=arguments[C];v.fn.apply(v.context,y)}else{var T=v.length,A;for(C=0;C<T;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(!y)for(A=1,y=new Array(b-1);A<b;A++)y[A-1]=arguments[A];v[C].fn.apply(v[C].context,y)}}return!0},a.prototype.on=function(l,c,u){return o(this,l,c,u,!1)},a.prototype.once=function(l,c,u){return o(this,l,c,u,!0)},a.prototype.removeListener=function(l,c,u,d){var h=i?i+l:l;if(!this._events[h])return this;if(!c)return r(this,h),this;var p=this._events[h];if(p.fn)p.fn===c&&(!d||p.once)&&(!u||p.context===u)&&r(this,h);else{for(var m=0,v=[],b=p.length;m<b;m++)(p[m].fn!==c||d&&!p[m].once||u&&p[m].context!==u)&&v.push(p[m]);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}(Of)),Of.exports}var Ew=kw();const Fn=Mf(Ew),va=new Fn;var _a={exports:{}},Iw=_a.exports,Nf;function Aw(){return Nf||(Nf=1,function(t){(function(e,i){t.exports?t.exports=i():e.log=i()})(Iw,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 y=v[b];if(typeof y.bind=="function")return y.bind(v);try{return Function.prototype.bind.call(y,v)}catch{return function(){return Function.prototype.apply.apply(y,[v,arguments])}}}function l(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(v){return v==="debug"&&(v="log"),typeof console===i?!1:v==="trace"&&n?l:console[v]!==void 0?a(console,v):console.log!==void 0?a(console,"log"):e}function u(){for(var v=this.getLevel(),b=0;b<s.length;b++){var y=s[b];this[y]=b<v?e:this.methodFactory(y,v,this.name)}if(this.log=this.debug,typeof console===i&&v<this.levels.SILENT)return"No console available for logging"}function d(v){return function(){typeof console!==i&&(u.call(this),this[v].apply(this,arguments))}}function h(v,b,y){return c(v)||d.apply(this,arguments)}function p(v,b){var y=this,C,T,A,x="loglevel";typeof v=="string"?x+=":"+v:typeof v=="symbol"&&(x=void 0);function N(g){var S=(s[g]||"silent").toUpperCase();if(!(typeof window===i||!x)){try{window.localStorage[x]=S;return}catch{}try{window.document.cookie=encodeURIComponent(x)+"="+S+";"}catch{}}}function E(){var g;if(!(typeof window===i||!x)){try{g=window.localStorage[x]}catch{}if(typeof g===i)try{var S=window.document.cookie,I=encodeURIComponent(x),M=S.indexOf(I+"=");M!==-1&&(g=/^([^;]+)/.exec(S.slice(M+I.length+1))[1])}catch{}return y.levels[g]===void 0&&(g=void 0),g}}function k(){if(!(typeof window===i||!x)){try{window.localStorage.removeItem(x)}catch{}try{window.document.cookie=encodeURIComponent(x)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function f(g){var S=g;if(typeof S=="string"&&y.levels[S.toUpperCase()]!==void 0&&(S=y.levels[S.toUpperCase()]),typeof S=="number"&&S>=0&&S<=y.levels.SILENT)return S;throw new TypeError("log.setLevel() called with invalid level: "+g)}y.name=v,y.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},y.methodFactory=b||h,y.getLevel=function(){return A??T??C},y.setLevel=function(g,S){return A=f(g),S!==!1&&N(A),u.call(y)},y.setDefaultLevel=function(g){T=f(g),E()||y.setLevel(g,!1)},y.resetLevel=function(){A=null,k(),u.call(y)},y.enableAll=function(g){y.setLevel(y.levels.TRACE,g)},y.disableAll=function(g){y.setLevel(y.levels.SILENT,g)},y.rebuild=function(){if(r!==y&&(C=f(r.getLevel())),u.call(y),r===y)for(var g in o)o[g].rebuild()},C=f(r?r.getLevel():"WARN");var _=E();_!=null&&(A=f(_)),u.call(y)}r=new p,r.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var b=o[v];return b||(b=o[v]=new p(v,r.methodFactory)),b};var m=typeof window!==i?window.log:void 0;return r.noConflict=function(){return typeof window!==i&&window.log===r&&(window.log=m),r},r.getLoggers=function(){return o},r.default=r,r})}(_a)),_a.exports}var Rw=Aw();const xw=Mf(Rw),Dw=()=>new Date().toISOString().replace("T"," ").replace("Z",""),pe=xw.getLogger("telnyx-ai-agent"),Lw=pe.methodFactory;pe.methodFactory=(t,e,i)=>{const n=Lw(t,e,i);return function(...s){n(Dw(),"-",...s)}},pe.setLevel("info");function Mw(t,e){let i=0;return(...n)=>{const s=Date.now();s-i>=e&&(i=s,t(...n))}}const Ow=10,Pw=500,Nw=100,Fw=300,Ff=20;class Uw{constructor(e){B(this,"remoteIntervalId",null);B(this,"localIntervalId",null);B(this,"remoteStream",null);B(this,"localStream",null);B(this,"remoteAudioContext",null);B(this,"remoteSource",null);B(this,"remoteAnalyser",null);B(this,"localAudioContext",null);B(this,"localSource",null);B(this,"localAnalyser",null);B(this,"thinkingStartTime",null);B(this,"lastState",null);B(this,"userIsSpeaking",!1);B(this,"lastUserAudioTime",null);B(this,"userSpeechStartTime",null);B(this,"remoteSilenceStartTime",null);B(this,"remoteSilenceThresholdMs");B(this,"userSilenceStartTime",null);B(this,"isFirstAgentSpeech",!0);B(this,"monitorStartTime",null);B(this,"volumeThreshold");B(this,"silenceDurationMs");B(this,"minSpeechDurationMs");B(this,"maxLatencyMs");B(this,"updateAgentState",Mw(e=>{pe.debug("AudioStreamMonitor updateAgentState",e),pe.debug("Previous state:",this.lastState),e.state!==this.lastState&&(this.lastState=e.state,va.emit("conversation.agent.state",e))},100));this.volumeThreshold=(e==null?void 0:e.volumeThreshold)??Ow,this.silenceDurationMs=(e==null?void 0:e.silenceDurationMs)??Pw,this.minSpeechDurationMs=(e==null?void 0:e.minSpeechDurationMs)??Nw,this.maxLatencyMs=e==null?void 0:e.maxLatencyMs,this.remoteSilenceThresholdMs=(e==null?void 0:e.remoteSilenceThresholdMs)??Fw}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){pe.debug("Remote monitor: no stream, skipping");return}this.monitorStartTime=performance.now(),this.remoteAudioContext=new AudioContext,pe.debug("Remote AudioContext state:",this.remoteAudioContext.state),this.remoteAudioContext.state==="suspended"&&(pe.debug("Resuming suspended AudioContext..."),this.remoteAudioContext.resume().then(()=>{var o;pe.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&&pe.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,Ff)}startLocalMonitor(){if(!this.localStream){pe.debug("Local monitor: no stream, skipping");return}this.localAudioContext=new AudioContext,pe.debug("Local AudioContext state:",this.localAudioContext.state),this.localAudioContext.state==="suspended"&&(pe.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&&pe.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,Ff)}destroy(){this.stopAudioStreamMonitor()}}function Bw(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"}function Vw(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="response.text.delta"?!1:!!e.params.delta}function $w(t){if(!t||typeof t!="object")return!1;const e=t;return e.params.type!=="conversation.item.created"?!1:!!e.params.item.content}function Un(t){if(!t||typeof t!="object")return!1;const e=t;return e.method==="ai_conversation"&&typeof e.params=="object"&&e.params!==null}function jw(t){if(!Un(t))return null;const e=t.params;return Tw(e)?e.item:null}function Hw(t){if(!Un(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 Ww(t){if(!Un(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 Gw(t){var e;return Un(t)?((e=t.params)==null?void 0:e.type)==="response.audio_stream.subscribed":!1}function qw(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 zw=3e4;function Kw(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 ya(t){return JSON.stringify({error:t})}class Yw{constructor(e){B(this,"registry",new Map);B(this,"toolTimeouts",new Map);B(this,"inFlight",new Set);B(this,"completed",new Set);B(this,"generation",0);B(this,"getActiveCall");B(this,"timeoutMs");B(this,"events");B(this,"handleEvent",e=>{const i=Hw(e);if(i){this.ingestToolSettings(i);return}const n=jw(e);n&&this.execute(n)});this.getActiveCall=e.getActiveCall,this.timeoutMs=e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:zw,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){pe.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)){pe.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){pe.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,ya("unknown_tool"),!0,s,o);return}let a;try{a=e.arguments&&e.arguments.length>0?JSON.parse(e.arguments):void 0}catch{pe.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,ya("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,Kw(u),!1,s,o)}catch(u){const d=u instanceof Uf?"timeout":"handler_error";pe.warn(`[client-tools] tool "${n}" failed (call_id=${i}, reason=${d})`),this.events.onError({callId:i,toolName:n,reason:d}),this.sendOutput(i,n,ya(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 Uf(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){pe.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){pe.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){pe.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){pe.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 Uf extends Error{constructor(e,i,n){super(`Client tool "${e}" timed out after ${n}ms (call_id=${i})`),this.name="ToolTimeoutError"}}const Gs=class Gs{constructor(e){B(this,"enabled");B(this,"getActiveCall");B(this,"events");B(this,"subscriptionConfirmed",!1);B(this,"subscribeAttempts",0);B(this,"handleEvent",e=>{if(!this.enabled)return;if(Gw(e)){this.subscriptionConfirmed=!0;return}this.subscriptionConfirmed||this.sendSubscription();const i=Ww(e);if(i){if(this.subscriptionConfirmed=!0,i.type==="response.audio.delta"){let n;try{n=Xw(i.delta)}catch(s){pe.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>=Gs.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){pe.warn(`[streaming-audio] failed to subscribe: ${i instanceof Error?i.message:"unknown error"}`)}}emitSafely(e){try{e()}catch(i){pe.warn(`[streaming-audio] event listener threw: ${i instanceof Error?i.message:"unknown error"}`)}}};B(Gs,"MAX_SUBSCRIBE_ATTEMPTS",10);let ba=Gs;function Xw(t){const e=globalThis.atob(t);return Uint8Array.from(e,i=>i.charCodeAt(0))}function Bf(t){if(!Un(t))return null;const e=t.params;if(e.type==="response.error"){if(!e.error||typeof e.error!="object")return null;const n=e.error.reason;return typeof n=="string"&&n.length>0?{type:"response.error",reason:n}:null}if(e.type!=="response.text.delta"&&e.type!=="response.text.done"||typeof e.item_id!="string"||!e.item_id||typeof e.response_id!="string"||!e.response_id)return null;const i=e.type==="response.text.delta"?e.delta:e.text;return typeof i!="string"||e.type==="response.text.delta"&&!i?null:{type:e.type,itemId:e.item_id,text:i}}function Vf(t){return Vw(t)?{id:`${t.params.item_id}-${Date.now()}`,role:"assistant",content:t.params.delta,timestamp:new Date}:null}function Jw(t){if(!$w(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 $f extends Fn{constructor(i,n={}){super();B(this,"source");B(this,"assembleAssistantMessages");B(this,"completedItemIds",new Set);B(this,"transcript",[]);B(this,"onSocketMessage",i=>{if(!(!Bw(i)||!i.params))switch(i.params.type){case"response.text.delta":{if(this.assembleAssistantMessages){this.handleAssistantText(i);return}const n=Vf(i);n&&(this.transcript.push(n),this.emit("transcript.item",n));return}case"response.text.done":{this.assembleAssistantMessages&&this.handleAssistantText(i);return}case"conversation.item.deleted":{if(qw(i)){const n=i.params.item_id,s=this.transcript.findIndex(o=>o.id===n);s!==-1&&(this.transcript.splice(s,1),this.emitTranscriptUpdated())}return}case"conversation.item.created":{const n=Jw(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),this.emitTranscriptUpdated()}return}}});this.source=i,this.assembleAssistantMessages=n.assembleAssistantMessages??!1,this.source.on(F.SocketMessage,this.onSocketMessage)}detach(){this.source.off(F.SocketMessage,this.onSocketMessage)}emitTranscriptUpdated(){this.assembleAssistantMessages&&this.emit("transcript.updated",[...this.transcript])}handleAssistantText(i){const n=Bf(i);if(!n||n.type==="response.error"||this.completedItemIds.has(n.itemId))return;const s=this.transcript.findIndex(a=>a.role==="assistant"&&a.id===n.itemId),o=this.transcript[s],r={id:n.itemId,role:"assistant",content:n.type==="response.text.delta"?((o==null?void 0:o.content)??"")+n.text:n.text,timestamp:(o==null?void 0:o.timestamp)??new Date};if(o?this.transcript[s]=r:r.content&&this.transcript.push(r),n.type==="response.text.done")this.completedItemIds.add(n.itemId),this.emit("response.done"),!o&&r.content&&this.emit("transcript.item",r);else{const a=Vf(i);a&&this.emit("transcript.item",a)}this.emitTranscriptUpdated()}}const Ht=t=>typeof t=="object"&&t!==null,jf=t=>{const e=Ht(t)&&Ht(t.result)?t.result:t;if(!(!Ht(e)||e.message!=="logged in"))return typeof e.sessid=="string"?e.sessid:null},Qw=t=>Ht(t)&&Ht(t.request)&&(t.request.method==="login"||t.request.method==="anonymous_login"),Zw=(t,e)=>{if(!e||!Ht(t)||!Ht(t.request))return;const{request:i}=t;if(i.method!=="login"&&i.method!=="anonymous_login"||!Ht(i.params))return;const n=i.params;Ht(n["User-Agent"])&&(n["User-Agent"].widgetVersion=e),i.method==="anonymous_login"&&(n.widget_version=e)};class eS extends Fn{constructor(i){super();B(this,"telnyxRTC");B(this,"transcription");B(this,"removeLoginSuccessHook",null);B(this,"authenticated",!1);B(this,"authenticating",!1);B(this,"agentId");B(this,"versionId");B(this,"widgetVersion");B(this,"conversationId");B(this,"debug");B(this,"audioStreamMonitor");B(this,"clientTools");B(this,"streamingAudio");B(this,"activeCall");B(this,"chatMode");B(this,"dc",null);B(this,"region",null);B(this,"callReportId",null);B(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)});B(this,"onClientOrSocketError",i=>{this.emit("agent.error",i.error)});B(this,"onSocketClose",()=>{this.authenticated=!1,this.authenticating=!1,this.clientTools.reset(),this.streamingAudio.reset()});B(this,"onSocketMessage",i=>{const n=jf(i);n!==void 0&&this.emitLoginSuccess({sessionId:n})});B(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()))});B(this,"onTranscriptItem",i=>{this.emit("transcript.item",i)});B(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,pe.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 Cw({env:i.environment||"production",anonymous_login:n,debug:i.debug||!1,trickleIce:i.trickleIce,prefetchIceCandidates:i.prefetchIceCandidates,region:i.region,skipLastVoiceSdkId:i.skipLastVoiceSdkId??!0,rtcIp:i.rtcIp,rtcPort:i.rtcPort}),this.removeLoginSuccessHook=this.installLoginSuccessHook(),this.telnyxRTC.on(F.Ready,this.onClientReady),this.telnyxRTC.on(F.Error,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.on(F.SocketClose,this.onSocketClose),this.telnyxRTC.on(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.on(F.Notification,this.onNotification),this.transcription=new $f(this.telnyxRTC),this.transcription.addListener("transcript.item",this.onTranscriptItem),va.addListener("conversation.agent.state",this.onAgentStateChange),this.audioStreamMonitor=new Uw(i.vad),this.clientTools=new Yw({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(F.AIConversationMessage,this.clientTools.handleEvent),this.streamingAudio=new ba({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(F.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(F.AIConversationMessage,this.clientTools.handleEvent),this.telnyxRTC.off(F.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(F.Ready,this.onClientReady),this.telnyxRTC.off(F.Error,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketError,this.onClientOrSocketError),this.telnyxRTC.off(F.SocketClose,this.onSocketClose),this.telnyxRTC.off(F.SocketMessage,this.onSocketMessage),this.telnyxRTC.off(F.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(),va.removeAllListeners(),this.removeAllListeners()}sendConversationMessage(i,n=[]){if(!this.activeCall){pe.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 pe.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 pe.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 m=Qw(p),v=c;return m&&Zw(p,a),n.call(this,p).then(b=>{const y=m?jf(b):void 0;return l&&y!==void 0&&(u(v),r({sessionId:y})),b})},h=function(p){const m=++c;if(l){const v={sessionId:i.sessionid||null};o(v)}return s.call(this,p).finally(()=>{l&&i.login===h&&u(m)})};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}))}}const tS={production:"rtc.telnyx.com",development:"rtcdev.telnyx.com"};function iS(t){if(t.url)return t.url;const e=tS[t.environment??"production"];return`wss://${t.region?`${t.region}.`:""}${e}`}let nS=0;const sS=()=>`text-chat-${Date.now()}-${++nS}`;class oS extends Fn{constructor(i){super();B(this,"socket",null);B(this,"pending",new Map);B(this,"options");B(this,"closedByUs",!1);B(this,"conversationId",null);B(this,"assistantVersionId",null);B(this,"onMessage",i=>{let n;try{n=JSON.parse(i.data)}catch{pe.warn("[TextChat] dropping non-JSON frame");return}const s=n,o=s.id?this.pending.get(s.id):void 0;if(o){this.pending.delete(s.id),s.error?o.reject(new Error(s.error.message??"Text chat error")):o.resolve(s.result??{});return}this.emit(F.SocketMessage,n)});B(this,"onClose",i=>{this.closedByUs||this.teardown("Text chat socket closed"),this.emit(F.SocketClose,i)});B(this,"onError",()=>{this.emit(F.SocketError,new Error("Text chat socket error"))});this.options=i,this.conversationId=i.conversationId??null}get isConnected(){var i;return((i=this.socket)==null?void 0:i.readyState)===WebSocket.OPEN}async connect(){if(this.socket)throw new Error("Text chat transport is already connected");const i=iS(this.options);pe.debug("[TextChat] connecting to",i);const n=new WebSocket(i);this.socket=n,this.closedByUs=!1;try{if(await new Promise((o,r)=>{const a=()=>{u(),o()},l=()=>{u(),r(new Error(`Failed to connect to ${i}`))},c=()=>{u(),r(new Error(`Connection to ${i} closed before it opened`))},u=()=>{n.removeEventListener("open",a),n.removeEventListener("error",l),n.removeEventListener("close",c)};n.addEventListener("open",a),n.addEventListener("error",l),n.addEventListener("close",c)}),this.socket!==n)throw new Error("Text chat transport is not connected");n.addEventListener("message",this.onMessage),n.addEventListener("close",this.onClose),n.addEventListener("error",this.onError);const s=await this.request("text_chat_login",{target_type:"ai_assistant",target_id:this.options.assistantId,target_version_id:this.options.versionId,conversation_id:this.conversationId??void 0});return this.conversationId=s.conversation_id??null,this.assistantVersionId=s.ai_assistant_version_id??null,{conversationId:this.conversationId,assistantVersionId:this.assistantVersionId}}catch(s){throw this.socket===n&&this.teardown("Text chat transport failed to connect"),s}}async sendMessage(i){await this.request("text_chat_message",{content:i})}disconnect(){this.closedByUs=!0,this.teardown("Text chat transport disconnected")}teardown(i){var n,s,o,r;this.rejectPending(i),(n=this.socket)==null||n.removeEventListener("message",this.onMessage),(s=this.socket)==null||s.removeEventListener("close",this.onClose),(o=this.socket)==null||o.removeEventListener("error",this.onError),(r=this.socket)==null||r.close(),this.socket=null}rejectPending(i){for(const[,n]of this.pending)n.reject(new Error(i));this.pending.clear()}request(i,n){const s=this.socket;if(!s||s.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Text chat transport is not connected"));const o=sS();return new Promise((r,a)=>{this.pending.set(o,{resolve:r,reject:a}),s.send(JSON.stringify({jsonrpc:"2.0",id:o,method:i,params:n}))})}}class rS extends Error{constructor(i){const n={stream_truncated:"The assistant response ended before it was complete.",stream_failed:"The assistant response stream failed.",assistant_error:"The assistant could not complete its response."};super(Object.hasOwn(n,i)?n[i]:`Assistant response failed: ${i}`);B(this,"reason");this.name="TextChatResponseError",this.reason=i}}class aS extends Fn{constructor(i){super();B(this,"agentId");B(this,"transport");B(this,"transcription");B(this,"connected",!1);B(this,"agentState","listening");B(this,"onSocketClose",()=>{this.connected&&(this.connected=!1,this.setAgentState("listening"),this.emit("agent.disconnected"))});B(this,"onSocketMessage",i=>{const n=Bf(i);(n==null?void 0:n.type)==="response.error"&&(this.setAgentState("listening"),this.emit("agent.error",new rS(n.reason)))});B(this,"onResponseDone",()=>{this.setAgentState("listening")});B(this,"onTranscriptUpdated",i=>{this.emit("transcript.updated",i)});B(this,"onTranscriptItem",i=>{i.role==="assistant"&&this.setAgentState("listening"),this.emit("transcript.item",i)});this.agentId=i.agentId,pe.setLevel(i.debug?"debug":"info"),this.transport=new oS({assistantId:i.agentId,versionId:i.versionId,conversationId:i.conversationId,environment:i.environment,region:i.region,url:i.url}),this.transcription=new $f(this.transport,{assembleAssistantMessages:!0}),this.transcription.addListener("transcript.item",this.onTranscriptItem),this.transcription.on("transcript.updated",this.onTranscriptUpdated),this.transcription.on("response.done",this.onResponseDone),this.transport.on(F.SocketMessage,this.onSocketMessage),this.transport.on(F.SocketClose,this.onSocketClose)}get socketEvents(){return this.transport}get conversationId(){return this.transport.conversationId}get isConnected(){return this.connected}get transcript(){return this.transcription.transcript}async connect(){try{const{conversationId:i}=await this.transport.connect();this.connected=!0,this.emit("agent.connected",{conversationId:i})}catch(i){const n=i instanceof Error?i:new Error(String(i));throw this.emit("agent.error",n),n}}async sendMessage(i){if(!this.connected)throw new Error("Not connected. Call connect() first.");this.setAgentState("thinking");try{await this.transport.sendMessage(i)}catch(n){const s=n instanceof Error?n:new Error(String(n));throw this.setAgentState("listening"),this.emit("agent.error",s),s}}disconnect(){this.transport.disconnect();const i=this.connected;this.connected=!1,this.setAgentState("listening"),i&&this.emit("agent.disconnected")}setAgentState(i){this.agentState!==i&&(this.agentState=i,this.emit("conversation.agent.state",{state:i}))}}var Hf={exports:{}},Bn={},Wf;function lS(){if(Wf)return Bn;Wf=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 Gf;function cS(){return Gf||(Gf=1,Hf.exports=lS()),Hf.exports}cS(),Ft(void 0),Ft(null);const dS=(t,e,i,n,s,o,r,a,l,c,u,d,h,p)=>new eS({agentId:t,environment:e,versionId:i,debug:n,trickleIce:s,prefetchIceCandidates:o,vad:r,conversationId:a,chatMode:l,region:c,skipLastVoiceSdkId:u??!0,streamingAudio:d,rtcIp:h,rtcPort:p}),Ws=10,qf=5e3,uS=[46001,46003],hS=["login incorrect","authentication required","authentication failed"];function zf(t){var n;const e=t.code;if(e&&uS.includes(e))return!0;const i=((n=t.message)==null?void 0:n.toLowerCase())||"";return hS.some(s=>i.includes(s))}const fS=(t,e,i,n,s,o,r,a,l,c,u,d,h,p)=>{const m=u??!0,[v,b]=ve(null),[y,C]=ve(!1),[T,A]=ve(null),[x,N]=ve(!1),E=ce(0),k=ce(null),f=ce(null),_=ce(!1),g=ce(!1),S=ce(0),I=ce(0),M=Ne(()=>{k.current&&(clearTimeout(k.current),k.current=null)},[]),R=Ne(()=>{M(),E.current=0,g.current=!0,N(!1),A(null)},[M]),P=Ne(()=>{M(),N(!1)},[M]),O=Ne(L=>{if(M(),E.current>=Ws){re.error(`Max login retry attempts (${Ws}) exceeded`),N(!1);return}E.current+=1;const V=S.current,$=I.current;re.info(`Scheduling login retry attempt ${E.current}/${Ws} in ${qf}ms due to: ${L}`),N(!0),k.current=window.setTimeout(()=>{var G;k.current=null;const W=f.current,q=W==null?void 0:W.telnyxRTC;if(S.current!==V||I.current!==$||W!=null&&W.isAuthenticating){re.info("Skipping login retry because a newer socket/login is already in progress"),P();return}if(_.current||g.current||W!=null&&W.isAuthenticated){re.info("Skipping login retry because login already succeeded before retry timeout fired"),R();return}f.current&&(re.info(`Executing reconnect attempt ${E.current} (socket disconnect)`),(G=q==null?void 0:q.socketDisconnect)==null||G.call(q))},qf)},[M,P,R]);return Le(()=>{if(!t)return;const L=dS(t,e,i,n,s,o,r,a,l,c,m,d,h,p);_.current=!1,g.current=!1,C(!1),A(null),N(!1),f.current=L;const V=()=>{re.info("Agent connected successfully"),_.current=!0,C(!0),R()},$=()=>{re.info("Agent disconnected"),_.current=!1,g.current=!1,C(!1)},W=Y=>{if(re.error("AI Agent error:",Y),zf(Y)){if(_.current||g.current){re.debug("Ignoring retryable error — login already succeeded");return}E.current<Ws?(A(null),O(Y.message)):(A(Y),N(!1))}else A(Y),N(!1)},q=L.telnyxRTC??null,G=()=>{I.current+=1,g.current=!1},oe=()=>{re.info("Login succeeded; clearing pending login retry flow"),R()},K=()=>{S.current+=1,g.current=!1},Z=()=>{g.current=!1};return L.on("agent.connected",V),L.on("agent.disconnected",$),L.on("agent.error",W),L.on("agent.login.started",G),L.on("agent.login.success",oe),q&&typeof q=="object"&&(q.on(F.SocketOpen,K),q.on(F.SocketClose,Z)),L.connect(),b(L),()=>{M(),L.off("agent.connected",V),L.off("agent.disconnected",$),L.off("agent.error",W),L.off("agent.login.started",G),L.off("agent.login.success",oe),q&&typeof q=="object"&&(q.off(F.SocketOpen,K),q.off(F.SocketClose,Z)),L.disconnect(),_.current=!1,f.current=null}},[t,e,i,n,s,o,r,a,l,c,u,m,d,h,p,M,R,O]),{client:v,isConnected:y,error:T,isReconnecting:x}},pS="telnyx-ai-agent",Re={AGENT_CONNECTED:"agent.connected",AGENT_DISCONNECTED:"agent.disconnected",AGENT_ERROR:"agent.error",SOCKET_CLOSE:"agent.socket.close",TRANSCRIPT_ITEM:"transcript.item",TRANSCRIPT_UPDATED:"transcript.updated",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",ASSISTANT_AUDIO_DELTA:"assistant.audio.delta",ASSISTANT_AUDIO_DONE:"assistant.audio.done",ASSISTANT_AUDIO_INTERRUPTED:"assistant.audio.interrupted"};function gS(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 Kf(){const t=document.querySelector(pS);return t instanceof HTMLElement?t:null}function nt(t,e,i){const n=i||Kf();if(!n){re.warn(`Cannot dispatch event "${t}": widget element not found`);return}const s=new CustomEvent(t,{detail:e,bubbles:!0,composed:!0});n.dispatchEvent(s),re.debug(`[WidgetEvent] Dispatched "${t}"`,e)}const mS=(t,e,i)=>{const{onReady:n,onConversationUpdate:s,onError:o,onConfigMessage:r}=e,a=ce(null),l=Jn(Qu);Le(()=>{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??Kf()},[i]),Le(()=>{if(!t)return;const c=a.current,u=()=>{n();const f=t.telnyxRTC,_={dc:(f==null?void 0:f.dc)??null,region:(f==null?void 0:f.region)??null,callReportId:(f==null?void 0:f.callReportId)??null};l(_),nt(Re.AGENT_CONNECTED,_,c)},d=()=>{l(null),nt(Re.AGENT_DISCONNECTED,void 0,c)},h=k=>{const f={message:k.message,name:k.name};if(zf(k)){re.debug("Ignoring retryable agent.error in widget event layer"),nt(Re.AGENT_ERROR,f,c);return}o(k),nt(Re.AGENT_ERROR,f,c)},p=k=>{var f;s(k),nt(Re.CONVERSATION_UPDATE,{type:k.type,callState:(f=k.call)==null?void 0:f.state},c)},m=k=>{nt(Re.TRANSCRIPT_ITEM,k,c)},v=k=>{nt(Re.CONVERSATION_AGENT_STATE,k,c)},b=k=>{nt(Re.AGENT_AUDIO_MUTE,{muted:k},c)},C=t.telnyxRTC,T=k=>{r(k);const f=gS(k);f&&nt(Re.CLIENT_TOOLS_CONFIGURED,{tools:f},c)},A=k=>{const f=k,_={code:f==null?void 0:f.code,reason:f==null?void 0:f.reason,wasClean:f==null?void 0:f.wasClean,timestamp:new Date().toISOString()};re.info("[socket.close]",_),nt(Re.SOCKET_CLOSE,_,c)};C&&typeof C=="object"&&(C.on(F.SocketMessage,T),C.on(F.SocketClose,A));const x=k=>{var _;const f={responseId:k.responseId,itemId:k.itemId,sequence:k.sequence,byteLength:((_=k.audio)==null?void 0:_.byteLength)??0,format:{encoding:k.format.encoding,sampleRate:k.format.sampleRate,channels:k.format.channels}};nt(Re.ASSISTANT_AUDIO_DELTA,f,c)},N=k=>{nt(Re.ASSISTANT_AUDIO_DONE,{responseId:k.responseId},c)},E=k=>{nt(Re.ASSISTANT_AUDIO_INTERRUPTED,{responseId:k.responseId},c)};return t.on("agent.connected",u),t.on("agent.disconnected",d),t.on("agent.error",h),t.on("conversation.update",p),t.on("transcript.item",m),t.on("conversation.agent.state",v),t.on("agent.audio.mute",b),t.on("assistant.audio.delta",x),t.on("assistant.audio.done",N),t.on("assistant.audio.interrupted",E),()=>{t.off("agent.connected",u),t.off("agent.disconnected",d),t.off("agent.error",h),t.off("conversation.update",p),t.off("transcript.item",m),t.off("conversation.agent.state",v),t.off("agent.audio.mute",b),t.off("assistant.audio.delta",x),t.off("assistant.audio.done",N),t.off("assistant.audio.interrupted",E),C&&typeof C=="object"&&(C.off(F.SocketMessage,T),C.off(F.SocketClose,A))}},[t,n,s,o,r,l])},vS=(t,e,i,n,s,o,r,a)=>{const[l,c]=ve(null),[u,d]=ve([]),[h,p]=ve(!1),[m,v]=ve(!1),[b,y]=ve(!1),[C,T]=ve(null),[A,x]=ve(null),[,N]=ms(),E=Au(),k=ce(null),f=ce(!1),[_,g]=ve(!1),[S,I]=ve(0);Le(()=>{var Ze;if(c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),!t||f.current)return;N("listening"),console.log(e);const L=new aS({agentId:t,environment:e,versionId:i,conversationId:n,region:s,debug:o,url:a});let V=!1,$=!1,W=!1,q=!1,G=null,oe=null;const K=new Set,Z=(Ze=r==null?void 0:r.current)==null?void 0:Ze.getRootNode(),Y=Z instanceof ShadowRoot?Z.host:null,te=(ne,ye)=>{V||nt(ne,ye,Y)},me=()=>{oe=null,y(!1)},Oe=ne=>{te(Re.TRANSCRIPT_ITEM,ne)},_e=ne=>{V||(d([...ne]),te(Re.TRANSCRIPT_UPDATED,[...ne]))},xe=ne=>{if(V||$)return;const ye="reason"in ne&&typeof ne.reason=="string"?ne.reason:void 0,Be=ne.name==="TextChatResponseError"?"response":q||L.isConnected?"send":"connection";Be==="connection"?T(ne):Be==="response"&&x(ne),te(Re.AGENT_ERROR,{message:ne.message,name:ne.name,reason:ye,scope:Be})},he=()=>{V||(p(!1),me(),W&&(W=!1,te(Re.AGENT_DISCONNECTED)),$||T(new Error("Connection to the assistant was lost. Reconnect to continue.")))},de=ne=>{if(V)return;if(Eu(ne)){const vi=ne.params.widget_settings;vi&&Object.keys(vi).length&&E(vi)}if(!ne||typeof ne!="object")return;const ye=ne;if(ye.method!=="ai_conversation"||!ye.params)return;const{type:Be,response_id:Ee,item_id:at,text:Vn,error:St}=ye.params;if(Be==="response.error"&&St&&typeof St=="object"&&"reason"in St&&typeof St.reason=="string"&&St.reason)me();else if(typeof Ee=="string"&&Ee&&typeof at=="string"&&at){if(K.has(Ee))return;oe&&!oe.responseId&&(oe.responseId=Ee),Be==="response.text.done"&&typeof Vn=="string"&&(K.add(Ee),(oe==null?void 0:oe.responseId)===Ee&&me())}},fe=ne=>{V||(N(ne.state==="thinking"?"thinking":"listening"),te(Re.CONVERSATION_AGENT_STATE,ne))};L.on("transcript.item",Oe),L.on("transcript.updated",_e),L.on("agent.error",xe),L.on("agent.disconnected",he),L.on("conversation.agent.state",fe),L.socketEvents.on(F.SocketMessage,de);const Je=()=>V?Promise.resolve():G||($=!0,L.disconnect(),$=!1,me(),v(!0),p(!1),T(null),x(null),G=L.connect().then(()=>{V||(p(L.isConnected),L.isConnected&&(W=!0,te(Re.AGENT_CONNECTED,{conversationId:L.conversationId})))}).catch(ne=>{V||T(ne instanceof Error?ne:new Error(String(ne)))}).finally(()=>{G=null,V||v(!1)}),G),Qe=async ne=>{if(V||!L.isConnected||G)throw new Error("Reconnect before sending.");if(oe)throw new Error("Wait for the current reply to finish.");const ye={};oe=ye,y(!0),x(null),q=!0;try{await L.sendMessage(ne)}catch(Be){throw!V&&oe===ye&&me(),Be}finally{q=!1}},Ot=()=>{var ne;V||($=!0,L.disconnect(),V=!0,((ne=k.current)==null?void 0:ne.agent)===L&&(k.current=null),L.off("transcript.item",Oe),L.off("transcript.updated",_e),L.off("agent.error",xe),L.off("agent.disconnected",he),L.off("conversation.agent.state",fe),L.socketEvents.off(F.SocketMessage,de),N("listening"))};return k.current={agent:L,send:Qe,connect:Je,end:Ot},c(L),Je(),Ot},[t,e,i,n,s,o,a,r,S,N,E]);const M=Ne(async L=>{if(!k.current)throw new Error("Connect before sending.");await k.current.send(L)},[]),R=Ne(()=>{var L;(L=k.current)==null||L.connect()},[]),P=Ne(()=>{var L;f.current||(f.current=!0,(L=k.current)==null||L.end(),g(!0),c(null),d([]),p(!1),v(!1),y(!1),T(null),x(null),N("listening"))},[N]),O=Ne(()=>{f.current&&(f.current=!1,g(!1),I(L=>L+1))},[]);return{isEnded:_,sessionKey:S,endChat:P,startChat:O,client:l,transcript:u,isConnected:h,isConnecting:m,isResponding:b,error:C,responseError:A,sendMessage:M,retry:R}},_S=2e3;async function yS(t){return new Promise((e,i)=>{const n=new FileReader;n.readAsDataURL(t),n.onload=()=>e(n.result),n.onerror=s=>i(s)})}function Yf(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 bS=(t,e)=>{const[i,n]=ve([]),[,s]=ms(),o=ce(e);Le(()=>{o.current=e},[e]);const r=ce(void 0),a=ce(void 0);return Le(()=>{if(!t)return;const c=h=>{n(p=>{const m=p[p.length-1];if(h.role==="assistant"&&m&&Yf(m.id)===Yf(h.id)&&m.role==="assistant"){const v=o.current.showUserPerceivedLatency&&r.current!==void 0&&m.userPerceivedLatencyMs===void 0,b=o.current.showGreetingLatency&&a.current!==void 0&&m.greetingLatencyMs===void 0,y={...m,content:m.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),y]}if(h.role==="assistant"){s(y=>y==="thinking"||y==="processing_image"?"speaking":y);const v=o.current.showUserPerceivedLatency&&r.current!==void 0,b=o.current.showGreetingLatency&&a.current!==void 0;if(v||b){const y={...h,...v&&{userPerceivedLatencyMs:r.current},...b&&{greetingLatencyMs:a.current}};return r.current=void 0,a.current=void 0,[...p,y]}r.current=void 0,a.current=void 0}if(h.role==="user"){const v=p.findIndex(y=>y.id===h.id);if(v!==-1){const y=[...p];return y[v]={...p[v],content:h.content,timestamp:h.timestamp,attachments:h.attachments},y}if(m&&m.role==="user"&&h.timestamp.getTime()-m.timestamp.getTime()<_S){const C={...m,id:h.id,content:m.content+" "+h.content,timestamp:h.timestamp,attachments:[...m.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:m,thinkingStartedAt:v})=>{(p!==void 0||m!==void 0)&&re.info(`[AgentState] state=${h} userPerceivedLatencyMs=${p} greetingLatencyMs=${m} thinkingStartedAt=${v}`),h==="speaking"?(s("speaking"),p!==void 0&&(r.current=p),m!==void 0&&(a.current=m)):h==="listening"&&s(b=>b==="processing_image"||b==="thinking"?b:"listening")},d=h=>{var m;const p=(m=h.call)==null?void 0:m.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 yS(h);d.push(p)}catch(p){throw re.error("Failed to convert file to base64:",p),p}t.sendConversationMessage(c,d)}}},Yi={INVOKED:"client.tool.invoked",COMPLETED:"client.tool.completed",ERROR:"client.tool.error"};class wS{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),re.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&&(re.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(Yi.INVOKED,this.boundInvoked),e.on(Yi.COMPLETED,this.boundCompleted),e.on(Yi.ERROR,this.boundError),this.handlers.size>0&&re.debug(`[client-tools] re-applied ${this.handlers.size} handler(s) to new agent`)}detach(){const e=this.agent;e&&(this.boundInvoked&&e.off(Yi.INVOKED,this.boundInvoked),this.boundCompleted&&e.off(Yi.COMPLETED,this.boundCompleted),this.boundError&&e.off(Yi.ERROR,this.boundError)),this.agent=null,this.listeners=null,this.boundInvoked=null,this.boundCompleted=null,this.boundError=null}}function wa(t,e,i){t&&t.dispatchEvent(new CustomEvent(e,{detail:i,bubbles:!0,composed:!0}))}const SS=(t,e)=>{const i=ce(null);i.current===null&&(i.current=new wS),oo(()=>{const n=e.current;if(!n)return;const s=n.getRootNode(),o=s instanceof ShadowRoot?s.host:null;if(!o){re.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]),Le(()=>{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=>{wa(s(),Re.CLIENT_TOOL_INVOKED,o)},onCompleted:o=>{wa(s(),Re.CLIENT_TOOL_COMPLETED,o)},onError:o=>{wa(s(),Re.CLIENT_TOOL_ERROR,o)}}),()=>{n.detach()}},[t,e])},CS=({call:t,client:e,latencySettings:i,chatMode:n,debug:s=!1})=>{const o=ui(),[r,a]=ve(n?"expanded":o.default_state),l=()=>a("expanded"),c=()=>a("collapsed"),{transcript:u}=bS(e,i),d=ce(!1);switch(Le(()=>{if(n&&t&&!d.current){const h="remoteStream"in t?t.remoteStream:null;h&&(d.current=!0,h.getAudioTracks().forEach(p=>{p.enabled=!1,re.info(`[ChatMode] Disabled remote audio track: ${p.label}`)}))}},[n,t]),r){case"collapsed":return D(oh,{onExpand:l,call:t,client:e,chatMode:n,debug:s});case"expanded":return D(x0,{transcript:u,onCollapse:c,call:t,chatMode:n,debug:s});default:return D(oh,{onExpand:l,call:t,client:e,chatMode:n,debug:s})}},Sa=({message:t})=>D(Xt.div,{layoutId:Tn,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(i0,{})}),t&&D("p",{role:"status",children:t})]}),TS=({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(Sa,{});case"done":case"purged":case"destroy":return null;case"active":return D(CS,{client:e,call:t,latencySettings:i,chatMode:n,debug:s});default:return D(Sa,{})}},Xf=({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 Jf(){const t=ui();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(Xf,{className:"w-8 h-8 mr-2"})}const kS=({client:t,callProps:e,chatMode:i,isReady:n})=>{const s=ui(),o=ce(!1),r=Ne(async()=>{if(!t){re.error("Client is not initialized.");return}if(!n){re.warn("AI Agent client is not ready to start a conversation.");return}try{await t.startConversation({...e})}catch(a){re.error("Failed to start AI Agent conversation:",a)}},[t,e,n]);return Le(()=>{i&&t&&n&&!o.current&&(o.current=!0,re.info("[ChatMode] Auto-starting conversation"),r())},[i,t,n,r]),i?D(Xt.div,{layoutId:Tn,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(Jf,{}),"Connecting..."]}):D(Xt.button,{layoutId:Tn,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(Jf,{}),s.start_call_text]})},ES=({transcript:t,onSendMessage:e,isConnected:i,isConnecting:n,isResponding:s,connectionError:o,responseError:r,onRetry:a,isEnded:l,onEndChat:c,onStartChat:u,startLabel:d="Start new chat",onClose:h,debug:p=!1})=>l?D(Xt.button,{type:"button",initial:{opacity:0},animate:{opacity:1},transition:{duration:.15,ease:"easeOut"},onClick:u,className:"inline-flex w-fit max-w-full items-center justify-center gap-2.5 rounded-full bg-[#FEFDF5] px-4 py-3 text-base font-medium leading-6 text-black shadow-lg shadow-[#38383840] cursor-pointer transition-colors hover:bg-[#F3F2EA] focus-visible:outline-2 focus-visible:outline-offset-4 dark:bg-black dark:text-white dark:hover:bg-[#1C1C1E]",children:[D(Xf,{className:"h-6 w-6 shrink-0"}),D("span",{children:d})]}):D(Gc,{children:D(Xt.div,{exit:{opacity:0,scale:.95},initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},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("div",{className:"flex items-center justify-between w-full",children:[D(rh,{}),D("button",{type:"button",onClick:c,className:"ml-auto flex items-center gap-1.5 rounded-full border border-[#969696] dark:border-[#3D3D46] px-3 py-1.5 text-sm cursor-pointer focus-visible:outline focus-visible:outline-offset-2",children:[D(In,{className:"w-4 h-4","aria-hidden":"true"}),"End chat"]}),h&&D(xt,{tooltip:"Close",className:"ml-auto",onClick:h,children:D(In,{className:"text-black dark:text-white"})})]}),D(Dr,{size:"large",className:"mb-4"}),D(Ur,{className:"mt-2",debug:p})]}),D("div",{className:"px-4 pb-2 text-sm",children:[o&&D("p",{role:"alert",children:o.message}),!i&&(n?D("p",{role:"status",children:"Connecting…"}):D("button",{className:"underline",onClick:a,children:"Reconnect"})),r&&D("p",{role:"alert",children:r.message}),s&&D("p",{role:"status",children:"Receiving reply…"})]}),D(fh,{transcript:t,onSendMessage:e,allowAttachments:!1,awaitAcceptance:!0,sendDisabled:!i||s||n})]})}),IS='@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-leading:initial;--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;--tw-outline-style:solid}}}@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-base:1rem;--text-base--line-height: 1.5 ;--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}.visible{visibility:visible}.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}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.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-6{height:calc(var(--spacing)*6)}.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-6{width:calc(var(--spacing)*6)}.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-fit{width:fit-content}.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}.shrink-0{flex-shrink:0}.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-1\\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-2\\.5{gap:calc(var(--spacing)*2.5)}.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)}.pb-2{padding-bottom:calc(var(--spacing)*2)}.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-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--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))}.leading-6{--tw-leading:calc(var(--spacing)*6);line-height:calc(var(--spacing)*6)}.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-\\[\\#38383840\\]{--tw-shadow-color:#38383840}@supports (color:color-mix(in lab,red,red)){.shadow-\\[\\#38383840\\]{--tw-shadow-color:color-mix(in oklab,#38383840 var(--tw-shadow-alpha),transparent)}}.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-\\[\\#F3F2EA\\]:hover{background-color:#f3f2ea}.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)}}.focus-visible\\:outline:focus-visible{outline-style:var(--tw-outline-style);outline-width:1px}.focus-visible\\:outline-2:focus-visible{outline-style:var(--tw-outline-style);outline-width:2px}.focus-visible\\:outline-offset-2:focus-visible{outline-offset:2px}.focus-visible\\:outline-offset-4:focus-visible{outline-offset:4px}.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-\\[\\#1C1C1E\\]:where(.dark,.dark *):hover{background-color:#1c1c1e}.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-leading{syntax:"*";inherits:false}@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}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@keyframes spin{to{transform:rotate(360deg)}}',AS=({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})}),RS={duration:.1,ease:"circOut"},xS=({children:t,position:e="fixed",rootRef:i})=>{const n=ui(),o=(e??n.position??"fixed")==="fixed"?D(AS,{children:t}):t;return D("div",{ref:i,className:Vt(n.theme==="dark"&&"dark"),children:D(Ym,{transition:RS,children:[D("style",{children:IS}),o]})})},DS=t=>D(Xt.div,{layoutId:Tn,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(e0,{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(c0,{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(a0,{className:"w-4 h-4"}),"Retry"]})]});function Zt(t){return typeof t=="boolean"?t:t===void 0?!1:t!=="false"}function Qf(t,e){return t===void 0?e:Zt(t)}function LS({"agent-id":t,debug:e,"trickle-ice":i,"prefetch-ice-candidates":n,"call-destination-number":s,"call-caller-number":o,"call-caller-name":r,"call-custom-headers":a,"call-audio":l,vad:c,"show-user-perceived-latency":u,"show-greeting-latency":d,"conversation-id":h,"chat-mode":p,"text-only":m,"text-chat-url":v,region:b,"rtc-ip":y,"rtc-port":C,"skip-last-voice-sdk-id":T,"streaming-audio":A,environment:x,position:N="fixed","version-id":E}){const k=Zt(e),f=C!=null&&C.trim()?Number(C):void 0,_=Qf(i,!0),g=Qf(n,!0),S=Zt(p),I=Zt(m),M=Zt(A),R=T===void 0?!0:Zt(T),P=dt(()=>{if(c)try{return JSON.parse(c)}catch(Ee){re.error("Invalid JSON for vad attribute:",c,Ee);return}},[c]),O=dt(()=>({showUserPerceivedLatency:Zt(u),showGreetingLatency:Zt(d)}),[u,d]),{client:L,error:V,isConnected:$,isReconnecting:W}=fS(I?void 0:t,x,E,k,_,g,P,h,S,b,R,M,y,f),[q,G]=ve(null),[oe,K]=ve(!1),[Z,Y]=ve(!1),[te,me]=ve(!1),[Oe,_e]=ve(!1),xe=Jn(nh),he=Au(),de={};if(s&&(de.destinationNumber=s),o&&(de.callerNumber=o),r&&(de.callerName=r),a)try{de.customHeaders=JSON.parse(a)}catch(Ee){re.error("Invalid JSON for call-custom-headers attribute:",a,Ee)}if(l)try{de.audio=JSON.parse(l);const Ee=de.audio;if(typeof Ee=="object"){const at=navigator.mediaDevices.getSupportedConstraints();Object.keys(Ee).forEach(Vn=>{at[Vn]||re.warn(`Audio constraint not supported by browser: ${Vn}`)})}}catch(Ee){re.error("Invalid JSON for call-audio attribute:",l,Ee)}const fe=Ne(()=>{K(!1)},[]),Je=Ne(Ee=>{var at;if(((at=Ee.call)==null?void 0:at.state)==="destroy")return xe(!1),_e(!0),G(null);G(Ee)},[xe]),Qe=Ne(()=>{K(!1),W||Y(!0)},[W]),Ot=Ne(()=>{re.info("User triggered retry"),Y(!1),K(!0),L&&L.connect()},[L]),Ze=Ne(Ee=>{if(Eu(Ee)){const at=Ee.params.widget_settings;at&&Object.keys(at).length>0&&(he(at),me(!0))}},[he]),ne=ce(null),ye=vS(I?t:void 0,x,E,h,b,k,ne,v);return mS(L,{onReady:fe,onConversationUpdate:Je,onError:Qe,onConfigMessage:Ze},ne),SS(L,ne),D(xS,{position:N,rootRef:ne,children:t?I?D(ES,{isConnected:ye.isConnected,isConnecting:ye.isConnecting,isResponding:ye.isResponding,connectionError:ye.error,responseError:ye.responseError,onRetry:ye.retry,isEnded:ye.isEnded,onEndChat:ye.endChat,onStartChat:ye.startChat,startLabel:h?"Start chat":"Start new chat",transcript:ye.transcript,onSendMessage:ye.sendMessage,debug:k},JSON.stringify([t,x,E,h,b,k,v,ye.sessionKey])):Z||V?D(DS,{agentId:t,onRetry:Ot}):oe||W?D(Sa,{message:W?"Retrying...":void 0}):q!=null&&q.call?D(TS,{call:q.call,client:L,latencySettings:O,chatMode:S,debug:k}):te?D(kS,{client:L,callProps:de,chatMode:S&&!Oe,isReady:$&&!!L}):null:D("div",{children:"Please provide an assistant ID."})})}gp(LS,"telnyx-ai-agent",Ey,{shadow:!0})})();
|