@anam-ai/agent-widget 0.1.0-alpha.17 → 0.1.0-alpha.18

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/dist/index.js CHANGED
@@ -874,6 +874,7 @@ const oi = {
874
874
  showCaptions: !1,
875
875
  showTextInput: !0,
876
876
  showMuteButton: !0,
877
+ removeWatermark: !1,
877
878
  callToAction: "Talk to our assistant"
878
879
  }, He = {
879
880
  "bottom-right": { bottom: "24px", right: "24px" },
@@ -3769,7 +3770,7 @@ function Tr({
3769
3770
  ] })
3770
3771
  ] })
3771
3772
  ] }),
3772
- /* @__PURE__ */ w(
3773
+ !t.removeWatermark && /* @__PURE__ */ w(
3773
3774
  "a",
3774
3775
  {
3775
3776
  class: "anam-watermark",
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(le,ne){typeof exports=="object"&&typeof module<"u"?ne(exports):typeof define=="function"&&define.amd?define(["exports"],ne):(le=typeof globalThis<"u"?globalThis:le||self,ne(le.AnamAgentWidget={}))})(this,(function(le){"use strict";var ne,x,Pt,Ft,ge,$t,Vt,Gt,jt,at,lt,ct,xe={},Ht=[],Ji=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ge=Array.isArray;function ee(t,e){for(var n in e)t[n]=e[n];return t}function ut(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Se(t,e,n){var o,u,a,c={};for(a in e)a=="key"?o=e[a]:a=="ref"?u=e[a]:c[a]=e[a];if(arguments.length>2&&(c.children=arguments.length>3?ne.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(a in t.defaultProps)c[a]===void 0&&(c[a]=t.defaultProps[a]);return Oe(t,c,o,u,null)}function Oe(t,e,n,o,u){var a={type:t,props:e,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:u??++Pt,__i:-1,__u:0};return u==null&&x.vnode!=null&&x.vnode(a),a}function ce(t){return t.children}function ke(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Wt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Wt(t)}}function zt(t){(!t.__d&&(t.__d=!0)&&ge.push(t)&&!je.__r++||$t!=x.debounceRendering)&&(($t=x.debounceRendering)||Vt)(je)}function je(){for(var t,e,n,o,u,a,c,l=1;ge.length;)ge.length>l&&ge.sort(Gt),t=ge.shift(),l=ge.length,t.__d&&(n=void 0,o=void 0,u=(o=(e=t).__v).__e,a=[],c=[],e.__P&&((n=ee({},o)).__v=o.__v+1,x.vnode&&x.vnode(n),dt(e.__P,n,o,e.__n,e.__P.namespaceURI,32&o.__u?[u]:null,a,u??we(o),!!(32&o.__u),c),n.__v=o.__v,n.__.__k[n.__i]=n,Xt(a,n,c),o.__e=o.__=null,n.__e!=u&&Wt(n)));je.__r=0}function qt(t,e,n,o,u,a,c,l,m,p,_){var d,S,g,y,C,A,I,b=o&&o.__k||Ht,N=e.length;for(m=Xi(n,e,b,m,N),d=0;d<N;d++)(g=n.__k[d])!=null&&(S=g.__i==-1?xe:b[g.__i]||xe,g.__i=d,A=dt(t,g,S,u,a,c,l,m,p,_),y=g.__e,g.ref&&S.ref!=g.ref&&(S.ref&&ft(S.ref,null,g),_.push(g.ref,g.__c||y,g)),C==null&&y!=null&&(C=y),(I=!!(4&g.__u))||S.__k===g.__k?m=Yt(g,m,t,I):typeof g.type=="function"&&A!==void 0?m=A:y&&(m=y.nextSibling),g.__u&=-7);return n.__e=C,m}function Xi(t,e,n,o,u){var a,c,l,m,p,_=n.length,d=_,S=0;for(t.__k=new Array(u),a=0;a<u;a++)(c=e[a])!=null&&typeof c!="boolean"&&typeof c!="function"?(typeof c=="string"||typeof c=="number"||typeof c=="bigint"||c.constructor==String?c=t.__k[a]=Oe(null,c,null,null,null):Ge(c)?c=t.__k[a]=Oe(ce,{children:c},null,null,null):c.constructor===void 0&&c.__b>0?c=t.__k[a]=Oe(c.type,c.props,c.key,c.ref?c.ref:null,c.__v):t.__k[a]=c,m=a+S,c.__=t,c.__b=t.__b+1,l=null,(p=c.__i=Zi(c,n,m,d))!=-1&&(d--,(l=n[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(u>_?S--:u<_&&S++),typeof c.type!="function"&&(c.__u|=4)):p!=m&&(p==m-1?S--:p==m+1?S++:(p>m?S--:S++,c.__u|=4))):t.__k[a]=null;if(d)for(a=0;a<_;a++)(l=n[a])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=we(l)),Qt(l,l));return o}function Yt(t,e,n,o){var u,a;if(typeof t.type=="function"){for(u=t.__k,a=0;u&&a<u.length;a++)u[a]&&(u[a].__=t,e=Yt(u[a],e,n,o));return e}t.__e!=e&&(o&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Zi(t,e,n,o){var u,a,c,l=t.key,m=t.type,p=e[n],_=p!=null&&(2&p.__u)==0;if(p===null&&l==null||_&&l==p.key&&m==p.type)return n;if(o>(_?1:0)){for(u=n-1,a=n+1;u>=0||a<e.length;)if((p=e[c=u>=0?u--:a++])!=null&&(2&p.__u)==0&&l==p.key&&m==p.type)return c}return-1}function Kt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ji.test(e)?n:n+"px"}function He(t,e,n,o,u){var a,c;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof o=="string"&&(t.style.cssText=o=""),o)for(e in o)n&&e in n||Kt(t.style,e,"");if(n)for(e in n)o&&n[e]==o[e]||Kt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")a=e!=(e=e.replace(jt,"$1")),c=e.toLowerCase(),e=c in t||e=="onFocusOut"||e=="onFocusIn"?c.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+a]=n,n?o?n.u=o.u:(n.u=at,t.addEventListener(e,a?ct:lt,a)):t.removeEventListener(e,a?ct:lt,a);else{if(u=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Jt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=at++;else if(e.t<n.u)return;return n(x.event?x.event(e):e)}}}function dt(t,e,n,o,u,a,c,l,m,p){var _,d,S,g,y,C,A,I,b,N,M,k,Y,oe,V,se,ae,Q=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(m=!!(32&n.__u),a=[l=e.__e=n.__e]),(_=x.__b)&&_(e);e:if(typeof Q=="function")try{if(I=e.props,b="prototype"in Q&&Q.prototype.render,N=(_=Q.contextType)&&o[_.__c],M=_?N?N.props.value:_.__:o,n.__c?A=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new Q(I,M):(e.__c=d=new ke(I,M),d.constructor=Q,d.render=en),N&&N.sub(d),d.state||(d.state={}),d.__n=o,S=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&Q.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ee({},d.__s)),ee(d.__s,Q.getDerivedStateFromProps(I,d.__s))),g=d.props,y=d.state,d.__v=e,S)b&&Q.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&Q.getDerivedStateFromProps==null&&I!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(I,M),e.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(I,d.__s,M)===!1){for(e.__v!=n.__v&&(d.props=I,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Ee){Ee&&(Ee.__=e)}),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[],d.__h.length&&c.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(I,d.__s,M),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,C)})}if(d.context=M,d.props=I,d.__P=t,d.__e=!1,Y=x.__r,oe=0,b){for(d.state=d.__s,d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),V=0;V<d._sb.length;V++)d.__h.push(d._sb[V]);d._sb=[]}else do d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++oe<25);d.state=d.__s,d.getChildContext!=null&&(o=ee(ee({},o),d.getChildContext())),b&&!S&&d.getSnapshotBeforeUpdate!=null&&(C=d.getSnapshotBeforeUpdate(g,y)),se=_,_!=null&&_.type===ce&&_.key==null&&(se=Zt(_.props.children)),l=qt(t,Ge(se)?se:[se],e,n,o,u,a,c,l,m,p),d.base=e.__e,e.__u&=-161,d.__h.length&&c.push(d),A&&(d.__E=d.__=null)}catch(Ee){if(e.__v=null,m||a!=null)if(Ee.then){for(e.__u|=m?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;a[a.indexOf(l)]=null,e.__e=l}else{for(ae=a.length;ae--;)ut(a[ae]);ht(e)}else e.__e=n.__e,e.__k=n.__k,Ee.then||ht(e);x.__e(Ee,e,n)}else a==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Qi(n.__e,e,n,o,u,a,c,m,p);return(_=x.diffed)&&_(e),128&e.__u?void 0:l}function ht(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(ht)}function Xt(t,e,n){for(var o=0;o<n.length;o++)ft(n[o],n[++o],n[++o]);x.__c&&x.__c(e,t),t.some(function(u){try{t=u.__h,u.__h=[],t.some(function(a){a.call(u)})}catch(a){x.__e(a,u.__v)}})}function Zt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ge(t)?t.map(Zt):ee({},t)}function Qi(t,e,n,o,u,a,c,l,m){var p,_,d,S,g,y,C,A=n.props||xe,I=e.props,b=e.type;if(b=="svg"?u="http://www.w3.org/2000/svg":b=="math"?u="http://www.w3.org/1998/Math/MathML":u||(u="http://www.w3.org/1999/xhtml"),a!=null){for(p=0;p<a.length;p++)if((g=a[p])&&"setAttribute"in g==!!b&&(b?g.localName==b:g.nodeType==3)){t=g,a[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(I);t=document.createElementNS(u,b,I.is&&I),l&&(x.__m&&x.__m(e,a),l=!1),a=null}if(b==null)A===I||l&&t.data==I||(t.data=I);else{if(a=a&&ne.call(t.childNodes),!l&&a!=null)for(A={},p=0;p<t.attributes.length;p++)A[(g=t.attributes[p]).name]=g.value;for(p in A)if(g=A[p],p!="children"){if(p=="dangerouslySetInnerHTML")d=g;else if(!(p in I)){if(p=="value"&&"defaultValue"in I||p=="checked"&&"defaultChecked"in I)continue;He(t,p,null,g,u)}}for(p in I)g=I[p],p=="children"?S=g:p=="dangerouslySetInnerHTML"?_=g:p=="value"?y=g:p=="checked"?C=g:l&&typeof g!="function"||A[p]===g||He(t,p,g,A[p],u);if(_)l||d&&(_.__html==d.__html||_.__html==t.innerHTML)||(t.innerHTML=_.__html),e.__k=[];else if(d&&(t.innerHTML=""),qt(e.type=="template"?t.content:t,Ge(S)?S:[S],e,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":u,a,c,a?a[0]:n.__k&&we(n,0),l,m),a!=null)for(p=a.length;p--;)ut(a[p]);l||(p="value",b=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[p]||b=="progress"&&!y||b=="option"&&y!=A[p])&&He(t,p,y,A[p],u),p="checked",C!=null&&C!=t[p]&&He(t,p,C,A[p],u))}return t}function ft(t,e,n){try{if(typeof t=="function"){var o=typeof t.__u=="function";o&&t.__u(),o&&e==null||(t.__u=t(e))}else t.current=e}catch(u){x.__e(u,n)}}function Qt(t,e,n){var o,u;if(x.unmount&&x.unmount(t),(o=t.ref)&&(o.current&&o.current!=t.__e||ft(o,null,e)),(o=t.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(a){x.__e(a,e)}o.base=o.__P=null}if(o=t.__k)for(u=0;u<o.length;u++)o[u]&&Qt(o[u],e,n||typeof t.type!="function");n||ut(t.__e),t.__c=t.__=t.__e=void 0}function en(t,e,n){return this.constructor(t,n)}function We(t,e,n){var o,u,a,c;e==document&&(e=document.documentElement),x.__&&x.__(t,e),u=(o=typeof n=="function")?null:n&&n.__k||e.__k,a=[],c=[],dt(e,t=(!o&&n||e).__k=Se(ce,null,[t]),u||xe,xe,e.namespaceURI,!o&&n?[n]:u?null:e.firstChild?ne.call(e.childNodes):null,a,!o&&n?n:u?u.__e:e.firstChild,o,c),Xt(a,t,c)}function ei(t,e){We(t,e,ei)}function ti(t,e,n){var o,u,a,c,l=ee({},t.props);for(a in t.type&&t.type.defaultProps&&(c=t.type.defaultProps),e)a=="key"?o=e[a]:a=="ref"?u=e[a]:l[a]=e[a]===void 0&&c!=null?c[a]:e[a];return arguments.length>2&&(l.children=arguments.length>3?ne.call(arguments,2):n),Oe(t.type,l,o||t.key,u||t.ref,null)}ne=Ht.slice,x={__e:function(t,e,n,o){for(var u,a,c;e=e.__;)if((u=e.__c)&&!u.__)try{if((a=u.constructor)&&a.getDerivedStateFromError!=null&&(u.setState(a.getDerivedStateFromError(t)),c=u.__d),u.componentDidCatch!=null&&(u.componentDidCatch(t,o||{}),c=u.__d),c)return u.__E=u}catch(l){t=l}throw t}},Pt=0,Ft=function(t){return t!=null&&t.constructor===void 0},ke.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ee({},this.state),typeof t=="function"&&(t=t(ee({},n),this.props)),t&&ee(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),zt(this))},ke.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),zt(this))},ke.prototype.render=ce,ge=[],Vt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Gt=function(t,e){return t.__v.__b-e.__v.__b},je.__r=0,jt=/(PointerCapture)$|Capture$/i,at=0,lt=Jt(!1),ct=Jt(!0);function ze(){return ze=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},ze.apply(this,arguments)}function ii(t,e){if(t==null)return{};var n,o,u={},a=Object.keys(t);for(o=0;o<a.length;o++)e.indexOf(n=a[o])>=0||(u[n]=t[n]);return u}var tn=["context","children"],nn=["useFragment"];function rn(t,e,n,o){function u(){var a,c=Reflect.construct(HTMLElement,[],u);return c._vdomComponent=t,o&&o.shadow?(c._root=c.attachShadow({mode:o.mode||"open",serializable:(a=o.serializable)!=null&&a}),o.adoptedStyleSheets&&(c._root.adoptedStyleSheets=o.adoptedStyleSheets)):c._root=c,c}return(u.prototype=Object.create(HTMLElement.prototype)).constructor=u,u.prototype.connectedCallback=function(){sn.call(this,o)},u.prototype.attributeChangedCallback=an,u.prototype.disconnectedCallback=ln,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),u.observedAttributes=n,t.formAssociated&&(u.formAssociated=!0),n.forEach(function(a){Object.defineProperty(u.prototype,a,{get:function(){return this._vdom?this._vdom.props[a]:this._props[a]},set:function(c){this._vdom?this.attributeChangedCallback(a,null,c):(this._props||(this._props={}),this._props[a]=c);var l=typeof c;c!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(a,c)}})}),customElements.define(e||t.tagName||t.displayName||t.name,u),u}function on(t){this.getChildContext=function(){return t.context};var e=t.children,n=ii(t,tn);return ti(e,n)}function sn(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Se(on,ze({},this._props,{context:e.detail.context}),oi(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?ei:We)(this._vdom,this._root)}function ni(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function an(t,e,n){if(this._vdom){var o={};o[t]=n=n??void 0,o[ni(t)]=n,this._vdom=ti(this._vdom,o),We(this._vdom,this._root)}}function ln(){We(this._vdom=null,this._root)}function ri(t,e){var n=this,o=t.useFragment,u=ii(t,nn);return Se(o?ce:"slot",ze({},u,{ref:function(a){a?(n.ref=a,n._listener||(n._listener=function(c){c.stopPropagation(),c.detail.context=e},a.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function oi(t,e,n){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var o=[],u={},a=0,c=t.attributes,l=t.childNodes;for(a=c.length;a--;)c[a].name!=="slot"&&(u[c[a].name]=c[a].value,u[ni(c[a].name)]=c[a].value);for(a=l.length;a--;){var m=oi(l[a],null,n),p=l[a].slot;p?u[p]=Se(ri,{name:p},m):o[a]=m}var _=!(!n||!n.shadow),d=e?Se(ri,{useFragment:!_},o):o;return!_&&e&&(t.innerHTML=""),Se(e||t.nodeName.toLowerCase(),u,d)}var cn=0;function w(t,e,n,o,u,a){e||(e={});var c,l,m=e;if("ref"in m)for(l in m={},e)l=="ref"?c=e[l]:m[l]=e[l];var p={type:t,props:m,key:n,ref:c,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cn,__i:-1,__u:0,__source:u,__self:a};if(typeof t=="function"&&(c=t.defaultProps))for(l in c)m[l]===void 0&&(m[l]=c[l]);return x.vnode&&x.vnode(p),p}var De,P,pt,si,Me=0,ai=[],F=x,li=F.__b,ci=F.__r,ui=F.diffed,di=F.__c,hi=F.unmount,fi=F.__;function _t(t,e){F.__h&&F.__h(P,t,Me||e),Me=0;var n=P.__H||(P.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function qe(t){return Me=1,un(Ei,t)}function un(t,e,n){var o=_t(De++,2);if(o.t=t,!o.__c&&(o.__=[Ei(void 0,e),function(l){var m=o.__N?o.__N[0]:o.__[0],p=o.t(m,l);m!==p&&(o.__N=[p,o.__[1]],o.__c.setState({}))}],o.__c=P,!P.__f)){var u=function(l,m,p){if(!o.__c.__H)return!0;var _=o.__c.__H.__.filter(function(S){return!!S.__c});if(_.every(function(S){return!S.__N}))return!a||a.call(this,l,m,p);var d=o.__c.props!==l;return _.forEach(function(S){if(S.__N){var g=S.__[0];S.__=S.__N,S.__N=void 0,g!==S.__[0]&&(d=!0)}}),a&&a.call(this,l,m,p)||d};P.__f=!0;var a=P.shouldComponentUpdate,c=P.componentWillUpdate;P.componentWillUpdate=function(l,m,p){if(this.__e){var _=a;a=void 0,u(l,m,p),a=_}c&&c.call(this,l,m,p)},P.shouldComponentUpdate=u}return o.__N||o.__}function Et(t,e){var n=_t(De++,3);!F.__s&&_i(n.__H,e)&&(n.__=t,n.u=e,P.__H.__h.push(n))}function mt(t){return Me=5,Ce(function(){return{current:t}},[])}function Ce(t,e){var n=_t(De++,7);return _i(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ye(t,e){return Me=8,Ce(function(){return t},e)}function dn(){for(var t;t=ai.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Ke),t.__H.__h.forEach(gt),t.__H.__h=[]}catch(e){t.__H.__h=[],F.__e(e,t.__v)}}F.__b=function(t){P=null,li&&li(t)},F.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),fi&&fi(t,e)},F.__r=function(t){ci&&ci(t),De=0;var e=(P=t.__c).__H;e&&(pt===P?(e.__h=[],P.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Ke),e.__h.forEach(gt),e.__h=[],De=0)),pt=P},F.diffed=function(t){ui&&ui(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ai.push(e)!==1&&si===F.requestAnimationFrame||((si=F.requestAnimationFrame)||hn)(dn)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),pt=P=null},F.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Ke),n.__h=n.__h.filter(function(o){return!o.__||gt(o)})}catch(o){e.some(function(u){u.__h&&(u.__h=[])}),e=[],F.__e(o,n.__v)}}),di&&di(t,e)},F.unmount=function(t){hi&&hi(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(o){try{Ke(o)}catch(u){e=u}}),n.__H=void 0,e&&F.__e(e,n.__v))};var pi=typeof requestAnimationFrame=="function";function hn(t){var e,n=function(){clearTimeout(o),pi&&cancelAnimationFrame(e),setTimeout(t)},o=setTimeout(n,35);pi&&(e=requestAnimationFrame(n))}function Ke(t){var e=P,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),P=e}function gt(t){var e=P;t.__c=t.__(),P=e}function _i(t,e){return!t||t.length!==e.length||e.some(function(n,o){return n!==t[o]})}function Ei(t,e){return typeof e=="function"?e(t):e}var fn=Symbol.for("preact-signals");function Je(){if(ue>1)ue--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,vt++;n!==void 0;){var o=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&vi(n))try{n.c()}catch(u){e||(t=u,e=!0)}n=o}}if(vt=0,ue--,e)throw t}}function pn(t){if(ue>0)return t();ue++;try{return t()}finally{Je()}}var O=void 0;function mi(t){var e=O;O=void 0;try{return t()}finally{O=e}}var Ue=void 0,ue=0,vt=0,Xe=0;function gi(t){if(O!==void 0){var e=t.n;if(e===void 0||e.t!==O)return e={i:0,S:t,p:O.s,n:void 0,t:O,e:void 0,x:void 0,r:e},O.s!==void 0&&(O.s.n=e),O.s=e,t.n=e,32&O.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=O.s,e.n=void 0,O.s.n=e,O.s=e),e}}function j(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}j.prototype.brand=fn,j.prototype.h=function(){return!0},j.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:mi(function(){var o;(o=e.W)==null||o.call(e)}))},j.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,o=t.x;n!==void 0&&(n.x=o,t.e=void 0),o!==void 0&&(o.e=n,t.x=void 0),t===this.t&&(this.t=o,o===void 0&&mi(function(){var u;(u=e.Z)==null||u.call(e)}))}},j.prototype.subscribe=function(t){var e=this;return Le(function(){var n=e.value,o=O;O=void 0;try{t(n)}finally{O=o}},{name:"sub"})},j.prototype.valueOf=function(){return this.value},j.prototype.toString=function(){return this.value+""},j.prototype.toJSON=function(){return this.value},j.prototype.peek=function(){var t=O;O=void 0;try{return this.value}finally{O=t}},Object.defineProperty(j.prototype,"value",{get:function(){var t=gi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(vt>100)throw new Error("Cycle detected");this.v=t,this.i++,Xe++,ue++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function z(t,e){return new j(t,e)}function vi(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function yi(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function Si(t){for(var e=t.s,n=void 0;e!==void 0;){var o=e.p;e.i===-1?(e.S.U(e),o!==void 0&&(o.n=e.n),e.n!==void 0&&(e.n.p=o)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=o}t.s=n}function ve(t,e){j.call(this,void 0),this.x=t,this.s=void 0,this.g=Xe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ve.prototype=new j,ve.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Xe))return!0;if(this.g=Xe,this.f|=1,this.i>0&&!vi(this))return this.f&=-2,!0;var t=O;try{yi(this),O=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return O=t,Si(this),this.f&=-2,!0},ve.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}j.prototype.S.call(this,t)},ve.prototype.U=function(t){if(this.t!==void 0&&(j.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ve.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ve.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=gi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function wi(t,e){return new ve(t,e)}function Ci(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ue++;var n=O;O=void 0;try{e()}catch(o){throw t.f&=-2,t.f|=8,yt(t),o}finally{O=n,Je()}}}function yt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,Ci(t)}function _n(t){if(O!==this)throw new Error("Out-of-order effect");Si(this),O=t,this.f&=-2,8&this.f&&yt(this),Je()}function Ie(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ie.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ie.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Ci(this),yi(this),ue++;var t=O;return O=this,_n.bind(this,t)},Ie.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ie.prototype.d=function(){this.f|=8,1&this.f||yt(this)},Ie.prototype.dispose=function(){this.d()};function Le(t,e){var n=new Ie(t,e);try{n.c()}catch(u){throw n.d(),u}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Ii,St,En=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bi=[];Le(function(){Ii=this.N})();function be(t,e){x[t]=e.bind(null,x[t]||function(){})}function Ze(t){St&&St(),St=t&&t.S()}function Ai(t){var e=this,n=t.data,o=Ti(n);o.value=n;var u=Ce(function(){for(var l=e,m=e.__v;m=m.__;)if(m.__c){m.__c.__$f|=4;break}var p=wi(function(){var g=o.value.value;return g===0?0:g===!0?"":g||""}),_=wi(function(){return!Array.isArray(p.value)&&!Ft(p.value)}),d=Le(function(){if(this.N=Ri,_.value){var g=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=g)}}),S=e.__$u.d;return e.__$u.d=function(){d(),S.call(this)},[_,p]},[]),a=u[0],c=u[1];return a.value?c.peek():c.value}Ai.displayName="ReactiveTextNode",Object.defineProperties(j.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ai},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),be("__b",function(t,e){if(typeof e.type=="string"){var n,o=e.props;for(var u in o)if(u!=="children"){var a=o[u];a instanceof j&&(n||(e.__np=n={}),n[u]=a,o[u]=a.peek())}}t(e)}),be("__r",function(t,e){if(e.type!==ce){Ze();var n,o=e.__c;o&&(o.__$f&=-2,(n=o.__$u)===void 0&&(o.__$u=n=(function(u,a){var c;return Le(function(){c=this},{name:a}),c.c=u,c})(function(){var u;En&&((u=n.y)==null||u.call(n)),o.__$f|=1,o.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Ze(n)}t(e)}),be("__e",function(t,e,n,o){Ze(),t(e,n,o)}),be("diffed",function(t,e){Ze();var n;if(typeof e.type=="string"&&(n=e.__e)){var o=e.__np,u=e.props;if(o){var a=n.U;if(a)for(var c in a){var l=a[c];l!==void 0&&!(c in o)&&(l.d(),a[c]=void 0)}else a={},n.U=a;for(var m in o){var p=a[m],_=o[m];p===void 0?(p=mn(n,m,_,u),a[m]=p):p.o(_,u)}}}t(e)});function mn(t,e,n,o){var u=e in t&&t.ownerSVGElement===void 0,a=z(n);return{o:function(c,l){a.value=c,o=l},d:Le(function(){this.N=Ri;var c=a.value.value;o[e]!==c&&(o[e]=c,u?t[e]=c:c!=null&&(c!==!1||e[4]==="-")?t.setAttribute(e,c):t.removeAttribute(e))})}}be("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var u in o){var a=o[u];a&&a.d()}}}}else{var c=e.__c;if(c){var l=c.__$u;l&&(c.__$u=void 0,l.d())}}t(e)}),be("__h",function(t,e,n,o){(o<3||o===9)&&(e.__$f|=2),t(e,n,o)}),ke.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var u in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(o||a||4&this.__$f)||1&this.__$f)return!0}else if(!(o||4&this.__$f)||3&this.__$f)return!0;for(var c in t)if(c!=="__source"&&t[c]!==this.props[c])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Ti(t,e){return qe(function(){return z(t,e)})[0]}var gn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function vn(){pn(function(){for(var t;t=bi.shift();)Ii.call(t)})}function Ri(){bi.push(this)===1&&(x.requestAnimationFrame||gn)(vn)}const wt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,callToAction:"Talk to our assistant"},Qe={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}};function yn(t){if(Qe[t])return Qe[t];const e=t.match(/^\[(.+)\]$/);if(!e)return Qe["bottom-right"];const n={};for(const o of e[1].split(",")){const u=o.trim(),a=u.lastIndexOf("-");if(a<=0)continue;const c=u.slice(0,a),l=u.slice(a+1);n[c]=/^\d+$/.test(l)?`${l}px`:l}return Object.keys(n).length>0?n:Qe["bottom-right"]}var Ct={},Be={},Ni;function Sn(){if(Ni)return Be;Ni=1,Be.byteLength=l,Be.toByteArray=p,Be.fromByteArray=S;for(var t=[],e=[],n=typeof Uint8Array<"u"?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,a=o.length;u<a;++u)t[u]=o[u],e[o.charCodeAt(u)]=u;e[45]=62,e[95]=63;function c(g){var y=g.length;if(y%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var C=g.indexOf("=");C===-1&&(C=y);var A=C===y?0:4-C%4;return[C,A]}function l(g){var y=c(g),C=y[0],A=y[1];return(C+A)*3/4-A}function m(g,y,C){return(y+C)*3/4-C}function p(g){var y,C=c(g),A=C[0],I=C[1],b=new n(m(g,A,I)),N=0,M=I>0?A-4:A,k;for(k=0;k<M;k+=4)y=e[g.charCodeAt(k)]<<18|e[g.charCodeAt(k+1)]<<12|e[g.charCodeAt(k+2)]<<6|e[g.charCodeAt(k+3)],b[N++]=y>>16&255,b[N++]=y>>8&255,b[N++]=y&255;return I===2&&(y=e[g.charCodeAt(k)]<<2|e[g.charCodeAt(k+1)]>>4,b[N++]=y&255),I===1&&(y=e[g.charCodeAt(k)]<<10|e[g.charCodeAt(k+1)]<<4|e[g.charCodeAt(k+2)]>>2,b[N++]=y>>8&255,b[N++]=y&255),b}function _(g){return t[g>>18&63]+t[g>>12&63]+t[g>>6&63]+t[g&63]}function d(g,y,C){for(var A,I=[],b=y;b<C;b+=3)A=(g[b]<<16&16711680)+(g[b+1]<<8&65280)+(g[b+2]&255),I.push(_(A));return I.join("")}function S(g){for(var y,C=g.length,A=C%3,I=[],b=16383,N=0,M=C-A;N<M;N+=b)I.push(d(g,N,N+b>M?M:N+b));return A===1?(y=g[C-1],I.push(t[y>>2]+t[y<<4&63]+"==")):A===2&&(y=(g[C-2]<<8)+g[C-1],I.push(t[y>>10]+t[y>>4&63]+t[y<<2&63]+"=")),I.join("")}return Be}var et={};var xi;function wn(){return xi||(xi=1,et.read=function(t,e,n,o,u){var a,c,l=u*8-o-1,m=(1<<l)-1,p=m>>1,_=-7,d=n?u-1:0,S=n?-1:1,g=t[e+d];for(d+=S,a=g&(1<<-_)-1,g>>=-_,_+=l;_>0;a=a*256+t[e+d],d+=S,_-=8);for(c=a&(1<<-_)-1,a>>=-_,_+=o;_>0;c=c*256+t[e+d],d+=S,_-=8);if(a===0)a=1-p;else{if(a===m)return c?NaN:(g?-1:1)*(1/0);c=c+Math.pow(2,o),a=a-p}return(g?-1:1)*c*Math.pow(2,a-o)},et.write=function(t,e,n,o,u,a){var c,l,m,p=a*8-u-1,_=(1<<p)-1,d=_>>1,S=u===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=o?0:a-1,y=o?1:-1,C=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=_):(c=Math.floor(Math.log(e)/Math.LN2),e*(m=Math.pow(2,-c))<1&&(c--,m*=2),c+d>=1?e+=S/m:e+=S*Math.pow(2,1-d),e*m>=2&&(c++,m/=2),c+d>=_?(l=0,c=_):c+d>=1?(l=(e*m-1)*Math.pow(2,u),c=c+d):(l=e*Math.pow(2,d-1)*Math.pow(2,u),c=0));u>=8;t[n+g]=l&255,g+=y,l/=256,u-=8);for(c=c<<u|l,p+=u;p>0;t[n+g]=c&255,g+=y,c/=256,p-=8);t[n+g-y]|=C*128}),et}var Oi;function Cn(){return Oi||(Oi=1,(function(t){const e=Sn(),n=wn(),o=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=b,t.INSPECT_MAX_BYTES=50;const u=2147483647;t.kMaxLength=u,l.TYPED_ARRAY_SUPPORT=a(),!l.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{const s=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(s,i),s.foo()===42}catch{return!1}}Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}});function c(s){if(s>u)throw new RangeError('The value "'+s+'" is invalid for option "size"');const i=new Uint8Array(s);return Object.setPrototypeOf(i,l.prototype),i}function l(s,i,r){if(typeof s=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(s)}return m(s,i,r)}l.poolSize=8192;function m(s,i,r){if(typeof s=="string")return S(s,i);if(ArrayBuffer.isView(s))return y(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ie(s,ArrayBuffer)||s&&ie(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ie(s,SharedArrayBuffer)||s&&ie(s.buffer,SharedArrayBuffer)))return C(s,i,r);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=s.valueOf&&s.valueOf();if(h!=null&&h!==s)return l.from(h,i,r);const f=A(s);if(f)return f;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return l.from(s[Symbol.toPrimitive]("string"),i,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}l.from=function(s,i,r){return m(s,i,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function _(s,i,r){return p(s),s<=0?c(s):i!==void 0?typeof r=="string"?c(s).fill(i,r):c(s).fill(i):c(s)}l.alloc=function(s,i,r){return _(s,i,r)};function d(s){return p(s),c(s<0?0:I(s)|0)}l.allocUnsafe=function(s){return d(s)},l.allocUnsafeSlow=function(s){return d(s)};function S(s,i){if((typeof i!="string"||i==="")&&(i="utf8"),!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const r=N(s,i)|0;let h=c(r);const f=h.write(s,i);return f!==r&&(h=h.slice(0,f)),h}function g(s){const i=s.length<0?0:I(s.length)|0,r=c(i);for(let h=0;h<i;h+=1)r[h]=s[h]&255;return r}function y(s){if(ie(s,Uint8Array)){const i=new Uint8Array(s);return C(i.buffer,i.byteOffset,i.byteLength)}return g(s)}function C(s,i,r){if(i<0||s.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<i+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return i===void 0&&r===void 0?h=new Uint8Array(s):r===void 0?h=new Uint8Array(s,i):h=new Uint8Array(s,i,r),Object.setPrototypeOf(h,l.prototype),h}function A(s){if(l.isBuffer(s)){const i=I(s.length)|0,r=c(i);return r.length===0||s.copy(r,0,0,i),r}if(s.length!==void 0)return typeof s.length!="number"||Bt(s.length)?c(0):g(s);if(s.type==="Buffer"&&Array.isArray(s.data))return g(s.data)}function I(s){if(s>=u)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+u.toString(16)+" bytes");return s|0}function b(s){return+s!=s&&(s=0),l.alloc(+s)}l.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==l.prototype},l.compare=function(i,r){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),ie(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(i)||!l.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===r)return 0;let h=i.length,f=r.length;for(let E=0,v=Math.min(h,f);E<v;++E)if(i[E]!==r[E]){h=i[E],f=r[E];break}return h<f?-1:f<h?1:0},l.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(i,r){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return l.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<i.length;++h)r+=i[h].length;const f=l.allocUnsafe(r);let E=0;for(h=0;h<i.length;++h){let v=i[h];if(ie(v,Uint8Array))E+v.length>f.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(f,E)):Uint8Array.prototype.set.call(f,v,E);else if(l.isBuffer(v))v.copy(f,E);else throw new TypeError('"list" argument must be an Array of Buffers');E+=v.length}return f};function N(s,i){if(l.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ie(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const r=s.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let f=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Lt(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Ki(s).length;default:if(f)return h?-1:Lt(s).length;i=(""+i).toLowerCase(),f=!0}}l.byteLength=N;function M(s,i,r){let h=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,i>>>=0,r<=i))return"";for(s||(s="utf8");;)switch(s){case"hex":return Cr(this,i,r);case"utf8":case"utf-8":return $i(this,i,r);case"ascii":return Sr(this,i,r);case"latin1":case"binary":return wr(this,i,r);case"base64":return vr(this,i,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ir(this,i,r);default:if(h)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function k(s,i,r){const h=s[i];s[i]=s[r],s[r]=h}l.prototype.swap16=function(){const i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<i;r+=2)k(this,r,r+1);return this},l.prototype.swap32=function(){const i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<i;r+=4)k(this,r,r+3),k(this,r+1,r+2);return this},l.prototype.swap64=function(){const i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<i;r+=8)k(this,r,r+7),k(this,r+1,r+6),k(this,r+2,r+5),k(this,r+3,r+4);return this},l.prototype.toString=function(){const i=this.length;return i===0?"":arguments.length===0?$i(this,0,i):M.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(i){if(!l.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:l.compare(this,i)===0},l.prototype.inspect=function(){let i="";const r=t.INSPECT_MAX_BYTES;return i=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(i+=" ... "),"<Buffer "+i+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(i,r,h,f,E){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),!l.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(r===void 0&&(r=0),h===void 0&&(h=i?i.length:0),f===void 0&&(f=0),E===void 0&&(E=this.length),r<0||h>i.length||f<0||E>this.length)throw new RangeError("out of range index");if(f>=E&&r>=h)return 0;if(f>=E)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,f>>>=0,E>>>=0,this===i)return 0;let v=E-f,T=h-r;const L=Math.min(v,T),U=this.slice(f,E),B=i.slice(r,h);for(let D=0;D<L;++D)if(U[D]!==B[D]){v=U[D],T=B[D];break}return v<T?-1:T<v?1:0};function Y(s,i,r,h,f){if(s.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Bt(r)&&(r=f?0:s.length-1),r<0&&(r=s.length+r),r>=s.length){if(f)return-1;r=s.length-1}else if(r<0)if(f)r=0;else return-1;if(typeof i=="string"&&(i=l.from(i,h)),l.isBuffer(i))return i.length===0?-1:oe(s,i,r,h,f);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?f?Uint8Array.prototype.indexOf.call(s,i,r):Uint8Array.prototype.lastIndexOf.call(s,i,r):oe(s,[i],r,h,f);throw new TypeError("val must be string, number or Buffer")}function oe(s,i,r,h,f){let E=1,v=s.length,T=i.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(s.length<2||i.length<2)return-1;E=2,v/=2,T/=2,r/=2}function L(B,D){return E===1?B[D]:B.readUInt16BE(D*E)}let U;if(f){let B=-1;for(U=r;U<v;U++)if(L(s,U)===L(i,B===-1?0:U-B)){if(B===-1&&(B=U),U-B+1===T)return B*E}else B!==-1&&(U-=U-B),B=-1}else for(r+T>v&&(r=v-T),U=r;U>=0;U--){let B=!0;for(let D=0;D<T;D++)if(L(s,U+D)!==L(i,D)){B=!1;break}if(B)return U}return-1}l.prototype.includes=function(i,r,h){return this.indexOf(i,r,h)!==-1},l.prototype.indexOf=function(i,r,h){return Y(this,i,r,h,!0)},l.prototype.lastIndexOf=function(i,r,h){return Y(this,i,r,h,!1)};function V(s,i,r,h){r=Number(r)||0;const f=s.length-r;h?(h=Number(h),h>f&&(h=f)):h=f;const E=i.length;h>E/2&&(h=E/2);let v;for(v=0;v<h;++v){const T=parseInt(i.substr(v*2,2),16);if(Bt(T))return v;s[r+v]=T}return v}function se(s,i,r,h){return st(Lt(i,s.length-r),s,r,h)}function ae(s,i,r,h){return st(Rr(i),s,r,h)}function Q(s,i,r,h){return st(Ki(i),s,r,h)}function Ee(s,i,r,h){return st(Nr(i,s.length-r),s,r,h)}l.prototype.write=function(i,r,h,f){if(r===void 0)f="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")f=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,f===void 0&&(f="utf8")):(f=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const E=this.length-r;if((h===void 0||h>E)&&(h=E),i.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");f||(f="utf8");let v=!1;for(;;)switch(f){case"hex":return V(this,i,r,h);case"utf8":case"utf-8":return se(this,i,r,h);case"ascii":case"latin1":case"binary":return ae(this,i,r,h);case"base64":return Q(this,i,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ee(this,i,r,h);default:if(v)throw new TypeError("Unknown encoding: "+f);f=(""+f).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function vr(s,i,r){return i===0&&r===s.length?e.fromByteArray(s):e.fromByteArray(s.slice(i,r))}function $i(s,i,r){r=Math.min(s.length,r);const h=[];let f=i;for(;f<r;){const E=s[f];let v=null,T=E>239?4:E>223?3:E>191?2:1;if(f+T<=r){let L,U,B,D;switch(T){case 1:E<128&&(v=E);break;case 2:L=s[f+1],(L&192)===128&&(D=(E&31)<<6|L&63,D>127&&(v=D));break;case 3:L=s[f+1],U=s[f+2],(L&192)===128&&(U&192)===128&&(D=(E&15)<<12|(L&63)<<6|U&63,D>2047&&(D<55296||D>57343)&&(v=D));break;case 4:L=s[f+1],U=s[f+2],B=s[f+3],(L&192)===128&&(U&192)===128&&(B&192)===128&&(D=(E&15)<<18|(L&63)<<12|(U&63)<<6|B&63,D>65535&&D<1114112&&(v=D))}}v===null?(v=65533,T=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),f+=T}return yr(h)}const Vi=4096;function yr(s){const i=s.length;if(i<=Vi)return String.fromCharCode.apply(String,s);let r="",h=0;for(;h<i;)r+=String.fromCharCode.apply(String,s.slice(h,h+=Vi));return r}function Sr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]&127);return h}function wr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]);return h}function Cr(s,i,r){const h=s.length;(!i||i<0)&&(i=0),(!r||r<0||r>h)&&(r=h);let f="";for(let E=i;E<r;++E)f+=xr[s[E]];return f}function Ir(s,i,r){const h=s.slice(i,r);let f="";for(let E=0;E<h.length-1;E+=2)f+=String.fromCharCode(h[E]+h[E+1]*256);return f}l.prototype.slice=function(i,r){const h=this.length;i=~~i,r=r===void 0?h:~~r,i<0?(i+=h,i<0&&(i=0)):i>h&&(i=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<i&&(r=i);const f=this.subarray(i,r);return Object.setPrototypeOf(f,l.prototype),f};function G(s,i,r){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+i>r)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return f},l.prototype.readUintBE=l.prototype.readUIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i+--r],E=1;for(;r>0&&(E*=256);)f+=this[i+--r]*E;return f},l.prototype.readUint8=l.prototype.readUInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]|this[i+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]<<8|this[i+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])},l.prototype.readBigUInt64LE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,E=this[++i]+this[++i]*2**8+this[++i]*2**16+h*2**24;return BigInt(f)+(BigInt(E)<<BigInt(32))}),l.prototype.readBigUInt64BE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],E=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h;return(BigInt(f)<<BigInt(32))+BigInt(E)}),l.prototype.readIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return E*=128,f>=E&&(f-=Math.pow(2,8*r)),f},l.prototype.readIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=r,E=1,v=this[i+--f];for(;f>0&&(E*=256);)v+=this[i+--f]*E;return E*=128,v>=E&&(v-=Math.pow(2,8*r)),v},l.prototype.readInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]},l.prototype.readInt16LE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i]|this[i+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i+1]|this[i]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24},l.prototype.readInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]},l.prototype.readBigInt64LE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(h<<24);return(BigInt(f)<<BigInt(32))+BigInt(r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)}),l.prototype.readBigInt64BE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=(r<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(f)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h)}),l.prototype.readFloatLE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!0,23,4)},l.prototype.readFloatBE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!1,23,4)},l.prototype.readDoubleLE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!0,52,8)},l.prototype.readDoubleBE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!1,52,8)};function K(s,i,r,h,f,E){if(!l.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>f||i<E)throw new RangeError('"value" argument is out of bounds');if(r+h>s.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;K(this,i,r,h,T,0)}let E=1,v=0;for(this[r]=i&255;++v<h&&(E*=256);)this[r+v]=i/E&255;return r+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;K(this,i,r,h,T,0)}let E=h-1,v=1;for(this[r+E]=i&255;--E>=0&&(v*=256);)this[r+E]=i/v&255;return r+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,255,0),this[r]=i&255,r+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r+3]=i>>>24,this[r+2]=i>>>16,this[r+1]=i>>>8,this[r]=i&255,r+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};function Gi(s,i,r,h,f){Yi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,r}function ji(s,i,r,h,f){Yi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r+7]=E,E=E>>8,s[r+6]=E,E=E>>8,s[r+5]=E,E=E>>8,s[r+4]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r+3]=v,v=v>>8,s[r+2]=v,v=v>>8,s[r+1]=v,v=v>>8,s[r]=v,r+8}l.prototype.writeBigUInt64LE=me(function(i,r=0){return Gi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=me(function(i,r=0){return ji(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let E=0,v=1,T=0;for(this[r]=i&255;++E<h&&(v*=256);)i<0&&T===0&&this[r+E-1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let E=h-1,v=1,T=0;for(this[r+E]=i&255;--E>=0&&(v*=256);)i<0&&T===0&&this[r+E+1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,127,-128),i<0&&(i=255+i+1),this[r]=i&255,r+1},l.prototype.writeInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),this[r]=i&255,this[r+1]=i>>>8,this[r+2]=i>>>16,this[r+3]=i>>>24,r+4},l.prototype.writeInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4},l.prototype.writeBigInt64LE=me(function(i,r=0){return Gi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=me(function(i,r=0){return ji(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Hi(s,i,r,h,f,E){if(r+h>s.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Wi(s,i,r,h,f){return i=+i,r=r>>>0,f||Hi(s,i,r,4),n.write(s,i,r,h,23,4),r+4}l.prototype.writeFloatLE=function(i,r,h){return Wi(this,i,r,!0,h)},l.prototype.writeFloatBE=function(i,r,h){return Wi(this,i,r,!1,h)};function zi(s,i,r,h,f){return i=+i,r=r>>>0,f||Hi(s,i,r,8),n.write(s,i,r,h,52,8),r+8}l.prototype.writeDoubleLE=function(i,r,h){return zi(this,i,r,!0,h)},l.prototype.writeDoubleBE=function(i,r,h){return zi(this,i,r,!1,h)},l.prototype.copy=function(i,r,h,f){if(!l.isBuffer(i))throw new TypeError("argument should be a Buffer");if(h||(h=0),!f&&f!==0&&(f=this.length),r>=i.length&&(r=i.length),r||(r=0),f>0&&f<h&&(f=h),f===h||i.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("sourceEnd out of bounds");f>this.length&&(f=this.length),i.length-r<f-h&&(f=i.length-r+h);const E=f-h;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,f):Uint8Array.prototype.set.call(i,this.subarray(h,f),r),E},l.prototype.fill=function(i,r,h,f){if(typeof i=="string"){if(typeof r=="string"?(f=r,r=0,h=this.length):typeof h=="string"&&(f=h,h=this.length),f!==void 0&&typeof f!="string")throw new TypeError("encoding must be a string");if(typeof f=="string"&&!l.isEncoding(f))throw new TypeError("Unknown encoding: "+f);if(i.length===1){const v=i.charCodeAt(0);(f==="utf8"&&v<128||f==="latin1")&&(i=v)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(r<0||this.length<r||this.length<h)throw new RangeError("Out of range index");if(h<=r)return this;r=r>>>0,h=h===void 0?this.length:h>>>0,i||(i=0);let E;if(typeof i=="number")for(E=r;E<h;++E)this[E]=i;else{const v=l.isBuffer(i)?i:l.from(i,f),T=v.length;if(T===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(E=0;E<h-r;++E)this[E+r]=v[E%T]}return this};const Re={};function Ut(s,i,r){Re[s]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(f){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:f,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}Ut("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Ut("ERR_INVALID_ARG_TYPE",function(s,i){return`The "${s}" argument must be of type number. Received type ${typeof i}`},TypeError),Ut("ERR_OUT_OF_RANGE",function(s,i,r){let h=`The value of "${s}" is out of range.`,f=r;return Number.isInteger(r)&&Math.abs(r)>2**32?f=qi(String(r)):typeof r=="bigint"&&(f=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(f=qi(f)),f+="n"),h+=` It must be ${i}. Received ${f}`,h},RangeError);function qi(s){let i="",r=s.length;const h=s[0]==="-"?1:0;for(;r>=h+4;r-=3)i=`_${s.slice(r-3,r)}${i}`;return`${s.slice(0,r)}${i}`}function br(s,i,r){Ne(i,"offset"),(s[i]===void 0||s[i+r]===void 0)&&Ve(i,s.length-(r+1))}function Yi(s,i,r,h,f,E){if(s>r||s<i){const v=typeof i=="bigint"?"n":"";let T;throw i===0||i===BigInt(0)?T=`>= 0${v} and < 2${v} ** ${(E+1)*8}${v}`:T=`>= -(2${v} ** ${(E+1)*8-1}${v}) and < 2 ** ${(E+1)*8-1}${v}`,new Re.ERR_OUT_OF_RANGE("value",T,s)}br(h,f,E)}function Ne(s,i){if(typeof s!="number")throw new Re.ERR_INVALID_ARG_TYPE(i,"number",s)}function Ve(s,i,r){throw Math.floor(s)!==s?(Ne(s,r),new Re.ERR_OUT_OF_RANGE("offset","an integer",s)):i<0?new Re.ERR_BUFFER_OUT_OF_BOUNDS:new Re.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${i}`,s)}const Ar=/[^+/0-9A-Za-z-_]/g;function Tr(s){if(s=s.split("=")[0],s=s.trim().replace(Ar,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function Lt(s,i){i=i||1/0;let r;const h=s.length;let f=null;const E=[];for(let v=0;v<h;++v){if(r=s.charCodeAt(v),r>55295&&r<57344){if(!f){if(r>56319){(i-=3)>-1&&E.push(239,191,189);continue}else if(v+1===h){(i-=3)>-1&&E.push(239,191,189);continue}f=r;continue}if(r<56320){(i-=3)>-1&&E.push(239,191,189),f=r;continue}r=(f-55296<<10|r-56320)+65536}else f&&(i-=3)>-1&&E.push(239,191,189);if(f=null,r<128){if((i-=1)<0)break;E.push(r)}else if(r<2048){if((i-=2)<0)break;E.push(r>>6|192,r&63|128)}else if(r<65536){if((i-=3)<0)break;E.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((i-=4)<0)break;E.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return E}function Rr(s){const i=[];for(let r=0;r<s.length;++r)i.push(s.charCodeAt(r)&255);return i}function Nr(s,i){let r,h,f;const E=[];for(let v=0;v<s.length&&!((i-=2)<0);++v)r=s.charCodeAt(v),h=r>>8,f=r%256,E.push(f),E.push(h);return E}function Ki(s){return e.toByteArray(Tr(s))}function st(s,i,r,h){let f;for(f=0;f<h&&!(f+r>=i.length||f>=s.length);++f)i[f+r]=s[f];return f}function ie(s,i){return s instanceof i||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===i.name}function Bt(s){return s!==s}const xr=(function(){const s="0123456789abcdef",i=new Array(256);for(let r=0;r<16;++r){const h=r*16;for(let f=0;f<16;++f)i[h+f]=s[r]+s[f]}return i})();function me(s){return typeof BigInt>"u"?Or:s}function Or(){throw new Error("BigInt not supported")}})(Ct)),Ct}var In=Cn();const bn="https://api.anam.ai",An="/v1",ki={client:"js-sdk",version:"4.8.0"};var Tn=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Di="https://api.anam.ai",It="/v1";var re;(function(t){t.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(re||(re={}));let bt=Di,Mi=It,de,Ui=!1;const Rn=(t,e=It)=>{bt=t,Mi=e},Nn=t=>{de=t},xn=t=>{Ui=t};let he={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ae=t=>{he=Object.assign(Object.assign({},he),t)},ye=(t,e,n)=>Tn(void 0,void 0,void 0,function*(){if(!Ui)try{const o=Object.assign(Object.assign({},ki),n);he.sessionId&&(o.sessionId=he.sessionId),he.organizationId&&(o.organizationId=he.organizationId),he.attemptCorrelationId&&(o.attemptCorrelationId=he.attemptCorrelationId);const u=`${Mi}/metrics/client`;let a,c={"Content-Type":"application/json"};de?.enabled&&de?.baseUrl?(a=`${de.baseUrl}${u}`,c["X-Anam-Target-Url"]=`${bt}${u}`):a=`${bt}${u}`,yield fetch(a,{method:"POST",headers:c,body:JSON.stringify({name:t,value:e,tags:o})})}catch(o){console.error("Failed to send error metric:",o)}}),On=(t,e="console")=>{var n,o,u;const a={};t.forEach(d=>{a[d.type]||(a[d.type]=[]),a[d.type].push(d)});const c={issues:[]},l=((n=a["inbound-rtp"])===null||n===void 0?void 0:n.filter(d=>d.kind==="video"))||[];l.length>0&&(c.personaVideoStream=[],l.forEach(d=>{var S,g,y,C,A;const I={framesReceived:(S=d.framesReceived)!==null&&S!==void 0?S:"unknown",framesDropped:(g=d.framesDropped)!==null&&g!==void 0?g:"unknown",framesPerSecond:(y=d.framesPerSecond)!==null&&y!==void 0?y:"unknown",packetsReceived:(C=d.packetsReceived)!==null&&C!==void 0?C:"unknown",packetsLost:(A=d.packetsLost)!==null&&A!==void 0?A:"unknown",resolution:d.frameWidth&&d.frameHeight?`${d.frameWidth}x${d.frameHeight}`:void 0,jitter:d.jitter!==void 0?d.jitter:void 0};c.personaVideoStream.push(I)}));const m=((o=a["inbound-rtp"])===null||o===void 0?void 0:o.filter(d=>d.kind==="audio"))||[];m.length>0&&(c.personaAudioStream=[],m.forEach(d=>{var S,g,y;const C={packetsReceived:(S=d.packetsReceived)!==null&&S!==void 0?S:"unknown",packetsLost:(g=d.packetsLost)!==null&&g!==void 0?g:"unknown",audioLevel:(y=d.audioLevel)!==null&&y!==void 0?y:"unknown",jitter:d.jitter!==void 0?d.jitter:void 0,totalAudioEnergy:d.totalAudioEnergy!==void 0?d.totalAudioEnergy:void 0};c.personaAudioStream.push(C)}));const p=((u=a["outbound-rtp"])===null||u===void 0?void 0:u.filter(d=>d.kind==="audio"))||[];p.length>0&&(c.userAudioInput=[],p.forEach(d=>{var S,g;const y={packetsSent:(S=d.packetsSent)!==null&&S!==void 0?S:"unknown",retransmittedPackets:(g=d.retransmittedPacketsSent)!==null&&g!==void 0?g:void 0,avgPacketSendDelay:d.totalPacketSendDelay!==void 0?d.totalPacketSendDelay/(d.packetsSent||1)*1e3:void 0};c.userAudioInput.push(y)})),a.codec&&(c.codecs=[],a.codec.forEach(d=>{const S={status:d.payloadType?"Active":"Available",mimeType:d.mimeType||"Unknown",payloadType:d.payloadType||"N/A",clockRate:d.clockRate||void 0,channels:d.channels||void 0};c.codecs.push(S)})),a.transport&&(c.transportLayer=[],a.transport.forEach(d=>{const S={dtlsState:d.dtlsState||"unknown",iceState:d.iceState||"unknown",bytesSent:d.bytesSent||void 0,bytesReceived:d.bytesReceived||void 0};c.transportLayer.push(S)}));const _=[];if(l.forEach(d=>{typeof d.framesDropped=="number"&&d.framesDropped>0&&_.push(`Video: ${d.framesDropped} frames dropped`),typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Video: ${d.packetsLost} packets lost`),typeof d.framesPerSecond=="number"&&d.framesPerSecond<23&&_.push(`Video: Low frame rate (${d.framesPerSecond} fps)`)}),m.forEach(d=>{typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Audio: ${d.packetsLost} packets lost`),typeof d.jitter=="number"&&d.jitter>.1&&_.push(`Audio: High jitter (${(d.jitter*1e3).toFixed(1)}ms)`)}),c.issues=_,e==="json")return c;console.group("📊 WebRTC Session Statistics Report"),c.personaVideoStream&&c.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),c.personaVideoStream.forEach(d=>{console.log(`Frames Received: ${d.framesReceived}`),console.log(`Frames Dropped: ${d.framesDropped}`),console.log(`Frames Per Second: ${d.framesPerSecond}`),console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),d.resolution&&console.log(`Resolution: ${d.resolution}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`)}),console.groupEnd()),c.personaAudioStream&&c.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),c.personaAudioStream.forEach(d=>{console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),console.log(`Audio Level: ${d.audioLevel}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`),d.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${d.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),c.userAudioInput&&c.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),c.userAudioInput.forEach(d=>{console.log(`Packets Sent: ${typeof d.packetsSent=="number"?d.packetsSent.toLocaleString():d.packetsSent}`),d.retransmittedPackets&&console.log(`Retransmitted Packets: ${d.retransmittedPackets}`),d.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${d.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),c.codecs&&c.codecs.length>0&&(console.group("🔧 Codecs Used"),c.codecs.forEach(d=>{console.log(`${d.status} ${d.mimeType} - Payload Type: ${d.payloadType}`),d.clockRate&&console.log(` Clock Rate: ${d.clockRate}Hz`),d.channels&&console.log(` Channels: ${d.channels}`)}),console.groupEnd()),c.transportLayer&&c.transportLayer.length>0&&(console.group("🚚 Transport Layer"),c.transportLayer.forEach(d=>{console.log(`DTLS State: ${d.dtlsState}`),console.log(`ICE State: ${d.iceState}`),(d.bytesReceived||d.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(d.bytesSent||0).toLocaleString()}, Received: ${(d.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),c.issues.length>0?(console.group("⚠️ Potential Issues Detected"),c.issues.forEach(d=>console.warn(d)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var H;(function(t){t.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",t.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",t.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",t.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",t.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",t.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",t.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",t.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",t.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",t.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(H||(H={}));class $ extends Error{constructor(e,n,o=500,u){super(e),this.name="ClientError",this.code=n,this.statusCode=o,this.details=u,Object.setPrototypeOf(this,$.prototype),ye(re.CLIENT_METRIC_MEASUREMENT_ERROR,n,{details:u,statusCode:o})}}function Li(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function kn(t){if(!(!t||!t.enabled)){if(!t.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(t.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${t.baseUrl}`}if(t.wsPath&&!t.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var W;(function(t){t.OFFER="offer",t.ANSWER="answer",t.ICE_CANDIDATE="icecandidate",t.END_SESSION="endsession",t.HEARTBEAT="heartbeat",t.WARNING="warning",t.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",t.TALK_STREAM_INPUT="talkstream",t.SESSION_READY="sessionready",t.AGENT_AUDIO_INPUT="agentaudioinput",t.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(W||(W={}));var Pe;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.REASONING_TEXT="reasoningText"})(Pe||(Pe={}));var fe;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(fe||(fe={}));var tt;(function(t){t.USER="user",t.PERSONA="persona"})(tt||(tt={}));var R;(function(t){t.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",t.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",t.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",t.CONNECTION_CLOSED="CONNECTION_CLOSED",t.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",t.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",t.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",t.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",t.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",t.SESSION_READY="SESSION_READY",t.SERVER_WARNING="SERVER_WARNING",t.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",t.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",t.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",t.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",t.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"})(R||(R={}));var J;(function(t){t.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",t.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",t.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(J||(J={}));var pe;(function(t){t.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",t.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",t.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",t.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",t.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(pe||(pe={}));class Dn{constructor(e,n){this.sequenceNumber=0,this.config=e,this.signallingClient=n}sendAudioChunk(e){const o={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(o)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const n=e instanceof Uint8Array?e:new Uint8Array(e),o=Array.from(n,u=>String.fromCharCode(u)).join("");return btoa(o)}}var Te=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Mn=5,Un=5;class Ln{constructor(e,n,o,u,a){var c,l,m,p,_;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=o,this.internalEventEmitter=u,this.apiGatewayConfig=a,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:d,maxWsReconnectionAttempts:S,url:g}=n;if(this.heartbeatIntervalSeconds=d||Mn,this.maxWsReconnectionAttempts=S||Un,!g.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((c=this.apiGatewayConfig)===null||c===void 0)&&c.enabled&&(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.baseUrl)){const y=new URL(this.apiGatewayConfig.baseUrl),C=(m=this.apiGatewayConfig.wsPath)!==null&&m!==void 0?m:"/ws";y.protocol=y.protocol.replace("http","ws"),y.pathname=C,this.url=y;const A=g.protocol||"https",I=A==="http"?"ws":"wss",b=`${A}://${g.baseUrl}`,N=(p=g.signallingPath)!==null&&p!==void 0?p:"/ws",M=new URL(b);M.protocol=I==="ws"?"ws:":"wss:",g.port&&(M.port=g.port),M.pathname=N,M.searchParams.append("session_id",e),this.url.searchParams.append("target_url",M.href)}else{const C=`${g.protocol||"https"}://${g.baseUrl}`;this.url=new URL(C),this.url.protocol=g.protocol==="http"?"ws:":"wss:",g.port&&(this.url.port=g.port),this.url.pathname=(_=g.signallingPath)!==null&&_!==void 0?_:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Te(this,void 0,void 0,function*(){const n={connectionDescription:e,userUid:this.sessionId},o={actionType:W.OFFER,sessionId:this.sessionId,payload:n};this.sendSignalMessage(o)})}sendIceCandidate(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(n)})}sendSignalMessage(e){var n;if(((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(o){console.error("SignallingClient - sendSignalMessage: error sending message",o)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)})}sendAgentAudioInput(e){const n={actionType:W.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)}sendAgentAudioInputEnd(){const e={actionType:W.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Te(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(J.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Te(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(n=>{var o;((o=this.socket)===null||o===void 0?void 0:o.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(n)):e.push(n)}),this.sendingBuffer=e}onMessage(e){return Te(this,void 0,void 0,function*(){const n=JSON.parse(e.data);this.internalEventEmitter.emit(J.SIGNAL_MESSAGE_RECEIVED,n)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,n={actionType:W.HEARTBEAT,sessionId:this.sessionId,payload:""},o=JSON.stringify(n);this.heartBeatIntervalRef=setInterval(()=>{var u;this.stopSignal||((u=this.socket)===null||u===void 0?void 0:u.readyState)===WebSocket.OPEN&&this.socket.send(o)},e)}}function Bn(t){return"brainType"in t||"llmId"in t}var Bi=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Pn{constructor(e,n,o){if(!e&&!n)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=n||null,this.baseUrl=o?.baseUrl||bn,this.apiVersion=o?.apiVersion||An,this.apiGatewayConfig=o?.apiGateway||void 0}buildGatewayUrlAndHeaders(e,n){var o,u;if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((u=this.apiGatewayConfig)===null||u===void 0)&&u.baseUrl)){const a=`${this.apiGatewayConfig.baseUrl}${e}`,c=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},n),{"X-Anam-Target-Url":c.href});return{url:a,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:n}}startSession(e,n){return Bi(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const o=`${this.apiVersion}/engine/session`,{url:u,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),c=yield fetch(u,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:n,clientMetadata:ki})}),l=yield c.json(),m=l.error;switch(c.status){case 200:case 201:return l;case 400:throw new $("Invalid request to start session",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new $("Please sign up for a plan to start a session",H.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw m==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):m==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",H.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new $("Usage limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new $("There are no available personas, please try again later",H.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new $("Unknown error when starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(o){throw o instanceof $?o:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:o instanceof Error?o.message:String(o)})}})}unsafe_getSessionToken(e){return Bi(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let n={clientLabel:"js-sdk-api-key"};Bn(e)&&(n=Object.assign(Object.assign({},n),{personaConfig:e}));try{const o=`${this.apiVersion}/auth/session-token`,{url:u,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(u,{method:"POST",headers:a,body:JSON.stringify(n)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Fn=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class $n{constructor(e,n,o){this.baseUrl=e,this.sessionId=n,this.apiGatewayConfig=o}sendTalkCommand(e){return Fn(this,void 0,void 0,function*(){var n,o;try{let u,a={"Content-Type":"application/json"};const c="/talk",l=`?session_id=${this.sessionId}`;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.baseUrl)){u=`${this.apiGatewayConfig.baseUrl}${c}${l}`;const p=new URL(`${this.baseUrl}${c}${l}`);a["X-Anam-Target-Url"]=p.href}else u=`${this.baseUrl}${c}${l}`;const m=yield fetch(u,{method:"POST",headers:a,body:JSON.stringify({content:e})});if(!m.ok)throw new Error(`Failed to send talk command: ${m.status} ${m.statusText}`)}catch(u){throw console.error(u),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Vn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}class Gn{constructor(e,n){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const n={id:e.id,content:e.content,role:e.role};this.messages.push(n)}processPersonaMessage(e){const n={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},o=this.messages.findIndex(u=>u.id===n.id);if(o!==-1){const u=this.messages[o];this.messages[o]=Object.assign(Object.assign({},u),{content:u.content+n.content,interrupted:u.interrupted||n.interrupted})}else this.messages.push(n)}processWebRtcTextMessageEvent(e){const n=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(R.MESSAGE_STREAM_EVENT_RECEIVED,n),n.role){case tt.USER:this.processUserMessage(n);break;case tt.PERSONA:this.processPersonaMessage(n);break}n.endOfSpeech&&this.publicEventEmitter.emit(R.MESSAGE_HISTORY_UPDATED,this.messages)}}class jn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){if(e===R.CONNECTION_ESTABLISHED&&ye(re.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===R.CONNECTION_CLOSED){const[o,u]=n;ye(re.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,o,u?{details:u}:void 0)}this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}var q;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(q||(q={}));var At=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Hn{constructor(e,n,o){this.state=q.UNSTARTED,this.correlationId=e,this.internalEventEmitter=n,this.signallingClient=o,this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return At(this,void 0,void 0,function*(){e.actionType===W.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=q.INTERRUPTED,this.onDeactivate())})}endMessage(){return At(this,void 0,void 0,function*(){if(this.state===q.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==q.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=q.ENDED,this.onDeactivate()})}streamMessageChunk(e,n){return At(this,void 0,void 0,function*(){if(this.state!==q.STREAMING&&this.state!==q.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const o={content:e,startOfSpeech:this.state===q.UNSTARTED,endOfSpeech:n,correlationId:this.correlationId};this.state=n?q.ENDED:q.STREAMING,this.state===q.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(o)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===q.STREAMING||this.state===q.UNSTARTED}getState(){return this.state}}var X=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Wn=15e3,zn=5e3,qn=2;class Yn{constructor(e,n,o,u){var a,c,l,m;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:fe.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=o,this.internalEventEmitter=u,this.apiGatewayConfig=n.apiGateway;const{inputAudio:p}=n;this.inputAudioState=p.inputAudioState,n.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=n.inputAudio.userProvidedMediaStream),this.disableInputAudio=n.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(J.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.iceServers=n.iceServers,this.signallingClient=new Ln(e,n.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new $n(n.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=n.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(c=(a=n.metrics)===null||a===void 0?void 0:a.showPeerConnectionStatsReport)!==null&&c!==void 0?c:!1,this.peerConnectionStatsReportOutputFormat=(m=(l=n.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&m!==void 0?m:"console"}onInputAudioStateChange(e,n){e.isMuted!==n.isMuted&&(n.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>X(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),zn))}sendClientSideMetrics(e){e.forEach(n=>{if(n.type==="inbound-rtp"){const o={message_type:"remote_rtp_stats",data:n};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(o))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Wn);this.successMetricPoller=setInterval(()=>X(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const n=yield this.peerConnection.getStats();let o=!1,u=null;n.forEach(a=>{a.type==="inbound-rtp"&&a.kind==="video"&&(a.framesDecoded!==void 0&&a.framesDecoded>0?(o=!0,u="framesDecoded"):a.framesReceived!==void 0&&a.framesReceived>0?(o=!0,u="framesReceived"):a.bytesReceived>0&&a.packetsReceived>0&&a.bytesReceived>1e5&&(o=!0,u="bytesReceived"))}),o&&!this.successMetricFired&&(this.successMetricFired=!0,ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",u?{detectionMethod:u}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const n=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(u=>{u.stop()});const o={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:o}),this.audioDeviceId=e,yield this.setupAudioTrack(),n&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(R.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(o){throw console.error("Failed to change audio input device:",o),new Error(`StreamingClient - changeAudioInputDevice: ${o instanceof Error?o.message:String(o)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const n=document.getElementById(e);if(!n)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=n}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return X(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Hn(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Dn(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return X(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:qn}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case W.ANSWER:const n=e.payload;yield this.peerConnection.setRemoteDescription(n),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case W.ICE_CANDIDATE:const o=e.payload,u=new RTCIceCandidate(o);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(u):this.remoteIceCandidateBuffer.push(u);break;case W.END_SESSION:const a=e.payload;this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SERVER_CLOSED_CONNECTION,a),this.shutdown();break;case W.WARNING:const c=e.payload;console.warn("Warning received from server: "+c),this.publicEventEmitter.emit(R.SERVER_WARNING,c);break;case W.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(R.TALK_STREAM_INTERRUPTED,l.correlationId);break;case W.SESSION_READY:const m=e.sessionId;this.publicEventEmitter.emit(R.SESSION_READY,m);break;case W.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return X(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var n;(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,n;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(R.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.WEBRTC_FAILURE);try{this.stopConnection()}catch(n){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",n)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(R.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const n=this.videoElement.requestVideoFrameCallback(()=>{var o;(o=this.videoElement)===null||o===void 0||o.cancelVideoFrameCallback(n),this.publicEventEmitter.emit(R.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(R.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=n=>{try{const o=JSON.parse(n.data);switch(o.messageType){case Pe.SPEECH_TEXT:this.internalEventEmitter.emit(J.WEBRTC_CHAT_MESSAGE_RECEIVED,o.data);break;case Pe.CLIENT_TOOL_EVENT:const u=o.data;this.internalEventEmitter.emit(J.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,u);const a=Kn.WebRTCClientToolEventToClientToolEvent(u);this.publicEventEmitter.emit(R.CLIENT_TOOL_EVENT_RECEIVED,a);break;case Pe.REASONING_TEXT:this.internalEventEmitter.emit(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,o.data);break;default:break}}catch(o){console.error("Failed to parse data channel message:",o)}}})}requestMicrophonePermissionAsync(){return X(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==fe.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.PENDING}),this.publicEventEmitter.emit(R.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.GRANTED}),this.publicEventEmitter.emit(R.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.DENIED});const n=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(R.MIC_PERMISSION_DENIED,n)}}})}setupAudioTrack(){return X(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],o=this.peerConnection.getSenders().find(u=>{var a;return((a=u.track)===null||a===void 0?void 0:a.kind)==="audio"||u.track===null&&u.dtmf!==null});if(o)try{yield o.replaceTrack(e)}catch(u){console.error("Failed to replace audio track:",u),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(R.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return X(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return X(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const n=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(n){const o=On(n,this.peerConnectionStatsReportOutputFormat);o&&console.log(o,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(n=>{n.stop()}),this.inputAudioStream=null}catch(n){console.error("StreamingClient - shutdown: error stopping input audio stream",n)}try{this.signallingClient.stop()}catch(n){console.error("StreamingClient - shutdown: error stopping signallilng",n)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(n){console.error("StreamingClient - shutdown: error closing peer connection",n)}})}}class Kn{static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}class Jn{constructor(e,n){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const n=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(R.REASONING_STREAM_EVENT_RECEIVED,n);const o={id:n.id,content:n.content,role:n.role},u=this.reasoning_messages.findIndex(a=>a.id===o.id);if(u!==-1){const a=this.reasoning_messages[u];a.content+=o.content,this.reasoning_messages[u]=a}else this.reasoning_messages.push(o);n.endOfThought&&this.publicEventEmitter.emit(R.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var _e=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Xn{constructor(e,n,o){var u,a,c,l,m;this.inputAudioState={isMuted:!1,permissionState:fe.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,n,o);if(p)throw new $(p,H.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=n,this.clientOptions=o,(!((u=o?.api)===null||u===void 0)&&u.baseUrl||!((a=o?.api)===null||a===void 0)&&a.apiVersion)&&Rn(o.api.baseUrl||Di,o.api.apiVersion||It),!((l=(c=o?.api)===null||c===void 0?void 0:c.apiGateway)===null||l===void 0)&&l.enabled&&Nn(o.api.apiGateway),!((m=o?.metrics)===null||m===void 0)&&m.disableClientMetrics&&xn(!0),this.publicEventEmitter=new jn,this.internalEventEmitter=new Vn,this.apiClient=new Pn(e,o?.apiKey,o?.api),this.messageHistoryClient=new Gn(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Jn(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const n=e.split(".")[1],o=In.Buffer.from(n,"base64").toString("utf8");return JSON.parse(o)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,n,o){var u,a;if(!e&&!o?.apiKey)return"Either sessionToken or apiKey must be provided";if(o?.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const c=kn((u=o?.api)===null||u===void 0?void 0:u.apiGateway);if(c)return c;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,Ae({organizationId:this.organizationId});const m=(a=l.type)===null||a===void 0?void 0:a.toLowerCase();if(m==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((m==="ephemeral"||m==="stateful")&&n)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!n)return"Missing persona config. Persona configuration must be provided when using apiKey";if(o?.voiceDetection){if(o.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(o.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof o.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(o.voiceDetection.endOfSpeechSensitivity<0||o.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const n={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(n.voiceDetection=this.clientOptions.voiceDetection),Object.keys(n).length!==0)return n}startSession(e){return _e(this,void 0,void 0,function*(){var n,o,u,a,c,l,m,p,_,d,S,g;const y=this.personaConfig,C=this.buildStartSessionOptionsForClient(),A=yield this.apiClient.startSession(y,C),{sessionId:I,clientConfig:b,engineHost:N,engineProtocol:M,signallingEndpoint:k}=A,{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:oe,iceServers:V}=b;this.sessionId=I,Ae({sessionId:this.sessionId});const se=!((n=this.clientOptions)===null||n===void 0)&&n.iceServers?this.clientOptions.iceServers:V;try{this.streamingClient=new Yn(I,{engine:{baseUrl:`${M}://${N}`},signalling:{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:oe,url:{baseUrl:N,protocol:M,signallingPath:k}},iceServers:se,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio?void 0:e,audioDeviceId:(u=this.clientOptions)===null||u===void 0?void 0:u.audioDeviceId,disableInputAudio:(a=this.clientOptions)===null||a===void 0?void 0:a.disableInputAudio},apiGateway:(l=(c=this.clientOptions)===null||c===void 0?void 0:c.api)===null||l===void 0?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:(_=(p=(m=this.clientOptions)===null||m===void 0?void 0:m.metrics)===null||p===void 0?void 0:p.showPeerConnectionStatsReport)!==null&&_!==void 0?_:!1,peerConnectionStatsReportOutputFormat:(g=(S=(d=this.clientOptions)===null||d===void 0?void 0:d.metrics)===null||S===void 0?void 0:S.peerConnectionStatsReportOutputFormat)!==null&&g!==void 0?g:"console"}},this.publicEventEmitter,this.internalEventEmitter)}catch(ae){throw Ae({sessionId:null}),new $("Failed to initialize streaming client",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:ae instanceof Error?ae.message:String(ae),sessionId:I})}return I})}startSessionIfNeeded(e){return _e(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new $("Session ID or streaming client is not available after starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return _e(this,void 0,void 0,function*(){var n;if(this._isStreaming)throw new Error("Already streaming");const o=Li();return Ae({attemptCorrelationId:o,sessionId:null}),ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(u=>{var a;const c=[];let l=!1,m=!1;this.publicEventEmitter.addListener(R.VIDEO_STREAM_STARTED,p=>{c.push(p),l=!0,m&&u(c)}),this.publicEventEmitter.addListener(R.AUDIO_STREAM_STARTED,p=>{c.push(p),m=!0,l&&u(c)}),(a=this.streamingClient)===null||a===void 0||a.startConnection()})})}streamToVideoAndAudioElements(e,n,o){return _e(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,o)})}streamToVideoElement(e,n){return _e(this,void 0,void 0,function*(){var o;const u=Li();Ae({attemptCorrelationId:u,sessionId:null}),ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio&&n&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(n)}catch(a){throw a instanceof $?a:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a instanceof Error?a.message:String(a),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return _e(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const n=this.getActiveSessionId();if(!n)throw new Error("Failed to send user message: no active session");const o=new Date().toISOString().replace("Z",""),u=JSON.stringify({content:e,timestamp:o,session_id:n,message_type:"speech"});this.sendDataMessage(u)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const n=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(n)}stopStreaming(){return _e(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ae({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return _e(this,void 0,void 0,function*(){var n;if(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,n){this.publicEventEmitter.addListener(e,n)}removeListener(e,n){this.publicEventEmitter.removeListener(e,n)}getActiveSessionId(){return this.sessionId}}const Zn=(t,e)=>new Xn(t,void 0,e),Qn="https://api.anam.ai";function er(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}const Z=z(null),te=z("idle"),Fe=z(!1),it=z(!1),nt=z([]),$e=z(null),rt=z(null),Tt=z(null),Rt=z(null),Nt=z(null),xt=z(null),Pi=z(!1),ot=z(!1);function tr(t,e){return e===401||e===403?"This agent is not authorized. Check your agent ID.":e===404?"Agent not found. Check your agent ID.":e===429?"Too many requests. Please wait a moment.":e&&e>=500?"Server error. Please try again later.":t instanceof TypeError&&t.message==="Failed to fetch"?"Unable to connect. Check your network connection.":t instanceof Error&&t.message.length<80?t.message:"Something went wrong. Please try again."}async function ir(t,e){ot.value=!1;try{const n=await fetch(`${e}/v1/personas/${t}/widget`);if(!n.ok)return;const o=await n.json();Tt.value=o.persona?.avatarImageUrl||null,Rt.value=o.persona?.avatarVideoUrl||null,Nt.value=o.persona?.name||null,xt.value=o.widgetConfig||null}catch{}finally{ot.value=!0}}async function nr(t,e,n,o){if(te.value==="connecting"||te.value==="connected")return;te.value="connecting",$e.value=null;let u;try{let a;if(o)console.log("[AnamWidget] Using pre-created session token"),a=o;else{console.log("[AnamWidget] Fetching session for agent:",t);const m=await fetch(`${e}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:t})});if(u=m.status,!m.ok){const _=await m.json().catch(()=>({}));throw new Error(_.error||`HTTP ${m.status}`)}const p=await m.json();console.log("[AnamWidget] Got session from agent-id:",{hasToken:!!p.sessionToken}),a=p.sessionToken}const c=Zn(a,{api:e?{baseUrl:e}:void 0,metrics:{disableClientMetrics:!0}});c.addListener(R.CONNECTION_ESTABLISHED,()=>{console.log("[AnamWidget] Connection established"),te.value="connected"}),c.addListener(R.VIDEO_STREAM_STARTED,()=>{console.log("[AnamWidget] Video stream started"),Fe.value=!0}),c.addListener(R.AUDIO_STREAM_STARTED,()=>{console.log("[AnamWidget] Audio stream started")}),c.addListener(R.MESSAGE_HISTORY_UPDATED,m=>{nt.value=[...m]}),c.addListener(R.CONNECTION_CLOSED,(m,p)=>{console.log("[AnamWidget] Connection closed:",m,p),te.value="idle",Fe.value=!1,rt.value=null}),c.addListener(R.SESSION_READY,m=>{console.log("[AnamWidget] Session ready:",m),rt.value=m}),Z.value=c;const l=await c.stream();if(n&&l.length>0){const m=l.find(p=>p.getVideoTracks().length>0);m&&(n.srcObject=m)}}catch(a){console.error("[AnamWidget] Failed to start session:",a),$e.value=tr(a,u),te.value="error",Z.value=null}}async function rr(){if(Z.value)try{await Z.value.stopStreaming()}catch(t){console.error("[AnamWidget] Failed to stop session:",t)}Z.value=null,te.value="idle",Fe.value=!1,nt.value=[]}function or(t){!Z.value||te.value!=="connected"||Z.value.sendUserMessage(t)}function sr(){Z.value&&(it.value?(Z.value.unmuteInputAudio(),it.value=!1):(Z.value.muteInputAudio(),it.value=!0))}function ar(){Z.value?.isStreaming()&&Z.value.stopStreaming(),Z.value=null,te.value="idle",Fe.value=!1,nt.value=[],$e.value=null,rt.value=null,Tt.value=null,Rt.value=null,Nt.value=null,xt.value=null}function lr(t,e,n){const o=t||(n?er(n).personaId:void 0);Pi.value=!!o||!!n;const u=e||Qn;return{connectionStatus:te,isStreaming:Fe,isMuted:it,messages:nt,error:$e,sessionId:rt,isConfigured:Pi,isReady:ot,avatarThumbnailUrl:Tt,avatarVideoUrl:Rt,personaName:Nt,serverConfig:xt,fetchWidgetConfig:()=>{if(!o){ot.value=!0;return}ir(o,u)},startSession:l=>!o&&!n?($e.value="No agent ID or session token configured",Promise.resolve()):nr(o||"",u,l,n),stopSession:rr,sendMessage:or,toggleMute:sr,cleanup:ar}}const Fi='@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-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--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;--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%;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}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-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 components;@layer utilities{.visible{visibility:visible}.block{display:block}.flex{display:flex}.inline{display:inline}.flex-shrink{flex-shrink:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.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,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))}}:host{--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:#18181b;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:DM Sans,system-ui,-apple-system,sans-serif;font-size:15px;line-height:1.5}@media(max-width:640px){:host{--anam-trigger-size:72px;--anam-sheet-width: calc(100vw - 24px) ;--anam-sheet-height: calc(100dvh - 100px) }}.anam-widget{z-index:9999;font-family:inherit}.anam-widget[data-layout=floating]{position:fixed}.anam-widget[data-layout=inline]{position:relative}.anam-trigger{width:var(--anam-trigger-size);height:var(--anam-trigger-size);cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:all .25s cubic-bezier(.4,0,.2,1);display:flex;overflow:hidden;box-shadow:0 2px 8px #00000014,0 8px 24px -4px #0000002e}.anam-trigger:hover{transform:scale(1.06);box-shadow:0 4px 12px #0000001a,0 12px 32px -4px #00000040}.anam-trigger:active{transform:scale(.97)}.anam-trigger img{object-fit:cover;width:100%;height:100%;display:block}.anam-sheet{width:var(--anam-sheet-width);aspect-ratio:16/10;max-height:var(--anam-sheet-height);border-radius:8px;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-widget[data-layout=inline] .anam-sheet{aspect-ratio:3/2;border-radius:8px;width:100%;max-height:none;animation:none}@keyframes sheetIn{0%{opacity:0;transform:translateY(8px)scale(.97)}to{opacity:1;transform:translateY(0)scale(1)}}.anam-video{object-fit:cover;background:#000;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-video[data-hidden=true]{visibility:hidden}.anam-overlay-idle{z-index:2;position:absolute;inset:0}.anam-overlay-idle img{object-fit:cover;width:100%;height:100%;display:block}.anam-preview-video{object-fit:cover;z-index:1;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-preview-fallback{z-index:0;position:absolute;inset:0}.anam-cta-pill{z-index:2;-webkit-backdrop-filter:blur(8px);color:#fff;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#ffffff24;border:1px solid #ffffff38;border-radius:999px;align-items:center;gap:12px;min-width:200px;padding:12px 26px;font-family:inherit;font-size:16px;font-weight:600;transition:all .2s;display:flex;position:absolute;bottom:20px;left:50%;transform:translate(-50%)}.anam-cta-pill:hover{background:#ffffff38;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0}.anam-overlay-unconfigured{z-index:2;background:#111;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-unconfigured span{color:#ffffff59;letter-spacing:-.01em;font-size:14px;font-weight:400}.anam-overlay-loading{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:20px;display:flex;position:absolute;inset:0}.anam-overlay-loading span{color:#fffc;letter-spacing:-.01em;font-size:15px;font-weight:400}.anam-overlay-error{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-error-text{color:#fff9;text-align:center;max-width:260px;font-size:14px;line-height:1.5}.anam-overlay-error .anam-retry-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff1f;border:1px solid #ffffff1a;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s}.anam-overlay-error .anam-retry-btn:hover{background:#fff3}.anam-spinner{border:2.5px solid #ffffff1f;border-top-color:#fff;border-radius:50%;width:32px;height:32px;animation:.75s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}}.anam-close-btn{z-index:10;-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#00000073;border:1px solid #ffffff38;border-radius:50%;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex;position:absolute;top:12px;right:12px}.anam-close-btn:hover{background:#0009}.anam-toast{z-index:10;-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:#0009;border:1px solid #ffffff0f;border-radius:999px;max-width:85%;padding:10px 22px;font-size:14px;font-weight:400;animation:.25s cubic-bezier(.16,1,.3,1) toastIn;position:absolute;bottom:80px;left:50%;overflow:hidden;transform:translate(-50%)}.anam-toast-out{animation:.4s forwards toastOut}@keyframes toastIn{0%{opacity:0;transform:translate(-50%)translateY(6px)}to{opacity:1;transform:translate(-50%)translateY(0)}}@keyframes toastOut{0%{opacity:1}to{opacity:0}}.anam-control-bar{z-index:10;background:linear-gradient(#0000,#00000040 40%,#0000008c);justify-content:center;align-items:center;gap:8px;padding:48px 16px 16px;display:flex;position:absolute;bottom:0;left:0;right:0}.anam-ctl-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff24;border:1px solid #ffffff38;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex}.anam-ctl-btn:hover{background:#ffffff38}.anam-ctl-btn:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-input-wrap{flex:1;align-items:center;min-width:0;margin-right:56px;display:flex;position:relative}.anam-ctl-input{-webkit-backdrop-filter:blur(8px);color:#fff;background:#ffffff1a;border:1px solid #ffffff38;border-radius:999px;outline:none;width:100%;padding:11px 44px 11px 18px;font-family:inherit;font-size:14px;transition:background .15s,border-color .15s}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff26;border-color:#ffffff2e}.anam-ctl-input:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-send{color:#ffffff80;cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:color .15s;display:flex;position:absolute;right:6px}.anam-ctl-send:hover{color:#fff}.anam-ctl-send:disabled{opacity:.35;cursor:not-allowed}.anam-watermark{z-index:11;opacity:.5;line-height:0;text-decoration:none;transition:opacity .15s;position:absolute;top:16px;left:16px}.anam-watermark:hover{opacity:.8}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}';function Ot(t,e){const n={...t};for(const o of Object.keys(e)){const u=e[o];u!==void 0&&(u!==null&&typeof u=="object"&&!Array.isArray(u)&&typeof n[o]=="object"&&n[o]!==null&&!Array.isArray(n[o])?n[o]=Ot(n[o],u):n[o]=u)}return n}function kt(t){if(t!==void 0)return t==="true"}function cr(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const n=kt(t["ui-mute-button"]);n!==void 0&&(e.showMuteButton=n);const o=kt(t["ui-text-input"]);o!==void 0&&(e.showTextInput=o);const u=kt(t["ui-captions"]);return u!==void 0&&(e.showCaptions=u),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const ur=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round",children:w("path",{d:"M18 6L6 18M6 6l12 12"})}),dr=()=>w("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:w("path",{d:"M8 5.14v13.72a1 1 0 0 0 1.5.86l11.04-6.86a1 1 0 0 0 0-1.72L9.5 4.28A1 1 0 0 0 8 5.14Z"})}),hr=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),w("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),fr=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),w("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),w("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),pr=()=>w("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),w("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),Dt=()=>w("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[w("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),w("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function _r({config:t,session:e,videoRef:n,avatarSrc:o,avatarVideoSrc:u,displayCta:a,onCollapse:c,onStop:l}){const m=mt(null),[p,_]=qe(""),[d,S]=qe(null),[g,y]=qe(!1),C=mt(null),A=e.connectionStatus.value==="connected",I=e.connectionStatus.value==="connecting",b=e.connectionStatus.value==="error",N=e.isStreaming.value,M=!I&&!A&&!b,k=Ye(async()=>{n.current&&await e.startSession(n.current)},[e.startSession]);Ye(async()=>{await e.stopSession()},[e.stopSession]);const Y=Ye(()=>{if(!p.trim())return;const V=p.trim();e.sendMessage(V),_(""),m.current?.focus(),C.current&&clearTimeout(C.current),y(!1),S(V),C.current=window.setTimeout(()=>{y(!0),C.current=window.setTimeout(()=>{S(null),y(!1)},400)},2600)},[p]),oe=Ye(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Y())},[Y]);return Et(()=>()=>{C.current&&clearTimeout(C.current)},[]),w("div",{class:"anam-sheet",children:[w("video",{ref:n,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":N?void 0:"true"}),M&&(e.isConfigured.value?w("div",{class:"anam-overlay-idle",children:[u?w("video",{src:u,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:V=>{V.target.style.display="none"}}):null,o?w("img",{src:o,alt:"Avatar",class:u?"anam-preview-fallback":void 0}):w(Dt,{}),w("button",{class:"anam-cta-pill",onClick:k,children:[w(dr,{}),a]})]}):w("div",{class:"anam-overlay-unconfigured",children:[w(Dt,{}),w("span",{children:"Agent not configured"})]})),I&&w("div",{class:"anam-overlay-loading",children:[w("span",{class:"anam-spinner"}),w("span",{children:"Starting your conversation..."})]}),b&&w("div",{class:"anam-overlay-error",children:[w("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),w("button",{class:"anam-retry-btn",onClick:k,children:"Try Again"})]}),(c||l&&(A||I||N))&&w("button",{class:"anam-close-btn",onClick:c||l,"aria-label":c?"Close":"End call",children:w(ur,{})}),(A||N)&&w(ce,{children:[d&&w("div",{class:`anam-toast ${g?"anam-toast-out":""}`,children:d}),w("div",{class:"anam-control-bar",children:[t.showMuteButton&&w("button",{class:`anam-ctl-btn ${e.isMuted.value?"anam-ctl-btn-muted":""}`,onClick:()=>e.toggleMute(),"aria-label":e.isMuted.value?"Unmute":"Mute",children:e.isMuted.value?w(fr,{}):w(hr,{})}),t.showTextInput&&w("div",{class:"anam-ctl-input-wrap",children:[w("input",{ref:m,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:p,onInput:V=>_(V.target.value),onKeyDown:oe,disabled:!A}),w("button",{class:"anam-ctl-send",onClick:Y,disabled:!A||!p.trim(),"aria-label":"Send message",children:w(pr,{})})]})]})]}),w("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:w("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[w("path",{d:"M18.1491 28.1986L16.2127 21.63L6.3408 21.63L4.40439 28.1986H0L9.03659 -1.79687L13.4789 -1.79687L22.5535 28.1986H18.1491ZM7.47986 17.8331L15.0736 17.8331L11.2767 4.96161L7.47986 17.8331Z"}),w("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),w("path",{d:"M61.0239 28.1984V7.69518L85.7037 7.69518V28.1984H81.5271V11.4921L75.4521 11.4921V28.1984L71.2755 28.1984V11.4921L65.2005 11.4921V28.1984H61.0239Z"}),w("path",{d:"M42.8948 7.69518L57.7026 7.69518V28.1984L53.5261 28.1984V27.1353C52.4629 28.0466 51.0201 28.5781 49.3495 28.5781C45.4007 28.5781 42.8948 25.7305 42.8948 21.2501C42.8948 16.8457 45.4007 14.074 49.3495 14.074C51.0201 14.074 52.4629 14.5676 53.5261 15.4788V11.3022L42.8948 11.3022V7.69518ZM50.4885 24.7812C52.6148 24.7812 53.9437 23.4143 53.9057 21.2501C53.8678 19.0859 52.5389 17.681 50.4885 17.681C48.4003 17.681 47.0713 19.0859 47.0713 21.2501C47.0713 23.4143 48.4003 24.7812 50.4885 24.7812Z"})]})})]})}function Er(t){const e=mt(null);t["agent-id"]&&t["session-token"]&&console.warn("[AnamWidget] Both agent-id and session-token are set. Use one or the other. Ignoring agent-id.");const n=t["session-token"]?void 0:t["agent-id"],o=lr(n,t["api-base-url"],t["session-token"]),u=Ce(()=>cr(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["call-to-action"]]),a=Ce(()=>{const I=o.serverConfig.value;return Ot(Ot({...wt},I??{}),u)},[o.serverConfig.value,u]),c=Ti(a.layout==="floating"?a.initialState:"expanded");Et(()=>{a.layout==="inline"?c.value="expanded":c.value=a.initialState},[a.layout,a.initialState]),Et(()=>{o.fetchWidgetConfig()},[n,t["api-base-url"],t["session-token"]]);const l=t["avatar-url"]||o.avatarThumbnailUrl.value||null,m=t["avatar-video-url"]||o.avatarVideoUrl.value||null,_=t["agent-name"]||o.personaName.value,d=a.callToAction===wt.callToAction&&_?`Talk to ${_}`:a.callToAction,S=Ce(()=>{if(a.layout==="inline")return"";const I=yn(a.position);return Object.entries(I).map(([b,N])=>`${b}: ${N}`).join("; ")},[a.layout,a.position]),g=a.layout==="floating",y=()=>{c.value="expanded"},C=async()=>{o.connectionStatus.value!=="idle"&&await o.stopSession(),c.value="minimized"},A=g?c.value==="expanded":!0;return o.isReady.value?w(ce,{children:[w("style",{children:Fi}),w("div",{class:"anam-widget","data-layout":a.layout,"data-state":c.value,style:S,children:[g&&c.value==="minimized"&&w("button",{class:"anam-trigger",onClick:y,"aria-label":d,children:l?w("img",{src:l,alt:"Avatar"}):w(Dt,{})}),A&&w(_r,{config:a,session:o,videoRef:e,avatarSrc:l,avatarVideoSrc:m,displayCta:d,onCollapse:g?C:null,onStop:g?null:()=>o.stopSession()})]})]}):w("style",{children:Fi})}const mr=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","call-to-action","avatar-url","avatar-video-url","agent-name"],gr={SESSION_STARTED:"anam-agent:session-started",SESSION_ENDED:"anam-agent:session-ended",MESSAGE_RECEIVED:"anam-agent:message-received",MESSAGE_SENT:"anam-agent:message-sent",EXPANDED:"anam-agent:expanded",COLLAPSED:"anam-agent:collapsed",ERROR:"anam-agent:error",MIC_MUTED:"anam-agent:mic-muted",MIC_UNMUTED:"anam-agent:mic-unmuted"};function Mt(t="anam-agent"){rn(Er,t,[...mr],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Mt()):Mt()),le.DefaultConfig=wt,le.WidgetEventNames=gr,le.registerWidget=Mt,Object.defineProperty(le,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(le,ne){typeof exports=="object"&&typeof module<"u"?ne(exports):typeof define=="function"&&define.amd?define(["exports"],ne):(le=typeof globalThis<"u"?globalThis:le||self,ne(le.AnamAgentWidget={}))})(this,(function(le){"use strict";var ne,x,Pt,Ft,ge,$t,Vt,Gt,jt,at,lt,ct,xe={},Ht=[],Ji=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ge=Array.isArray;function ee(t,e){for(var n in e)t[n]=e[n];return t}function ut(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Se(t,e,n){var o,u,a,c={};for(a in e)a=="key"?o=e[a]:a=="ref"?u=e[a]:c[a]=e[a];if(arguments.length>2&&(c.children=arguments.length>3?ne.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(a in t.defaultProps)c[a]===void 0&&(c[a]=t.defaultProps[a]);return Oe(t,c,o,u,null)}function Oe(t,e,n,o,u){var a={type:t,props:e,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:u??++Pt,__i:-1,__u:0};return u==null&&x.vnode!=null&&x.vnode(a),a}function ce(t){return t.children}function ke(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Wt(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Wt(t)}}function zt(t){(!t.__d&&(t.__d=!0)&&ge.push(t)&&!je.__r++||$t!=x.debounceRendering)&&(($t=x.debounceRendering)||Vt)(je)}function je(){for(var t,e,n,o,u,a,c,l=1;ge.length;)ge.length>l&&ge.sort(Gt),t=ge.shift(),l=ge.length,t.__d&&(n=void 0,o=void 0,u=(o=(e=t).__v).__e,a=[],c=[],e.__P&&((n=ee({},o)).__v=o.__v+1,x.vnode&&x.vnode(n),dt(e.__P,n,o,e.__n,e.__P.namespaceURI,32&o.__u?[u]:null,a,u??we(o),!!(32&o.__u),c),n.__v=o.__v,n.__.__k[n.__i]=n,Xt(a,n,c),o.__e=o.__=null,n.__e!=u&&Wt(n)));je.__r=0}function qt(t,e,n,o,u,a,c,l,m,p,_){var d,S,g,y,C,A,I,b=o&&o.__k||Ht,N=e.length;for(m=Xi(n,e,b,m,N),d=0;d<N;d++)(g=n.__k[d])!=null&&(S=g.__i==-1?xe:b[g.__i]||xe,g.__i=d,A=dt(t,g,S,u,a,c,l,m,p,_),y=g.__e,g.ref&&S.ref!=g.ref&&(S.ref&&ft(S.ref,null,g),_.push(g.ref,g.__c||y,g)),C==null&&y!=null&&(C=y),(I=!!(4&g.__u))||S.__k===g.__k?m=Yt(g,m,t,I):typeof g.type=="function"&&A!==void 0?m=A:y&&(m=y.nextSibling),g.__u&=-7);return n.__e=C,m}function Xi(t,e,n,o,u){var a,c,l,m,p,_=n.length,d=_,S=0;for(t.__k=new Array(u),a=0;a<u;a++)(c=e[a])!=null&&typeof c!="boolean"&&typeof c!="function"?(typeof c=="string"||typeof c=="number"||typeof c=="bigint"||c.constructor==String?c=t.__k[a]=Oe(null,c,null,null,null):Ge(c)?c=t.__k[a]=Oe(ce,{children:c},null,null,null):c.constructor===void 0&&c.__b>0?c=t.__k[a]=Oe(c.type,c.props,c.key,c.ref?c.ref:null,c.__v):t.__k[a]=c,m=a+S,c.__=t,c.__b=t.__b+1,l=null,(p=c.__i=Zi(c,n,m,d))!=-1&&(d--,(l=n[p])&&(l.__u|=2)),l==null||l.__v==null?(p==-1&&(u>_?S--:u<_&&S++),typeof c.type!="function"&&(c.__u|=4)):p!=m&&(p==m-1?S--:p==m+1?S++:(p>m?S--:S++,c.__u|=4))):t.__k[a]=null;if(d)for(a=0;a<_;a++)(l=n[a])!=null&&(2&l.__u)==0&&(l.__e==o&&(o=we(l)),Qt(l,l));return o}function Yt(t,e,n,o){var u,a;if(typeof t.type=="function"){for(u=t.__k,a=0;u&&a<u.length;a++)u[a]&&(u[a].__=t,e=Yt(u[a],e,n,o));return e}t.__e!=e&&(o&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Zi(t,e,n,o){var u,a,c,l=t.key,m=t.type,p=e[n],_=p!=null&&(2&p.__u)==0;if(p===null&&l==null||_&&l==p.key&&m==p.type)return n;if(o>(_?1:0)){for(u=n-1,a=n+1;u>=0||a<e.length;)if((p=e[c=u>=0?u--:a++])!=null&&(2&p.__u)==0&&l==p.key&&m==p.type)return c}return-1}function Kt(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Ji.test(e)?n:n+"px"}function He(t,e,n,o,u){var a,c;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof o=="string"&&(t.style.cssText=o=""),o)for(e in o)n&&e in n||Kt(t.style,e,"");if(n)for(e in n)o&&n[e]==o[e]||Kt(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")a=e!=(e=e.replace(jt,"$1")),c=e.toLowerCase(),e=c in t||e=="onFocusOut"||e=="onFocusIn"?c.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+a]=n,n?o?n.u=o.u:(n.u=at,t.addEventListener(e,a?ct:lt,a)):t.removeEventListener(e,a?ct:lt,a);else{if(u=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Jt(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=at++;else if(e.t<n.u)return;return n(x.event?x.event(e):e)}}}function dt(t,e,n,o,u,a,c,l,m,p){var _,d,S,g,y,C,A,I,b,N,M,k,Y,oe,V,se,ae,Q=e.type;if(e.constructor!==void 0)return null;128&n.__u&&(m=!!(32&n.__u),a=[l=e.__e=n.__e]),(_=x.__b)&&_(e);e:if(typeof Q=="function")try{if(I=e.props,b="prototype"in Q&&Q.prototype.render,N=(_=Q.contextType)&&o[_.__c],M=_?N?N.props.value:_.__:o,n.__c?A=(d=e.__c=n.__c).__=d.__E:(b?e.__c=d=new Q(I,M):(e.__c=d=new ke(I,M),d.constructor=Q,d.render=en),N&&N.sub(d),d.state||(d.state={}),d.__n=o,S=d.__d=!0,d.__h=[],d._sb=[]),b&&d.__s==null&&(d.__s=d.state),b&&Q.getDerivedStateFromProps!=null&&(d.__s==d.state&&(d.__s=ee({},d.__s)),ee(d.__s,Q.getDerivedStateFromProps(I,d.__s))),g=d.props,y=d.state,d.__v=e,S)b&&Q.getDerivedStateFromProps==null&&d.componentWillMount!=null&&d.componentWillMount(),b&&d.componentDidMount!=null&&d.__h.push(d.componentDidMount);else{if(b&&Q.getDerivedStateFromProps==null&&I!==g&&d.componentWillReceiveProps!=null&&d.componentWillReceiveProps(I,M),e.__v==n.__v||!d.__e&&d.shouldComponentUpdate!=null&&d.shouldComponentUpdate(I,d.__s,M)===!1){for(e.__v!=n.__v&&(d.props=I,d.state=d.__s,d.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Ee){Ee&&(Ee.__=e)}),k=0;k<d._sb.length;k++)d.__h.push(d._sb[k]);d._sb=[],d.__h.length&&c.push(d);break e}d.componentWillUpdate!=null&&d.componentWillUpdate(I,d.__s,M),b&&d.componentDidUpdate!=null&&d.__h.push(function(){d.componentDidUpdate(g,y,C)})}if(d.context=M,d.props=I,d.__P=t,d.__e=!1,Y=x.__r,oe=0,b){for(d.state=d.__s,d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),V=0;V<d._sb.length;V++)d.__h.push(d._sb[V]);d._sb=[]}else do d.__d=!1,Y&&Y(e),_=d.render(d.props,d.state,d.context),d.state=d.__s;while(d.__d&&++oe<25);d.state=d.__s,d.getChildContext!=null&&(o=ee(ee({},o),d.getChildContext())),b&&!S&&d.getSnapshotBeforeUpdate!=null&&(C=d.getSnapshotBeforeUpdate(g,y)),se=_,_!=null&&_.type===ce&&_.key==null&&(se=Zt(_.props.children)),l=qt(t,Ge(se)?se:[se],e,n,o,u,a,c,l,m,p),d.base=e.__e,e.__u&=-161,d.__h.length&&c.push(d),A&&(d.__E=d.__=null)}catch(Ee){if(e.__v=null,m||a!=null)if(Ee.then){for(e.__u|=m?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;a[a.indexOf(l)]=null,e.__e=l}else{for(ae=a.length;ae--;)ut(a[ae]);ht(e)}else e.__e=n.__e,e.__k=n.__k,Ee.then||ht(e);x.__e(Ee,e,n)}else a==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Qi(n.__e,e,n,o,u,a,c,m,p);return(_=x.diffed)&&_(e),128&e.__u?void 0:l}function ht(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(ht)}function Xt(t,e,n){for(var o=0;o<n.length;o++)ft(n[o],n[++o],n[++o]);x.__c&&x.__c(e,t),t.some(function(u){try{t=u.__h,u.__h=[],t.some(function(a){a.call(u)})}catch(a){x.__e(a,u.__v)}})}function Zt(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ge(t)?t.map(Zt):ee({},t)}function Qi(t,e,n,o,u,a,c,l,m){var p,_,d,S,g,y,C,A=n.props||xe,I=e.props,b=e.type;if(b=="svg"?u="http://www.w3.org/2000/svg":b=="math"?u="http://www.w3.org/1998/Math/MathML":u||(u="http://www.w3.org/1999/xhtml"),a!=null){for(p=0;p<a.length;p++)if((g=a[p])&&"setAttribute"in g==!!b&&(b?g.localName==b:g.nodeType==3)){t=g,a[p]=null;break}}if(t==null){if(b==null)return document.createTextNode(I);t=document.createElementNS(u,b,I.is&&I),l&&(x.__m&&x.__m(e,a),l=!1),a=null}if(b==null)A===I||l&&t.data==I||(t.data=I);else{if(a=a&&ne.call(t.childNodes),!l&&a!=null)for(A={},p=0;p<t.attributes.length;p++)A[(g=t.attributes[p]).name]=g.value;for(p in A)if(g=A[p],p!="children"){if(p=="dangerouslySetInnerHTML")d=g;else if(!(p in I)){if(p=="value"&&"defaultValue"in I||p=="checked"&&"defaultChecked"in I)continue;He(t,p,null,g,u)}}for(p in I)g=I[p],p=="children"?S=g:p=="dangerouslySetInnerHTML"?_=g:p=="value"?y=g:p=="checked"?C=g:l&&typeof g!="function"||A[p]===g||He(t,p,g,A[p],u);if(_)l||d&&(_.__html==d.__html||_.__html==t.innerHTML)||(t.innerHTML=_.__html),e.__k=[];else if(d&&(t.innerHTML=""),qt(e.type=="template"?t.content:t,Ge(S)?S:[S],e,n,o,b=="foreignObject"?"http://www.w3.org/1999/xhtml":u,a,c,a?a[0]:n.__k&&we(n,0),l,m),a!=null)for(p=a.length;p--;)ut(a[p]);l||(p="value",b=="progress"&&y==null?t.removeAttribute("value"):y!=null&&(y!==t[p]||b=="progress"&&!y||b=="option"&&y!=A[p])&&He(t,p,y,A[p],u),p="checked",C!=null&&C!=t[p]&&He(t,p,C,A[p],u))}return t}function ft(t,e,n){try{if(typeof t=="function"){var o=typeof t.__u=="function";o&&t.__u(),o&&e==null||(t.__u=t(e))}else t.current=e}catch(u){x.__e(u,n)}}function Qt(t,e,n){var o,u;if(x.unmount&&x.unmount(t),(o=t.ref)&&(o.current&&o.current!=t.__e||ft(o,null,e)),(o=t.__c)!=null){if(o.componentWillUnmount)try{o.componentWillUnmount()}catch(a){x.__e(a,e)}o.base=o.__P=null}if(o=t.__k)for(u=0;u<o.length;u++)o[u]&&Qt(o[u],e,n||typeof t.type!="function");n||ut(t.__e),t.__c=t.__=t.__e=void 0}function en(t,e,n){return this.constructor(t,n)}function We(t,e,n){var o,u,a,c;e==document&&(e=document.documentElement),x.__&&x.__(t,e),u=(o=typeof n=="function")?null:n&&n.__k||e.__k,a=[],c=[],dt(e,t=(!o&&n||e).__k=Se(ce,null,[t]),u||xe,xe,e.namespaceURI,!o&&n?[n]:u?null:e.firstChild?ne.call(e.childNodes):null,a,!o&&n?n:u?u.__e:e.firstChild,o,c),Xt(a,t,c)}function ei(t,e){We(t,e,ei)}function ti(t,e,n){var o,u,a,c,l=ee({},t.props);for(a in t.type&&t.type.defaultProps&&(c=t.type.defaultProps),e)a=="key"?o=e[a]:a=="ref"?u=e[a]:l[a]=e[a]===void 0&&c!=null?c[a]:e[a];return arguments.length>2&&(l.children=arguments.length>3?ne.call(arguments,2):n),Oe(t.type,l,o||t.key,u||t.ref,null)}ne=Ht.slice,x={__e:function(t,e,n,o){for(var u,a,c;e=e.__;)if((u=e.__c)&&!u.__)try{if((a=u.constructor)&&a.getDerivedStateFromError!=null&&(u.setState(a.getDerivedStateFromError(t)),c=u.__d),u.componentDidCatch!=null&&(u.componentDidCatch(t,o||{}),c=u.__d),c)return u.__E=u}catch(l){t=l}throw t}},Pt=0,Ft=function(t){return t!=null&&t.constructor===void 0},ke.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ee({},this.state),typeof t=="function"&&(t=t(ee({},n),this.props)),t&&ee(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),zt(this))},ke.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),zt(this))},ke.prototype.render=ce,ge=[],Vt=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Gt=function(t,e){return t.__v.__b-e.__v.__b},je.__r=0,jt=/(PointerCapture)$|Capture$/i,at=0,lt=Jt(!1),ct=Jt(!0);function ze(){return ze=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},ze.apply(this,arguments)}function ii(t,e){if(t==null)return{};var n,o,u={},a=Object.keys(t);for(o=0;o<a.length;o++)e.indexOf(n=a[o])>=0||(u[n]=t[n]);return u}var tn=["context","children"],nn=["useFragment"];function rn(t,e,n,o){function u(){var a,c=Reflect.construct(HTMLElement,[],u);return c._vdomComponent=t,o&&o.shadow?(c._root=c.attachShadow({mode:o.mode||"open",serializable:(a=o.serializable)!=null&&a}),o.adoptedStyleSheets&&(c._root.adoptedStyleSheets=o.adoptedStyleSheets)):c._root=c,c}return(u.prototype=Object.create(HTMLElement.prototype)).constructor=u,u.prototype.connectedCallback=function(){sn.call(this,o)},u.prototype.attributeChangedCallback=an,u.prototype.disconnectedCallback=ln,n=n||t.observedAttributes||Object.keys(t.propTypes||{}),u.observedAttributes=n,t.formAssociated&&(u.formAssociated=!0),n.forEach(function(a){Object.defineProperty(u.prototype,a,{get:function(){return this._vdom?this._vdom.props[a]:this._props[a]},set:function(c){this._vdom?this.attributeChangedCallback(a,null,c):(this._props||(this._props={}),this._props[a]=c);var l=typeof c;c!=null&&l!=="string"&&l!=="boolean"&&l!=="number"||this.setAttribute(a,c)}})}),customElements.define(e||t.tagName||t.displayName||t.name,u),u}function on(t){this.getChildContext=function(){return t.context};var e=t.children,n=ii(t,tn);return ti(e,n)}function sn(t){var e=new CustomEvent("_preact",{detail:{},bubbles:!0,cancelable:!0});this.dispatchEvent(e),this._vdom=Se(on,ze({},this._props,{context:e.detail.context}),oi(this,this._vdomComponent,t)),(this.hasAttribute("hydrate")?ei:We)(this._vdom,this._root)}function ni(t){return t.replace(/-(\w)/g,function(e,n){return n?n.toUpperCase():""})}function an(t,e,n){if(this._vdom){var o={};o[t]=n=n??void 0,o[ni(t)]=n,this._vdom=ti(this._vdom,o),We(this._vdom,this._root)}}function ln(){We(this._vdom=null,this._root)}function ri(t,e){var n=this,o=t.useFragment,u=ii(t,nn);return Se(o?ce:"slot",ze({},u,{ref:function(a){a?(n.ref=a,n._listener||(n._listener=function(c){c.stopPropagation(),c.detail.context=e},a.addEventListener("_preact",n._listener))):n.ref.removeEventListener("_preact",n._listener)}}))}function oi(t,e,n){if(t.nodeType===3)return t.data;if(t.nodeType!==1)return null;var o=[],u={},a=0,c=t.attributes,l=t.childNodes;for(a=c.length;a--;)c[a].name!=="slot"&&(u[c[a].name]=c[a].value,u[ni(c[a].name)]=c[a].value);for(a=l.length;a--;){var m=oi(l[a],null,n),p=l[a].slot;p?u[p]=Se(ri,{name:p},m):o[a]=m}var _=!(!n||!n.shadow),d=e?Se(ri,{useFragment:!_},o):o;return!_&&e&&(t.innerHTML=""),Se(e||t.nodeName.toLowerCase(),u,d)}var cn=0;function w(t,e,n,o,u,a){e||(e={});var c,l,m=e;if("ref"in m)for(l in m={},e)l=="ref"?c=e[l]:m[l]=e[l];var p={type:t,props:m,key:n,ref:c,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--cn,__i:-1,__u:0,__source:u,__self:a};if(typeof t=="function"&&(c=t.defaultProps))for(l in c)m[l]===void 0&&(m[l]=c[l]);return x.vnode&&x.vnode(p),p}var De,P,pt,si,Me=0,ai=[],F=x,li=F.__b,ci=F.__r,ui=F.diffed,di=F.__c,hi=F.unmount,fi=F.__;function _t(t,e){F.__h&&F.__h(P,t,Me||e),Me=0;var n=P.__H||(P.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function qe(t){return Me=1,un(Ei,t)}function un(t,e,n){var o=_t(De++,2);if(o.t=t,!o.__c&&(o.__=[Ei(void 0,e),function(l){var m=o.__N?o.__N[0]:o.__[0],p=o.t(m,l);m!==p&&(o.__N=[p,o.__[1]],o.__c.setState({}))}],o.__c=P,!P.__f)){var u=function(l,m,p){if(!o.__c.__H)return!0;var _=o.__c.__H.__.filter(function(S){return!!S.__c});if(_.every(function(S){return!S.__N}))return!a||a.call(this,l,m,p);var d=o.__c.props!==l;return _.forEach(function(S){if(S.__N){var g=S.__[0];S.__=S.__N,S.__N=void 0,g!==S.__[0]&&(d=!0)}}),a&&a.call(this,l,m,p)||d};P.__f=!0;var a=P.shouldComponentUpdate,c=P.componentWillUpdate;P.componentWillUpdate=function(l,m,p){if(this.__e){var _=a;a=void 0,u(l,m,p),a=_}c&&c.call(this,l,m,p)},P.shouldComponentUpdate=u}return o.__N||o.__}function Et(t,e){var n=_t(De++,3);!F.__s&&_i(n.__H,e)&&(n.__=t,n.u=e,P.__H.__h.push(n))}function mt(t){return Me=5,Ce(function(){return{current:t}},[])}function Ce(t,e){var n=_t(De++,7);return _i(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Ye(t,e){return Me=8,Ce(function(){return t},e)}function dn(){for(var t;t=ai.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(Ke),t.__H.__h.forEach(gt),t.__H.__h=[]}catch(e){t.__H.__h=[],F.__e(e,t.__v)}}F.__b=function(t){P=null,li&&li(t)},F.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),fi&&fi(t,e)},F.__r=function(t){ci&&ci(t),De=0;var e=(P=t.__c).__H;e&&(pt===P?(e.__h=[],P.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(Ke),e.__h.forEach(gt),e.__h=[],De=0)),pt=P},F.diffed=function(t){ui&&ui(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(ai.push(e)!==1&&si===F.requestAnimationFrame||((si=F.requestAnimationFrame)||hn)(dn)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),pt=P=null},F.__c=function(t,e){e.some(function(n){try{n.__h.forEach(Ke),n.__h=n.__h.filter(function(o){return!o.__||gt(o)})}catch(o){e.some(function(u){u.__h&&(u.__h=[])}),e=[],F.__e(o,n.__v)}}),di&&di(t,e)},F.unmount=function(t){hi&&hi(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(o){try{Ke(o)}catch(u){e=u}}),n.__H=void 0,e&&F.__e(e,n.__v))};var pi=typeof requestAnimationFrame=="function";function hn(t){var e,n=function(){clearTimeout(o),pi&&cancelAnimationFrame(e),setTimeout(t)},o=setTimeout(n,35);pi&&(e=requestAnimationFrame(n))}function Ke(t){var e=P,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),P=e}function gt(t){var e=P;t.__c=t.__(),P=e}function _i(t,e){return!t||t.length!==e.length||e.some(function(n,o){return n!==t[o]})}function Ei(t,e){return typeof e=="function"?e(t):e}var fn=Symbol.for("preact-signals");function Je(){if(ue>1)ue--;else{for(var t,e=!1;Ue!==void 0;){var n=Ue;for(Ue=void 0,vt++;n!==void 0;){var o=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&vi(n))try{n.c()}catch(u){e||(t=u,e=!0)}n=o}}if(vt=0,ue--,e)throw t}}function pn(t){if(ue>0)return t();ue++;try{return t()}finally{Je()}}var O=void 0;function mi(t){var e=O;O=void 0;try{return t()}finally{O=e}}var Ue=void 0,ue=0,vt=0,Xe=0;function gi(t){if(O!==void 0){var e=t.n;if(e===void 0||e.t!==O)return e={i:0,S:t,p:O.s,n:void 0,t:O,e:void 0,x:void 0,r:e},O.s!==void 0&&(O.s.n=e),O.s=e,t.n=e,32&O.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=O.s,e.n=void 0,O.s.n=e,O.s=e),e}}function j(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}j.prototype.brand=fn,j.prototype.h=function(){return!0},j.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:mi(function(){var o;(o=e.W)==null||o.call(e)}))},j.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,o=t.x;n!==void 0&&(n.x=o,t.e=void 0),o!==void 0&&(o.e=n,t.x=void 0),t===this.t&&(this.t=o,o===void 0&&mi(function(){var u;(u=e.Z)==null||u.call(e)}))}},j.prototype.subscribe=function(t){var e=this;return Le(function(){var n=e.value,o=O;O=void 0;try{t(n)}finally{O=o}},{name:"sub"})},j.prototype.valueOf=function(){return this.value},j.prototype.toString=function(){return this.value+""},j.prototype.toJSON=function(){return this.value},j.prototype.peek=function(){var t=O;O=void 0;try{return this.value}finally{O=t}},Object.defineProperty(j.prototype,"value",{get:function(){var t=gi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(vt>100)throw new Error("Cycle detected");this.v=t,this.i++,Xe++,ue++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{Je()}}}});function z(t,e){return new j(t,e)}function vi(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function yi(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function Si(t){for(var e=t.s,n=void 0;e!==void 0;){var o=e.p;e.i===-1?(e.S.U(e),o!==void 0&&(o.n=e.n),e.n!==void 0&&(e.n.p=o)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=o}t.s=n}function ve(t,e){j.call(this,void 0),this.x=t,this.s=void 0,this.g=Xe-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ve.prototype=new j,ve.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===Xe))return!0;if(this.g=Xe,this.f|=1,this.i>0&&!vi(this))return this.f&=-2,!0;var t=O;try{yi(this),O=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return O=t,Si(this),this.f&=-2,!0},ve.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}j.prototype.S.call(this,t)},ve.prototype.U=function(t){if(this.t!==void 0&&(j.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ve.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ve.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=gi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function wi(t,e){return new ve(t,e)}function Ci(t){var e=t.u;if(t.u=void 0,typeof e=="function"){ue++;var n=O;O=void 0;try{e()}catch(o){throw t.f&=-2,t.f|=8,yt(t),o}finally{O=n,Je()}}}function yt(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,Ci(t)}function _n(t){if(O!==this)throw new Error("Out-of-order effect");Si(this),O=t,this.f&=-2,8&this.f&&yt(this),Je()}function Ie(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ie.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ie.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,Ci(this),yi(this),ue++;var t=O;return O=this,_n.bind(this,t)},Ie.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ue,Ue=this)},Ie.prototype.d=function(){this.f|=8,1&this.f||yt(this)},Ie.prototype.dispose=function(){this.d()};function Le(t,e){var n=new Ie(t,e);try{n.c()}catch(u){throw n.d(),u}var o=n.d.bind(n);return o[Symbol.dispose]=o,o}var Ii,St,En=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,bi=[];Le(function(){Ii=this.N})();function be(t,e){x[t]=e.bind(null,x[t]||function(){})}function Ze(t){St&&St(),St=t&&t.S()}function Ai(t){var e=this,n=t.data,o=Ti(n);o.value=n;var u=Ce(function(){for(var l=e,m=e.__v;m=m.__;)if(m.__c){m.__c.__$f|=4;break}var p=wi(function(){var g=o.value.value;return g===0?0:g===!0?"":g||""}),_=wi(function(){return!Array.isArray(p.value)&&!Ft(p.value)}),d=Le(function(){if(this.N=Ri,_.value){var g=p.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=g)}}),S=e.__$u.d;return e.__$u.d=function(){d(),S.call(this)},[_,p]},[]),a=u[0],c=u[1];return a.value?c.peek():c.value}Ai.displayName="ReactiveTextNode",Object.defineProperties(j.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ai},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),be("__b",function(t,e){if(typeof e.type=="string"){var n,o=e.props;for(var u in o)if(u!=="children"){var a=o[u];a instanceof j&&(n||(e.__np=n={}),n[u]=a,o[u]=a.peek())}}t(e)}),be("__r",function(t,e){if(e.type!==ce){Ze();var n,o=e.__c;o&&(o.__$f&=-2,(n=o.__$u)===void 0&&(o.__$u=n=(function(u,a){var c;return Le(function(){c=this},{name:a}),c.c=u,c})(function(){var u;En&&((u=n.y)==null||u.call(n)),o.__$f|=1,o.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),Ze(n)}t(e)}),be("__e",function(t,e,n,o){Ze(),t(e,n,o)}),be("diffed",function(t,e){Ze();var n;if(typeof e.type=="string"&&(n=e.__e)){var o=e.__np,u=e.props;if(o){var a=n.U;if(a)for(var c in a){var l=a[c];l!==void 0&&!(c in o)&&(l.d(),a[c]=void 0)}else a={},n.U=a;for(var m in o){var p=a[m],_=o[m];p===void 0?(p=mn(n,m,_,u),a[m]=p):p.o(_,u)}}}t(e)});function mn(t,e,n,o){var u=e in t&&t.ownerSVGElement===void 0,a=z(n);return{o:function(c,l){a.value=c,o=l},d:Le(function(){this.N=Ri;var c=a.value.value;o[e]!==c&&(o[e]=c,u?t[e]=c:c!=null&&(c!==!1||e[4]==="-")?t.setAttribute(e,c):t.removeAttribute(e))})}}be("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var o=n.U;if(o){n.U=void 0;for(var u in o){var a=o[u];a&&a.d()}}}}else{var c=e.__c;if(c){var l=c.__$u;l&&(c.__$u=void 0,l.d())}}t(e)}),be("__h",function(t,e,n,o){(o<3||o===9)&&(e.__$f|=2),t(e,n,o)}),ke.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,o=n&&n.s!==void 0;for(var u in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var a=2&this.__$f;if(!(o||a||4&this.__$f)||1&this.__$f)return!0}else if(!(o||4&this.__$f)||3&this.__$f)return!0;for(var c in t)if(c!=="__source"&&t[c]!==this.props[c])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Ti(t,e){return qe(function(){return z(t,e)})[0]}var gn=function(t){queueMicrotask(function(){queueMicrotask(t)})};function vn(){pn(function(){for(var t;t=bi.shift();)Ii.call(t)})}function Ri(){bi.push(this)===1&&(x.requestAnimationFrame||gn)(vn)}const wt={layout:"floating",initialState:"expanded",position:"bottom-right",showCaptions:!1,showTextInput:!0,showMuteButton:!0,removeWatermark:!1,callToAction:"Talk to our assistant"},Qe={"bottom-right":{bottom:"24px",right:"24px"},"bottom-left":{bottom:"24px",left:"24px"},"top-right":{top:"24px",right:"24px"},"top-left":{top:"24px",left:"24px"}};function yn(t){if(Qe[t])return Qe[t];const e=t.match(/^\[(.+)\]$/);if(!e)return Qe["bottom-right"];const n={};for(const o of e[1].split(",")){const u=o.trim(),a=u.lastIndexOf("-");if(a<=0)continue;const c=u.slice(0,a),l=u.slice(a+1);n[c]=/^\d+$/.test(l)?`${l}px`:l}return Object.keys(n).length>0?n:Qe["bottom-right"]}var Ct={},Be={},Ni;function Sn(){if(Ni)return Be;Ni=1,Be.byteLength=l,Be.toByteArray=p,Be.fromByteArray=S;for(var t=[],e=[],n=typeof Uint8Array<"u"?Uint8Array:Array,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=0,a=o.length;u<a;++u)t[u]=o[u],e[o.charCodeAt(u)]=u;e[45]=62,e[95]=63;function c(g){var y=g.length;if(y%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var C=g.indexOf("=");C===-1&&(C=y);var A=C===y?0:4-C%4;return[C,A]}function l(g){var y=c(g),C=y[0],A=y[1];return(C+A)*3/4-A}function m(g,y,C){return(y+C)*3/4-C}function p(g){var y,C=c(g),A=C[0],I=C[1],b=new n(m(g,A,I)),N=0,M=I>0?A-4:A,k;for(k=0;k<M;k+=4)y=e[g.charCodeAt(k)]<<18|e[g.charCodeAt(k+1)]<<12|e[g.charCodeAt(k+2)]<<6|e[g.charCodeAt(k+3)],b[N++]=y>>16&255,b[N++]=y>>8&255,b[N++]=y&255;return I===2&&(y=e[g.charCodeAt(k)]<<2|e[g.charCodeAt(k+1)]>>4,b[N++]=y&255),I===1&&(y=e[g.charCodeAt(k)]<<10|e[g.charCodeAt(k+1)]<<4|e[g.charCodeAt(k+2)]>>2,b[N++]=y>>8&255,b[N++]=y&255),b}function _(g){return t[g>>18&63]+t[g>>12&63]+t[g>>6&63]+t[g&63]}function d(g,y,C){for(var A,I=[],b=y;b<C;b+=3)A=(g[b]<<16&16711680)+(g[b+1]<<8&65280)+(g[b+2]&255),I.push(_(A));return I.join("")}function S(g){for(var y,C=g.length,A=C%3,I=[],b=16383,N=0,M=C-A;N<M;N+=b)I.push(d(g,N,N+b>M?M:N+b));return A===1?(y=g[C-1],I.push(t[y>>2]+t[y<<4&63]+"==")):A===2&&(y=(g[C-2]<<8)+g[C-1],I.push(t[y>>10]+t[y>>4&63]+t[y<<2&63]+"=")),I.join("")}return Be}var et={};var xi;function wn(){return xi||(xi=1,et.read=function(t,e,n,o,u){var a,c,l=u*8-o-1,m=(1<<l)-1,p=m>>1,_=-7,d=n?u-1:0,S=n?-1:1,g=t[e+d];for(d+=S,a=g&(1<<-_)-1,g>>=-_,_+=l;_>0;a=a*256+t[e+d],d+=S,_-=8);for(c=a&(1<<-_)-1,a>>=-_,_+=o;_>0;c=c*256+t[e+d],d+=S,_-=8);if(a===0)a=1-p;else{if(a===m)return c?NaN:(g?-1:1)*(1/0);c=c+Math.pow(2,o),a=a-p}return(g?-1:1)*c*Math.pow(2,a-o)},et.write=function(t,e,n,o,u,a){var c,l,m,p=a*8-u-1,_=(1<<p)-1,d=_>>1,S=u===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=o?0:a-1,y=o?1:-1,C=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(l=isNaN(e)?1:0,c=_):(c=Math.floor(Math.log(e)/Math.LN2),e*(m=Math.pow(2,-c))<1&&(c--,m*=2),c+d>=1?e+=S/m:e+=S*Math.pow(2,1-d),e*m>=2&&(c++,m/=2),c+d>=_?(l=0,c=_):c+d>=1?(l=(e*m-1)*Math.pow(2,u),c=c+d):(l=e*Math.pow(2,d-1)*Math.pow(2,u),c=0));u>=8;t[n+g]=l&255,g+=y,l/=256,u-=8);for(c=c<<u|l,p+=u;p>0;t[n+g]=c&255,g+=y,c/=256,p-=8);t[n+g-y]|=C*128}),et}var Oi;function Cn(){return Oi||(Oi=1,(function(t){const e=Sn(),n=wn(),o=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=l,t.SlowBuffer=b,t.INSPECT_MAX_BYTES=50;const u=2147483647;t.kMaxLength=u,l.TYPED_ARRAY_SUPPORT=a(),!l.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function a(){try{const s=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(s,i),s.foo()===42}catch{return!1}}Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}});function c(s){if(s>u)throw new RangeError('The value "'+s+'" is invalid for option "size"');const i=new Uint8Array(s);return Object.setPrototypeOf(i,l.prototype),i}function l(s,i,r){if(typeof s=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return d(s)}return m(s,i,r)}l.poolSize=8192;function m(s,i,r){if(typeof s=="string")return S(s,i);if(ArrayBuffer.isView(s))return y(s);if(s==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s);if(ie(s,ArrayBuffer)||s&&ie(s.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(ie(s,SharedArrayBuffer)||s&&ie(s.buffer,SharedArrayBuffer)))return C(s,i,r);if(typeof s=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const h=s.valueOf&&s.valueOf();if(h!=null&&h!==s)return l.from(h,i,r);const f=A(s);if(f)return f;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof s[Symbol.toPrimitive]=="function")return l.from(s[Symbol.toPrimitive]("string"),i,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof s)}l.from=function(s,i,r){return m(s,i,r)},Object.setPrototypeOf(l.prototype,Uint8Array.prototype),Object.setPrototypeOf(l,Uint8Array);function p(s){if(typeof s!="number")throw new TypeError('"size" argument must be of type number');if(s<0)throw new RangeError('The value "'+s+'" is invalid for option "size"')}function _(s,i,r){return p(s),s<=0?c(s):i!==void 0?typeof r=="string"?c(s).fill(i,r):c(s).fill(i):c(s)}l.alloc=function(s,i,r){return _(s,i,r)};function d(s){return p(s),c(s<0?0:I(s)|0)}l.allocUnsafe=function(s){return d(s)},l.allocUnsafeSlow=function(s){return d(s)};function S(s,i){if((typeof i!="string"||i==="")&&(i="utf8"),!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const r=N(s,i)|0;let h=c(r);const f=h.write(s,i);return f!==r&&(h=h.slice(0,f)),h}function g(s){const i=s.length<0?0:I(s.length)|0,r=c(i);for(let h=0;h<i;h+=1)r[h]=s[h]&255;return r}function y(s){if(ie(s,Uint8Array)){const i=new Uint8Array(s);return C(i.buffer,i.byteOffset,i.byteLength)}return g(s)}function C(s,i,r){if(i<0||s.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(s.byteLength<i+(r||0))throw new RangeError('"length" is outside of buffer bounds');let h;return i===void 0&&r===void 0?h=new Uint8Array(s):r===void 0?h=new Uint8Array(s,i):h=new Uint8Array(s,i,r),Object.setPrototypeOf(h,l.prototype),h}function A(s){if(l.isBuffer(s)){const i=I(s.length)|0,r=c(i);return r.length===0||s.copy(r,0,0,i),r}if(s.length!==void 0)return typeof s.length!="number"||Bt(s.length)?c(0):g(s);if(s.type==="Buffer"&&Array.isArray(s.data))return g(s.data)}function I(s){if(s>=u)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+u.toString(16)+" bytes");return s|0}function b(s){return+s!=s&&(s=0),l.alloc(+s)}l.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==l.prototype},l.compare=function(i,r){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),ie(r,Uint8Array)&&(r=l.from(r,r.offset,r.byteLength)),!l.isBuffer(i)||!l.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===r)return 0;let h=i.length,f=r.length;for(let E=0,v=Math.min(h,f);E<v;++E)if(i[E]!==r[E]){h=i[E],f=r[E];break}return h<f?-1:f<h?1:0},l.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(i,r){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return l.alloc(0);let h;if(r===void 0)for(r=0,h=0;h<i.length;++h)r+=i[h].length;const f=l.allocUnsafe(r);let E=0;for(h=0;h<i.length;++h){let v=i[h];if(ie(v,Uint8Array))E+v.length>f.length?(l.isBuffer(v)||(v=l.from(v)),v.copy(f,E)):Uint8Array.prototype.set.call(f,v,E);else if(l.isBuffer(v))v.copy(f,E);else throw new TypeError('"list" argument must be an Array of Buffers');E+=v.length}return f};function N(s,i){if(l.isBuffer(s))return s.length;if(ArrayBuffer.isView(s)||ie(s,ArrayBuffer))return s.byteLength;if(typeof s!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof s);const r=s.length,h=arguments.length>2&&arguments[2]===!0;if(!h&&r===0)return 0;let f=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Lt(s).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Ki(s).length;default:if(f)return h?-1:Lt(s).length;i=(""+i).toLowerCase(),f=!0}}l.byteLength=N;function M(s,i,r){let h=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,i>>>=0,r<=i))return"";for(s||(s="utf8");;)switch(s){case"hex":return Cr(this,i,r);case"utf8":case"utf-8":return $i(this,i,r);case"ascii":return Sr(this,i,r);case"latin1":case"binary":return wr(this,i,r);case"base64":return vr(this,i,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ir(this,i,r);default:if(h)throw new TypeError("Unknown encoding: "+s);s=(s+"").toLowerCase(),h=!0}}l.prototype._isBuffer=!0;function k(s,i,r){const h=s[i];s[i]=s[r],s[r]=h}l.prototype.swap16=function(){const i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;r<i;r+=2)k(this,r,r+1);return this},l.prototype.swap32=function(){const i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let r=0;r<i;r+=4)k(this,r,r+3),k(this,r+1,r+2);return this},l.prototype.swap64=function(){const i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let r=0;r<i;r+=8)k(this,r,r+7),k(this,r+1,r+6),k(this,r+2,r+5),k(this,r+3,r+4);return this},l.prototype.toString=function(){const i=this.length;return i===0?"":arguments.length===0?$i(this,0,i):M.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(i){if(!l.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:l.compare(this,i)===0},l.prototype.inspect=function(){let i="";const r=t.INSPECT_MAX_BYTES;return i=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(i+=" ... "),"<Buffer "+i+">"},o&&(l.prototype[o]=l.prototype.inspect),l.prototype.compare=function(i,r,h,f,E){if(ie(i,Uint8Array)&&(i=l.from(i,i.offset,i.byteLength)),!l.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(r===void 0&&(r=0),h===void 0&&(h=i?i.length:0),f===void 0&&(f=0),E===void 0&&(E=this.length),r<0||h>i.length||f<0||E>this.length)throw new RangeError("out of range index");if(f>=E&&r>=h)return 0;if(f>=E)return-1;if(r>=h)return 1;if(r>>>=0,h>>>=0,f>>>=0,E>>>=0,this===i)return 0;let v=E-f,T=h-r;const L=Math.min(v,T),U=this.slice(f,E),B=i.slice(r,h);for(let D=0;D<L;++D)if(U[D]!==B[D]){v=U[D],T=B[D];break}return v<T?-1:T<v?1:0};function Y(s,i,r,h,f){if(s.length===0)return-1;if(typeof r=="string"?(h=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,Bt(r)&&(r=f?0:s.length-1),r<0&&(r=s.length+r),r>=s.length){if(f)return-1;r=s.length-1}else if(r<0)if(f)r=0;else return-1;if(typeof i=="string"&&(i=l.from(i,h)),l.isBuffer(i))return i.length===0?-1:oe(s,i,r,h,f);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?f?Uint8Array.prototype.indexOf.call(s,i,r):Uint8Array.prototype.lastIndexOf.call(s,i,r):oe(s,[i],r,h,f);throw new TypeError("val must be string, number or Buffer")}function oe(s,i,r,h,f){let E=1,v=s.length,T=i.length;if(h!==void 0&&(h=String(h).toLowerCase(),h==="ucs2"||h==="ucs-2"||h==="utf16le"||h==="utf-16le")){if(s.length<2||i.length<2)return-1;E=2,v/=2,T/=2,r/=2}function L(B,D){return E===1?B[D]:B.readUInt16BE(D*E)}let U;if(f){let B=-1;for(U=r;U<v;U++)if(L(s,U)===L(i,B===-1?0:U-B)){if(B===-1&&(B=U),U-B+1===T)return B*E}else B!==-1&&(U-=U-B),B=-1}else for(r+T>v&&(r=v-T),U=r;U>=0;U--){let B=!0;for(let D=0;D<T;D++)if(L(s,U+D)!==L(i,D)){B=!1;break}if(B)return U}return-1}l.prototype.includes=function(i,r,h){return this.indexOf(i,r,h)!==-1},l.prototype.indexOf=function(i,r,h){return Y(this,i,r,h,!0)},l.prototype.lastIndexOf=function(i,r,h){return Y(this,i,r,h,!1)};function V(s,i,r,h){r=Number(r)||0;const f=s.length-r;h?(h=Number(h),h>f&&(h=f)):h=f;const E=i.length;h>E/2&&(h=E/2);let v;for(v=0;v<h;++v){const T=parseInt(i.substr(v*2,2),16);if(Bt(T))return v;s[r+v]=T}return v}function se(s,i,r,h){return st(Lt(i,s.length-r),s,r,h)}function ae(s,i,r,h){return st(Rr(i),s,r,h)}function Q(s,i,r,h){return st(Ki(i),s,r,h)}function Ee(s,i,r,h){return st(Nr(i,s.length-r),s,r,h)}l.prototype.write=function(i,r,h,f){if(r===void 0)f="utf8",h=this.length,r=0;else if(h===void 0&&typeof r=="string")f=r,h=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(h)?(h=h>>>0,f===void 0&&(f="utf8")):(f=h,h=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const E=this.length-r;if((h===void 0||h>E)&&(h=E),i.length>0&&(h<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");f||(f="utf8");let v=!1;for(;;)switch(f){case"hex":return V(this,i,r,h);case"utf8":case"utf-8":return se(this,i,r,h);case"ascii":case"latin1":case"binary":return ae(this,i,r,h);case"base64":return Q(this,i,r,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ee(this,i,r,h);default:if(v)throw new TypeError("Unknown encoding: "+f);f=(""+f).toLowerCase(),v=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function vr(s,i,r){return i===0&&r===s.length?e.fromByteArray(s):e.fromByteArray(s.slice(i,r))}function $i(s,i,r){r=Math.min(s.length,r);const h=[];let f=i;for(;f<r;){const E=s[f];let v=null,T=E>239?4:E>223?3:E>191?2:1;if(f+T<=r){let L,U,B,D;switch(T){case 1:E<128&&(v=E);break;case 2:L=s[f+1],(L&192)===128&&(D=(E&31)<<6|L&63,D>127&&(v=D));break;case 3:L=s[f+1],U=s[f+2],(L&192)===128&&(U&192)===128&&(D=(E&15)<<12|(L&63)<<6|U&63,D>2047&&(D<55296||D>57343)&&(v=D));break;case 4:L=s[f+1],U=s[f+2],B=s[f+3],(L&192)===128&&(U&192)===128&&(B&192)===128&&(D=(E&15)<<18|(L&63)<<12|(U&63)<<6|B&63,D>65535&&D<1114112&&(v=D))}}v===null?(v=65533,T=1):v>65535&&(v-=65536,h.push(v>>>10&1023|55296),v=56320|v&1023),h.push(v),f+=T}return yr(h)}const Vi=4096;function yr(s){const i=s.length;if(i<=Vi)return String.fromCharCode.apply(String,s);let r="",h=0;for(;h<i;)r+=String.fromCharCode.apply(String,s.slice(h,h+=Vi));return r}function Sr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]&127);return h}function wr(s,i,r){let h="";r=Math.min(s.length,r);for(let f=i;f<r;++f)h+=String.fromCharCode(s[f]);return h}function Cr(s,i,r){const h=s.length;(!i||i<0)&&(i=0),(!r||r<0||r>h)&&(r=h);let f="";for(let E=i;E<r;++E)f+=xr[s[E]];return f}function Ir(s,i,r){const h=s.slice(i,r);let f="";for(let E=0;E<h.length-1;E+=2)f+=String.fromCharCode(h[E]+h[E+1]*256);return f}l.prototype.slice=function(i,r){const h=this.length;i=~~i,r=r===void 0?h:~~r,i<0?(i+=h,i<0&&(i=0)):i>h&&(i=h),r<0?(r+=h,r<0&&(r=0)):r>h&&(r=h),r<i&&(r=i);const f=this.subarray(i,r);return Object.setPrototypeOf(f,l.prototype),f};function G(s,i,r){if(s%1!==0||s<0)throw new RangeError("offset is not uint");if(s+i>r)throw new RangeError("Trying to access beyond buffer length")}l.prototype.readUintLE=l.prototype.readUIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return f},l.prototype.readUintBE=l.prototype.readUIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i+--r],E=1;for(;r>0&&(E*=256);)f+=this[i+--r]*E;return f},l.prototype.readUint8=l.prototype.readUInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]|this[i+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(i,r){return i=i>>>0,r||G(i,2,this.length),this[i]<<8|this[i+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])},l.prototype.readBigUInt64LE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,E=this[++i]+this[++i]*2**8+this[++i]*2**16+h*2**24;return BigInt(f)+(BigInt(E)<<BigInt(32))}),l.prototype.readBigUInt64BE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=r*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],E=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h;return(BigInt(f)<<BigInt(32))+BigInt(E)}),l.prototype.readIntLE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=this[i],E=1,v=0;for(;++v<r&&(E*=256);)f+=this[i+v]*E;return E*=128,f>=E&&(f-=Math.pow(2,8*r)),f},l.prototype.readIntBE=function(i,r,h){i=i>>>0,r=r>>>0,h||G(i,r,this.length);let f=r,E=1,v=this[i+--f];for(;f>0&&(E*=256);)v+=this[i+--f]*E;return E*=128,v>=E&&(v-=Math.pow(2,8*r)),v},l.prototype.readInt8=function(i,r){return i=i>>>0,r||G(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]},l.prototype.readInt16LE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i]|this[i+1]<<8;return h&32768?h|4294901760:h},l.prototype.readInt16BE=function(i,r){i=i>>>0,r||G(i,2,this.length);const h=this[i+1]|this[i]<<8;return h&32768?h|4294901760:h},l.prototype.readInt32LE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24},l.prototype.readInt32BE=function(i,r){return i=i>>>0,r||G(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]},l.prototype.readBigInt64LE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(h<<24);return(BigInt(f)<<BigInt(32))+BigInt(r+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)}),l.prototype.readBigInt64BE=me(function(i){i=i>>>0,Ne(i,"offset");const r=this[i],h=this[i+7];(r===void 0||h===void 0)&&Ve(i,this.length-8);const f=(r<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(f)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+h)}),l.prototype.readFloatLE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!0,23,4)},l.prototype.readFloatBE=function(i,r){return i=i>>>0,r||G(i,4,this.length),n.read(this,i,!1,23,4)},l.prototype.readDoubleLE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!0,52,8)},l.prototype.readDoubleBE=function(i,r){return i=i>>>0,r||G(i,8,this.length),n.read(this,i,!1,52,8)};function K(s,i,r,h,f,E){if(!l.isBuffer(s))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>f||i<E)throw new RangeError('"value" argument is out of bounds');if(r+h>s.length)throw new RangeError("Index out of range")}l.prototype.writeUintLE=l.prototype.writeUIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;K(this,i,r,h,T,0)}let E=1,v=0;for(this[r]=i&255;++v<h&&(E*=256);)this[r+v]=i/E&255;return r+h},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,h=h>>>0,!f){const T=Math.pow(2,8*h)-1;K(this,i,r,h,T,0)}let E=h-1,v=1;for(this[r+E]=i&255;--E>=0&&(v*=256);)this[r+E]=i/v&255;return r+h},l.prototype.writeUint8=l.prototype.writeUInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,255,0),this[r]=i&255,r+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,65535,0),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r+3]=i>>>24,this[r+2]=i>>>16,this[r+1]=i>>>8,this[r]=i&255,r+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,4294967295,0),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4};function Gi(s,i,r,h,f){Yi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E,E=E>>8,s[r++]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,v=v>>8,s[r++]=v,r}function ji(s,i,r,h,f){Yi(i,h,f,s,r,7);let E=Number(i&BigInt(4294967295));s[r+7]=E,E=E>>8,s[r+6]=E,E=E>>8,s[r+5]=E,E=E>>8,s[r+4]=E;let v=Number(i>>BigInt(32)&BigInt(4294967295));return s[r+3]=v,v=v>>8,s[r+2]=v,v=v>>8,s[r+1]=v,v=v>>8,s[r]=v,r+8}l.prototype.writeBigUInt64LE=me(function(i,r=0){return Gi(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=me(function(i,r=0){return ji(this,i,r,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let E=0,v=1,T=0;for(this[r]=i&255;++E<h&&(v*=256);)i<0&&T===0&&this[r+E-1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeIntBE=function(i,r,h,f){if(i=+i,r=r>>>0,!f){const L=Math.pow(2,8*h-1);K(this,i,r,h,L-1,-L)}let E=h-1,v=1,T=0;for(this[r+E]=i&255;--E>=0&&(v*=256);)i<0&&T===0&&this[r+E+1]!==0&&(T=1),this[r+E]=(i/v>>0)-T&255;return r+h},l.prototype.writeInt8=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,1,127,-128),i<0&&(i=255+i+1),this[r]=i&255,r+1},l.prototype.writeInt16LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i&255,this[r+1]=i>>>8,r+2},l.prototype.writeInt16BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,2,32767,-32768),this[r]=i>>>8,this[r+1]=i&255,r+2},l.prototype.writeInt32LE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),this[r]=i&255,this[r+1]=i>>>8,this[r+2]=i>>>16,this[r+3]=i>>>24,r+4},l.prototype.writeInt32BE=function(i,r,h){return i=+i,r=r>>>0,h||K(this,i,r,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[r]=i>>>24,this[r+1]=i>>>16,this[r+2]=i>>>8,this[r+3]=i&255,r+4},l.prototype.writeBigInt64LE=me(function(i,r=0){return Gi(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=me(function(i,r=0){return ji(this,i,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Hi(s,i,r,h,f,E){if(r+h>s.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Wi(s,i,r,h,f){return i=+i,r=r>>>0,f||Hi(s,i,r,4),n.write(s,i,r,h,23,4),r+4}l.prototype.writeFloatLE=function(i,r,h){return Wi(this,i,r,!0,h)},l.prototype.writeFloatBE=function(i,r,h){return Wi(this,i,r,!1,h)};function zi(s,i,r,h,f){return i=+i,r=r>>>0,f||Hi(s,i,r,8),n.write(s,i,r,h,52,8),r+8}l.prototype.writeDoubleLE=function(i,r,h){return zi(this,i,r,!0,h)},l.prototype.writeDoubleBE=function(i,r,h){return zi(this,i,r,!1,h)},l.prototype.copy=function(i,r,h,f){if(!l.isBuffer(i))throw new TypeError("argument should be a Buffer");if(h||(h=0),!f&&f!==0&&(f=this.length),r>=i.length&&(r=i.length),r||(r=0),f>0&&f<h&&(f=h),f===h||i.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(h<0||h>=this.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("sourceEnd out of bounds");f>this.length&&(f=this.length),i.length-r<f-h&&(f=i.length-r+h);const E=f-h;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,h,f):Uint8Array.prototype.set.call(i,this.subarray(h,f),r),E},l.prototype.fill=function(i,r,h,f){if(typeof i=="string"){if(typeof r=="string"?(f=r,r=0,h=this.length):typeof h=="string"&&(f=h,h=this.length),f!==void 0&&typeof f!="string")throw new TypeError("encoding must be a string");if(typeof f=="string"&&!l.isEncoding(f))throw new TypeError("Unknown encoding: "+f);if(i.length===1){const v=i.charCodeAt(0);(f==="utf8"&&v<128||f==="latin1")&&(i=v)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(r<0||this.length<r||this.length<h)throw new RangeError("Out of range index");if(h<=r)return this;r=r>>>0,h=h===void 0?this.length:h>>>0,i||(i=0);let E;if(typeof i=="number")for(E=r;E<h;++E)this[E]=i;else{const v=l.isBuffer(i)?i:l.from(i,f),T=v.length;if(T===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(E=0;E<h-r;++E)this[E+r]=v[E%T]}return this};const Re={};function Ut(s,i,r){Re[s]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${s}]`,this.stack,delete this.name}get code(){return s}set code(f){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:f,writable:!0})}toString(){return`${this.name} [${s}]: ${this.message}`}}}Ut("ERR_BUFFER_OUT_OF_BOUNDS",function(s){return s?`${s} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Ut("ERR_INVALID_ARG_TYPE",function(s,i){return`The "${s}" argument must be of type number. Received type ${typeof i}`},TypeError),Ut("ERR_OUT_OF_RANGE",function(s,i,r){let h=`The value of "${s}" is out of range.`,f=r;return Number.isInteger(r)&&Math.abs(r)>2**32?f=qi(String(r)):typeof r=="bigint"&&(f=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(f=qi(f)),f+="n"),h+=` It must be ${i}. Received ${f}`,h},RangeError);function qi(s){let i="",r=s.length;const h=s[0]==="-"?1:0;for(;r>=h+4;r-=3)i=`_${s.slice(r-3,r)}${i}`;return`${s.slice(0,r)}${i}`}function br(s,i,r){Ne(i,"offset"),(s[i]===void 0||s[i+r]===void 0)&&Ve(i,s.length-(r+1))}function Yi(s,i,r,h,f,E){if(s>r||s<i){const v=typeof i=="bigint"?"n":"";let T;throw i===0||i===BigInt(0)?T=`>= 0${v} and < 2${v} ** ${(E+1)*8}${v}`:T=`>= -(2${v} ** ${(E+1)*8-1}${v}) and < 2 ** ${(E+1)*8-1}${v}`,new Re.ERR_OUT_OF_RANGE("value",T,s)}br(h,f,E)}function Ne(s,i){if(typeof s!="number")throw new Re.ERR_INVALID_ARG_TYPE(i,"number",s)}function Ve(s,i,r){throw Math.floor(s)!==s?(Ne(s,r),new Re.ERR_OUT_OF_RANGE("offset","an integer",s)):i<0?new Re.ERR_BUFFER_OUT_OF_BOUNDS:new Re.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${i}`,s)}const Ar=/[^+/0-9A-Za-z-_]/g;function Tr(s){if(s=s.split("=")[0],s=s.trim().replace(Ar,""),s.length<2)return"";for(;s.length%4!==0;)s=s+"=";return s}function Lt(s,i){i=i||1/0;let r;const h=s.length;let f=null;const E=[];for(let v=0;v<h;++v){if(r=s.charCodeAt(v),r>55295&&r<57344){if(!f){if(r>56319){(i-=3)>-1&&E.push(239,191,189);continue}else if(v+1===h){(i-=3)>-1&&E.push(239,191,189);continue}f=r;continue}if(r<56320){(i-=3)>-1&&E.push(239,191,189),f=r;continue}r=(f-55296<<10|r-56320)+65536}else f&&(i-=3)>-1&&E.push(239,191,189);if(f=null,r<128){if((i-=1)<0)break;E.push(r)}else if(r<2048){if((i-=2)<0)break;E.push(r>>6|192,r&63|128)}else if(r<65536){if((i-=3)<0)break;E.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((i-=4)<0)break;E.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return E}function Rr(s){const i=[];for(let r=0;r<s.length;++r)i.push(s.charCodeAt(r)&255);return i}function Nr(s,i){let r,h,f;const E=[];for(let v=0;v<s.length&&!((i-=2)<0);++v)r=s.charCodeAt(v),h=r>>8,f=r%256,E.push(f),E.push(h);return E}function Ki(s){return e.toByteArray(Tr(s))}function st(s,i,r,h){let f;for(f=0;f<h&&!(f+r>=i.length||f>=s.length);++f)i[f+r]=s[f];return f}function ie(s,i){return s instanceof i||s!=null&&s.constructor!=null&&s.constructor.name!=null&&s.constructor.name===i.name}function Bt(s){return s!==s}const xr=(function(){const s="0123456789abcdef",i=new Array(256);for(let r=0;r<16;++r){const h=r*16;for(let f=0;f<16;++f)i[h+f]=s[r]+s[f]}return i})();function me(s){return typeof BigInt>"u"?Or:s}function Or(){throw new Error("BigInt not supported")}})(Ct)),Ct}var In=Cn();const bn="https://api.anam.ai",An="/v1",ki={client:"js-sdk",version:"4.8.0"};var Tn=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Di="https://api.anam.ai",It="/v1";var re;(function(t){t.CLIENT_METRIC_MEASUREMENT_ERROR="client_error",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED="client_connection_closed",t.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED="client_connection_established",t.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT="client_session_attempt",t.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS="client_session_success"})(re||(re={}));let bt=Di,Mi=It,de,Ui=!1;const Rn=(t,e=It)=>{bt=t,Mi=e},Nn=t=>{de=t},xn=t=>{Ui=t};let he={sessionId:null,organizationId:null,attemptCorrelationId:null};const Ae=t=>{he=Object.assign(Object.assign({},he),t)},ye=(t,e,n)=>Tn(void 0,void 0,void 0,function*(){if(!Ui)try{const o=Object.assign(Object.assign({},ki),n);he.sessionId&&(o.sessionId=he.sessionId),he.organizationId&&(o.organizationId=he.organizationId),he.attemptCorrelationId&&(o.attemptCorrelationId=he.attemptCorrelationId);const u=`${Mi}/metrics/client`;let a,c={"Content-Type":"application/json"};de?.enabled&&de?.baseUrl?(a=`${de.baseUrl}${u}`,c["X-Anam-Target-Url"]=`${bt}${u}`):a=`${bt}${u}`,yield fetch(a,{method:"POST",headers:c,body:JSON.stringify({name:t,value:e,tags:o})})}catch(o){console.error("Failed to send error metric:",o)}}),On=(t,e="console")=>{var n,o,u;const a={};t.forEach(d=>{a[d.type]||(a[d.type]=[]),a[d.type].push(d)});const c={issues:[]},l=((n=a["inbound-rtp"])===null||n===void 0?void 0:n.filter(d=>d.kind==="video"))||[];l.length>0&&(c.personaVideoStream=[],l.forEach(d=>{var S,g,y,C,A;const I={framesReceived:(S=d.framesReceived)!==null&&S!==void 0?S:"unknown",framesDropped:(g=d.framesDropped)!==null&&g!==void 0?g:"unknown",framesPerSecond:(y=d.framesPerSecond)!==null&&y!==void 0?y:"unknown",packetsReceived:(C=d.packetsReceived)!==null&&C!==void 0?C:"unknown",packetsLost:(A=d.packetsLost)!==null&&A!==void 0?A:"unknown",resolution:d.frameWidth&&d.frameHeight?`${d.frameWidth}x${d.frameHeight}`:void 0,jitter:d.jitter!==void 0?d.jitter:void 0};c.personaVideoStream.push(I)}));const m=((o=a["inbound-rtp"])===null||o===void 0?void 0:o.filter(d=>d.kind==="audio"))||[];m.length>0&&(c.personaAudioStream=[],m.forEach(d=>{var S,g,y;const C={packetsReceived:(S=d.packetsReceived)!==null&&S!==void 0?S:"unknown",packetsLost:(g=d.packetsLost)!==null&&g!==void 0?g:"unknown",audioLevel:(y=d.audioLevel)!==null&&y!==void 0?y:"unknown",jitter:d.jitter!==void 0?d.jitter:void 0,totalAudioEnergy:d.totalAudioEnergy!==void 0?d.totalAudioEnergy:void 0};c.personaAudioStream.push(C)}));const p=((u=a["outbound-rtp"])===null||u===void 0?void 0:u.filter(d=>d.kind==="audio"))||[];p.length>0&&(c.userAudioInput=[],p.forEach(d=>{var S,g;const y={packetsSent:(S=d.packetsSent)!==null&&S!==void 0?S:"unknown",retransmittedPackets:(g=d.retransmittedPacketsSent)!==null&&g!==void 0?g:void 0,avgPacketSendDelay:d.totalPacketSendDelay!==void 0?d.totalPacketSendDelay/(d.packetsSent||1)*1e3:void 0};c.userAudioInput.push(y)})),a.codec&&(c.codecs=[],a.codec.forEach(d=>{const S={status:d.payloadType?"Active":"Available",mimeType:d.mimeType||"Unknown",payloadType:d.payloadType||"N/A",clockRate:d.clockRate||void 0,channels:d.channels||void 0};c.codecs.push(S)})),a.transport&&(c.transportLayer=[],a.transport.forEach(d=>{const S={dtlsState:d.dtlsState||"unknown",iceState:d.iceState||"unknown",bytesSent:d.bytesSent||void 0,bytesReceived:d.bytesReceived||void 0};c.transportLayer.push(S)}));const _=[];if(l.forEach(d=>{typeof d.framesDropped=="number"&&d.framesDropped>0&&_.push(`Video: ${d.framesDropped} frames dropped`),typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Video: ${d.packetsLost} packets lost`),typeof d.framesPerSecond=="number"&&d.framesPerSecond<23&&_.push(`Video: Low frame rate (${d.framesPerSecond} fps)`)}),m.forEach(d=>{typeof d.packetsLost=="number"&&d.packetsLost>0&&_.push(`Audio: ${d.packetsLost} packets lost`),typeof d.jitter=="number"&&d.jitter>.1&&_.push(`Audio: High jitter (${(d.jitter*1e3).toFixed(1)}ms)`)}),c.issues=_,e==="json")return c;console.group("📊 WebRTC Session Statistics Report"),c.personaVideoStream&&c.personaVideoStream.length>0&&(console.group("📹 Persona Video Stream (Inbound)"),c.personaVideoStream.forEach(d=>{console.log(`Frames Received: ${d.framesReceived}`),console.log(`Frames Dropped: ${d.framesDropped}`),console.log(`Frames Per Second: ${d.framesPerSecond}`),console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),d.resolution&&console.log(`Resolution: ${d.resolution}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`)}),console.groupEnd()),c.personaAudioStream&&c.personaAudioStream.length>0&&(console.group("🔊 Persona Audio Stream (Inbound)"),c.personaAudioStream.forEach(d=>{console.log(`Packets Received: ${typeof d.packetsReceived=="number"?d.packetsReceived.toLocaleString():d.packetsReceived}`),console.log(`Packets Lost: ${d.packetsLost}`),console.log(`Audio Level: ${d.audioLevel}`),d.jitter!==void 0&&console.log(`Jitter: ${d.jitter.toFixed(5)}ms`),d.totalAudioEnergy!==void 0&&console.log(`Total Audio Energy: ${d.totalAudioEnergy.toFixed(6)}`)}),console.groupEnd()),c.userAudioInput&&c.userAudioInput.length>0&&(console.group("🎤 User Audio Input (Outbound)"),c.userAudioInput.forEach(d=>{console.log(`Packets Sent: ${typeof d.packetsSent=="number"?d.packetsSent.toLocaleString():d.packetsSent}`),d.retransmittedPackets&&console.log(`Retransmitted Packets: ${d.retransmittedPackets}`),d.avgPacketSendDelay!==void 0&&console.log(`Avg Packet Send Delay: ${d.avgPacketSendDelay.toFixed(5)}ms`)}),console.groupEnd()),c.codecs&&c.codecs.length>0&&(console.group("🔧 Codecs Used"),c.codecs.forEach(d=>{console.log(`${d.status} ${d.mimeType} - Payload Type: ${d.payloadType}`),d.clockRate&&console.log(` Clock Rate: ${d.clockRate}Hz`),d.channels&&console.log(` Channels: ${d.channels}`)}),console.groupEnd()),c.transportLayer&&c.transportLayer.length>0&&(console.group("🚚 Transport Layer"),c.transportLayer.forEach(d=>{console.log(`DTLS State: ${d.dtlsState}`),console.log(`ICE State: ${d.iceState}`),(d.bytesReceived||d.bytesSent)&&console.log(`Data Transfer (bytes) - Sent: ${(d.bytesSent||0).toLocaleString()}, Received: ${(d.bytesReceived||0).toLocaleString()}`)}),console.groupEnd()),c.issues.length>0?(console.group("⚠️ Potential Issues Detected"),c.issues.forEach(d=>console.warn(d)),console.groupEnd()):console.log("✅ No significant issues detected"),console.groupEnd()};var H;(function(t){t.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED="CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED",t.CLIENT_ERROR_CODE_SPEND_CAP_REACHED="CLIENT_ERROR_CODE_SPEND_CAP_REACHED",t.CLIENT_ERROR_CODE_VALIDATION_ERROR="CLIENT_ERROR_CODE_VALIDATION_ERROR",t.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR="CLIENT_ERROR_CODE_AUTHENTICATION_ERROR",t.CLIENT_ERROR_CODE_SERVER_ERROR="CLIENT_ERROR_CODE_SERVER_ERROR",t.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED="CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED",t.CLIENT_ERROR_CODE_SERVICE_BUSY="CLIENT_ERROR_CODE_SERVICE_BUSY",t.CLIENT_ERROR_CODE_NO_PLAN_FOUND="CLIENT_ERROR_CODE_NO_PLAN_FOUND",t.CLIENT_ERROR_CODE_UNKNOWN_ERROR="CLIENT_ERROR_CODE_UNKNOWN_ERROR",t.CLIENT_ERROR_CODE_CONFIGURATION_ERROR="CLIENT_ERROR_CODE_CONFIGURATION_ERROR"})(H||(H={}));class $ extends Error{constructor(e,n,o=500,u){super(e),this.name="ClientError",this.code=n,this.statusCode=o,this.details=u,Object.setPrototypeOf(this,$.prototype),ye(re.CLIENT_METRIC_MEASUREMENT_ERROR,n,{details:u,statusCode:o})}}function Li(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString(36)+Math.random().toString(36).substr(2,9)}function kn(t){if(!(!t||!t.enabled)){if(!t.baseUrl)return"API Gateway baseUrl is required when enabled";try{const e=new URL(t.baseUrl);if(!["http:","https:","ws:","wss:"].includes(e.protocol))return`Invalid API Gateway baseUrl protocol: ${e.protocol}. Must be http:, https:, ws:, or wss:`}catch{return`Invalid API Gateway baseUrl: ${t.baseUrl}`}if(t.wsPath&&!t.wsPath.startsWith("/"))return"API Gateway wsPath must start with /"}}var W;(function(t){t.OFFER="offer",t.ANSWER="answer",t.ICE_CANDIDATE="icecandidate",t.END_SESSION="endsession",t.HEARTBEAT="heartbeat",t.WARNING="warning",t.TALK_STREAM_INTERRUPTED="talkinputstreaminterrupted",t.TALK_STREAM_INPUT="talkstream",t.SESSION_READY="sessionready",t.AGENT_AUDIO_INPUT="agentaudioinput",t.AGENT_AUDIO_INPUT_END="agentaudioinputend"})(W||(W={}));var Pe;(function(t){t.SPEECH_TEXT="speechText",t.CLIENT_TOOL_EVENT="clientToolEvent",t.REASONING_TEXT="reasoningText"})(Pe||(Pe={}));var fe;(function(t){t.PENDING="pending",t.GRANTED="granted",t.DENIED="denied",t.NOT_REQUESTED="not_requested"})(fe||(fe={}));var tt;(function(t){t.USER="user",t.PERSONA="persona"})(tt||(tt={}));var R;(function(t){t.MESSAGE_HISTORY_UPDATED="MESSAGE_HISTORY_UPDATED",t.MESSAGE_STREAM_EVENT_RECEIVED="MESSAGE_STREAM_EVENT_RECEIVED",t.CONNECTION_ESTABLISHED="CONNECTION_ESTABLISHED",t.CONNECTION_CLOSED="CONNECTION_CLOSED",t.INPUT_AUDIO_STREAM_STARTED="INPUT_AUDIO_STREAM_STARTED",t.VIDEO_STREAM_STARTED="VIDEO_STREAM_STARTED",t.VIDEO_PLAY_STARTED="VIDEO_PLAY_STARTED",t.AUDIO_STREAM_STARTED="AUDIO_STREAM_STARTED",t.TALK_STREAM_INTERRUPTED="TALK_STREAM_INTERRUPTED",t.SESSION_READY="SESSION_READY",t.SERVER_WARNING="SERVER_WARNING",t.MIC_PERMISSION_PENDING="MIC_PERMISSION_PENDING",t.MIC_PERMISSION_GRANTED="MIC_PERMISSION_GRANTED",t.MIC_PERMISSION_DENIED="MIC_PERMISSION_DENIED",t.INPUT_AUDIO_DEVICE_CHANGED="INPUT_AUDIO_DEVICE_CHANGED",t.CLIENT_TOOL_EVENT_RECEIVED="CLIENT_TOOL_EVENT_RECEIVED",t.REASONING_HISTORY_UPDATED="REASONING_HISTORY_UPDATED",t.REASONING_STREAM_EVENT_RECEIVED="REASONING_STREAM_EVENT_RECEIVED"})(R||(R={}));var J;(function(t){t.WEB_SOCKET_OPEN="WEB_SOCKET_OPEN",t.SIGNAL_MESSAGE_RECEIVED="SIGNAL_MESSAGE_RECEIVED",t.WEBRTC_CHAT_MESSAGE_RECEIVED="WEBRTC_CHAT_MESSAGE_RECEIVED",t.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED="WEBRTC_CLIENT_TOOL_EVENT_RECEIVED",t.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED="WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED"})(J||(J={}));var pe;(function(t){t.NORMAL="CONNECTION_CLOSED_CODE_NORMAL",t.MICROPHONE_PERMISSION_DENIED="CONNECTION_CLOSED_CODE_MICROPHONE_PERMISSION_DENIED",t.SIGNALLING_CLIENT_CONNECTION_FAILURE="CONNECTION_CLOSED_CODE_SIGNALLING_CLIENT_CONNECTION_FAILURE",t.WEBRTC_FAILURE="CONNECTION_CLOSED_CODE_WEBRTC_FAILURE",t.SERVER_CLOSED_CONNECTION="CONNECTION_CLOSED_CODE_SERVER_CLOSED_CONNECTION"})(pe||(pe={}));class Dn{constructor(e,n){this.sequenceNumber=0,this.config=e,this.signallingClient=n}sendAudioChunk(e){const o={audioData:typeof e=="string"?e:this.arrayBufferToBase64(e),encoding:this.config.encoding,sampleRate:this.config.sampleRate,channels:this.config.channels,sequenceNumber:this.sequenceNumber++};this.signallingClient.sendAgentAudioInput(o)}endSequence(){this.signallingClient.sendAgentAudioInputEnd(),this.sequenceNumber=0}getSequenceNumber(){return this.sequenceNumber}getConfig(){return this.config}arrayBufferToBase64(e){const n=e instanceof Uint8Array?e:new Uint8Array(e),o=Array.from(n,u=>String.fromCharCode(u)).join("");return btoa(o)}}var Te=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Mn=5,Un=5;class Ln{constructor(e,n,o,u,a){var c,l,m,p,_;if(this.stopSignal=!1,this.sendingBuffer=[],this.wsConnectionAttempts=0,this.socket=null,this.heartBeatIntervalRef=null,this.publicEventEmitter=o,this.internalEventEmitter=u,this.apiGatewayConfig=a,!e)throw new Error("Signalling Client: sessionId is required");this.sessionId=e;const{heartbeatIntervalSeconds:d,maxWsReconnectionAttempts:S,url:g}=n;if(this.heartbeatIntervalSeconds=d||Mn,this.maxWsReconnectionAttempts=S||Un,!g.baseUrl)throw new Error("Signalling Client: baseUrl is required");if(!((c=this.apiGatewayConfig)===null||c===void 0)&&c.enabled&&(!((l=this.apiGatewayConfig)===null||l===void 0)&&l.baseUrl)){const y=new URL(this.apiGatewayConfig.baseUrl),C=(m=this.apiGatewayConfig.wsPath)!==null&&m!==void 0?m:"/ws";y.protocol=y.protocol.replace("http","ws"),y.pathname=C,this.url=y;const A=g.protocol||"https",I=A==="http"?"ws":"wss",b=`${A}://${g.baseUrl}`,N=(p=g.signallingPath)!==null&&p!==void 0?p:"/ws",M=new URL(b);M.protocol=I==="ws"?"ws:":"wss:",g.port&&(M.port=g.port),M.pathname=N,M.searchParams.append("session_id",e),this.url.searchParams.append("target_url",M.href)}else{const C=`${g.protocol||"https"}://${g.baseUrl}`;this.url=new URL(C),this.url.protocol=g.protocol==="http"?"ws:":"wss:",g.port&&(this.url.port=g.port),this.url.pathname=(_=g.signallingPath)!==null&&_!==void 0?_:"/ws",this.url.searchParams.append("session_id",e)}}stop(){this.stopSignal=!0,this.closeSocket()}connect(){return this.socket=new WebSocket(this.url.href),this.socket.onopen=this.onOpen.bind(this),this.socket.onclose=this.onClose.bind(this),this.socket.onerror=this.onError.bind(this),this.socket}sendOffer(e){return Te(this,void 0,void 0,function*(){const n={connectionDescription:e,userUid:this.sessionId},o={actionType:W.OFFER,sessionId:this.sessionId,payload:n};this.sendSignalMessage(o)})}sendIceCandidate(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.ICE_CANDIDATE,sessionId:this.sessionId,payload:e.toJSON()};this.sendSignalMessage(n)})}sendSignalMessage(e){var n;if(((n=this.socket)===null||n===void 0?void 0:n.readyState)===WebSocket.OPEN)try{this.socket.send(JSON.stringify(e))}catch(o){console.error("SignallingClient - sendSignalMessage: error sending message",o)}else this.sendingBuffer.push(e)}sendTalkMessage(e){return Te(this,void 0,void 0,function*(){const n={actionType:W.TALK_STREAM_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)})}sendAgentAudioInput(e){const n={actionType:W.AGENT_AUDIO_INPUT,sessionId:this.sessionId,payload:e};this.sendSignalMessage(n)}sendAgentAudioInputEnd(){const e={actionType:W.AGENT_AUDIO_INPUT_END,sessionId:this.sessionId,payload:{}};this.sendSignalMessage(e)}closeSocket(){this.socket&&(this.socket.close(),this.socket=null),this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null)}onOpen(){return Te(this,void 0,void 0,function*(){if(!this.socket)throw new Error("SignallingClient - onOpen: socket is null");try{this.wsConnectionAttempts=0,this.flushSendingBuffer(),this.socket.onmessage=this.onMessage.bind(this),this.startSendingHeartBeats(),this.internalEventEmitter.emit(J.WEB_SOCKET_OPEN)}catch(e){console.error("SignallingClient - onOpen: error in onOpen",e),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)}})}onClose(){return Te(this,void 0,void 0,function*(){this.wsConnectionAttempts+=1,!this.stopSignal&&(this.wsConnectionAttempts<=this.maxWsReconnectionAttempts?(this.socket=null,setTimeout(()=>{this.connect()},100*this.wsConnectionAttempts)):(this.heartBeatIntervalRef&&(clearInterval(this.heartBeatIntervalRef),this.heartBeatIntervalRef=null),this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SIGNALLING_CLIENT_CONNECTION_FAILURE)))})}onError(e){this.stopSignal||console.error("SignallingClient - onError: ",e)}flushSendingBuffer(){const e=[];this.sendingBuffer.length>0&&this.sendingBuffer.forEach(n=>{var o;((o=this.socket)===null||o===void 0?void 0:o.readyState)===WebSocket.OPEN?this.socket.send(JSON.stringify(n)):e.push(n)}),this.sendingBuffer=e}onMessage(e){return Te(this,void 0,void 0,function*(){const n=JSON.parse(e.data);this.internalEventEmitter.emit(J.SIGNAL_MESSAGE_RECEIVED,n)})}startSendingHeartBeats(){if(!this.socket)throw new Error("SignallingClient - startSendingHeartBeats: socket is null");this.heartBeatIntervalRef&&console.warn("SignallingClient - startSendingHeartBeats: heartbeat interval already set");const e=this.heartbeatIntervalSeconds*1e3,n={actionType:W.HEARTBEAT,sessionId:this.sessionId,payload:""},o=JSON.stringify(n);this.heartBeatIntervalRef=setInterval(()=>{var u;this.stopSignal||((u=this.socket)===null||u===void 0?void 0:u.readyState)===WebSocket.OPEN&&this.socket.send(o)},e)}}function Bn(t){return"brainType"in t||"llmId"in t}var Bi=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Pn{constructor(e,n,o){if(!e&&!n)throw new Error("Either sessionToken or apiKey must be provided");this.sessionToken=e||null,this.apiKey=n||null,this.baseUrl=o?.baseUrl||bn,this.apiVersion=o?.apiVersion||An,this.apiGatewayConfig=o?.apiGateway||void 0}buildGatewayUrlAndHeaders(e,n){var o,u;if(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.enabled&&(!((u=this.apiGatewayConfig)===null||u===void 0)&&u.baseUrl)){const a=`${this.apiGatewayConfig.baseUrl}${e}`,c=new URL(`${this.baseUrl}${e}`),l=Object.assign(Object.assign({},n),{"X-Anam-Target-Url":c.href});return{url:a,headers:l}}else return{url:`${this.baseUrl}${e}`,headers:n}}startSession(e,n){return Bi(this,void 0,void 0,function*(){if(!this.sessionToken){if(!e)throw new $("Persona configuration must be provided when using apiKey",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400);this.sessionToken=yield this.unsafe_getSessionToken(e)}e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");try{const o=`${this.apiVersion}/engine/session`,{url:u,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.sessionToken}`}),c=yield fetch(u,{method:"POST",headers:a,body:JSON.stringify({personaConfig:e,sessionOptions:n,clientMetadata:ki})}),l=yield c.json(),m=l.error;switch(c.status){case 200:case 201:return l;case 400:throw new $("Invalid request to start session",H.CLIENT_ERROR_CODE_VALIDATION_ERROR,400,{cause:l.message});case 401:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,401,{cause:l.message});case 402:throw new $("Please sign up for a plan to start a session",H.CLIENT_ERROR_CODE_NO_PLAN_FOUND,402,{cause:l.message});case 403:throw new $("Authentication failed when starting session",H.CLIENT_ERROR_CODE_AUTHENTICATION_ERROR,403,{cause:l.message});case 429:throw m==="Concurrent session limit reached"?new $("Concurrency limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_MAX_CONCURRENT_SESSIONS_REACHED,429,{cause:l.message}):m==="Spend cap reached"?new $("Spend cap reached, please upgrade your plan",H.CLIENT_ERROR_CODE_SPEND_CAP_REACHED,429,{cause:l.message}):new $("Usage limit reached, please upgrade your plan",H.CLIENT_ERROR_CODE_USAGE_LIMIT_REACHED,429,{cause:l.message});case 503:throw new $("There are no available personas, please try again later",H.CLIENT_ERROR_CODE_SERVICE_BUSY,503,{cause:l.message});default:throw new $("Unknown error when starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:l.message})}}catch(o){throw o instanceof $?o:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:o instanceof Error?o.message:String(o)})}})}unsafe_getSessionToken(e){return Bi(this,void 0,void 0,function*(){if(console.warn("Using unsecure method. This method should not be used in production."),!this.apiKey)throw new Error("No apiKey provided");e&&"brainType"in e&&console.warn("Warning: brainType is deprecated and will be removed in a future version. Please use llmId instead.");let n={clientLabel:"js-sdk-api-key"};Bn(e)&&(n=Object.assign(Object.assign({},n),{personaConfig:e}));try{const o=`${this.apiVersion}/auth/session-token`,{url:u,headers:a}=this.buildGatewayUrlAndHeaders(o,{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`});return(yield(yield fetch(u,{method:"POST",headers:a,body:JSON.stringify(n)})).json()).sessionToken}catch{throw new Error("Failed to get session token")}})}getApiUrl(){return`${this.baseUrl}${this.apiVersion}`}}var Fn=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class $n{constructor(e,n,o){this.baseUrl=e,this.sessionId=n,this.apiGatewayConfig=o}sendTalkCommand(e){return Fn(this,void 0,void 0,function*(){var n,o;try{let u,a={"Content-Type":"application/json"};const c="/talk",l=`?session_id=${this.sessionId}`;if(!((n=this.apiGatewayConfig)===null||n===void 0)&&n.enabled&&(!((o=this.apiGatewayConfig)===null||o===void 0)&&o.baseUrl)){u=`${this.apiGatewayConfig.baseUrl}${c}${l}`;const p=new URL(`${this.baseUrl}${c}${l}`);a["X-Anam-Target-Url"]=p.href}else u=`${this.baseUrl}${c}${l}`;const m=yield fetch(u,{method:"POST",headers:a,body:JSON.stringify({content:e})});if(!m.ok)throw new Error(`Failed to send talk command: ${m.status} ${m.statusText}`)}catch(u){throw console.error(u),new Error("EngineApiRestClient - sendTalkCommand: Failed to send talk command")}})}}class Vn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}class Gn{constructor(e,n){this.messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_CHAT_MESSAGE_RECEIVED,this.processWebRtcTextMessageEvent.bind(this))}webRtcTextMessageEventToMessageStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,role:e.role,endOfSpeech:e.end_of_speech,interrupted:e.interrupted}}processUserMessage(e){const n={id:e.id,content:e.content,role:e.role};this.messages.push(n)}processPersonaMessage(e){const n={id:e.id,content:e.content,role:e.role,interrupted:e.interrupted},o=this.messages.findIndex(u=>u.id===n.id);if(o!==-1){const u=this.messages[o];this.messages[o]=Object.assign(Object.assign({},u),{content:u.content+n.content,interrupted:u.interrupted||n.interrupted})}else this.messages.push(n)}processWebRtcTextMessageEvent(e){const n=this.webRtcTextMessageEventToMessageStreamEvent(e);switch(this.publicEventEmitter.emit(R.MESSAGE_STREAM_EVENT_RECEIVED,n),n.role){case tt.USER:this.processUserMessage(n);break;case tt.PERSONA:this.processPersonaMessage(n);break}n.endOfSpeech&&this.publicEventEmitter.emit(R.MESSAGE_HISTORY_UPDATED,this.messages)}}class jn{constructor(){this.listeners={}}addListener(e,n){this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(n)}removeListener(e,n){this.listeners[e]&&this.listeners[e].delete(n)}emit(e,...n){if(e===R.CONNECTION_ESTABLISHED&&ye(re.CLIENT_METRIC_MEASUREMENT_CONNECTION_ESTABLISHED,"1"),e===R.CONNECTION_CLOSED){const[o,u]=n;ye(re.CLIENT_METRIC_MEASUREMENT_CONNECTION_CLOSED,o,u?{details:u}:void 0)}this.listeners[e]&&this.listeners[e].forEach(o=>{o(...n)})}}var q;(function(t){t[t.UNSTARTED=0]="UNSTARTED",t[t.STREAMING=1]="STREAMING",t[t.INTERRUPTED=2]="INTERRUPTED",t[t.ENDED=3]="ENDED"})(q||(q={}));var At=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Hn{constructor(e,n,o){this.state=q.UNSTARTED,this.correlationId=e,this.internalEventEmitter=n,this.signallingClient=o,this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onDeactivate(){this.internalEventEmitter.removeListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this))}onSignalMessage(e){return At(this,void 0,void 0,function*(){e.actionType===W.TALK_STREAM_INTERRUPTED&&e.payload.correlationId===this.correlationId&&(this.state=q.INTERRUPTED,this.onDeactivate())})}endMessage(){return At(this,void 0,void 0,function*(){if(this.state===q.ENDED){console.warn("Talk stream is already ended via end of speech. No need to call endMessage.");return}if(this.state!==q.STREAMING){console.warn("Talk stream is not active state: "+this.state);return}const e={content:"",startOfSpeech:!1,endOfSpeech:!0,correlationId:this.correlationId};yield this.signallingClient.sendTalkMessage(e),this.state=q.ENDED,this.onDeactivate()})}streamMessageChunk(e,n){return At(this,void 0,void 0,function*(){if(this.state!==q.STREAMING&&this.state!==q.UNSTARTED)throw new Error("Talk stream is not in an active state: "+this.state);const o={content:e,startOfSpeech:this.state===q.UNSTARTED,endOfSpeech:n,correlationId:this.correlationId};this.state=n?q.ENDED:q.STREAMING,this.state===q.ENDED&&this.onDeactivate(),yield this.signallingClient.sendTalkMessage(o)})}getCorrelationId(){return this.correlationId}isActive(){return this.state===q.STREAMING||this.state===q.UNSTARTED}getState(){return this.state}}var X=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};const Wn=15e3,zn=5e3,qn=2;class Yn{constructor(e,n,o,u){var a,c,l,m;this.peerConnection=null,this.connectionReceivedAnswer=!1,this.remoteIceCandidateBuffer=[],this.inputAudioStream=null,this.dataChannel=null,this.videoElement=null,this.videoStream=null,this.audioStream=null,this.inputAudioState={isMuted:!1,permissionState:fe.NOT_REQUESTED},this.successMetricPoller=null,this.successMetricFired=!1,this.showPeerConnectionStatsReport=!1,this.peerConnectionStatsReportOutputFormat="console",this.statsCollectionInterval=null,this.agentAudioInputStream=null,this.publicEventEmitter=o,this.internalEventEmitter=u,this.apiGatewayConfig=n.apiGateway;const{inputAudio:p}=n;this.inputAudioState=p.inputAudioState,n.inputAudio.userProvidedMediaStream&&(this.inputAudioStream=n.inputAudio.userProvidedMediaStream),this.disableInputAudio=n.inputAudio.disableInputAudio===!0,this.internalEventEmitter.addListener(J.WEB_SOCKET_OPEN,this.onSignallingClientConnected.bind(this)),this.internalEventEmitter.addListener(J.SIGNAL_MESSAGE_RECEIVED,this.onSignalMessage.bind(this)),this.iceServers=n.iceServers,this.signallingClient=new Ln(e,n.signalling,this.publicEventEmitter,this.internalEventEmitter,this.apiGatewayConfig),this.engineApiRestClient=new $n(n.engine.baseUrl,e,this.apiGatewayConfig),this.audioDeviceId=n.inputAudio.audioDeviceId,this.showPeerConnectionStatsReport=(c=(a=n.metrics)===null||a===void 0?void 0:a.showPeerConnectionStatsReport)!==null&&c!==void 0?c:!1,this.peerConnectionStatsReportOutputFormat=(m=(l=n.metrics)===null||l===void 0?void 0:l.peerConnectionStatsReportOutputFormat)!==null&&m!==void 0?m:"console"}onInputAudioStateChange(e,n){e.isMuted!==n.isMuted&&(n.isMuted?this.muteAllAudioTracks():this.unmuteAllAudioTracks())}muteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!1})}unmuteAllAudioTracks(){var e;(e=this.inputAudioStream)===null||e===void 0||e.getAudioTracks().forEach(n=>{n.enabled=!0})}startStatsCollection(){this.statsCollectionInterval||(this.statsCollectionInterval=setInterval(()=>X(this,void 0,void 0,function*(){if(!(!this.peerConnection||!this.dataChannel||this.dataChannel.readyState!=="open"))try{const e=yield this.peerConnection.getStats();this.sendClientSideMetrics(e)}catch(e){console.error("Failed to collect and send stats:",e)}}),zn))}sendClientSideMetrics(e){e.forEach(n=>{if(n.type==="inbound-rtp"){const o={message_type:"remote_rtp_stats",data:n};this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(JSON.stringify(o))}})}startSuccessMetricPolling(){if(this.successMetricPoller||this.successMetricFired)return;const e=setTimeout(()=>{this.successMetricPoller&&(console.warn("No video frames received, there is a problem with the connection."),clearInterval(this.successMetricPoller),this.successMetricPoller=null)},Wn);this.successMetricPoller=setInterval(()=>X(this,void 0,void 0,function*(){if(!this.peerConnection||this.successMetricFired){this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e);return}try{const n=yield this.peerConnection.getStats();let o=!1,u=null;n.forEach(a=>{a.type==="inbound-rtp"&&a.kind==="video"&&(a.framesDecoded!==void 0&&a.framesDecoded>0?(o=!0,u="framesDecoded"):a.framesReceived!==void 0&&a.framesReceived>0?(o=!0,u="framesReceived"):a.bytesReceived>0&&a.packetsReceived>0&&a.bytesReceived>1e5&&(o=!0,u="bytesReceived"))}),o&&!this.successMetricFired&&(this.successMetricFired=!0,ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",u?{detectionMethod:u}:void 0),this.successMetricPoller&&clearInterval(this.successMetricPoller),clearTimeout(e),this.successMetricPoller=null)}catch{}}),500)}muteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}unmuteInputAudio(){const e=this.inputAudioState,n=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1});return this.inputAudioState=n,this.onInputAudioStateChange(e,n),this.inputAudioState}getInputAudioState(){return this.inputAudioState}getPeerConnection(){return this.peerConnection}changeAudioInputDevice(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - changeAudioInputDevice: peer connection is not initialized. Start streaming first.");if(e==null)throw new Error("StreamingClient - changeAudioInputDevice: deviceId is required");const n=this.inputAudioState.isMuted;try{this.inputAudioStream&&this.inputAudioStream.getAudioTracks().forEach(u=>{u.stop()});const o={echoCancellation:!0,deviceId:{exact:e}};this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:o}),this.audioDeviceId=e,yield this.setupAudioTrack(),n&&this.muteAllAudioTracks(),this.publicEventEmitter.emit(R.INPUT_AUDIO_DEVICE_CHANGED,e)}catch(o){throw console.error("Failed to change audio input device:",o),new Error(`StreamingClient - changeAudioInputDevice: ${o instanceof Error?o.message:String(o)}`)}})}getInputAudioStream(){return this.inputAudioStream}getVideoStream(){return this.videoStream}getAudioStream(){return this.audioStream}sendDataMessage(e){this.dataChannel&&this.dataChannel.readyState==="open"&&this.dataChannel.send(e)}setMediaStreamTargetById(e){if(e){const n=document.getElementById(e);if(!n)throw new Error(`StreamingClient: video element with id ${e} not found`);this.videoElement=n}}startConnection(){try{if(this.peerConnection){console.error("StreamingClient - startConnection: peer connection already exists");return}this.signallingClient.connect()}catch(e){console.error("StreamingClient - startConnection: error",e),this.handleWebrtcFailure(e)}}stopConnection(){return X(this,void 0,void 0,function*(){yield this.shutdown()})}sendTalkCommand(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection)throw new Error("StreamingClient - sendTalkCommand: peer connection is null");yield this.engineApiRestClient.sendTalkCommand(e)})}startTalkMessageStream(e){return e||(e=Math.random().toString(36).substring(2,15)),new Hn(e,this.internalEventEmitter,this.signallingClient)}createAgentAudioInputStream(e){return this.agentAudioInputStream=new Dn(e,this.signallingClient),this.agentAudioInputStream}getAgentAudioInputStream(){return this.agentAudioInputStream}initPeerConnection(){return X(this,void 0,void 0,function*(){this.peerConnection=new RTCPeerConnection({iceServers:this.iceServers,iceCandidatePoolSize:qn}),this.peerConnection.onicecandidate=this.onIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onIceConnectionStateChange.bind(this),this.peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this.peerConnection.addEventListener("track",this.onTrackEventHandler.bind(this)),yield this.setupDataChannels(),this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.disableInputAudio?this.peerConnection.addTransceiver("audio",{direction:"recvonly"}):(this.peerConnection.addTransceiver("audio",{direction:"sendrecv"}),this.inputAudioStream?yield this.setupAudioTrack():this.requestMicrophonePermissionAsync().catch(e=>{console.error("Async microphone permission request failed:",e)}))})}onSignalMessage(e){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - onSignalMessage: peerConnection is not initialized");return}switch(e.actionType){case W.ANSWER:const n=e.payload;yield this.peerConnection.setRemoteDescription(n),this.connectionReceivedAnswer=!0,this.flushRemoteIceCandidateBuffer();break;case W.ICE_CANDIDATE:const o=e.payload,u=new RTCIceCandidate(o);this.connectionReceivedAnswer?yield this.peerConnection.addIceCandidate(u):this.remoteIceCandidateBuffer.push(u);break;case W.END_SESSION:const a=e.payload;this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.SERVER_CLOSED_CONNECTION,a),this.shutdown();break;case W.WARNING:const c=e.payload;console.warn("Warning received from server: "+c),this.publicEventEmitter.emit(R.SERVER_WARNING,c);break;case W.TALK_STREAM_INTERRUPTED:const l=e.payload;this.publicEventEmitter.emit(R.TALK_STREAM_INTERRUPTED,l.correlationId);break;case W.SESSION_READY:const m=e.sessionId;this.publicEventEmitter.emit(R.SESSION_READY,m);break;case W.HEARTBEAT:break;default:console.warn("StreamingClient - onSignalMessage: unknown signal message action type. Is your anam-sdk version up to date?",e)}})}onSignallingClientConnected(){return X(this,void 0,void 0,function*(){if(!this.peerConnection)try{yield this.initPeerConnectionAndSendOffer()}catch(e){console.error("StreamingClient - onSignallingClientConnected: Error initializing peer connection",e),this.handleWebrtcFailure(e)}})}flushRemoteIceCandidateBuffer(){this.remoteIceCandidateBuffer.forEach(e=>{var n;(n=this.peerConnection)===null||n===void 0||n.addIceCandidate(e)}),this.remoteIceCandidateBuffer=[]}onIceCandidate(e){e.candidate&&this.signallingClient.sendIceCandidate(e.candidate)}onIceConnectionStateChange(){var e,n;(((e=this.peerConnection)===null||e===void 0?void 0:e.iceConnectionState)==="connected"||((n=this.peerConnection)===null||n===void 0?void 0:n.iceConnectionState)==="completed")&&(this.publicEventEmitter.emit(R.CONNECTION_ESTABLISHED),this.startStatsCollection())}onConnectionStateChange(){var e;((e=this.peerConnection)===null||e===void 0?void 0:e.connectionState)==="closed"&&(console.error("StreamingClient - onConnectionStateChange: Connection closed"),this.handleWebrtcFailure("The connection to our servers was lost. Please try again."))}handleWebrtcFailure(e){console.error({message:"StreamingClient - handleWebrtcFailure: ",err:e}),e.name==="NotAllowedError"&&e.message==="Permission denied"?this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.MICROPHONE_PERMISSION_DENIED):this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.WEBRTC_FAILURE);try{this.stopConnection()}catch(n){console.error("StreamingClient - handleWebrtcFailure: error stopping connection",n)}}onTrackEventHandler(e){if(e.track.kind==="video"){if(this.startSuccessMetricPolling(),this.videoStream=e.streams[0],this.publicEventEmitter.emit(R.VIDEO_STREAM_STARTED,this.videoStream),this.videoElement){this.videoElement.srcObject=this.videoStream;const n=this.videoElement.requestVideoFrameCallback(()=>{var o;(o=this.videoElement)===null||o===void 0||o.cancelVideoFrameCallback(n),this.publicEventEmitter.emit(R.VIDEO_PLAY_STARTED),this.successMetricFired||(this.successMetricFired=!0,ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_SUCCESS,"1",{detectionMethod:"videoElement"}))})}}else e.track.kind==="audio"&&(this.audioStream=e.streams[0],this.publicEventEmitter.emit(R.AUDIO_STREAM_STARTED,this.audioStream))}setupDataChannels(){return X(this,void 0,void 0,function*(){if(!this.peerConnection){console.error("StreamingClient - setupDataChannels: peer connection is not initialized");return}if(!this.disableInputAudio&&this.inputAudioStream&&!this.inputAudioStream.getAudioTracks().length)throw new Error("StreamingClient - setupDataChannels: user provided stream does not have audio tracks");const e=this.peerConnection.createDataChannel("session",{ordered:!0});e.onopen=()=>{this.dataChannel=e??null},e.onclose=()=>{},e.onmessage=n=>{try{const o=JSON.parse(n.data);switch(o.messageType){case Pe.SPEECH_TEXT:this.internalEventEmitter.emit(J.WEBRTC_CHAT_MESSAGE_RECEIVED,o.data);break;case Pe.CLIENT_TOOL_EVENT:const u=o.data;this.internalEventEmitter.emit(J.WEBRTC_CLIENT_TOOL_EVENT_RECEIVED,u);const a=Kn.WebRTCClientToolEventToClientToolEvent(u);this.publicEventEmitter.emit(R.CLIENT_TOOL_EVENT_RECEIVED,a);break;case Pe.REASONING_TEXT:this.internalEventEmitter.emit(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,o.data);break;default:break}}catch(o){console.error("Failed to parse data channel message:",o)}}})}requestMicrophonePermissionAsync(){return X(this,void 0,void 0,function*(){if(this.inputAudioState.permissionState!==fe.PENDING){this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.PENDING}),this.publicEventEmitter.emit(R.MIC_PERMISSION_PENDING);try{const e={echoCancellation:!0};this.audioDeviceId&&(e.deviceId={exact:this.audioDeviceId}),this.inputAudioStream=yield navigator.mediaDevices.getUserMedia({audio:e}),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.GRANTED}),this.publicEventEmitter.emit(R.MIC_PERMISSION_GRANTED),yield this.setupAudioTrack()}catch(e){console.error("Failed to get microphone permission:",e),this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{permissionState:fe.DENIED});const n=e instanceof Error?e.message:String(e);this.publicEventEmitter.emit(R.MIC_PERMISSION_DENIED,n)}}})}setupAudioTrack(){return X(this,void 0,void 0,function*(){if(!this.peerConnection||!this.inputAudioStream)return;if(!this.inputAudioStream.getAudioTracks().length){console.error("StreamingClient - setupAudioTrack: stream does not have audio tracks");return}this.inputAudioState.isMuted&&this.muteAllAudioTracks();const e=this.inputAudioStream.getAudioTracks()[0],o=this.peerConnection.getSenders().find(u=>{var a;return((a=u.track)===null||a===void 0?void 0:a.kind)==="audio"||u.track===null&&u.dtmf!==null});if(o)try{yield o.replaceTrack(e)}catch(u){console.error("Failed to replace audio track:",u),this.peerConnection.addTrack(e,this.inputAudioStream)}else this.peerConnection.addTrack(e,this.inputAudioStream);this.publicEventEmitter.emit(R.INPUT_AUDIO_STREAM_STARTED,this.inputAudioStream)})}initPeerConnectionAndSendOffer(){return X(this,void 0,void 0,function*(){if(yield this.initPeerConnection(),!this.peerConnection){console.error("StreamingClient - initPeerConnectionAndSendOffer: peer connection is not initialized");return}try{const e=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(e)}catch(e){console.error("StreamingClient - initPeerConnectionAndSendOffer: error creating offer",e)}if(!this.peerConnection.localDescription)throw new Error("StreamingClient - initPeerConnectionAndSendOffer: local description is null");yield this.signallingClient.sendOffer(this.peerConnection.localDescription)})}shutdown(){return X(this,void 0,void 0,function*(){var e;if(this.showPeerConnectionStatsReport){const n=yield(e=this.peerConnection)===null||e===void 0?void 0:e.getStats();if(n){const o=On(n,this.peerConnectionStatsReportOutputFormat);o&&console.log(o,void 0,2)}}this.statsCollectionInterval&&(clearInterval(this.statsCollectionInterval),this.statsCollectionInterval=null),this.successMetricPoller&&(clearInterval(this.successMetricPoller),this.successMetricPoller=null),this.successMetricFired=!1;try{this.inputAudioStream&&this.inputAudioStream.getTracks().forEach(n=>{n.stop()}),this.inputAudioStream=null}catch(n){console.error("StreamingClient - shutdown: error stopping input audio stream",n)}try{this.signallingClient.stop()}catch(n){console.error("StreamingClient - shutdown: error stopping signallilng",n)}try{this.peerConnection&&this.peerConnection.connectionState!=="closed"&&(this.peerConnection.onconnectionstatechange=null,this.peerConnection.close(),this.peerConnection=null)}catch(n){console.error("StreamingClient - shutdown: error closing peer connection",n)}})}}class Kn{static WebRTCClientToolEventToClientToolEvent(e){return{eventUid:e.event_uid,sessionId:e.session_id,eventName:e.event_name,eventData:e.event_data,timestamp:e.timestamp,timestampUserAction:e.timestamp_user_action,userActionCorrelationId:e.user_action_correlation_id}}}class Jn{constructor(e,n){this.reasoning_messages=[],this.publicEventEmitter=e,this.internalEventEmitter=n,this.internalEventEmitter.addListener(J.WEBRTC_REASONING_TEXT_MESSAGE_RECEIVED,this.processWebRtcReasoningTextMessageEvent.bind(this))}webRtcTextMessageEventToReasoningStreamEvent(e){return{id:`${e.role}::${e.message_id}`,content:e.content,endOfThought:e.end_of_thought,role:e.role}}processWebRtcReasoningTextMessageEvent(e){const n=this.webRtcTextMessageEventToReasoningStreamEvent(e);this.publicEventEmitter.emit(R.REASONING_STREAM_EVENT_RECEIVED,n);const o={id:n.id,content:n.content,role:n.role},u=this.reasoning_messages.findIndex(a=>a.id===o.id);if(u!==-1){const a=this.reasoning_messages[u];a.content+=o.content,this.reasoning_messages[u]=a}else this.reasoning_messages.push(o);n.endOfThought&&this.publicEventEmitter.emit(R.REASONING_HISTORY_UPDATED,this.reasoning_messages)}}var _e=function(t,e,n,o){function u(a){return a instanceof n?a:new n(function(c){c(a)})}return new(n||(n=Promise))(function(a,c){function l(_){try{p(o.next(_))}catch(d){c(d)}}function m(_){try{p(o.throw(_))}catch(d){c(d)}}function p(_){_.done?a(_.value):u(_.value).then(l,m)}p((o=o.apply(t,e||[])).next())})};class Xn{constructor(e,n,o){var u,a,c,l,m;this.inputAudioState={isMuted:!1,permissionState:fe.NOT_REQUESTED},this.sessionId=null,this.organizationId=null,this.streamingClient=null,this._isStreaming=!1;const p=this.validateClientConfig(e,n,o);if(p)throw new $(p,H.CLIENT_ERROR_CODE_CONFIGURATION_ERROR,400);this.personaConfig=n,this.clientOptions=o,(!((u=o?.api)===null||u===void 0)&&u.baseUrl||!((a=o?.api)===null||a===void 0)&&a.apiVersion)&&Rn(o.api.baseUrl||Di,o.api.apiVersion||It),!((l=(c=o?.api)===null||c===void 0?void 0:c.apiGateway)===null||l===void 0)&&l.enabled&&Nn(o.api.apiGateway),!((m=o?.metrics)===null||m===void 0)&&m.disableClientMetrics&&xn(!0),this.publicEventEmitter=new jn,this.internalEventEmitter=new Vn,this.apiClient=new Pn(e,o?.apiKey,o?.api),this.messageHistoryClient=new Gn(this.publicEventEmitter,this.internalEventEmitter),this.reasoningHistoryClient=new Jn(this.publicEventEmitter,this.internalEventEmitter)}decodeJwt(e){try{const n=e.split(".")[1],o=In.Buffer.from(n,"base64").toString("utf8");return JSON.parse(o)}catch{throw new Error("Invalid session token format")}}validateClientConfig(e,n,o){var u,a;if(!e&&!o?.apiKey)return"Either sessionToken or apiKey must be provided";if(o?.apiKey&&e)return"Only one of sessionToken or apiKey should be used";const c=kn((u=o?.api)===null||u===void 0?void 0:u.apiGateway);if(c)return c;if(e){const l=this.decodeJwt(e);this.organizationId=l.accountId,Ae({organizationId:this.organizationId});const m=(a=l.type)===null||a===void 0?void 0:a.toLowerCase();if(m==="legacy")return"Legacy session tokens are no longer supported. Please define your persona when creating your session token. See https://docs.anam.ai/resources/migrating-legacy for more information.";if((m==="ephemeral"||m==="stateful")&&n)return"This session token already contains a persona configuration. Please remove the personaConfig parameter."}else if(!n)return"Missing persona config. Persona configuration must be provided when using apiKey";if(o?.voiceDetection){if(o.disableInputAudio)return"Voice detection is disabled because input audio is disabled. Please set disableInputAudio to false to enable voice detection.";if(o.voiceDetection.endOfSpeechSensitivity!==void 0){if(typeof o.voiceDetection.endOfSpeechSensitivity!="number")return"End of speech sensitivity must be a number";if(o.voiceDetection.endOfSpeechSensitivity<0||o.voiceDetection.endOfSpeechSensitivity>1)return"End of speech sensitivity must be between 0 and 1"}}}buildStartSessionOptionsForClient(){var e;const n={};if(!((e=this.clientOptions)===null||e===void 0)&&e.voiceDetection&&(n.voiceDetection=this.clientOptions.voiceDetection),Object.keys(n).length!==0)return n}startSession(e){return _e(this,void 0,void 0,function*(){var n,o,u,a,c,l,m,p,_,d,S,g;const y=this.personaConfig,C=this.buildStartSessionOptionsForClient(),A=yield this.apiClient.startSession(y,C),{sessionId:I,clientConfig:b,engineHost:N,engineProtocol:M,signallingEndpoint:k}=A,{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:oe,iceServers:V}=b;this.sessionId=I,Ae({sessionId:this.sessionId});const se=!((n=this.clientOptions)===null||n===void 0)&&n.iceServers?this.clientOptions.iceServers:V;try{this.streamingClient=new Yn(I,{engine:{baseUrl:`${M}://${N}`},signalling:{heartbeatIntervalSeconds:Y,maxWsReconnectionAttempts:oe,url:{baseUrl:N,protocol:M,signallingPath:k}},iceServers:se,inputAudio:{inputAudioState:this.inputAudioState,userProvidedMediaStream:!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio?void 0:e,audioDeviceId:(u=this.clientOptions)===null||u===void 0?void 0:u.audioDeviceId,disableInputAudio:(a=this.clientOptions)===null||a===void 0?void 0:a.disableInputAudio},apiGateway:(l=(c=this.clientOptions)===null||c===void 0?void 0:c.api)===null||l===void 0?void 0:l.apiGateway,metrics:{showPeerConnectionStatsReport:(_=(p=(m=this.clientOptions)===null||m===void 0?void 0:m.metrics)===null||p===void 0?void 0:p.showPeerConnectionStatsReport)!==null&&_!==void 0?_:!1,peerConnectionStatsReportOutputFormat:(g=(S=(d=this.clientOptions)===null||d===void 0?void 0:d.metrics)===null||S===void 0?void 0:S.peerConnectionStatsReportOutputFormat)!==null&&g!==void 0?g:"console"}},this.publicEventEmitter,this.internalEventEmitter)}catch(ae){throw Ae({sessionId:null}),new $("Failed to initialize streaming client",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:ae instanceof Error?ae.message:String(ae),sessionId:I})}return I})}startSessionIfNeeded(e){return _e(this,void 0,void 0,function*(){if((!this.sessionId||!this.streamingClient)&&(yield this.startSession(e),!this.sessionId||!this.streamingClient))throw new $("Session ID or streaming client is not available after starting session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:"Failed to initialize session properly"})})}stream(e){return _e(this,void 0,void 0,function*(){var n;if(this._isStreaming)throw new Error("Already streaming");const o=Li();return Ae({attemptCorrelationId:o,sessionId:null}),ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio&&e&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored."),yield this.startSessionIfNeeded(e),this._isStreaming=!0,new Promise(u=>{var a;const c=[];let l=!1,m=!1;this.publicEventEmitter.addListener(R.VIDEO_STREAM_STARTED,p=>{c.push(p),l=!0,m&&u(c)}),this.publicEventEmitter.addListener(R.AUDIO_STREAM_STARTED,p=>{c.push(p),m=!0,l&&u(c)}),(a=this.streamingClient)===null||a===void 0||a.startConnection()})})}streamToVideoAndAudioElements(e,n,o){return _e(this,void 0,void 0,function*(){console.warn("AnamClient: streamToVideoAndAudioElements is deprecated. To avoid possible audio issues, please use streamToVideoElement instead."),yield this.streamToVideoElement(e,o)})}streamToVideoElement(e,n){return _e(this,void 0,void 0,function*(){var o;const u=Li();Ae({attemptCorrelationId:u,sessionId:null}),ye(re.CLIENT_METRIC_MEASUREMENT_SESSION_ATTEMPT,"1"),!((o=this.clientOptions)===null||o===void 0)&&o.disableInputAudio&&n&&console.warn("AnamClient:Input audio is disabled. User provided audio stream will be ignored.");try{yield this.startSessionIfNeeded(n)}catch(a){throw a instanceof $?a:new $("Failed to start session",H.CLIENT_ERROR_CODE_SERVER_ERROR,500,{cause:a instanceof Error?a.message:String(a),sessionId:this.sessionId})}if(this._isStreaming)throw new Error("Already streaming");if(this._isStreaming=!0,!this.streamingClient)throw new Error("Failed to stream: streaming client is not available");this.streamingClient.setMediaStreamTargetById(e),this.streamingClient.startConnection()})}talk(e){return _e(this,void 0,void 0,function*(){if(!this.streamingClient)throw new Error("Failed to send talk command: session is not started. Have you called startSession?");if(!this._isStreaming)throw new Error("Failed to send talk command: not currently streaming. Have you called stream?");yield this.streamingClient.sendTalkCommand(e)})}sendDataMessage(e){if(this.streamingClient)this.streamingClient.sendDataMessage(e);else throw new Error("Failed to send message: session is not started.")}sendUserMessage(e){if(!this._isStreaming)throw console.warn("AnamClient: Not currently streaming. User message will not be sent."),new Error("Failed to send user message: not currently streaming");const n=this.getActiveSessionId();if(!n)throw new Error("Failed to send user message: no active session");const o=new Date().toISOString().replace("Z",""),u=JSON.stringify({content:e,timestamp:o,session_id:n,message_type:"speech"});this.sendDataMessage(u)}interruptPersona(){if(!this._isStreaming)throw new Error("Failed to send interrupt command: not currently streaming");const e=this.getActiveSessionId();if(!e)throw new Error("Failed to send interrupt command: no active session");const n=JSON.stringify({message_type:"interrupt",session_id:e,timestamp:new Date().toISOString()});this.sendDataMessage(n)}stopStreaming(){return _e(this,void 0,void 0,function*(){this.streamingClient&&(this.publicEventEmitter.emit(R.CONNECTION_CLOSED,pe.NORMAL),yield this.streamingClient.stopConnection(),this.streamingClient=null,this.sessionId=null,Ae({attemptCorrelationId:null,sessionId:null,organizationId:this.organizationId}),this._isStreaming=!1)})}isStreaming(){return this._isStreaming}setPersonaConfig(e){this.personaConfig=e}getPersonaConfig(){return this.personaConfig}getInputAudioState(){var e;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Audio state will not be used because input audio is disabled."),this.streamingClient&&(this.inputAudioState=this.streamingClient.getInputAudioState()),this.inputAudioState}muteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Muting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.muteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!0}),this.inputAudioState}unmuteInputAudio(){var e,n;return!((e=this.clientOptions)===null||e===void 0)&&e.disableInputAudio&&console.warn("AnamClient: Input audio is disabled. Unmuting input audio will have no effect."),this.streamingClient&&!(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)?this.inputAudioState=this.streamingClient.unmuteInputAudio():this.inputAudioState=Object.assign(Object.assign({},this.inputAudioState),{isMuted:!1}),this.inputAudioState}changeAudioInputDevice(e){return _e(this,void 0,void 0,function*(){var n;if(!((n=this.clientOptions)===null||n===void 0)&&n.disableInputAudio)throw new Error("AnamClient: Cannot change audio input device because input audio is disabled.");if(!this._isStreaming)throw new Error("AnamClient: Cannot change audio input device while not streaming. Start streaming first.");if(!this.streamingClient)throw new Error("AnamClient: Cannot change audio input device because streaming client is not available. Start streaming first.");yield this.streamingClient.changeAudioInputDevice(e)})}createTalkMessageStream(e){if(!this.streamingClient)throw new Error("Failed to start talk message stream: session is not started.");if(e&&e.trim()==="")throw new Error("Failed to start talk message stream: correlationId is empty");return this.streamingClient.startTalkMessageStream(e)}createAgentAudioInputStream(e){if(!this.streamingClient)throw new Error("Failed to create agent audio input stream: session is not started.");return this.streamingClient.createAgentAudioInputStream(e)}addListener(e,n){this.publicEventEmitter.addListener(e,n)}removeListener(e,n){this.publicEventEmitter.removeListener(e,n)}getActiveSessionId(){return this.sessionId}}const Zn=(t,e)=>new Xn(t,void 0,e),Qn="https://api.anam.ai";function er(t){try{const e=t.split(".")[1];return JSON.parse(atob(e))}catch{return{}}}const Z=z(null),te=z("idle"),Fe=z(!1),it=z(!1),nt=z([]),$e=z(null),rt=z(null),Tt=z(null),Rt=z(null),Nt=z(null),xt=z(null),Pi=z(!1),ot=z(!1);function tr(t,e){return e===401||e===403?"This agent is not authorized. Check your agent ID.":e===404?"Agent not found. Check your agent ID.":e===429?"Too many requests. Please wait a moment.":e&&e>=500?"Server error. Please try again later.":t instanceof TypeError&&t.message==="Failed to fetch"?"Unable to connect. Check your network connection.":t instanceof Error&&t.message.length<80?t.message:"Something went wrong. Please try again."}async function ir(t,e){ot.value=!1;try{const n=await fetch(`${e}/v1/personas/${t}/widget`);if(!n.ok)return;const o=await n.json();Tt.value=o.persona?.avatarImageUrl||null,Rt.value=o.persona?.avatarVideoUrl||null,Nt.value=o.persona?.name||null,xt.value=o.widgetConfig||null}catch{}finally{ot.value=!0}}async function nr(t,e,n,o){if(te.value==="connecting"||te.value==="connected")return;te.value="connecting",$e.value=null;let u;try{let a;if(o)console.log("[AnamWidget] Using pre-created session token"),a=o;else{console.log("[AnamWidget] Fetching session for agent:",t);const m=await fetch(`${e}/v1/auth/widget`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:t})});if(u=m.status,!m.ok){const _=await m.json().catch(()=>({}));throw new Error(_.error||`HTTP ${m.status}`)}const p=await m.json();console.log("[AnamWidget] Got session from agent-id:",{hasToken:!!p.sessionToken}),a=p.sessionToken}const c=Zn(a,{api:e?{baseUrl:e}:void 0,metrics:{disableClientMetrics:!0}});c.addListener(R.CONNECTION_ESTABLISHED,()=>{console.log("[AnamWidget] Connection established"),te.value="connected"}),c.addListener(R.VIDEO_STREAM_STARTED,()=>{console.log("[AnamWidget] Video stream started"),Fe.value=!0}),c.addListener(R.AUDIO_STREAM_STARTED,()=>{console.log("[AnamWidget] Audio stream started")}),c.addListener(R.MESSAGE_HISTORY_UPDATED,m=>{nt.value=[...m]}),c.addListener(R.CONNECTION_CLOSED,(m,p)=>{console.log("[AnamWidget] Connection closed:",m,p),te.value="idle",Fe.value=!1,rt.value=null}),c.addListener(R.SESSION_READY,m=>{console.log("[AnamWidget] Session ready:",m),rt.value=m}),Z.value=c;const l=await c.stream();if(n&&l.length>0){const m=l.find(p=>p.getVideoTracks().length>0);m&&(n.srcObject=m)}}catch(a){console.error("[AnamWidget] Failed to start session:",a),$e.value=tr(a,u),te.value="error",Z.value=null}}async function rr(){if(Z.value)try{await Z.value.stopStreaming()}catch(t){console.error("[AnamWidget] Failed to stop session:",t)}Z.value=null,te.value="idle",Fe.value=!1,nt.value=[]}function or(t){!Z.value||te.value!=="connected"||Z.value.sendUserMessage(t)}function sr(){Z.value&&(it.value?(Z.value.unmuteInputAudio(),it.value=!1):(Z.value.muteInputAudio(),it.value=!0))}function ar(){Z.value?.isStreaming()&&Z.value.stopStreaming(),Z.value=null,te.value="idle",Fe.value=!1,nt.value=[],$e.value=null,rt.value=null,Tt.value=null,Rt.value=null,Nt.value=null,xt.value=null}function lr(t,e,n){const o=t||(n?er(n).personaId:void 0);Pi.value=!!o||!!n;const u=e||Qn;return{connectionStatus:te,isStreaming:Fe,isMuted:it,messages:nt,error:$e,sessionId:rt,isConfigured:Pi,isReady:ot,avatarThumbnailUrl:Tt,avatarVideoUrl:Rt,personaName:Nt,serverConfig:xt,fetchWidgetConfig:()=>{if(!o){ot.value=!0;return}ir(o,u)},startSession:l=>!o&&!n?($e.value="No agent ID or session token configured",Promise.resolve()):nr(o||"",u,l,n),stopSession:rr,sendMessage:or,toggleMute:sr,cleanup:ar}}const Fi='@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-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--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;--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%;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}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-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 components;@layer utilities{.visible{visibility:visible}.block{display:block}.flex{display:flex}.inline{display:inline}.flex-shrink{flex-shrink:1}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.border{border-style:var(--tw-border-style);border-width:1px}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.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,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))}}:host{--anam-trigger-size:80px;--anam-sheet-width:400px;--anam-sheet-height:640px;all:initial;color:#18181b;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:DM Sans,system-ui,-apple-system,sans-serif;font-size:15px;line-height:1.5}@media(max-width:640px){:host{--anam-trigger-size:72px;--anam-sheet-width: calc(100vw - 24px) ;--anam-sheet-height: calc(100dvh - 100px) }}.anam-widget{z-index:9999;font-family:inherit}.anam-widget[data-layout=floating]{position:fixed}.anam-widget[data-layout=inline]{position:relative}.anam-trigger{width:var(--anam-trigger-size);height:var(--anam-trigger-size);cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;padding:0;transition:all .25s cubic-bezier(.4,0,.2,1);display:flex;overflow:hidden;box-shadow:0 2px 8px #00000014,0 8px 24px -4px #0000002e}.anam-trigger:hover{transform:scale(1.06);box-shadow:0 4px 12px #0000001a,0 12px 32px -4px #00000040}.anam-trigger:active{transform:scale(.97)}.anam-trigger img{object-fit:cover;width:100%;height:100%;display:block}.anam-sheet{width:var(--anam-sheet-width);aspect-ratio:16/10;max-height:var(--anam-sheet-height);border-radius:8px;animation:.25s cubic-bezier(.16,1,.3,1) sheetIn;position:relative;overflow:hidden;box-shadow:0 32px 64px -16px #00000040,0 0 0 1px #00000014}.anam-widget[data-layout=inline] .anam-sheet{aspect-ratio:3/2;border-radius:8px;width:100%;max-height:none;animation:none}@keyframes sheetIn{0%{opacity:0;transform:translateY(8px)scale(.97)}to{opacity:1;transform:translateY(0)scale(1)}}.anam-video{object-fit:cover;background:#000;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-video[data-hidden=true]{visibility:hidden}.anam-overlay-idle{z-index:2;position:absolute;inset:0}.anam-overlay-idle img{object-fit:cover;width:100%;height:100%;display:block}.anam-preview-video{object-fit:cover;z-index:1;width:100%;height:100%;display:block;position:absolute;inset:0}.anam-preview-fallback{z-index:0;position:absolute;inset:0}.anam-cta-pill{z-index:2;-webkit-backdrop-filter:blur(8px);color:#fff;letter-spacing:-.01em;cursor:pointer;white-space:nowrap;background:#ffffff24;border:1px solid #ffffff38;border-radius:999px;align-items:center;gap:12px;min-width:200px;padding:12px 26px;font-family:inherit;font-size:16px;font-weight:600;transition:all .2s;display:flex;position:absolute;bottom:20px;left:50%;transform:translate(-50%)}.anam-cta-pill:hover{background:#ffffff38;transform:translate(-50%)scale(1.03)}.anam-cta-pill:active{transform:translate(-50%)scale(.98)}.anam-cta-pill svg{flex-shrink:0}.anam-overlay-unconfigured{z-index:2;background:#111;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-unconfigured span{color:#ffffff59;letter-spacing:-.01em;font-size:14px;font-weight:400}.anam-overlay-loading{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:20px;display:flex;position:absolute;inset:0}.anam-overlay-loading span{color:#fffc;letter-spacing:-.01em;font-size:15px;font-weight:400}.anam-overlay-error{z-index:3;background:#000;flex-direction:column;justify-content:center;align-items:center;gap:16px;display:flex;position:absolute;inset:0}.anam-overlay-error-text{color:#fff9;text-align:center;max-width:260px;font-size:14px;line-height:1.5}.anam-overlay-error .anam-retry-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff1f;border:1px solid #ffffff1a;border-radius:999px;padding:10px 24px;font-family:inherit;font-size:14px;font-weight:500;transition:background .15s}.anam-overlay-error .anam-retry-btn:hover{background:#fff3}.anam-spinner{border:2.5px solid #ffffff1f;border-top-color:#fff;border-radius:50%;width:32px;height:32px;animation:.75s linear infinite spin}@keyframes spin{to{transform:rotate(360deg)}}.anam-close-btn{z-index:10;-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#00000073;border:1px solid #ffffff38;border-radius:50%;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex;position:absolute;top:12px;right:12px}.anam-close-btn:hover{background:#0009}.anam-toast{z-index:10;-webkit-backdrop-filter:blur(16px);color:#fff;letter-spacing:-.01em;white-space:nowrap;text-overflow:ellipsis;pointer-events:none;background:#0009;border:1px solid #ffffff0f;border-radius:999px;max-width:85%;padding:10px 22px;font-size:14px;font-weight:400;animation:.25s cubic-bezier(.16,1,.3,1) toastIn;position:absolute;bottom:80px;left:50%;overflow:hidden;transform:translate(-50%)}.anam-toast-out{animation:.4s forwards toastOut}@keyframes toastIn{0%{opacity:0;transform:translate(-50%)translateY(6px)}to{opacity:1;transform:translate(-50%)translateY(0)}}@keyframes toastOut{0%{opacity:1}to{opacity:0}}.anam-control-bar{z-index:10;background:linear-gradient(#0000,#00000040 40%,#0000008c);justify-content:center;align-items:center;gap:8px;padding:48px 16px 16px;display:flex;position:absolute;bottom:0;left:0;right:0}.anam-ctl-btn{-webkit-backdrop-filter:blur(8px);color:#fff;cursor:pointer;background:#ffffff24;border:1px solid #ffffff38;border-radius:50%;flex-shrink:0;justify-content:center;align-items:center;width:44px;height:44px;padding:0;transition:background .15s;display:flex}.anam-ctl-btn:hover{background:#ffffff38}.anam-ctl-btn:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-input-wrap{flex:1;align-items:center;min-width:0;margin-right:56px;display:flex;position:relative}.anam-ctl-input{-webkit-backdrop-filter:blur(8px);color:#fff;background:#ffffff1a;border:1px solid #ffffff38;border-radius:999px;outline:none;width:100%;padding:11px 44px 11px 18px;font-family:inherit;font-size:14px;transition:background .15s,border-color .15s}.anam-ctl-input::placeholder{color:#fff6}.anam-ctl-input:focus{background:#ffffff26;border-color:#ffffff2e}.anam-ctl-input:disabled{opacity:.35;cursor:not-allowed}.anam-ctl-send{color:#ffffff80;cursor:pointer;background:0 0;border:none;border-radius:50%;justify-content:center;align-items:center;width:32px;height:32px;padding:0;transition:color .15s;display:flex;position:absolute;right:6px}.anam-ctl-send:hover{color:#fff}.anam-ctl-send:disabled{opacity:.35;cursor:not-allowed}.anam-watermark{z-index:11;opacity:.5;line-height:0;text-decoration:none;transition:opacity .15s;position:absolute;top:16px;left:16px}.anam-watermark:hover{opacity:.8}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}';function Ot(t,e){const n={...t};for(const o of Object.keys(e)){const u=e[o];u!==void 0&&(u!==null&&typeof u=="object"&&!Array.isArray(u)&&typeof n[o]=="object"&&n[o]!==null&&!Array.isArray(n[o])?n[o]=Ot(n[o],u):n[o]=u)}return n}function kt(t){if(t!==void 0)return t==="true"}function cr(t){const e={};t.layout&&(e.layout=t.layout),t["initial-state"]&&(e.initialState=t["initial-state"]),t.position&&(e.position=t.position);const n=kt(t["ui-mute-button"]);n!==void 0&&(e.showMuteButton=n);const o=kt(t["ui-text-input"]);o!==void 0&&(e.showTextInput=o);const u=kt(t["ui-captions"]);return u!==void 0&&(e.showCaptions=u),t["call-to-action"]&&(e.callToAction=t["call-to-action"]),e}const ur=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2.5","stroke-linecap":"round",children:w("path",{d:"M18 6L6 18M6 6l12 12"})}),dr=()=>w("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",children:w("path",{d:"M8 5.14v13.72a1 1 0 0 0 1.5.86l11.04-6.86a1 1 0 0 0 0-1.72L9.5 4.28A1 1 0 0 0 8 5.14Z"})}),hr=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),w("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),fr=()=>w("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"1",y1:"1",x2:"23",y2:"23"}),w("path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"}),w("path",{d:"M17 16.95A7 7 0 0 1 5 12v-2m14 0v2c0 .87-.16 1.71-.46 2.49"}),w("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),pr=()=>w("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round",children:[w("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),w("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]}),Dt=()=>w("svg",{width:"48",height:"48",viewBox:"0 0 48 48",fill:"none",style:{opacity:.3},children:[w("circle",{cx:"24",cy:"18",r:"8",stroke:"white","stroke-width":"2",fill:"none"}),w("path",{d:"M8 42c0-8.837 7.163-16 16-16s16 7.163 16 16",stroke:"white","stroke-width":"2",fill:"none"})]});function _r({config:t,session:e,videoRef:n,avatarSrc:o,avatarVideoSrc:u,displayCta:a,onCollapse:c,onStop:l}){const m=mt(null),[p,_]=qe(""),[d,S]=qe(null),[g,y]=qe(!1),C=mt(null),A=e.connectionStatus.value==="connected",I=e.connectionStatus.value==="connecting",b=e.connectionStatus.value==="error",N=e.isStreaming.value,M=!I&&!A&&!b,k=Ye(async()=>{n.current&&await e.startSession(n.current)},[e.startSession]);Ye(async()=>{await e.stopSession()},[e.stopSession]);const Y=Ye(()=>{if(!p.trim())return;const V=p.trim();e.sendMessage(V),_(""),m.current?.focus(),C.current&&clearTimeout(C.current),y(!1),S(V),C.current=window.setTimeout(()=>{y(!0),C.current=window.setTimeout(()=>{S(null),y(!1)},400)},2600)},[p]),oe=Ye(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Y())},[Y]);return Et(()=>()=>{C.current&&clearTimeout(C.current)},[]),w("div",{class:"anam-sheet",children:[w("video",{ref:n,class:"anam-video",autoplay:!0,playsinline:!0,"data-hidden":N?void 0:"true"}),M&&(e.isConfigured.value?w("div",{class:"anam-overlay-idle",children:[u?w("video",{src:u,autoplay:!0,loop:!0,muted:!0,playsinline:!0,class:"anam-preview-video",onError:V=>{V.target.style.display="none"}}):null,o?w("img",{src:o,alt:"Avatar",class:u?"anam-preview-fallback":void 0}):w(Dt,{}),w("button",{class:"anam-cta-pill",onClick:k,children:[w(dr,{}),a]})]}):w("div",{class:"anam-overlay-unconfigured",children:[w(Dt,{}),w("span",{children:"Agent not configured"})]})),I&&w("div",{class:"anam-overlay-loading",children:[w("span",{class:"anam-spinner"}),w("span",{children:"Starting your conversation..."})]}),b&&w("div",{class:"anam-overlay-error",children:[w("div",{class:"anam-overlay-error-text",children:e.error.value||"Something went wrong"}),w("button",{class:"anam-retry-btn",onClick:k,children:"Try Again"})]}),(c||l&&(A||I||N))&&w("button",{class:"anam-close-btn",onClick:c||l,"aria-label":c?"Close":"End call",children:w(ur,{})}),(A||N)&&w(ce,{children:[d&&w("div",{class:`anam-toast ${g?"anam-toast-out":""}`,children:d}),w("div",{class:"anam-control-bar",children:[t.showMuteButton&&w("button",{class:`anam-ctl-btn ${e.isMuted.value?"anam-ctl-btn-muted":""}`,onClick:()=>e.toggleMute(),"aria-label":e.isMuted.value?"Unmute":"Mute",children:e.isMuted.value?w(fr,{}):w(hr,{})}),t.showTextInput&&w("div",{class:"anam-ctl-input-wrap",children:[w("input",{ref:m,type:"text",class:"anam-ctl-input",placeholder:"Type a message...",value:p,onInput:V=>_(V.target.value),onKeyDown:oe,disabled:!A}),w("button",{class:"anam-ctl-send",onClick:Y,disabled:!A||!p.trim(),"aria-label":"Send message",children:w(pr,{})})]})]})]}),!t.removeWatermark&&w("a",{class:"anam-watermark",href:"https://anam.ai",target:"_blank",rel:"noopener noreferrer",children:w("svg",{width:"48",height:"16",viewBox:"0 0 86 29",fill:"white",xmlns:"http://www.w3.org/2000/svg",children:[w("path",{d:"M18.1491 28.1986L16.2127 21.63L6.3408 21.63L4.40439 28.1986H0L9.03659 -1.79687L13.4789 -1.79687L22.5535 28.1986H18.1491ZM7.47986 17.8331L15.0736 17.8331L11.2767 4.96161L7.47986 17.8331Z"}),w("path",{d:"M24.7666 28.1984L24.7666 7.69518L39.5745 7.69518V28.1984L35.3979 28.1984V11.4921L28.9432 11.4921L28.9432 28.1984H24.7666Z"}),w("path",{d:"M61.0239 28.1984V7.69518L85.7037 7.69518V28.1984H81.5271V11.4921L75.4521 11.4921V28.1984L71.2755 28.1984V11.4921L65.2005 11.4921V28.1984H61.0239Z"}),w("path",{d:"M42.8948 7.69518L57.7026 7.69518V28.1984L53.5261 28.1984V27.1353C52.4629 28.0466 51.0201 28.5781 49.3495 28.5781C45.4007 28.5781 42.8948 25.7305 42.8948 21.2501C42.8948 16.8457 45.4007 14.074 49.3495 14.074C51.0201 14.074 52.4629 14.5676 53.5261 15.4788V11.3022L42.8948 11.3022V7.69518ZM50.4885 24.7812C52.6148 24.7812 53.9437 23.4143 53.9057 21.2501C53.8678 19.0859 52.5389 17.681 50.4885 17.681C48.4003 17.681 47.0713 19.0859 47.0713 21.2501C47.0713 23.4143 48.4003 24.7812 50.4885 24.7812Z"})]})})]})}function Er(t){const e=mt(null);t["agent-id"]&&t["session-token"]&&console.warn("[AnamWidget] Both agent-id and session-token are set. Use one or the other. Ignoring agent-id.");const n=t["session-token"]?void 0:t["agent-id"],o=lr(n,t["api-base-url"],t["session-token"]),u=Ce(()=>cr(t),[t.layout,t["initial-state"],t.position,t["ui-mute-button"],t["ui-text-input"],t["ui-captions"],t["call-to-action"]]),a=Ce(()=>{const I=o.serverConfig.value;return Ot(Ot({...wt},I??{}),u)},[o.serverConfig.value,u]),c=Ti(a.layout==="floating"?a.initialState:"expanded");Et(()=>{a.layout==="inline"?c.value="expanded":c.value=a.initialState},[a.layout,a.initialState]),Et(()=>{o.fetchWidgetConfig()},[n,t["api-base-url"],t["session-token"]]);const l=t["avatar-url"]||o.avatarThumbnailUrl.value||null,m=t["avatar-video-url"]||o.avatarVideoUrl.value||null,_=t["agent-name"]||o.personaName.value,d=a.callToAction===wt.callToAction&&_?`Talk to ${_}`:a.callToAction,S=Ce(()=>{if(a.layout==="inline")return"";const I=yn(a.position);return Object.entries(I).map(([b,N])=>`${b}: ${N}`).join("; ")},[a.layout,a.position]),g=a.layout==="floating",y=()=>{c.value="expanded"},C=async()=>{o.connectionStatus.value!=="idle"&&await o.stopSession(),c.value="minimized"},A=g?c.value==="expanded":!0;return o.isReady.value?w(ce,{children:[w("style",{children:Fi}),w("div",{class:"anam-widget","data-layout":a.layout,"data-state":c.value,style:S,children:[g&&c.value==="minimized"&&w("button",{class:"anam-trigger",onClick:y,"aria-label":d,children:l?w("img",{src:l,alt:"Avatar"}):w(Dt,{})}),A&&w(_r,{config:a,session:o,videoRef:e,avatarSrc:l,avatarVideoSrc:m,displayCta:d,onCollapse:g?C:null,onStop:g?null:()=>o.stopSession()})]})]}):w("style",{children:Fi})}const mr=["agent-id","api-base-url","session-token","layout","initial-state","position","ui-mute-button","ui-text-input","ui-captions","call-to-action","avatar-url","avatar-video-url","agent-name"],gr={SESSION_STARTED:"anam-agent:session-started",SESSION_ENDED:"anam-agent:session-ended",MESSAGE_RECEIVED:"anam-agent:message-received",MESSAGE_SENT:"anam-agent:message-sent",EXPANDED:"anam-agent:expanded",COLLAPSED:"anam-agent:collapsed",ERROR:"anam-agent:error",MIC_MUTED:"anam-agent:mic-muted",MIC_UNMUTED:"anam-agent:mic-unmuted"};function Mt(t="anam-agent"){rn(Er,t,[...mr],{shadow:!0})}typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Mt()):Mt()),le.DefaultConfig=wt,le.WidgetEventNames=gr,le.registerWidget=Mt,Object.defineProperty(le,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anam-ai/agent-widget",
3
- "version": "0.1.0-alpha.17",
3
+ "version": "0.1.0-alpha.18",
4
4
  "description": "Embeddable video agent widget for Anam AI",
5
5
  "type": "module",
6
6
  "main": "./dist/index.umd.js",