@eka-care/medassist-widget 0.1.130 → 0.1.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var wc=Object.defineProperty;var Nc=(e,t,n)=>t in e?wc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var O=(e,t,n)=>Nc(e,typeof t!="symbol"?t+"":t,n);var xn,Z,as,It,ls,cs,ds,jr,lr,Cn,us,zr,$r,Yr,hs,cr={},dr=[],xc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Tn=Array.isArray;function ft(e,t){for(var n in t)e[n]=t[n];return e}function Br(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Ke(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?xn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return kn(e,s,r,o,null)}function kn(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++as,__i:-1,__u:0};return o==null&&Z.vnode!=null&&Z.vnode(i),i}function ms(){return{current:null}}function ce(e){return e.children}function it(e,t){this.props=e,this.context=t}function rn(e,t){if(t==null)return e.__?rn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?rn(e):null}function Cc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=ft({},t);i.__v=t.__v+1,Z.vnode&&Z.vnode(i),Gr(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??rn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,ys(r,i,o),t.__e=t.__=null,i.__e!=n&&ps(i)}}function ps(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),ps(e)}function Hr(e){(!e.__d&&(e.__d=!0)&&It.push(e)&&!ur.__r++||ls!=Z.debounceRendering)&&((ls=Z.debounceRendering)||cs)(ur)}function ur(){try{for(var e,t=1;It.length;)It.length>t&&It.sort(ds),e=It.shift(),t=It.length,Cc(e)}finally{It.length=ur.__r=0}}function fs(e,t,n,r,o,i,s,a,c,d,h){var u,f,E,p,g,b,m,_=r&&r.__k||dr,y=t.length;for(c=Tc(n,t,_,c,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(f=E.__i!=-1&&_[E.__i]||cr,E.__i=u,b=Gr(e,E,f,o,i,s,a,c,d,h),p=E.__e,E.ref&&f.ref!=E.ref&&(f.ref&&Kr(f.ref,null,E),h.push(E.ref,E.__c||p,E)),g==null&&p!=null&&(g=p),(m=!!(4&E.__u))||f.__k===E.__k?(c=gs(E,c,e,m),m&&f.__e&&(f.__e=null)):typeof E.type=="function"&&b!==void 0?c=b:p&&(c=p.nextSibling),E.__u&=-7);return n.__e=g,c}function Tc(e,t,n,r,o){var i,s,a,c,d,h=n.length,u=h,f=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=kn(null,s,null,null,null):Tn(s)?s=e.__k[i]=kn(ce,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=kn(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+f,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=kc(s,n,c,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?f--:o<h&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=c&&(d==c-1?f--:d==c+1?f++:(d>c?f--:f++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=rn(a)),vs(a,a));return r}function gs(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=gs(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=rn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function wt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Tn(e)?e.some(function(n){wt(n,t)}):t.push(e)),t}function kc(e,t,n,r){var o,i,s,a=e.key,c=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&c==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&c==d.type)return s}return-1}function _s(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||xc.test(t)?n:n+"px"}function hr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||_s(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||_s(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(us,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Cn]=r[Cn]:(n[Cn]=zr,e.addEventListener(t,i?Yr:$r,i)):e.removeEventListener(t,i?Yr:$r,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Es(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[lr]==null)t[lr]=zr++;else if(t[lr]<n[Cn])return;return n(Z.event?Z.event(t):t)}}}function Gr(e,t,n,r,o,i,s,a,c,d){var h,u,f,E,p,g,b,m,_,y,k,T,S,x,v,w=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=Z.__b)&&h(t);e:if(typeof w=="function")try{if(m=t.props,_=w.prototype&&w.prototype.render,y=(h=w.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new w(m,k):(t.__c=u=new it(m,k),u.constructor=w,u.render=Oc),y&&y.sub(u),u.state||(u.state={}),u.__n=r,f=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&w.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=ft({},u.__s)),ft(u.__s,w.getDerivedStateFromProps(m,u.__s))),E=u.props,p=u.state,u.__v=t,f)_&&w.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&w.getDerivedStateFromProps==null&&m!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(m,k),t.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(m,u.__s,k)===!1){t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(N){N&&(N.__=t)}),dr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,p,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,T=Z.__r,S=0,_)u.state=u.__s,u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),dr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++S<25);u.state=u.__s,u.getChildContext!=null&&(r=ft(ft({},r),u.getChildContext())),_&&!f&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(E,p)),x=h!=null&&h.type===ce&&h.key==null?bs(h.props.children):h,a=fs(e,Tn(x)?x:[x],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(N){if(t.__v=null,c||i!=null)if(N.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(v=i.length;v--;)Br(i[v]);Wr(t)}else t.__e=n.__e,t.__k=n.__k,N.then||Wr(t);Z.__e(N,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=Rc(n.__e,t,n,r,o,i,s,c,d);return(h=Z.diffed)&&h(t),128&t.__u?void 0:a}function Wr(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Wr))}function ys(e,t,n){for(var r=0;r<n.length;r++)Kr(n[r],n[++r],n[++r]);Z.__c&&Z.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){Z.__e(i,o.__v)}})}function bs(e){return typeof e!="object"||e==null||e.__b>0?e:Tn(e)?e.map(bs):e.constructor!==void 0?null:ft({},e)}function Rc(e,t,n,r,o,i,s,a,c){var d,h,u,f,E,p,g,b=n.props||cr,m=t.props,_=t.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(d=0;d<i.length;d++)if((E=i[d])&&"setAttribute"in E==!!_&&(_?E.localName==_:E.nodeType==3)){e=E,i[d]=null;break}}if(e==null){if(_==null)return document.createTextNode(m);e=document.createElementNS(o,_,m.is&&m),a&&(Z.__m&&Z.__m(t,i),a=!1),i=null}if(_==null)b===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&xn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(E=e.attributes[d]).name]=E.value;for(d in b)E=b[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||hr(e,d,null,E,o);for(d in m)E=m[d],d=="children"?f=E:d=="dangerouslySetInnerHTML"?h=E:d=="value"?p=E:d=="checked"?g=E:a&&typeof E!="function"||b[d]===E||hr(e,d,E,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),fs(t.type=="template"?e.content:e,Tn(f)?f:[f],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&rn(n,0),a,c),i!=null)for(d=i.length;d--;)Br(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&p==null?e.removeAttribute("value"):p!=null&&(p!==e[d]||_=="progress"&&!p||_=="option"&&p!=b[d])&&hr(e,d,p,b[d],o),d="checked",g!=null&&g!=e[d]&&hr(e,d,g,b[d],o))}return e}function Kr(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){Z.__e(o,n)}}function vs(e,t,n){var r,o;if(Z.unmount&&Z.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Kr(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){Z.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&vs(r[o],t,n||typeof e.type!="function");n||Br(e.__e),e.__c=e.__=e.__e=void 0}function Oc(e,t,n){return this.constructor(e,n)}function Rn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),Z.__&&Z.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],Gr(t,e=(!r&&n||t).__k=Ke(ce,null,[e]),o||cr,cr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?xn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),ys(i,e,s)}function Ss(e,t){Rn(e,t,Ss)}function Ac(e,t,n){var r,o,i,s,a=ft({},e.props);for(i in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)i=="key"?r=t[i]:i=="ref"?o=t[i]:a[i]=t[i]===void 0&&s!=null?s[i]:t[i];return arguments.length>2&&(a.children=arguments.length>3?xn.call(arguments,2):n),kn(e.type,a,r||e.key,o||e.ref,null)}function Nt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,Hr(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+hs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}xn=dr.slice,Z={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(a){e=a}throw e}},as=0,it.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=ft({},this.state),typeof e=="function"&&(e=e(ft({},n),this.props)),e&&ft(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Hr(this))},it.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Hr(this))},it.prototype.render=ce,It=[],cs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ds=function(e,t){return e.__v.__b-t.__v.__b},ur.__r=0,jr=Math.random().toString(8),lr="__d"+jr,Cn="__a"+jr,us=/(PointerCapture)$|Capture$/i,zr=0,$r=Es(!1),Yr=Es(!0),hs=0;var Ic=0;function l(e,t,n,r,o,i){t||(t={});var s,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?s=t[a]:c[a]=t[a];var d={type:e,props:c,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ic,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)c[a]===void 0&&(c[a]=s[a]);return Z.vnode&&Z.vnode(d),d}var xt,he,qr,ws,on=0,Ns=[],we=Z,xs=we.__b,Cs=we.__r,Ts=we.diffed,ks=we.__c,Rs=we.unmount,Os=we.__;function $t(e,t){we.__h&&we.__h(he,e,on||t),on=0;var n=he.__H||(he.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function D(e){return on=1,sn(Is,e)}function sn(e,t,n){var r=$t(xt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Is(void 0,t),function(a){var c=r.__N?r.__N[0]:r.__[0],d=r.t(c,a);c!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=he,!he.__f)){var o=function(a,c,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(f){return f.__c});if(h.every(function(f){return!f.__N}))return!i||i.call(this,a,c,d);var u=r.__c.props!==a;return h.some(function(f){if(f.__N){var E=f.__[0];f.__=f.__N,f.__N=void 0,E!==f.__[0]&&(u=!0)}}),i&&i.call(this,a,c,d)||u};he.__f=!0;var i=he.shouldComponentUpdate,s=he.componentWillUpdate;he.componentWillUpdate=function(a,c,d){if(this.__e){var h=i;i=void 0,o(a,c,d),i=h}s&&s.call(this,a,c,d)},he.shouldComponentUpdate=o}return r.__N||r.__}function z(e,t){var n=$t(xt++,3);!we.__s&&eo(n.__H,t)&&(n.__=e,n.u=t,he.__H.__h.push(n))}function dt(e,t){var n=$t(xt++,4);!we.__s&&eo(n.__H,t)&&(n.__=e,n.u=t,he.__h.push(n))}function J(e){return on=5,ye(function(){return{current:e}},[])}function Xr(e,t,n){on=6,dt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ye(e,t){var n=$t(xt++,7);return eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function ge(e,t){return on=8,ye(function(){return e},t)}function Ct(e){var t=he.context[e.__c],n=$t(xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(he)),t.props.value):e.__}function Zr(e,t){we.useDebugValue&&we.useDebugValue(t?t(e):e)}function Mc(e){var t=$t(xt++,10),n=D();return t.__=e,he.componentDidCatch||(he.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Jr(){var e=$t(xt++,11);if(!e.__){for(var t=he.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function Pc(){for(var e;e=Ns.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(mr),t.__h.some(Qr),t.__h=[]}catch(n){t.__h=[],we.__e(n,e.__v)}}}we.__b=function(e){he=null,xs&&xs(e)},we.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Os&&Os(e,t)},we.__r=function(e){Cs&&Cs(e),xt=0;var t=(he=e.__c).__H;t&&(qr===he?(t.__h=[],he.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(mr),t.__h.some(Qr),t.__h=[],xt=0)),qr=he},we.diffed=function(e){Ts&&Ts(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ns.push(t)!==1&&ws===we.requestAnimationFrame||((ws=we.requestAnimationFrame)||Dc)(Pc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),qr=he=null},we.__c=function(e,t){t.some(function(n){try{n.__h.some(mr),n.__h=n.__h.filter(function(r){return!r.__||Qr(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],we.__e(r,n.__v)}}),ks&&ks(e,t)},we.unmount=function(e){Rs&&Rs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{mr(r)}catch(o){t=o}}),n.__H=void 0,t&&we.__e(t,n.__v))};var As=typeof requestAnimationFrame=="function";function Dc(e){var t,n=function(){clearTimeout(r),As&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);As&&(t=requestAnimationFrame(n))}function mr(e){var t=he,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),he=t}function Qr(e){var t=he;e.__c=e.__(),he=t}function eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Is(e,t){return typeof t=="function"?t(e):t}function Ms(e,t){for(var n in t)e[n]=t[n];return e}function to(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function no(e,t){var n=t(),r=D({t:{__:n,u:t}}),o=r[0].t,i=r[1];return dt(function(){o.__=n,o.u=t,ro(o)&&i({t:o})},[e,n,t]),z(function(){return ro(o)&&i({t:o}),e(function(){ro(o)&&i({t:o})})},[e]),n}function ro(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function oo(e){e()}function so(e){return e}function io(){return[!1,oo]}var ao=dt;function pr(e,t){this.props=e,this.context=t}function lo(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:to(this.props,o)}function r(o){return this.shouldComponentUpdate=n,Ke(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(pr.prototype=new it).isPureReactComponent=!0,pr.prototype.shouldComponentUpdate=function(e,t){return to(this.props,e)||to(this.state,t)};var Ps=Z.__b;Z.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Ps&&Ps(e)};var Lc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Q(e){function t(n){var r=Ms({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Lc,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Ds=function(e,t){return e==null?null:wt(wt(e).map(t))},Je={map:Ds,forEach:Ds,count:function(e){return e?wt(e).length:0},only:function(e){var t=wt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:wt},Uc=Z.__e;Z.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t)}Uc(e,t,n,r)};var Ls=Z.unmount;function Us(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=Ms({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Us(r,t,n)})),e}function Fs(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Fs(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function $e(){this.__u=0,this.o=null,this.__b=null}function Vs(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function qe(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(a){a&&(o=a.default||a),r=!0},function(a){n=a,r=!0}),n)throw n;if(!r)throw t;return o?Ke(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function an(){this.i=null,this.l=null}Z.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Ls&&Ls(e)},($e.prototype=new it).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=Vs(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(c):c())};n.__R=s;var a=n.__P;n.__P=null;var c=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Fs(d,d.__c.__P,d.__c.__O)}var h;for(r.setState({__a:r.__b=null});h=r.o.pop();)h.__P=a,h.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},$e.prototype.componentWillUnmount=function(){this.o=[]},$e.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Us(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&Ke(ce,null,e.fallback);return o&&(o.__u&=-33),[Ke(ce,null,t.__a?null:e.children),o]};var js=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function Fc(e){return this.getChildContext=function(){return e.context},e.children}function Vc(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Rn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Rn(Ke(Fc,{context:t.context},e.__v),t.v)}function zs(e,t){var n=Ke(Vc,{__v:e,h:t});return n.containerInfo=t,n}(an.prototype=new it).__a=function(e){var t=this,n=Vs(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),js(t,e,r)):o()};n?n(i):i()}},an.prototype.render=function(e){this.i=null,this.l=new Map;var t=wt(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},an.prototype.componentDidUpdate=an.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){js(e,n,t)})};var $s=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,jc=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,zc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,$c=/[A-Z0-9]/g,Yc=typeof document<"u",Bc=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function co(e,t,n){return t.__k==null&&(t.textContent=""),Rn(e,t),typeof n=="function"&&n(),e?e.__c:null}function Ys(e,t,n){return Ss(e,t),typeof n=="function"&&n(),e?e.__c:null}it.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(it.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var Bs=Z.event;Z.event=function(e){return Bs&&(e=Bs(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var uo,Hc={configurable:!0,get:function(){return this.class}},Hs=Z.vnode;Z.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||Yc&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||Bc(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":zc.test(s)&&(s=c):c=s="oninput":i&&jc.test(s)?s=s.replace($c,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&o[s=c]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=wt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=wt(n.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",Hc)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=$s,Hs&&Hs(e)};var Gs=Z.__r;Z.__r=function(e){Gs&&Gs(e),uo=e.__c};var Ws=Z.diffed;Z.diffed=function(e){Ws&&Ws(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),uo=null};var Ks={ReactCurrentDispatcher:{current:{readContext:function(e){return uo.__n[e.__c].props.value},useCallback:ge,useContext:Ct,useDebugValue:Zr,useDeferredValue:so,useEffect:z,useId:Jr,useImperativeHandle:Xr,useInsertionEffect:ao,useLayoutEffect:dt,useMemo:ye,useReducer:sn,useRef:J,useState:D,useSyncExternalStore:no,useTransition:io}}},Gc="18.3.1";function qs(e){return Ke.bind(null,e)}function Qe(e){return!!e&&e.$$typeof===$s}function Xs(e){return Qe(e)&&e.type===ce}function Zs(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Mt(e){return Qe(e)?Ac.apply(null,arguments):e}function ho(e){return!!e.__k&&(Rn(null,e),!0)}function Js(e){return e&&(e.base||e.nodeType===1&&e)||null}var Qs=function(e,t){return e(t)},ei=function(e,t){var n=Z.debounceRendering;Z.debounceRendering=function(o){return o()};var r=e(t);return Z.debounceRendering=n,r},ti=Qe,On={useState:D,useId:Jr,useReducer:sn,useEffect:z,useLayoutEffect:dt,useInsertionEffect:ao,useTransition:io,useDeferredValue:so,useSyncExternalStore:no,startTransition:oo,useRef:J,useImperativeHandle:Xr,useMemo:ye,useCallback:ge,useContext:Ct,useDebugValue:Zr,version:"18.3.1",Children:Je,render:co,hydrate:Ys,unmountComponentAtNode:ho,createPortal:zs,createElement:Ke,createContext:Nt,createFactory:qs,cloneElement:Mt,createRef:ms,Fragment:ce,isValidElement:Qe,isElement:ti,isFragment:Xs,isMemo:Zs,findDOMNode:Js,Component:it,PureComponent:pr,memo:lo,forwardRef:Q,flushSync:ei,unstable_batchedUpdates:Qs,StrictMode:ce,Suspense:$e,SuspenseList:an,lazy:qe,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ks};const mo=Object.freeze(Object.defineProperty({__proto__:null,Children:Je,Component:it,Fragment:ce,PureComponent:pr,StrictMode:ce,Suspense:$e,SuspenseList:an,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ks,cloneElement:Mt,createContext:Nt,createElement:Ke,createFactory:qs,createPortal:zs,createRef:ms,default:On,findDOMNode:Js,flushSync:ei,forwardRef:Q,hydrate:Ys,isElement:ti,isFragment:Xs,isMemo:Zs,isValidElement:Qe,lazy:qe,memo:lo,render:co,startTransition:oo,unmountComponentAtNode:ho,unstable_batchedUpdates:Qs,useCallback:ge,useContext:Ct,useDebugValue:Zr,useDeferredValue:so,useEffect:z,useErrorBoundary:Mc,useId:Jr,useImperativeHandle:Xr,useInsertionEffect:ao,useLayoutEffect:dt,useMemo:ye,useReducer:sn,useRef:J,useState:D,useSyncExternalStore:no,useTransition:io,version:Gc},Symbol.toStringTag,{value:"Module"}));function Wc(e){return{render:function(t){co(t,e)},unmount:function(){ho(e)}}}function ni(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function po(...e){return t=>{let n=!1;const r=e.map(o=>{const i=ni(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():ni(e[o],null)}}}}function Pt(...e){return ge(po(...e),e)}function Kc(e){const t=qc(e),n=Q((r,o)=>{const{children:i,...s}=r,a=Je.toArray(i),c=a.find(Zc);if(c){const d=c.props.children,h=a.map(u=>u===c?Je.count(d)>1?Je.only(null):Qe(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Qe(d)?Mt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function qc(e){const t=Q((n,r)=>{const{children:o,...i}=n;if(Qe(o)){const s=Qc(o),a=Jc(i,o.props);return o.type!==ce&&(a.ref=r?po(r,s):s),Mt(o,a)}return Je.count(o)>1?Je.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Xc=Symbol("radix.slottable");function Zc(e){return Qe(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Xc}function Jc(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Qc(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var ed=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ln=ed.reduce((e,t)=>{const n=Kc(`Primitive.${t}`),r=Q((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Yt=globalThis?.document?dt:()=>{};function td(e,t){return sn((n,r)=>t[n][r]??n,e)}var cn=e=>{const{present:t,children:n}=e,r=nd(t),o=typeof n=="function"?n({present:r.isPresent}):Je.only(n),i=Pt(r.ref,rd(o));return typeof n=="function"||r.isPresent?Mt(o,{ref:i}):null};cn.displayName="Presence";function nd(e){const[t,n]=D(),r=J(null),o=J(e),i=J("none"),s=e?"mounted":"unmounted",[a,c]=td(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return z(()=>{const d=fr(r.current);i.current=a==="mounted"?d:"none"},[a]),Yt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,f=fr(d);e?c("MOUNT"):f==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Yt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const p=fr(r.current).includes(CSS.escape(E.animationName));if(E.target===t&&p&&(c("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},f=E=>{E.target===t&&(i.current=fr(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:ge(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function fr(e){return e?.animationName||"none"}function rd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function ri(e,t=[]){let n=[];function r(i,s){const a=Nt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,b=ye(()=>p,Object.values(p));return l(g.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,od(o,...t)]}function od(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Dt(e){const t=J(e);return z(()=>{t.current=e}),ye(()=>(...n)=>t.current?.(...n),[])}var sd=Nt(void 0);function id(e){const t=Ct(sd);return e||t||"ltr"}function ad(e,[t,n]){return Math.min(n,Math.max(t,e))}function Lt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function ld(e,t){return sn((n,r)=>t[n][r]??n,e)}var fo="ScrollArea",[oi]=ri(fo),[cd,at]=oi(fo),si=Q((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=D(null),[d,h]=D(null),[u,f]=D(null),[E,p]=D(null),[g,b]=D(null),[m,_]=D(0),[y,k]=D(0),[T,S]=D(!1),[x,v]=D(!1),w=Pt(t,A=>c(A)),N=id(o);return l(cd,{scope:n,type:r,dir:N,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:f,scrollbarX:E,onScrollbarXChange:p,scrollbarXEnabled:T,onScrollbarXEnabledChange:S,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:x,onScrollbarYEnabledChange:v,onCornerWidthChange:_,onCornerHeightChange:k,children:l(ln.div,{dir:N,...s,ref:w,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});si.displayName=fo;var ii="ScrollAreaViewport",ai=Q((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=at(ii,n),a=J(null),c=Pt(t,a,s.onViewportChange);return l(ce,{children:[l("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),l(ln.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:l("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});ai.displayName=ii;var gt="ScrollAreaScrollbar",go=Q((e,t)=>{const{forceMount:n,...r}=e,o=at(gt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return z(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?l(dd,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(ud,{...r,ref:t,forceMount:n}):o.type==="auto"?l(li,{...r,ref:t,forceMount:n}):o.type==="always"?l(_o,{...r,ref:t}):null});go.displayName=gt;var dd=Q((e,t)=>{const{forceMount:n,...r}=e,o=at(gt,e.__scopeScrollArea),[i,s]=D(!1);return z(()=>{const a=o.scrollArea;let c=0;if(a){const d=()=>{window.clearTimeout(c),s(!0)},h=()=>{c=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),l(cn,{present:n||i,children:l(li,{"data-state":i?"visible":"hidden",...r,ref:t})})}),ud=Q((e,t)=>{const{forceMount:n,...r}=e,o=at(gt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=yr(()=>c("SCROLL_END"),100),[a,c]=ld("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return z(()=>{if(a==="idle"){const d=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,c]),z(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const f=()=>{const E=d[h];u!==E&&(c("SCROLL"),s()),u=E};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,c,s]),l(cn,{present:n||a!=="hidden",children:l(_o,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Lt(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Lt(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),li=Q((e,t)=>{const n=at(gt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=D(!1),a=e.orientation==="horizontal",c=yr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return dn(n.viewport,c),dn(n.content,c),l(cn,{present:r||i,children:l(_o,{"data-state":i?"visible":"hidden",...o,ref:t})})}),_o=Q((e,t)=>{const{orientation:n="vertical",...r}=e,o=at(gt,e.__scopeScrollArea),i=J(null),s=J(0),[a,c]=D({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=mi(a.viewport,a.content),h={...r,sizes:a,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function u(f,E){return _d(f,s.current,a,E)}return n==="horizontal"?l(hd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,E=pi(f,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=u(f,o.dir))}}):n==="vertical"?l(md,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,E=pi(f,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=u(f))}}):null}),hd=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=at(gt,e.__scopeScrollArea),[s,a]=D(),c=J(null),d=Pt(t,c,i.onScrollbarXChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(di,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Er(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(f),gi(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:_r(s.paddingLeft),paddingEnd:_r(s.paddingRight)}})}})}),md=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=at(gt,e.__scopeScrollArea),[s,a]=D(),c=J(null),d=Pt(t,c,i.onScrollbarYChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(di,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Er(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(f),gi(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:_r(s.paddingTop),paddingEnd:_r(s.paddingBottom)}})}})}),[pd,ci]=oi(gt),di=Q((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:u,...f}=e,E=at(gt,n),[p,g]=D(null),b=Pt(t,w=>g(w)),m=J(null),_=J(""),y=E.viewport,k=r.content-r.viewport,T=Dt(h),S=Dt(c),x=yr(u,10);function v(w){if(m.current){const N=w.clientX-m.current.left,A=w.clientY-m.current.top;d({x:N,y:A})}}return z(()=>{const w=N=>{const A=N.target;p?.contains(A)&&T(N,k)};return document.addEventListener("wheel",w,{passive:!1}),()=>document.removeEventListener("wheel",w,{passive:!1})},[y,p,k,T]),z(S,[r,S]),dn(p,x),dn(E.content,x),l(pd,{scope:n,scrollbar:p,hasThumb:o,onThumbChange:Dt(i),onThumbPointerUp:Dt(s),onThumbPositionChange:S,onThumbPointerDown:Dt(a),children:l(ln.div,{...f,ref:b,style:{position:"absolute",...f.style},onPointerDown:Lt(e.onPointerDown,w=>{w.button===0&&(w.target.setPointerCapture(w.pointerId),m.current=p.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),v(w))}),onPointerMove:Lt(e.onPointerMove,v),onPointerUp:Lt(e.onPointerUp,w=>{const N=w.target;N.hasPointerCapture(w.pointerId)&&N.releasePointerCapture(w.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),gr="ScrollAreaThumb",ui=Q((e,t)=>{const{forceMount:n,...r}=e,o=ci(gr,e.__scopeScrollArea);return l(cn,{present:n||o.hasThumb,children:l(fd,{ref:t,...r})})}),fd=Q((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=at(gr,n),s=ci(gr,n),{onThumbPositionChange:a}=s,c=Pt(t,u=>s.onThumbChange(u)),d=J(void 0),h=yr(()=>{d.current&&(d.current(),d.current=void 0)},100);return z(()=>{const u=i.viewport;if(u){const f=()=>{if(h(),!d.current){const E=Ed(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,h,a]),l(ln.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Lt(e.onPointerDownCapture,u=>{const f=u.target.getBoundingClientRect(),E=u.clientX-f.left,p=u.clientY-f.top;s.onThumbPointerDown({x:E,y:p})}),onPointerUp:Lt(e.onPointerUp,s.onThumbPointerUp)})});ui.displayName=gr;var Eo="ScrollAreaCorner",hi=Q((e,t)=>{const n=at(Eo,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(gd,{...e,ref:t}):null});hi.displayName=Eo;var gd=Q((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=at(Eo,n),[i,s]=D(0),[a,c]=D(0),d=!!(i&&a);return dn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),dn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(ln.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function _r(e){return e?parseInt(e,10):0}function mi(e,t){const n=e/t;return isNaN(n)?0:n}function Er(e){const t=mi(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function _d(e,t,n,r="ltr"){const o=Er(n),i=o/2,s=t||i,a=o-s,c=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return fi([c,d],u)(e)}function pi(e,t,n="ltr"){const r=Er(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,c=n==="ltr"?[0,s]:[s*-1,0],d=ad(e,c);return fi([0,s],[0,a])(d)}function fi(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function gi(e,t){return e>0&&e<t}var Ed=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function yr(e,t){const n=Dt(e),r=J(0);return z(()=>()=>window.clearTimeout(r.current),[]),ge(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function dn(e,t){const n=Dt(t);Yt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var _i=si,yd=ai,bd=hi;function vd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var un={},An={},Ei={},In={},Mn={},Pn={},yi;function yo(){if(yi)return Pn;yi=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.EventEmitter=void 0;let e=class{constructor(){O(this,"eventListeners",new Map)}on(t,n){const r=this.eventListeners.get(t)||new Set;r.add(n),this.eventListeners.set(t,r)}off(t,n){const r=this.eventListeners.get(t);r&&(r.delete(n),r.size===0&&this.eventListeners.delete(t))}emit(t,...n){const r=this.eventListeners.get(t);r&&r.forEach(o=>o(...n))}removeAllListeners(){this.eventListeners.clear()}};return Pn.EventEmitter=e,Pn}var hn={},bi;function Dn(){return bi||(bi=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.DisconnectionReason=hn.ConnectionStatus=void 0,hn.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},hn.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),hn}var vi;function bo(){if(vi)return Mn;vi=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.BaseConnection=void 0;const e=yo(),t=Dn();let n=class{constructor(){O(this,"status",t.ConnectionStatus.CONNECTING);O(this,"queue",[]);O(this,"eventEmitter",new e.EventEmitter);O(this,"disconnectionDetails",null);O(this,"onErrorCallback",null);O(this,"onDisconnectCallback",null);O(this,"onMessageCallback",null);O(this,"onOpenCallback",null);O(this,"onStatusChangeCallback",null)}getStatus(){return this.status}onOpen(r){this.onOpenCallback=r}onMessage(r){if(this.onMessageCallback=r,this.queue.length>0){const o=[...this.queue];this.queue.length=0,queueMicrotask(()=>{o.forEach(i=>{this.onMessageCallback?.(i)})})}}onDisconnect(r){this.onDisconnectCallback=r;const o=this.disconnectionDetails;o&&queueMicrotask(()=>{this.onDisconnectCallback?.(o)})}onError(r){this.onErrorCallback=r}on(r,o){this.eventEmitter.on(r,o)}off(r,o){this.eventEmitter.off(r,o)}emit(r,...o){this.eventEmitter.emit(r,...o)}onStatusChange(r){this.onStatusChangeCallback=r,queueMicrotask(()=>{r(this.status)})}disconnect(r){this.disconnectionDetails||(this.disconnectionDetails=r,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.onDisconnectCallback?.(r))}handleMessage(r){this.onMessageCallback?this.onMessageCallback(r):this.queue.push(r)}updateStatus(r){this.status!==r&&(this.status=r,this.onStatusChangeCallback?.(r))}};return Mn.BaseConnection=n,Mn}var Si={},wi;function et(){return wi||(wi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=T,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(v,w=e.SynapseErrorCode.UNKNOWN,N={}){super(v);O(this,"code");O(this,"timestamp");O(this,"cause");O(this,"context");O(this,"hint");O(this,"displayMessage");O(this,"reason");this.name="SynapseError",this.code=w,this.timestamp=new Date,this.cause=N.cause,this.context=N.context,this.hint=N.hint,this.reason=N.reason,this.displayMessage=N.displayMessage||N?.hint||v,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(v,w,N,A){const Y=n.makeMessage(w,N,v);super(Y,e.SynapseErrorCode.API,{cause:N,context:{status:w,hasBody:!!N},hint:w&&w>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:v||"Something went wrong"});O(this,"status");O(this,"error");O(this,"headers");this.name="APIError",this.status=w,this.error=N,this.headers=A}static makeMessage(v,w,N){const A=w instanceof Error?w.message:N;return v&&A?`HTTP ${v}: ${A}`:v?`${v} status code (no body)`:A||"(no status code or body)"}static generate(v,w,N,A){if(!v)return new r({message:N});const Y=w?.error,q=Y&&typeof Y=="object"&&!Array.isArray(Y)?Y:void 0;switch(v){case 400:return new i(N||"Bad Request",v,q,A);case 401:return new s(N||"Unauthorized",v,q,A);case 403:return new a(N||"Permission Denied",v,q,A);case 404:return new c(N||"Not Found",v,q,A);case 405:return new d(N||"Method Not Allowed",v,q,A);case 429:return new h(N||"Rate Limit Exceeded",v,q,A);case 500:return new u(N||"Internal Server Error",v,q,A);default:return new n(N||"API Error",v,q,A)}}}e.APIError=n;class r extends n{constructor({message:x}={}){super(x||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:x}={}){super(x||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(x,v,w,N){super(x,v,w,N),this.name="InternalServerError"}}e.InternalServerError=u;class f extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.CONNECTION,v),this.name="ConnectionError"}}e.ConnectionError=f;class E extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.RECORDING,v),this.name="RecordingError"}}e.RecordingError=E;class p extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.AUTH,v),this.name="AuthenticationError"}}e.AuthenticationError=p;class g extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.FILE,v),this.name="FileError"}}e.FileError=g;class b extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.SESSION,v),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.MESSAGE,v),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.STORE,v),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.CONFIGURATION,v),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(x,v={}){super(x,e.SynapseErrorCode.VALIDATION,v),this.name="ValidationError"}}e.ValidationError=k;function T(S,x,v,w={}){if(S instanceof x)return S;const N={...w,context:{...S instanceof t?S.context:void 0,...w.context},hint:w.hint??(S instanceof t?S.hint:void 0),reason:w.reason??(S instanceof t?S.reason:void 0),cause:w.cause??S};if(S instanceof t)return new x(S.message,N);const A=S instanceof Error&&S.message?S.message:v;return new x(A,N)}})(Si)),Si}var Ni;function xi(){if(Ni)return In;Ni=1,Object.defineProperty(In,"__esModule",{value:!0}),In.WebSocketConnection=void 0;const e=bo(),t=Dn(),n=et();class r extends e.BaseConnection{constructor(s){super();O(this,"conversationId");O(this,"socket",null);O(this,"config");O(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const c=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(c)}}handleError(s){}handleClose(s){const a=s.wasClean,c=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(c===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):c===1001||c===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):c===4001||c===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):c===4401||c===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(c===4401?"Session token expired":"Session credentials rejected")):c===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):c===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:c,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const c=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(c),c}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return In.WebSocketConnection=r,In}var Ln={},Ci={},Ti;function ki(){return Ti||(Ti=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=void 0,e.SYNAPSE_CHANNELS={WIDGET:"widget",WEB:"web",SIDE_PANEL:"side_panel"},e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS.WIDGET})(Ci)),Ci}var Ri;function Oi(){if(Ri)return Ln;Ri=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.SSEConnection=void 0;const e=bo(),t=Dn(),n=ki(),r=et();class o extends e.BaseConnection{constructor(a){super();O(this,"conversationId");O(this,"config");O(this,"connected",!1);O(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const c=new AbortController;this.activeStreamController=c,this.streamChat(a,c)}postChat(a,c,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(c),signal:d.signal})}async streamChat(a,c){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,c);if(h.status===401&&this.config.auth.onUnauthorized){const p=await this.config.auth.onUnauthorized();if(c.signal.aborted)return;p&&(h=await this.postChat(d,a,c))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),f=new TextDecoder;let E="";for(;;){const{done:p,value:g}=await u.read();if(p)break;E+=f.decode(g,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(c.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===c&&(this.activeStreamController=null)}}extractJsonObjects(a){let c=0;for(;c<a.length;){const d=a.indexOf("{",c);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const f=JSON.parse(u);this.handleMessage(f)}catch(f){const E=(0,r.normalizeError)(f,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(E)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let f=c;f<a.length;f++){const E=a[f];if(h){u?u=!1:E==="\\"?u=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")d++;else if(E==="}"&&(d--,d===0))return f}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Ln.SSEConnection=o,Ln}var Ai;function Ii(){return Ai||(Ai=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=xi(),n=Oi(),r=et();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(Ei)),Ei}var Un={},Mi;function vo(){if(Mi)return Un;Mi=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Un.getConfig=r,Un}var Fn={},Vn={},Pi;function br(){if(Pi)return Vn;Pi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.HttpClient=void 0;const e=et();let t=class{constructor(n){O(this,"baseUrl");O(this,"headers");O(this,"timeout");O(this,"maxRetries");O(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const c=this.buildUrl(r,o?.params),d=await fetch(c,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(c){if(s=c,a===i||!(c instanceof TypeError&&c.message==="Failed to fetch"||c instanceof DOMException&&c.name==="AbortError"||c instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Vn.HttpClient=t,Vn}var jn={},zn={},Di;function $n(){if(Di)return zn;Di=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.BaseResource=void 0;let e=class{constructor(t){O(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return zn.BaseResource=e,zn}var Li;function Ui(){if(Li)return jn;Li=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.Session=void 0;const e=$n();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:c}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...c&&{nps_base5:c}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return jn.Session=t,jn}var Yn={},Fi;function So(){if(Fi)return Yn;Fi=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.Config=void 0;const e=$n();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return Yn.Config=t,Yn}var Vi={},ji;function zi(){return ji||(ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=br(),n=vo(),r=So(),o=new Map,i=(c,d)=>`${c.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(c){const d=c.serverUrl||(0,n.getConfig)(c.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,c.agentId),u=o.get(h);if(u)return u;const f=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":c.agentId,...c.channel&&{"x-channel":c.channel}}}),E=new r.Config(f).retrieve(c.agentId);return E.catch(()=>{o.get(h)===E&&o.delete(h)}),o.set(h,E),E}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(Vi)),Vi}var Bn={},$i;function wo(){if($i)return Bn;$i=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.Auth=void 0;const e=$n();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Bn.Auth=t,Bn}var Hn={},mn={},Yi;function No(){return Yi||(Yi=1,Object.defineProperty(mn,"__esModule",{value:!0}),mn.ErrorType=mn.SYNAPSE_RECOVERY_REASON=void 0,mn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},mn.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),mn}var Gn={},Bi;function xo(){if(Bi)return Gn;Bi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.ErrorUtils=void 0;const e=et();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return Gn.ErrorUtils=t,Gn}var Hi={},Gi;function Wi(){return Gi||(Gi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=br(),n=vo(),r=xo(),o=wo(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),f=i.get(u);if(f)return f;const E=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),p=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return p.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===p&&i.delete(u)}),i.set(u,p),p}function c(d){const h=i.get(d);return h&&i.delete(d),h}})(Hi)),Hi}var Ki;function Sd(){if(Ki)return Hn;Ki=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.TokenManager=void 0;const e=et(),t=No(),n=xo(),r=Wi();let o=class{constructor(i,s,a,c){O(this,"auth");O(this,"httpClient");O(this,"agentId");O(this,"partnerAuthToken");O(this,"refreshToken");O(this,"sessToken");O(this,"_userId");O(this,"_level");O(this,"_expiresAt");O(this,"lastResponse");O(this,"initPromise",null);O(this,"refreshPromise",null);O(this,"prefetchKey");O(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=c.partnerAuthToken,this.refreshToken=c.refreshToken,this.onTokenExchange=c.onTokenExchange,this._level=c.level,this._userId=c.userId,c.sessToken&&(this.sessToken=c.sessToken,this.httpClient.setAuthorization(c.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(c.serverUrl,a,c.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,c){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,c,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return Hn.TokenManager=o,Hn}var Wn={},qi;function wd(){var n;if(qi)return Wn;qi=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.VoiceResource=void 0;const e=$n();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},O(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),O(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Wn.VoiceResource=t,Wn}var Xi;function Zi(){if(Xi)return Fn;Xi=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.ResourceManager=void 0;const e=br(),t=Ui(),n=et(),r=So(),o=zi(),i=wo(),s=Sd(),a=wd();class c{constructor(h){O(this,"resourceConfig");O(this,"httpClient");O(this,"session");O(this,"config");O(this,"auth");O(this,"tokenManager");O(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:f,intent:E,user_location:p,referer:g,...b}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...f&&{user_context:f},...(E||Object.keys(b).length>0)&&{session_context:{...E&&{intent:E},...p&&{user_location:p},...b}},...g&&{referer:g}},y=await this.session.create(_);if(!y?.session_id)throw new n.APIError("Failed to start session.",500,void 0,void 0);return y}catch(f){throw f instanceof n.APIError?f:new n.APIError("Failed to start session.",500,void 0,void 0)}}async getAgentConfig(){this.config||(this.config=new r.Config(this.httpClient));const h=(0,o.consumePrefetchedAgentConfig)((0,o.buildAgentConfigKey)(this.resourceConfig.serverUrl,this.resourceConfig.agentId));if(h)try{return await h}catch{}try{return await this.config.retrieve(this.resourceConfig.agentId)}catch{throw new n.APIError("Failed to get agent config.",500,void 0,void 0)}}async reinitialiseSession(h){return await this.session.retrieve(h)}async getPastSessions(){return await this.session.history()}async getSessionMessages(h){return(await this.session.retrieve(h,{includeMessages:!0}))?.messages??[]}async refreshTokens(){return await this.tokenManager.refresh()}async sendFeedback({sessionId:h,messageId:u,feedback:f,feedbacks:E,feedbackReason:p,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:f,feedbacks:E,feedbackReason:p,npsBase5:g})}async callTool(h,u,f,E){return await this.session.callTool(h,u,f,E)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Fn.ResourceManager=c,Fn}var Kn={},Ji={},Qi;function Co(){return Qi||(Qi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MULTI_SELECT_ADDITIONAL_OPTION=e.SOCKET_EVENTS=e.SOCKET_CONTENT_TYPES=void 0,e.IsValidSocketMesssage=t,e.SOCKET_CONTENT_TYPES={TEXT:"text",AUDIO:"audio",FILE:"file",TOOL_CALL:"tool",TIPS:"tips",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},e.SOCKET_EVENTS={PING:"ping",PONG:"pong",CHAT:"chat",STREAM:"stream",AUTH:"auth",END_OF_STREAM:"eos",SYNC:"sync",ERROR:"err",CONNECTION_ESTABLISHED:"conn"},e.MULTI_SELECT_ADDITIONAL_OPTION={NOTA:"none_of_the_above",AOTA:"all_of_the_above"};function t(n){return[e.SOCKET_EVENTS.PING,e.SOCKET_EVENTS.PONG,e.SOCKET_EVENTS.ERROR,e.SOCKET_EVENTS.SYNC,e.SOCKET_EVENTS.CONNECTION_ESTABLISHED,e.SOCKET_EVENTS.CHAT,e.SOCKET_EVENTS.STREAM,e.SOCKET_EVENTS.END_OF_STREAM].includes(n.ev)}})(Ji)),Ji}var ea={},ta;function Nd(){return ta||(ta=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=et();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){O(this,"pendingFiles",[]);O(this,"pendingMessage","");O(this,"pendingFormats",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.filter(a=>a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const c=s[a].url,d=await fetch(c,{method:"PUT",body:this.pendingFiles[a],headers:{"Content-Type":this.pendingFiles[a].type,"x-ms-blob-type":"BlockBlob"}});if(!d.ok)throw new t.FileError(`Failed to upload ${this.pendingFiles[a].name} to URL ${a+1}: ${d.status} ${d.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(s[a].id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[]}}e.Filemanager=n})(ea)),ea}var ut={},na;function vr(){if(na)return ut;na=1,Object.defineProperty(ut,"__esModule",{value:!0}),ut.SYNAPSE_REALTIME_RESERVED_EVENTS=ut.SYNAPSE_REALTIME_ERROR_CODES=ut.SYNAPSE_REALTIME_EVENTS=ut.SYNAPSE_MESSAGE_TYPES=void 0;const e=Co();return ut.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,ut.SYNAPSE_REALTIME_EVENTS={CONNECTED:"connected",DISCONNECTED:"disconnected",PROGRESS_MESSAGE:"progress_message",MESSAGE_CHUNK:"message_chunk",TIPS_MESSAGE:"tips_message",END_OF_STREAM:"end_of_stream",ERROR:"error",TOOL_CALL:"tool_call",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},ut.SYNAPSE_REALTIME_ERROR_CODES={SESSION_INACTIVE:"session_not_found",SESSION_TOKEN_EXPIRED:"sess_token_expired",INVALID_EVENT:"invalid_event",INVALID_CONTENT_TYPE:"invalid_content",PARSING_ERROR:"parsing",FILE_UPLOAD_INPROGRESS:"file_upload_inprogress",TIMEOUT:"timeout",SERVER_ERROR:"server_error",SESSION_TOKEN_MISMATCH:"session_token_mismatch",PROMPT_FETCH_ERROR:"prompt_fetch_error",INVALID_FILE_REQUEST:"invalid_file_request",SESSION_NOT_OWNED:"session_not_owned"},ut.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},ut}var qn={},ra;function xd(){if(ra)return qn;ra=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.AudioManager=void 0;const e=et();class t{constructor(r={}){O(this,"mediaRecorder",null);O(this,"mediaStream",null);O(this,"recordingStartTime",0);O(this,"autoPauseTimer",null);O(this,"config");O(this,"onAudioData",null);O(this,"onAudioError",null);O(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return qn.AudioManager=t,qn}var oa;function sa(){if(oa)return Kn;oa=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.MessageManager=void 0;const e=Co(),t=Nd(),n=vr(),r=xd(),o=et();let i=class{constructor(s){O(this,"connection",null);O(this,"callbacks",null);O(this,"fileManager",null);O(this,"audioManager",null);O(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:c,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(c&&c.length>0){const f=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:c,...f&&{text:f},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:c,urls:d,tool_declined:h,tool_id:u,tool_result:f,initial_prompts:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...c&&{audio:c},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...f&&{tool_result:f},...E&&{initial_prompts:E}};return}const p=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:f})}else s?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},...E&&{initial_prompts:E},...f&&{tool_result:f}}}:c&&c?.audio&&c?.format?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:c?.audio,format:c?.format,...h&&{tool_declined:h},...f&&{tool_result:f}}}:f&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:f}});if(!g){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}p.sendMessage(g)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(c=>{this.sendSocketMessage({urls:c})}).catch(c=>{const d=this.toFileError(c,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,c)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const c={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,c)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,c)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const c={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,c);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const c=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),c={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(c)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const c=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(c),c}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,c=>{const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(c){const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,c,d){return(0,o.normalizeError)(s,o.FileError,a,{context:c,hint:d})}toRecordingError(s,a,c,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:c,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return Kn.MessageManager=i,Kn}var ia={},aa;function Cd(){return aa||(aa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.outcomeForHttpStatus=e.outcomeForCloseCode=e.RECOVERY_OUTCOME=void 0,e.RECOVERY_OUTCOME={REFRESH_AND_RETRY:"refresh_and_retry",FORBIDDEN:"forbidden",SESSION_GONE:"session_gone",RETRY_LATER:"retry_later",SESSION_NOT_OWNED:"session_not_owned"};const t={4401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,4403:e.RECOVERY_OUTCOME.FORBIDDEN,4404:e.RECOVERY_OUTCOME.SESSION_GONE,1013:e.RECOVERY_OUTCOME.RETRY_LATER},n={401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,403:e.RECOVERY_OUTCOME.FORBIDDEN,404:e.RECOVERY_OUTCOME.SESSION_GONE,429:e.RECOVERY_OUTCOME.RETRY_LATER,503:e.RECOVERY_OUTCOME.RETRY_LATER},r=i=>i===void 0?void 0:t[i];e.outcomeForCloseCode=r;const o=i=>i===void 0?void 0:n[i];e.outcomeForHttpStatus=o})(ia)),ia}var Xn={},Zn={},la;function Td(){if(la)return Zn;la=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){O(this,"audioCtx",null);O(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),c=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(c)};c()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return Zn.VoiceAudioAnalyser=t,Zn}var pn={},ca;function da(){return ca||(ca=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.VOICE_AGENT_EVENTS=pn.VOICE_AGENT_STATE=void 0,pn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},pn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),pn}var ua;function kd(){if(ua)return Xn;ua=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.VoiceAgent=void 0;const e=yo(),t=Td(),n=et(),r=da(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(f=>{if(h.iceGatheringState==="complete"){f();return}const E=setTimeout(f,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),f())}})}let d=class{constructor(h,u,f){O(this,"config");O(this,"resourceManager");O(this,"getCredentials");O(this,"emitter",new e.EventEmitter);O(this,"remoteAnalyser",new t.VoiceAudioAnalyser);O(this,"localAnalyser",new t.VoiceAudioAnalyser);O(this,"pc",null);O(this,"pcId",null);O(this,"dataChannel",null);O(this,"localStream",null);O(this,"remoteAudio",null);O(this,"_state",r.VOICE_AGENT_STATE.IDLE);O(this,"_isMuted",!1);O(this,"manuallyDisconnected",!1);O(this,"_hasConnectionFailureNotified",!1);O(this,"_userSpeaking",!1);O(this,"_silenceTimer",null);O(this,"_cachedIceServers",null);O(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=f}get state(){return this._state}get isMuted(){return this._isMuted}on(h,u){this.emitter.on(h,u)}off(h,u){this.emitter.off(h,u)}async connect(){const h=await this.getCredentials();this.setState(r.VOICE_AGENT_STATE.CONNECTING),this._hasConnectionFailureNotified=!1;try{if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available. Please ensure you are using a secure (HTTPS) connection.");const u=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=u;const f=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:f,iceTransportPolicy:"all"});this.pc=E,this.dataChannel=E.createDataChannel("pipecat-events",{ordered:!0}),this.dataChannel.onopen=()=>{},this.dataChannel.onclose=()=>this.handleConnectionFailure(new Error("Data channel closed"),"Voice connection failed"),this.dataChannel.onerror=()=>this.handleConnectionFailure(new Error("Data channel error"),"Voice connection failed"),u.getAudioTracks().forEach(_=>E.addTrack(_,u)),E.ontrack=_=>this.handleRemoteTrack(_),E.onconnectionstatechange=()=>{E.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(E.connectionState==="failed"||E.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},E.oniceconnectionstatechange=()=>{(E.iceConnectionState==="connected"||E.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):E.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const p=await E.createOffer();await E.setLocalDescription(p);const g=this.config.iceGatheringTimeoutMs??o;await c(E,g);const b=_=>({sdp:E.localDescription.sdp,type:E.localDescription.type,pc_id:this.pcId,request_data:{session_id:_.sessionId,token:_.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(b(h))}catch(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(b(y))}else throw _}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,E.signalingState==="closed")return;await E.setRemoteDescription(new RTCSessionDescription({sdp:m.sdp,type:m.type}))}catch(u){this.handleConnectionFailure(u)}}disconnect(){this.manuallyDisconnected=!0,this.setState(r.VOICE_AGENT_STATE.DISCONNECTING),this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE)}toggleMute(){if(!this.localStream)return;const h=this.localStream.getAudioTracks()[0];if(!h)return;const u=h.enabled;this.localStream.getAudioTracks().forEach(f=>{f.enabled=!u}),this._isMuted=u,this.clearSilenceTimer(),this._userSpeaking=!1,this.setState(u?r.VOICE_AGENT_STATE.MUTED:r.VOICE_AGENT_STATE.LISTENING)}reset(){this.setState(r.VOICE_AGENT_STATE.IDLE)}destroy(){this.releaseResources(),this.emitter.removeAllListeners(),this._state=r.VOICE_AGENT_STATE.IDLE}async fetchIceServers(h){if(this.config.iceServers)return this.config.iceServers;const u=Date.now();if(this._cachedIceServers&&u-this._iceServersCachedAt<s)return this._cachedIceServers;let f;try{f=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const p=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(p.sessionId)}else throw E}if(!Array.isArray(f?.ice_servers)||f.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=f.ice_servers,this._iceServersCachedAt=Date.now(),this._cachedIceServers}setState(h){this._state=h,this.emitter.emit(r.VOICE_AGENT_EVENTS.STATE_CHANGED,h)}clearSilenceTimer(){this._silenceTimer!==null&&(clearTimeout(this._silenceTimer),this._silenceTimer=null)}handleConnectionFailure(h,u="Voice connection failed"){if(this._hasConnectionFailureNotified||this._state===r.VOICE_AGENT_STATE.DISCONNECTING||this.manuallyDisconnected)return;this._hasConnectionFailureNotified=!0,this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.ERROR);const f={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,f)}releaseResources(){this.remoteAnalyser.stop(),this.localAnalyser.stop(),this.clearSilenceTimer(),this._userSpeaking=!1,this.localStream&&(this.localStream.getTracks().forEach(h=>h.stop()),this.localStream=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.pc&&(this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.ondatachannel=null,this.pc.close(),this.pc=null),this.pcId=null,this._isMuted=!1,this.remoteAudio&&(this.remoteAudio.srcObject=null)}startLocalAudioAnalysis(h){const u=this.config.speakingThreshold??i;this.localAnalyser.start(h,u,f=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(f?(this._userSpeaking=!0,this.clearSilenceTimer(),this._state===r.VOICE_AGENT_STATE.THINKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)):this._userSpeaking&&this._silenceTimer===null&&(this._silenceTimer=setTimeout(()=>{this._silenceTimer=null,this._userSpeaking&&this._state===r.VOICE_AGENT_STATE.LISTENING&&(this._userSpeaking=!1,this.setState(r.VOICE_AGENT_STATE.THINKING))},a)))})}handleRemoteTrack(h){this.remoteAudio||(this.remoteAudio=new Audio,this.remoteAudio.autoplay=!0);const u=h.streams[0];this.remoteAudio.srcObject=u;const f=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,f,E=>{E?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return Xn.VoiceAgent=d,Xn}var ha;function Rd(){if(ha)return An;ha=1,Object.defineProperty(An,"__esModule",{value:!0}),An.SynapseSDK=void 0;const e=Ii(),t=Dn(),n=vo(),r=Zi(),o=sa(),i=vr(),s=yo(),a=et(),c=No(),d=Cd(),h=Co(),u=kd();class f{constructor(p){O(this,"connection",null);O(this,"messageManager");O(this,"resourceManager");O(this,"sessionConfig",null);O(this,"config");O(this,"connectionType");O(this,"isRefreshingSession",!1);O(this,"isRecovering",!1);O(this,"forceConsumed",!1);O(this,"connectionAttempts",0);O(this,"sdkEventEmitter",new s.EventEmitter);O(this,"_voice",null);O(this,"pendingNetworkReconnect",!1);O(this,"boundOnlineHandler",null);O(this,"isReconnecting",!1);O(this,"reconnectTimer",null);O(this,"boundVisibilityHandler",null);O(this,"isSessionNotOwned",!1);this.config={...p,environment:p.environment||"production"},this.connectionType=p.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const p=await this.resourceManager.refreshBearer();if(!p)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(g){this.emitError(this.toConnectionError(g,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return p}async startSession(p){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,p=void 0),await this.resourceManager.ensureCredentials();const g=p?.session_id?p:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:p,files:g,audio:b,tool_declined:m,tool_id:_,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:p,files:g,audio:b,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(S){this.emitError(S)}break;default:const T=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(T),T}}async sendMessageFeedback(p,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:p,feedback:g,feedbackReason:b});break}}async sendSessionFeedback(p,g){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!p?.length&&!g){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:p,npsBase5:g});break}}on(p,g){this.sdkEventEmitter.on(p,g)}off(p,g){this.sdkEventEmitter.off(p,g)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(p){return await this.resourceManager.getSessionMessages(p)}async callTool(p,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,p,g,b);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let _={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,_);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:p,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:p,onError:g})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const p=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(p),p}}async getAgentConfig(){return this.resourceManager.getAgentConfig()}isConnected(){return this.connection?.isConnected()??!1}clearTokens(){this.resourceManager.clearTokens()}get voice(){return this._voice||(this._voice=new u.VoiceAgent(this.buildVoiceConfig(),this.resourceManager,async()=>(await this.resourceManager.exchangeInit(),{sessionId:(await this.resourceManager.createSession()).session_id,sessionToken:this.resourceManager.getSessToken()||""}))),this._voice}endSession(){this._voice?.destroy(),this._voice=null,this.closeConnection(),this.cleanup()}buildVoiceConfig(){return{offerUrl:`${this.config.serverUrl||(0,n.getConfig)(this.config.environment).BASE_API_URL}/med-assist/voice/offer`,handleRefresh:async()=>{await this.resourceManager.refreshTokens()}}}toClientError(p){if(p instanceof a.APIError){const g=p.reason??(p.status===401||p.status===403?c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:p.error?.msg||p.message,error:p.error,code:p.code,...g&&{reason:g},status:p.status,context:p.context}}return p instanceof a.SynapseError?{message:p.displayMessage||p.message,code:p.code,...p.reason&&{reason:p.reason},context:p.context}:p instanceof Error?{message:p.message}:{message:"An unexpected error occurred"}}emitError(p){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(p))}toSessionError(p,g,b,m){return(0,a.normalizeError)(p,a.SessionError,g,{context:b,hint:m})}async initializeConnection(p){if(this.closeConnection(),!p.session_id||!this.resourceManager.getSessToken())throw new a.SessionError("Session ID or sess token not found",{context:{stage:"initializeConnection"},hint:"Ensure the token exchange and session API completed successfully."});this.sessionConfig=p;const g=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?g.WEBSOCKET_URL:g.BASE_API_URL,_=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:_||m,auth:{sessionId:p.session_id,getToken:()=>this.resourceManager.getSessToken()||"",onUnauthorized:()=>this.resourceManager.refreshBearer()},agentId:this.config.agentId,userId:this.config.userId,overrides:this.config.overrides,...this.config.channel&&{channel:this.config.channel}}),this.connectionAttempts++,this.messageManager.setConnection(this.connection);const y=this.connection.emit.bind(this.connection);this.connection.emit=(k,...T)=>{y(k,...T),this.sdkEventEmitter.emit(k,...T)}}async createNewSession(){return await this.resourceManager.createSession(this.config.userId,this.config.context)}setupEventHandlers(){if(!this.connection)return;this.connection.onOpen(()=>{switch(this.connectionType){case e.ConnectionType.SOCKET:this.onSocketConnectionOpen();break;case e.ConnectionType.HTTP_STREAM:this.messageManager.handleConnectionEstablished();break}}),this.connection.onMessage(g=>{this.onIncomingSocketMessage(g)}),this.connection.onError(g=>{this.onRealtimeConnectionError(g)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const p=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==p||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(g.code);if(b){await this.handleRecovery(b,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(p){if(p instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(p.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:p.message,code:p.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,p);const g=p instanceof a.APIError?p:this.toConnectionError(p,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const p=this.resourceManager.getSessToken();if(!p){const g=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(g),g}this.messageManager.sendSocketAuthMessage(p)}onIncomingSocketMessage(p){switch(p.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(p);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(p);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(p);break;case h.SOCKET_EVENTS.PING:this.messageManager.sendSocketPongMessage();break;case h.SOCKET_EVENTS.PONG:this.messageManager.sendSocketPingMessage();break;case h.SOCKET_EVENTS.SYNC:break;case h.SOCKET_EVENTS.ERROR:this.messageManager.handleIncomingSocketErrorMessage(p);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:p.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const p=this.resourceManager.getLevel();return p?p==="user":!!this.config.authToken}statusOf(p){if(p instanceof a.APIError)return p.status;if(p instanceof a.SynapseError&&typeof p.context?.status=="number")return p.context.status}emitRecoveryError(p,g,b){this.emitError(new a.SessionError(g,{reason:p,cause:b,context:{stage:"connectionRecovery",reason:p}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(p,g){if(p===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(p){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(p){const g=this.statusOf(p);if(g!==403&&g!==401){this.emitError(this.toSessionError(p,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",p)}}async recoverMissingSession(){const p=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!p){this.closeConnection(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(p);await this.connectTo(g);return}catch(g){const b=this.statusOf(g);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);return}try{await this.connectTo(await this.createNewSession())}catch(m){const _=this.statusOf(m);if(_===401||_===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(p){await this.initializeConnection(p),this.setupEventHandlers()}async handleAuthExpiry(){if(!(this.isRefreshingSession||this.isRecovering)){this.isRefreshingSession=!0,this.isRecovering=!0;try{await this.recoverExpiredCredentials()}finally{this.isRefreshingSession=!1,this.isRecovering=!1}}}async handleSessionInactiveMessage(){if(!this.isRecovering){this.isRecovering=!0;try{await this.recoverMissingSession()}finally{this.isRecovering=!1}}}toConnectionError(p,g,b,m){return(0,a.normalizeError)(p,a.ConnectionError,g,{context:b,hint:m})}scheduleReconnect(p){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(p);return}const g=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(p)}}},g)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return An.SynapseSDK=f,An}var ma={},pa;function Od(){return pa||(pa=1,Object.defineProperty(ma,"__esModule",{value:!0})),ma}var Sr={},fa;function Ad(){return fa||(fa=1,Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.USER_FEEDBACK=void 0,Sr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Sr}var ga={},_a;function Id(){return _a||(_a=1,Object.defineProperty(ga,"__esModule",{value:!0})),ga}var Jn={},Ea;function Md(){if(Ea)return Jn;Ea=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.ToolCall=void 0;const e=$n();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return Jn.ToolCall=t,Jn}var Ye={},ya;function Pd(){if(ya)return Ye;ya=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.SYNAPSE_EICITATION_STATUS=Ye.SYNAPSE_CTA_ACTIONS=Ye.SYNAPSE_TOOL_FORMATS=Ye.SYNAPSE_TOOL_CALLBACK_NAME=Ye.SYNAPSE_COMPONENTS=Ye.SYNAPSE_TOOL_NAME=void 0;var e;(function(s){s.MOBILE_VERIFICATION="mobile_verification",s.AVAILABILITY_DATES="availability_dates",s.AVAILABILITY_SLOTS="availability_slots",s.DOCTOR_AVAILABILITY="doctor_availability",s.DOCTOR_DETAILS="doctor_details",s.GET_LOCATION="get_location"})(e||(Ye.SYNAPSE_TOOL_NAME=e={}));var t;(function(s){s.MOBILE="mobile_number",s.OTP="otp",s.EMAIL="email_address",s.PILL="pills",s.MULTI="multi",s.DOCTOR_CARD="doctor_card",s.CARD="card",s.MEDIA_CARD="media_card"})(t||(Ye.SYNAPSE_COMPONENTS=t={}));var n;(function(s){s.DOCTOR_AVAILABILITY="get_doctor_availability",s.AVAILABILITY_DATES="get_available_dates",s.AVAILABILITY_SLOTS="get_available_slots",s.MOBILE_VERIFICATION="verify_mobile_number",s.DOCTOR_DETAILS="get_doctor_details"})(n||(Ye.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Ye.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Ye.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Ye.SYNAPSE_EICITATION_STATUS=i={})),Ye}var ba={},va;function Dd(){return va||(va=1,Object.defineProperty(ba,"__esModule",{value:!0})),ba}var Sa={},wa;function Ld(){return wa||(wa=1,Object.defineProperty(Sa,"__esModule",{value:!0})),Sa}var Qn={},Na;function Ud(){if(Na)return Qn;Na=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(Qn.SYNAPSE_CONVERSATION=e={})),Qn}var fn={},xa;function Fd(){return xa||(xa=1,(function(e){var t=fn&&fn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=fn&&fn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(da(),e)})(fn)),fn}var Ca;function Vd(){return Ca||(Ca=1,(function(e){var t=un&&un.__createBinding||(Object.create?(function(S,x,v,w){w===void 0&&(w=v);var N=Object.getOwnPropertyDescriptor(x,v);(!N||("get"in N?!x.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return x[v]}}),Object.defineProperty(S,w,N)}):(function(S,x,v,w){w===void 0&&(w=v),S[w]=x[v]})),n=un&&un.__exportStar||function(S,x){for(var v in S)v!=="default"&&!Object.prototype.hasOwnProperty.call(x,v)&&t(x,S,v)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=Rd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=bo();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=xi();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Oi();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Ii();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Dn(),e);var c=Zi();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(Od(),e);var d=Ui();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(Ad(),e);var h=wo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=Wi();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(Id(),e);var f=So();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var E=zi();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var p=Md();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return p.ToolCall}}),n(Pd(),e);var g=sa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(vr(),e),n(Dd(),e);var b=br();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=et();Object.defineProperty(e,"SynapseError",{enumerable:!0,get:function(){return m.SynapseError}}),Object.defineProperty(e,"APIError",{enumerable:!0,get:function(){return m.APIError}}),Object.defineProperty(e,"APIUserAbortError",{enumerable:!0,get:function(){return m.APIUserAbortError}}),Object.defineProperty(e,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return m.APIConnectionTimeoutError}}),Object.defineProperty(e,"BadRequestError",{enumerable:!0,get:function(){return m.BadRequestError}}),Object.defineProperty(e,"UnauthorizedError",{enumerable:!0,get:function(){return m.UnauthorizedError}}),Object.defineProperty(e,"PermissionDeniedError",{enumerable:!0,get:function(){return m.PermissionDeniedError}}),Object.defineProperty(e,"NotFoundError",{enumerable:!0,get:function(){return m.NotFoundError}}),Object.defineProperty(e,"MethodNotAllowedError",{enumerable:!0,get:function(){return m.MethodNotAllowedError}}),Object.defineProperty(e,"RateLimitError",{enumerable:!0,get:function(){return m.RateLimitError}}),Object.defineProperty(e,"InternalServerError",{enumerable:!0,get:function(){return m.InternalServerError}}),Object.defineProperty(e,"SynapseErrorCode",{enumerable:!0,get:function(){return m.SynapseErrorCode}});var _=No();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return _.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return _.SYNAPSE_RECOVERY_REASON}});var y=xo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(Ld(),e);var k=ki();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var T=vr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return T.SYNAPSE_MESSAGE_TYPES}}),n(Ud(),e),n(Fd(),e)})(un)),un}var M=Vd();function Ta(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=Ta(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function ka(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ta(e))&&(r&&(r+=" "),r+=t);return r}const jd=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},zd=(e,t)=>({classGroupId:e,validator:t}),Ra=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),wr="-",Oa=[],$d="arbitrary..",Yd=e=>{const t=Hd(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Bd(o);const i=o.split(wr),s=i[0]===""&&i.length>1?1:0;return Aa(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?jd(a,s):s:a||Oa}return n[o]||Oa}}},Aa=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=Aa(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(wr):e.slice(t).join(wr),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},Bd=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?$d+r:void 0})(),Hd=e=>{const{theme:t,classGroups:n}=e;return Gd(n,t)},Gd=(e,t)=>{const n=Ra();for(const r in e){const o=e[r];To(o,n,r,t)}return n},To=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];Wd(s,t,n,r)}},Wd=(e,t,n,r)=>{if(typeof e=="string"){Kd(e,t,n);return}if(typeof e=="function"){qd(e,t,n,r);return}Xd(e,t,n,r)},Kd=(e,t,n)=>{const r=e===""?t:Ia(t,e);r.classGroupId=n},qd=(e,t,n,r)=>{if(Zd(e)){To(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(zd(n,e))},Xd=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];To(c,Ia(t,a),n,r)}},Ia=(e,t)=>{let n=e;const r=t.split(wr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Ra(),n.nextPart.set(s,a)),n=a}return n},Zd=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Jd=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},ko="!",Ma=":",Qd=[],Pa=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),eu=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,c=0,d;const h=o.length;for(let g=0;g<h;g++){const b=o[g];if(s===0&&a===0){if(b===Ma){i.push(o.slice(c,g)),c=g+1;continue}if(b==="/"){d=g;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(c);let f=u,E=!1;u.endsWith(ko)?(f=u.slice(0,-1),E=!0):u.startsWith(ko)&&(f=u.slice(1),E=!0);const p=d&&d>c?d-c:void 0;return Pa(i,E,f,p)};if(t){const o=t+Ma,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Pa(Qd,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},tu=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",c=t.has(s);a||c?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},nu=e=>({cache:Jd(e.cacheSize),parseClassName:eu(e),sortModifiers:tu(e),...Yd(e)}),ru=/\s+/,ou=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(ru);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:f,hasImportantModifier:E,baseClassName:p,maybePostfixModifierPosition:g}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let b=!!g,m=r(b?p.substring(0,g):p);if(!m){if(!b){c=h+(c.length>0?" "+c:c);continue}if(m=r(p),!m){c=h+(c.length>0?" "+c:c);continue}b=!1}const _=f.length===0?"":f.length===1?f[0]:i(f).join(":"),y=E?_+ko:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const T=o(m,b);for(let S=0;S<T.length;++S){const x=T[S];s.push(y+x)}c=h+(c.length>0?" "+c:c)}return c},su=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Da(n))&&(o&&(o+=" "),o+=r);return o},Da=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Da(e[r]))&&(n&&(n+=" "),n+=t);return n},iu=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=nu(d),r=n.cache.get,o=n.cache.set,i=a,a(c)},a=c=>{const d=r(c);if(d)return d;const h=ou(c,n);return o(c,h),h};return i=s,(...c)=>i(su(...c))},au=[],Ae=e=>{const t=n=>n[e]||au;return t.isThemeGetter=!0,t},La=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Ua=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lu=/^\d+\/\d+$/,cu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,du=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,uu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,mu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,gn=e=>lu.test(e),te=e=>!!e&&!Number.isNaN(Number(e)),Ut=e=>!!e&&Number.isInteger(Number(e)),Ro=e=>e.endsWith("%")&&te(e.slice(0,-1)),Tt=e=>cu.test(e),pu=()=>!0,fu=e=>du.test(e)&&!uu.test(e),Fa=()=>!1,gu=e=>hu.test(e),_u=e=>mu.test(e),Eu=e=>!V(e)&&!j(e),yu=e=>_n(e,Ya,Fa),V=e=>La.test(e),Bt=e=>_n(e,Ba,fu),Oo=e=>_n(e,Nu,te),Va=e=>_n(e,za,Fa),bu=e=>_n(e,$a,_u),Nr=e=>_n(e,Ha,gu),j=e=>Ua.test(e),er=e=>En(e,Ba),vu=e=>En(e,xu),ja=e=>En(e,za),Su=e=>En(e,Ya),wu=e=>En(e,$a),xr=e=>En(e,Ha,!0),_n=(e,t,n)=>{const r=La.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},En=(e,t,n=!1)=>{const r=Ua.exec(e);return r?r[1]?t(r[1]):n:!1},za=e=>e==="position"||e==="percentage",$a=e=>e==="image"||e==="url",Ya=e=>e==="length"||e==="size"||e==="bg-size",Ba=e=>e==="length",Nu=e=>e==="number",xu=e=>e==="family-name",Ha=e=>e==="shadow",Cu=()=>{const e=Ae("color"),t=Ae("font"),n=Ae("text"),r=Ae("font-weight"),o=Ae("tracking"),i=Ae("leading"),s=Ae("breakpoint"),a=Ae("container"),c=Ae("spacing"),d=Ae("radius"),h=Ae("shadow"),u=Ae("inset-shadow"),f=Ae("text-shadow"),E=Ae("drop-shadow"),p=Ae("blur"),g=Ae("perspective"),b=Ae("aspect"),m=Ae("ease"),_=Ae("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...k(),j,V],S=()=>["auto","hidden","clip","visible","scroll"],x=()=>["auto","contain","none"],v=()=>[j,V,c],w=()=>[gn,"full","auto",...v()],N=()=>[Ut,"none","subgrid",j,V],A=()=>["auto",{span:["full",Ut,j,V]},Ut,j,V],Y=()=>[Ut,"auto",j,V],q=()=>["auto","min","max","fr",j,V],ae=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],de=()=>["start","end","center","stretch","center-safe","end-safe"],le=()=>["auto",...v()],ue=()=>[gn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],F=()=>[e,j,V],Ce=()=>[...k(),ja,Va,{position:[j,V]}],$=()=>["no-repeat",{repeat:["","x","y","space","round"]}],B=()=>["auto","cover","contain",Su,yu,{size:[j,V]}],H=()=>[Ro,er,Bt],L=()=>["","none","full",d,j,V],W=()=>["",te,er,Bt],oe=()=>["solid","dashed","dotted","double"],je=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],K=()=>[te,Ro,ja,Va],me=()=>["","none",p,j,V],Be=()=>["none",te,j,V],ze=()=>["none",te,j,V],tt=()=>[te,j,V],Xe=()=>[gn,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tt],breakpoint:[Tt],color:[pu],container:[Tt],"drop-shadow":[Tt],ease:["in","out","in-out"],font:[Eu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tt],shadow:[Tt],spacing:["px",te],text:[Tt],"text-shadow":[Tt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",gn,V,j,b]}],container:["container"],columns:[{columns:[te,V,j,a]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:x()}],"overscroll-x":[{"overscroll-x":x()}],"overscroll-y":[{"overscroll-y":x()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:w()}],"inset-x":[{"inset-x":w()}],"inset-y":[{"inset-y":w()}],start:[{start:w()}],end:[{end:w()}],top:[{top:w()}],right:[{right:w()}],bottom:[{bottom:w()}],left:[{left:w()}],visibility:["visible","invisible","collapse"],z:[{z:[Ut,"auto",j,V]}],basis:[{basis:[gn,"full","auto",a,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[te,gn,"auto","initial","none",V]}],grow:[{grow:["",te,j,V]}],shrink:[{shrink:["",te,j,V]}],order:[{order:[Ut,"first","last","none",j,V]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":Y()}],"col-end":[{"col-end":Y()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":Y()}],"row-end":[{"row-end":Y()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":q()}],"auto-rows":[{"auto-rows":q()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...ae(),"normal"]}],"justify-items":[{"justify-items":[...de(),"normal"]}],"justify-self":[{"justify-self":["auto",...de()]}],"align-content":[{content:["normal",...ae()]}],"align-items":[{items:[...de(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...de(),{baseline:["","last"]}]}],"place-content":[{"place-content":ae()}],"place-items":[{"place-items":[...de(),"baseline"]}],"place-self":[{"place-self":["auto",...de()]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:le()}],mx:[{mx:le()}],my:[{my:le()}],ms:[{ms:le()}],me:[{me:le()}],mt:[{mt:le()}],mr:[{mr:le()}],mb:[{mb:le()}],ml:[{ml:le()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:ue()}],w:[{w:[a,"screen",...ue()]}],"min-w":[{"min-w":[a,"screen","none",...ue()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...ue()]}],h:[{h:["screen","lh",...ue()]}],"min-h":[{"min-h":["screen","lh","none",...ue()]}],"max-h":[{"max-h":["screen","lh",...ue()]}],"font-size":[{text:["base",n,er,Bt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,j,Oo]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Ro,V]}],"font-family":[{font:[vu,V,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,j,V]}],"line-clamp":[{"line-clamp":[te,"none",j,Oo]}],leading:[{leading:[i,...v()]}],"list-image":[{"list-image":["none",j,V]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",j,V]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...oe(),"wavy"]}],"text-decoration-thickness":[{decoration:[te,"from-font","auto",j,Bt]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[te,"auto",j,V]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",j,V]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",j,V]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Ce()}],"bg-repeat":[{bg:$()}],"bg-size":[{bg:B()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ut,j,V],radial:["",j,V],conic:[Ut,j,V]},wu,bu]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:H()}],"gradient-via-pos":[{via:H()}],"gradient-to-pos":[{to:H()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:L()}],"rounded-s":[{"rounded-s":L()}],"rounded-e":[{"rounded-e":L()}],"rounded-t":[{"rounded-t":L()}],"rounded-r":[{"rounded-r":L()}],"rounded-b":[{"rounded-b":L()}],"rounded-l":[{"rounded-l":L()}],"rounded-ss":[{"rounded-ss":L()}],"rounded-se":[{"rounded-se":L()}],"rounded-ee":[{"rounded-ee":L()}],"rounded-es":[{"rounded-es":L()}],"rounded-tl":[{"rounded-tl":L()}],"rounded-tr":[{"rounded-tr":L()}],"rounded-br":[{"rounded-br":L()}],"rounded-bl":[{"rounded-bl":L()}],"border-w":[{border:W()}],"border-w-x":[{"border-x":W()}],"border-w-y":[{"border-y":W()}],"border-w-s":[{"border-s":W()}],"border-w-e":[{"border-e":W()}],"border-w-t":[{"border-t":W()}],"border-w-r":[{"border-r":W()}],"border-w-b":[{"border-b":W()}],"border-w-l":[{"border-l":W()}],"divide-x":[{"divide-x":W()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":W()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...oe(),"hidden","none"]}],"divide-style":[{divide:[...oe(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...oe(),"none","hidden"]}],"outline-offset":[{"outline-offset":[te,j,V]}],"outline-w":[{outline:["",te,er,Bt]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",h,xr,Nr]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",u,xr,Nr]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[te,Bt]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",f,xr,Nr]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[te,j,V]}],"mix-blend":[{"mix-blend":[...je(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":je()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[te]}],"mask-image-linear-from-pos":[{"mask-linear-from":K()}],"mask-image-linear-to-pos":[{"mask-linear-to":K()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":K()}],"mask-image-t-to-pos":[{"mask-t-to":K()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":K()}],"mask-image-r-to-pos":[{"mask-r-to":K()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":K()}],"mask-image-b-to-pos":[{"mask-b-to":K()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":K()}],"mask-image-l-to-pos":[{"mask-l-to":K()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":K()}],"mask-image-x-to-pos":[{"mask-x-to":K()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":K()}],"mask-image-y-to-pos":[{"mask-y-to":K()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[j,V]}],"mask-image-radial-from-pos":[{"mask-radial-from":K()}],"mask-image-radial-to-pos":[{"mask-radial-to":K()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[te]}],"mask-image-conic-from-pos":[{"mask-conic-from":K()}],"mask-image-conic-to-pos":[{"mask-conic-to":K()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Ce()}],"mask-repeat":[{mask:$()}],"mask-size":[{mask:B()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",j,V]}],filter:[{filter:["","none",j,V]}],blur:[{blur:me()}],brightness:[{brightness:[te,j,V]}],contrast:[{contrast:[te,j,V]}],"drop-shadow":[{"drop-shadow":["","none",E,xr,Nr]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",te,j,V]}],"hue-rotate":[{"hue-rotate":[te,j,V]}],invert:[{invert:["",te,j,V]}],saturate:[{saturate:[te,j,V]}],sepia:[{sepia:["",te,j,V]}],"backdrop-filter":[{"backdrop-filter":["","none",j,V]}],"backdrop-blur":[{"backdrop-blur":me()}],"backdrop-brightness":[{"backdrop-brightness":[te,j,V]}],"backdrop-contrast":[{"backdrop-contrast":[te,j,V]}],"backdrop-grayscale":[{"backdrop-grayscale":["",te,j,V]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[te,j,V]}],"backdrop-invert":[{"backdrop-invert":["",te,j,V]}],"backdrop-opacity":[{"backdrop-opacity":[te,j,V]}],"backdrop-saturate":[{"backdrop-saturate":[te,j,V]}],"backdrop-sepia":[{"backdrop-sepia":["",te,j,V]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",j,V]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[te,"initial",j,V]}],ease:[{ease:["linear","initial",m,j,V]}],delay:[{delay:[te,j,V]}],animate:[{animate:["none",_,j,V]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,j,V]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:Be()}],"rotate-x":[{"rotate-x":Be()}],"rotate-y":[{"rotate-y":Be()}],"rotate-z":[{"rotate-z":Be()}],scale:[{scale:ze()}],"scale-x":[{"scale-x":ze()}],"scale-y":[{"scale-y":ze()}],"scale-z":[{"scale-z":ze()}],"scale-3d":["scale-3d"],skew:[{skew:tt()}],"skew-x":[{"skew-x":tt()}],"skew-y":[{"skew-y":tt()}],transform:[{transform:[j,V,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Xe()}],"translate-x":[{"translate-x":Xe()}],"translate-y":[{"translate-y":Xe()}],"translate-z":[{"translate-z":Xe()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",j,V]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",j,V]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[te,er,Bt,Oo]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Tu=iu(Cu);function I(...e){return Tu(ka(e))}function Ht(e){if(!e&&e!==0)return"";const t=e instanceof Date?e:new Date(typeof e=="number"?e:Number(e)||e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}const ku=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},Ru=e=>new Promise(t=>setTimeout(t,e)),Ga=Q(({className:e,children:t,...n},r)=>l(_i,{ref:r,className:I("relative overflow-hidden",e),...n,children:[l(yd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(Wa,{}),l(bd,{})]}));Ga.displayName=_i.displayName;const Wa=Q(({className:e,orientation:t="vertical",...n},r)=>l(go,{ref:r,orientation:t,className:I("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:l(ui,{className:"relative flex-1 rounded-full bg-border"})}));Wa.displayName=go.displayName;var Ou=Symbol.for("react.lazy"),Cr=mo[" use ".trim().toString()];function Au(e){return typeof e=="object"&&e!==null&&"then"in e}function Ka(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Ou&&"_payload"in e&&Au(e._payload)}function qa(e){const t=Mu(e),n=Q((r,o)=>{let{children:i,...s}=r;Ka(i)&&typeof Cr=="function"&&(i=Cr(i._payload));const a=Je.toArray(i),c=a.find(Du);if(c){const d=c.props.children,h=a.map(u=>u===c?Je.count(d)>1?Je.only(null):Qe(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Qe(d)?Mt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var Iu=qa("Slot");function Mu(e){const t=Q((n,r)=>{let{children:o,...i}=n;if(Ka(o)&&typeof Cr=="function"&&(o=Cr(o._payload)),Qe(o)){const s=Uu(o),a=Lu(i,o.props);return o.type!==ce&&(a.ref=r?po(r,s):s),Mt(o,a)}return Je.count(o)>1?Je.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Pu=Symbol("radix.slottable");function Du(e){return Qe(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Pu}function Lu(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Uu(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const Xa=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Za=ka,Fu=(e,t)=>n=>{var r;if(t?.variants==null)return Za(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n?.[d],u=i?.[d];if(h===null)return null;const f=Xa(h)||Xa(u);return o[d][f]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,f]=h;return f===void 0||(d[u]=f),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:f,...E}=h;return Object.entries(E).every(p=>{let[g,b]=p;return Array.isArray(b)?b.includes({...i,...a}[g]):{...i,...a}[g]===b})?[...d,u,f]:d},[]);return Za(e,s,c,n?.class,n?.className)},Vu=Fu("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),ie=Q(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?Iu:"button",{className:I(Vu({variant:t,size:n,className:e})),ref:i,...o}));ie.displayName="Button";const ju=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zu=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),Ja=e=>{const t=zu(e);return t.charAt(0).toUpperCase()+t.slice(1)},Qa=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),$u=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Yu={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Bu=Q(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>Ke("svg",{ref:c,...Yu,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Qa("lucide",o),...!i&&!$u(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>Ke(d,h)),...Array.isArray(i)?i:[i]])),Pe=(e,t)=>{const n=Q(({className:r,...o},i)=>Ke(Bu,{ref:i,iconNode:t,className:Qa(`lucide-${ju(Ja(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Ja(e),n},Hu=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ao=Pe("chevron-down",Hu),Gu=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Wu=Pe("ellipsis-vertical",Gu),Ku=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],el=Pe("file-text",Ku),qu=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],tl=Pe("info",qu),Xu=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],Zu=Pe("maximize-2",Xu),Ju=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Qu=Pe("menu",Ju),eh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],tr=Pe("message-square-plus",eh),th=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],Io=Pe("mic",th),nh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],rh=Pe("minimize-2",nh),oh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],nl=Pe("plus",oh),sh=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],ih=Pe("rotate-ccw",sh),ah=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],rl=Pe("square",ah),lh=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],Tr=Pe("thumbs-up",lh),ch=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],kr=Pe("thumbs-down",ch),dh=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],uh=Pe("triangle-alert",dh),hh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],yn=Pe("x",hh),mh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],ph=Pe("zoom-in",mh),ol=e=>{let t;const n=new Set,r=(a,c)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=c??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},fh=(e=>e?ol(e):ol),gh=e=>e;function _h(e,t=gh){const n=On.useSyncExternalStore(e.subscribe,On.useCallback(()=>t(e.getState()),[e,t]),On.useCallback(()=>t(e.getInitialState()),[e,t]));return On.useDebugValue(n),n}const Eh=e=>{const t=fh(e),n=r=>_h(t,r);return Object.assign(n,t),n},yh=(e=>Eh);function sl(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var o;const i=a=>a===null?null:JSON.parse(a,void 0),s=(o=n.getItem(r))!=null?o:null;return s instanceof Promise?s.then(i):i(s)},setItem:(r,o)=>n.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>n.removeItem(r)}}const Mo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Mo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Mo(r)(n)}}}},bh=(e,t)=>(n,r,o)=>{let i={storage:sl(()=>localStorage),partialize:g=>g,version:0,merge:(g,b)=>({...b,...g}),...t},s=!1;const a=new Set,c=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,b)=>(u(g,b),h());const f=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>f;let E;const p=()=>{var g,b;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:f)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(g=r())!=null?g:f))||void 0;return Mo(d.getItem.bind(d))(i.name).then(_=>{if(_)if(typeof _.version=="number"&&_.version!==i.version){if(i.migrate){const y=i.migrate(_.state,_.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[k,T]=_;if(E=i.merge(T,(y=r())!=null?y:f),n(E,!0),k)return h()}).then(()=>{m?.(E,void 0),E=r(),s=!0,c.forEach(_=>_(E))}).catch(_=>{m?.(void 0,_)})};return o.persist={setOptions:g=>{i={...i,...g},g.storage&&(d=g.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(c.add(g),()=>{c.delete(g)})},i.skipHydration||p(),E||f},vh=bh,Ve={USER:"user",ASSISTANT:"assistant"};var be=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(be||{}),_e=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(_e||{});let kt="";const nr=e=>`med-assist-store-${e}`,Sh=e=>{kt=nr(e)},il={sessionId:"",isStreaming:!1,recordingStatus:be.IDLE,isWaitingForResponse:!1,error:null,isTimeoutError:!1,startNewConnection:!1,showRetryButton:!1,chats:{},inlineText:null,connectionStatus:_e.CONNECTING,streamingTimeoutId:null,responseTimeoutId:null,lastStreamingActivity:null,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},al={...il,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},G=yh()(vh((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:_e.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:be.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),inlineText:null,setInlineText:n=>e({inlineText:n}),isBotIconAnimating:!1,setIsBotIconAnimating:n=>e({isBotIconAnimating:n}),isMobile:!1,setIsMobile:n=>e({isMobile:n}),displayMode:"widget",setDisplayMode:n=>e({displayMode:n}),toggleDisplayMode:()=>e({displayMode:t().displayMode==="full"?"widget":"full"}),initialDisplayMode:"widget",setInitialDisplayMode:n=>e({initialDisplayMode:n}),chats:{},addMessageToSession:(n,r)=>{e(o=>({chats:{...o.chats,[n]:[...o.chats[n]||[],r]}}))},updateMessageInSession:(n,r,o)=>e(i=>({chats:{...i.chats,[n]:(i.chats[n]||[]).map(s=>s.id===r?{...s,...o}:s)}})),getMessagesForSession:n=>t().chats[n]||[],setMessagesForSession:(n,r)=>e(o=>({chats:{...o.chats,[n]:r}})),clearMessagesForSession:n=>e(r=>({chats:{...r.chats,[n]:[]}})),clearAllChats:()=>e({chats:{}}),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,isTimeoutError:!1,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),isTimeoutError:!1,setTimeoutError:n=>e({isTimeoutError:n}),clearSession:async()=>{e(il),await sessionStorage.removeItem(kt||nr(t().agentId))},clearUser:()=>{e(al),sessionStorage.removeItem(kt||nr(t().agentId))},streamingTimeoutId:null,setStreamingTimeoutId:n=>e({streamingTimeoutId:n}),clearStreamingTimeout:()=>{const n=t();n.streamingTimeoutId&&(clearTimeout(n.streamingTimeoutId),e({streamingTimeoutId:null}))},responseTimeoutId:null,setResponseTimeoutId:n=>e({responseTimeoutId:n}),clearResponseTimeout:()=>{const n=t();n.responseTimeoutId&&(clearTimeout(n.responseTimeoutId),e({responseTimeoutId:null}))},lastStreamingActivity:null,setLastStreamingActivity:n=>e({lastStreamingActivity:n})}),{name:"med-assist-store",storage:sl(()=>({getItem:()=>kt?sessionStorage.getItem(kt):null,setItem:(e,t)=>{kt&&sessionStorage.setItem(kt,t)},removeItem:()=>{kt&&sessionStorage.removeItem(kt)}})),partialize:e=>({agentId:e.agentId,userId:e.userId,context:e.context,chats:e.chats,sessionId:e.sessionId,refreshToken:e.refreshToken,sessToken:e.sessToken,level:e.level,initialMessage:e.initialMessage,sessionInitialMessages:e.sessionInitialMessages,connectionStatus:e.connectionStatus,elicitationState:e.elicitationState})})),wh=e=>{const t=nr(e);let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}G.setState(al),n&&G.setState(n)},Po=Nt(null),Nh=({children:e})=>{const[t,n]=D(null);return l(Po.Provider,{value:{synapse:t,setSynapse:n},children:e})},xh=()=>{const e=Ct(Po);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Ch=()=>{const e=Ct(Po);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},Th=()=>{const[e,t]=D(M.VOICE_AGENT_STATE.IDLE),[n,r]=D(!1),o=xh(),{setError:i}=G();z(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},f=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(M.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(M.VOICE_AGENT_EVENTS.ERROR,f),()=>{h.off(M.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(M.VOICE_AGENT_EVENTS.ERROR,f)}},[o,i]);const s=ge(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=ge(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),c=ge(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=ge(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:c,toggleMute:d}},Gt=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));Gt.displayName="Card";const ll=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("flex flex-col space-y-1.5 p-6",e),...t}));ll.displayName="CardHeader";const cl=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("font-semibold leading-none tracking-tight",e),...t}));cl.displayName="CardTitle";const kh=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("text-sm text-muted-foreground",e),...t}));kh.displayName="CardDescription";const dl=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("p-6 pt-0",e),...t}));dl.displayName="CardContent";const ul=Q(({className:e,...t},n)=>l("div",{ref:n,className:I("flex items-center p-6 pt-0",e),...t}));ul.displayName="CardFooter";const Do=5,Rh=10*1024*1024,Rr={width:384,height:600},Or=20,Oh=400,Ah=320,Ih=560,Mh=150;function Ph({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=ge(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Rr.width-Or,y:window.innerHeight-Rr.height-Or},[]),[i,s]=D(()=>e??o()),[a,c]=D(!1),d=J({x:0,y:0}),h=J(null),u=J(!1);z(()=>{t||(u.current=!1)},[t]),dt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),z(()=>{if(!t||typeof window>"u")return;let g=null;const b=()=>{s(_=>{const y=Math.max(0,window.innerWidth-Rr.width-Or),k=Math.max(0,window.innerHeight-Rr.height-Or),T=Math.max(0,Math.min(_.x,y)),S=Math.max(0,Math.min(_.y,k));return T===_.x&&S===_.y?_:{x:T,y:S}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(b,Mh)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const f=ge(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){c(!1);return}g.preventDefault(),c(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),E=ge(g=>{if(!t||!a)return;const b=g.clientX-d.current.x,m=g.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(b,_)),T=Math.max(0,Math.min(m,y));s({x:k,y:T})},[a,t]),p=ge(()=>{!t||!a||(c(!1),r?.())},[a,r]);return z(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",f),()=>{g.removeEventListener("mousedown",f)}},[t,f]),z(()=>{if(a)return document.addEventListener("mousemove",E),document.addEventListener("mouseup",p),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""}},[a,E,p]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Lo="#6B5CE0",Dh="#F0F0F0",Ar={background:Dh,backgroundImage:void 0,primary:Lo,textColor:"black"},Lh="rgba(0, 0, 0, 0.4)",Uh="24px";function Fh(e){if(e==="dark")return"white";if(e==="light")return"black"}function Vh(e){const t=e?.primary??e?.primaryColor??Ar.primary,n=e?.textColor??Fh(e?.mode);return{background:e?.background??Ar.background,backgroundImage:e?.backgroundImage??Ar.backgroundImage,primary:t,primaryColor:t,textColor:n??Ar.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function jh(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const c=(o+i)/2;if(o!==i){const h=o-i;switch(a=c>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(c*100);return`${s} ${a}% ${d}%`}function zh(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,c=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(c=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),c=Math.round(c*100);const h=Math.round(d*100);return`${a} ${c}% ${h}%`}function $h(e){const t=e.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(!t)throw new Error("Invalid HSL format");return`${t[1]} ${t[2]}% ${t[3]}%`}function Uo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return jh(t);if(t.startsWith("rgb"))return zh(t);if(t.startsWith("hsl"))return $h(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function hl(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Fo(e){return hl(e)>.5?"0 0% 9%":"0 0% 98%"}function Yh(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return"0 0% 96%";const n=t[1],r=Math.max(0,parseInt(t[2],10)-5);return`${n} ${r}% 96%`}function Bh(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return{50:"262 83% 98%",100:"262 83% 96%",200:"262 83% 92%",300:"262 83% 85%",400:"262 83% 75%",500:"262 83% 58%",600:"262 83% 50%",700:"262 83% 40%",800:"262 83% 30%",900:"262 83% 20%"};const n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);return{50:`${n} ${Math.max(0,r-20)}% ${Math.min(98,o+40)}%`,100:`${n} ${Math.max(0,r-15)}% ${Math.min(96,o+35)}%`,200:`${n} ${Math.max(0,r-10)}% ${Math.min(92,o+30)}%`,300:`${n} ${Math.max(0,r-5)}% ${Math.min(85,o+20)}%`,400:`${n} ${r}% ${Math.min(75,o+10)}%`,500:`${n} ${r}% ${o}%`,600:`${n} ${Math.min(100,r+5)}% ${Math.max(50,o-10)}%`,700:`${n} ${Math.min(100,r+10)}% ${Math.max(40,o-20)}%`,800:`${n} ${Math.min(100,r+15)}% ${Math.max(30,o-30)}%`,900:`${n} ${Math.min(100,r+20)}% ${Math.max(20,o-40)}%`}}function ml(e,t){const n=t.primary??Lo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,p)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(E,p)};let c;try{c=Uo(n)}catch{c=Uo(Lo)}a("--primary",c),a("--primary-foreground",Fo(c)),a("--ring",c),a("--border-primary",c);const d=Bh(c);for(const[E,p]of Object.entries(d))a(`--primary-${E}`,p);const h=Fo(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const E=i?"#191919":"#F0F0F0";try{a("--background",Uo(E))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${c} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",Yh(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${c})`),a("--header-stroke",`hsl(${c} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${c} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${c} / 0.3)`)),s&&!o){const E=hl(h)>.5;a("--header-tagline",E?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",c):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const f=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${f}-${E})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",c),a("--accent-foreground",Fo(c)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",Uh),a("--theme-background-overlay",Lh),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function Wt({className:e,style:t}){return l("div",{className:I("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function Vo(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function pl(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Vo,{}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[l("div",{className:"px-2 pt-2 pb-1",children:l(Wt,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Wt,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Wt,{className:"h-9 w-9 rounded-full"}),l(Wt,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function Hh(){return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(Vo,{}),[{role:"assistant",size:"h-16 w-[70%]"},{role:"user",size:"h-9 w-[45%]"},{role:"assistant",size:"h-24 w-[75%]"},{role:"user",size:"h-9 w-[35%]"},{role:"assistant",size:"h-16 w-[65%]"}].map((e,t)=>l("div",{className:I("flex",e.role==="user"?"justify-end":"justify-start"),children:l(Wt,{className:I("rounded-lg",e.size)})},t))]})}function Gh({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return l("div",{"aria-hidden":"true",children:[l(Vo,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Wt,{className:I("h-5 rounded-md",t[r%t.length])}),l(Wt,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function Wh(e,t=[]){let n=[];function r(i,s){const a=Nt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,b=ye(()=>p,Object.values(p));return l(g.Provider,{value:b,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Kh(o,...t)]}function Kh(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var qh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],jo=qh.reduce((e,t)=>{const n=qa(`Primitive.${t}`),r=Q((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),fl={exports:{}},zo={};const Xh=vd(mo);var gl;function Zh(){if(gl)return zo;gl=1;var e=Xh;function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,f){var E=f(),p=r({inst:{value:E,getSnapshot:f}}),g=p[0].inst,b=p[1];return i(function(){g.value=E,g.getSnapshot=f,c(g)&&b({inst:g})},[u,E,f]),o(function(){return c(g)&&b({inst:g}),u(function(){c(g)&&b({inst:g})})},[u]),s(E),E}function c(u){var f=u.getSnapshot;u=u.value;try{var E=f();return!n(u,E)}catch{return!0}}function d(u,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return zo.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,zo}var _l;function Jh(){return _l||(_l=1,fl.exports=Zh()),fl.exports}var Qh=Jh();function em(){return Qh.useSyncExternalStore(tm,()=>!0,()=>!1)}function tm(){return()=>{}}var $o="Avatar",[nm]=Wh($o),[rm,El]=nm($o),yl=Q((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=D("idle");return l(rm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(jo.span,{...r,ref:t})})});yl.displayName=$o;var bl="AvatarImage",vl=Q((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=El(bl,n),a=om(r,i),c=Dt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Yt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(jo.img,{...i,ref:t,src:r}):null});vl.displayName=bl;var Sl="AvatarFallback",wl=Q((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=El(Sl,n),[s,a]=D(r===void 0);return z(()=>{if(r!==void 0){const c=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(c)}},[r]),s&&i.imageLoadingStatus!=="loaded"?l(jo.span,{...o,ref:t}):null});wl.displayName=Sl;function Nl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function om(e,{referrerPolicy:t,crossOrigin:n}){const r=em(),o=J(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=D(()=>Nl(i,e));return Yt(()=>{a(Nl(i,e))},[i,e]),Yt(()=>{const c=u=>()=>{a(u)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var xl=yl,Cl=vl,Tl=wl;const Yo=Q(({className:e,...t},n)=>l(xl,{ref:n,className:I("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Yo.displayName=xl.displayName;const kl=Q(({className:e,...t},n)=>l(Cl,{ref:n,className:I("aspect-square h-full w-full",e),...t}));kl.displayName=Cl.displayName;const Bo=Q(({className:e,...t},n)=>l(Tl,{ref:n,className:I("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Bo.displayName=Tl.displayName;const Rl=Nt(!1);function sm({enabled:e,children:t}){return l(Rl.Provider,{value:e,children:t})}function im(){return Ct(Rl)}const Ol="(max-width: 768px), (pointer: coarse)",Al=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function am(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Ol)?.matches??!1,t=Al.test(navigator?.userAgent??"");return e||t}function Il(){const[e,t]=D(am);return z(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Ol),r=Al.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function lm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:c=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h,historyEnabled:u=!1}){const f=Il(),E=im(),p=G(A=>A.displayMode)==="side_panel",g=E&&!f&&!p,b=G(A=>A.displayMode)==="full",m=G(A=>A.initialDisplayMode)==="full",_=!b&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",y=G(A=>A.connectionStatus),k=G(A=>A.level)==="user",[T,S]=D(!1),x=J(null),v=ye(()=>a==="connected"||a==="connecting"||a==="listening"||a==="speaking"||a==="thinking",[a]),w=ge(()=>{T||(S(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,S(!1)},6e3),s())},[T,s]);z(()=>{y===_e.CONNECTED&&(S(!1),x.current&&clearTimeout(x.current))},[y]);const N=(()=>{switch(y){case _e.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case _e.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case _e.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return l("div",{className:"px-6 py-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative flex-shrink-0",children:[l(Yo,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(Bo,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?l("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):l("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),l("div",{className:I("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",N.dotColor,y===_e.CONNECTING&&"animate-pulse")})]}),l("div",{className:"flex flex-col",children:[r?l("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):l("p",{className:I("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",_),children:n||"Health Assist"}),l("div",{className:"flex items-center gap-1.5",children:l("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:N.text})})]})]}),l("div",{className:I("flex items-center",!g&&"gap-1"),children:[!v&&(!k||!u)&&l(ie,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:w,disabled:T,className:I("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",_),children:l(tr,{className:"w-5 h-5"})}),h&&k&&l(ie,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:I("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(Wu,{className:"w-5 h-5"})}),g&&l(ie,{onClick:d,type:"button",variant:"ghost",size:"icon",title:b?"Exit fullscreen":"Enter fullscreen",className:I("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:b?l(rh,{className:"w-8 h-8"}):l(Zu,{className:"w-8 h-8"})}),(t||!m)&&l(ie,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:I("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(yn,{className:"w-8 h-8"})})]})]})})}const Ho=Q(({className:e,...t},n)=>l("textarea",{className:I("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:n,...t}));Ho.displayName="Textarea";function Ml({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=D(!1),[s,a]=D(""),c=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";z(()=>{if(c){const f=URL.createObjectURL(e);return a(f),()=>URL.revokeObjectURL(f)}},[e,c]),z(()=>{i(!1)},[e]);const h=()=>c?"text-green-600":"text-text-secondary",u=f=>{if(f===0)return"0 B";const E=1024,p=["B","KB","MB","GB"],g=Math.floor(Math.log(f)/Math.log(E));return`${(f/Math.pow(E,g)).toFixed(1)} ${p[g]}`.toLowerCase()};return!c||o?l("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[l("div",{className:`flex-shrink-0 ${h()}`,children:l(el,{className:"h-5 w-5"})}),l("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&l("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&l("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:l(yn,{className:"h-3 w-3"})})]}):l("div",{className:`relative group flex-shrink-0 ${r}`,children:[l("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&l("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:l(yn,{className:"h-3 w-3"})})]})}function Go({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return l("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return l(Ml,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&l("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return l(Ml,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const Wo=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),Pl=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),cm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Dl=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),dm=qe(()=>Pl().then(e=>({default:e.ElicitationInput})));function um({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:c,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:f,theme:E,allowed:p,showStartNewChatButton:g,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:T}){const S=J(null),x=J(null),v=e.trim().length>0||a,w=!p||p.includes(M.SYNAPSE_CONVERSATION.AUDIO),N=!p||p.includes(M.SYNAPSE_CONVERSATION.VOICE),A=v||!w,Y=v,q=!p||p.includes(M.SYNAPSE_CONVERSATION.FILE),ae=(d||f!==be.IDLE)&&!s,de=I("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":ae?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),le=B=>{const H=Array.from(B.target.files||[]);H.length>0&&r(H)},ue=()=>{d||(S.current&&(S.current.value=""),S.current?.click())},F=B=>{B.key==="Enter"&&!B.shiftKey&&Y&&!d&&(B.preventDefault(),n())},Ce=B=>{B.style.height="auto",B.style.overflow="hidden";const H=B.scrollHeight,L=T?20:28,W=120,oe=Math.max(L,Math.min(H,W));B.style.height=oe+"px",H>W?B.style.overflow="auto":B.style.overflow="hidden"},$=B=>{Ce(B.currentTarget)};return z(()=>{x.current&&Ce(x.current)},[e]),z(()=>{!d&&!u&&x.current?.focus()},[d]),g&&b?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:b,className:I("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[l("span",{children:"Start new chat"}),l(tr,{className:"w-5 h-5","aria-hidden":!0})]})}):l(ce,{children:y?l($e,{fallback:l(pl,{}),children:l(dm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):T?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(Go,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:S,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:le,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:l(Ho,{ref:x,onInput:$,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:F,title:"Enter your message","aria-label":"Enter your message",className:I("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),l("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[l("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:q&&f===be.IDLE&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:ue,disabled:d,className:I("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(nl,{className:"w-6 h-6",strokeWidth:1.5})})}),l("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?l(ie,{type:"button",variant:"ghost",size:"icon",onClick:i,className:I("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(rl,{className:"w-4 h-4"})}):w&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:ae,className:I("h-10 w-10 shrink-0 p-2",de),title:"Start recording","aria-label":"Start recording",children:l(Io,{className:"w-6 h-6",strokeWidth:1.5})}),A&&!s?l(ie,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!Y,variant:"ghost",className:I("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",Y?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:Y?"Send message":"Type a message to send","aria-label":Y?"Send message":"Type a message to send",children:l(Wo,{className:"w-4 h-4 text-primary-foreground"})}):w&&N&&!s&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(Dl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:S,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:le,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(Go,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(Ho,{ref:x,onInput:$,placeholder:h,value:e,onChange:B=>t(B.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:F,title:"Enter your message","aria-label":"Enter your message",className:I("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center shrink-0",children:q&&f===be.IDLE&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:ue,disabled:d,className:I("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(nl,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(ie,{type:"button",variant:"ghost",size:"icon",onClick:i,className:I("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(rl,{className:"w-4 h-4"})}):A?l(ie,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!Y,variant:"ghost",className:I("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",Y?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:Y?"Send message":"Type a message to send","aria-label":Y?"Send message":"Type a message to send",children:l(Wo,{className:"w-4 h-4 text-primary-foreground"})}):w&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:ae,className:I("h-10 w-10 shrink-0",de),title:"Start recording","aria-label":"Start recording",children:l(Io,{className:"w-5 h-5",strokeWidth:1.5})}),w&&N&&!s&&l(ie,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(Dl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}function hm({message:e,onDismiss:t}){return l(ce,{children:[l("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),l("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:l("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[l("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),l("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:l(yn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function mm(){const e=G(r=>r.toastMessage),t=G(r=>r.setToastMessage),n=ge(()=>{t(null)},[t]);return z(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(hm,{message:e,onDismiss:n}):null}function Ko({isOpen:e,children:t,align:n="center",onClose:r}){return e?l("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:l("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const pm="Before we begin",fm=e=>`A quick note on how ${e} works and handles your information.`,gm=e=>[`This assistant is powered by AI. Replies are generated automatically and can be wrong, so please check anything important before you act on it. Don't use it in an urgent or emergency situation \u2014 contact ${e} directly or call your local emergency number.`,`To help you, ${e} and our authorised technology partners process what you share here \u2014 your contact details and your messages \u2014 under contractual and security safeguards, on secure servers. We use it only to provide this service, and keep it only as long as needed or as the law requires.`];function _m(e,t){return(Array.isArray(e)?e:e.split(/\n\s*\n|\n/)).map(n=>String(n??"").replace(/\{\{\s*name\s*\}\}/gi,t).trim()).filter(Boolean)}const Ll=(e,t)=>{if(t){const n=_m(t,e);if(n.length)return n}return gm(e)},Em="I agree and consent",ym="By continuing, you consent to the above.",bm="Continue";function Ul({botName:e,consentContent:t,isFullScreen:n}){return l(ce,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:I("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:pm}),l("p",{className:I("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:fm(e)})]}),l("div",{className:I("overflow-y-auto rounded-lg border border-border-subtle flex flex-col",n?"max-h-[340px] p-4 gap-4":"max-h-[180px] p-3 gap-3"),tabIndex:0,role:"region","aria-label":"Consent details",children:Ll(e,t).map((r,o)=>l("p",{className:I("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function vm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(Ko,{isOpen:e,onClose:t,children:l("div",{className:I("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?l(Ul,{botName:n,consentContent:o,isFullScreen:s}):l("div",{className:"flex flex-col gap-2",children:[l("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),Ll(n,o).map((a,c)=>l("p",{className:I("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(ie,{onClick:t,className:I("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Sm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=D(!1);return e?l(Ko,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:I("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[l(Ul,{botName:t,consentContent:n,isFullScreen:o}),l("div",{className:"flex flex-col gap-1.5",children:[l("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[l("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),l("div",{"aria-hidden":"true",className:I("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&l("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:I("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Em})]}),l("p",{className:I("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:ym})]}),l(ie,{disabled:!i,onClick:()=>i&&r(),className:I("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:bm})]})}):null}const wm=qe(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),Nm=qe(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),xm=qe(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),Cm=qe(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),Tm=qe(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),km=[{label:"Took longer than expected",value:"took_longer"},{label:"Asking too many questions",value:"too_many_questions"},{label:"Irrelevant response",value:"irrelevant_response"},{label:"Other",value:"other"}],Rm=[{Icon:wm,label:"Bad",score:1},{Icon:Nm,label:"Poor",score:2},{Icon:xm,label:"Okay",score:3},{Icon:Cm,label:"Good",score:4},{Icon:Tm,label:"Great!",score:5}];function Om(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Am({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=D(null),[d,h]=D(new Set),[u,f]=D(!1),E=s&&a!==null?Om(a,t):t.form?.default?.length?t.form.default:km,p=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},g=_=>{c(_),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(Ko,{isOpen:e,onClose:o,children:l("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[l("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),l("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[l("div",{className:"flex flex-col gap-1",children:[t.title&&l("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&l("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&l("div",{className:"flex items-center justify-between gap-1",children:Rm.map(({Icon:_,label:y,score:k})=>{const T=a===k,S=a!==null&&!T;return l("button",{onClick:()=>g(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[l("div",{className:`rounded-xl p-1 transition-all ${T?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${S?"opacity-50":""}`,style:T?{filter:"brightness(1.25)"}:void 0,children:l($e,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(_,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${T?"text-primary/50 font-medium":S?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&E.length>0&&l("div",{className:"flex flex-col gap-2",children:E.map(_=>l("div",{onClick:()=>p(_.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(_.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:_.label},_.value))}),l(ie,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),l("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>f(_=>!_),children:[l("div",{className:"relative w-3 h-3 shrink-0",children:l("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&l("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),l("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function Fl({isOpen:e,onClose:t,showCloseButton:n=!0,iconUrl:r,onStartNewSession:o,showStartNewChatButton:i,children:s,sidebar:a,sessionDrawer:c,fullScreenEmptyState:d,title:h,titleImg:u,tagline:f,sessionId:E,chatComposer:p,environment:g,mode:b,sidePanelMode:m,sidePanelWidth:_,side:y,onSidePanelPushChange:k,onToggleDisplayMode:T,onOpenSessionDrawer:S,historyEnabled:x=!1,isAuthComponent:v,activeElicitation:w,voiceAgentState:N,theme:A,feedbackModal:Y,consentModal:q}){const[ae,de]=D(!1),[le,ue]=D(!1),[F,Ce]=D(!1),$=J(null),B=G(P=>P.level),H=b,L=H==="full",W=H==="side_panel",oe=J(null),[je,K]=D("");z(()=>{oe.current!==null&&oe.current!==H&&K(H==="full"?"Switched to fullscreen mode":H==="side_panel"?"Switched to side panel mode":H==="widget"?"Switched to widget mode":"Switched to mobile layout"),oe.current=H},[H]);const me=ye(()=>Vh(A),[A]),{setIsMobile:Be}=G(P=>P),ze=!!v,tt=async P=>{if(!(!p?.onSend||le)){ue(!0);try{await p.onSend(P)}finally{ue(!1)}}};dt(()=>{if(!$.current)return;const P=H==="full"?{...me,headerTinted:!1}:me;ml($.current,P),H==="full"&&!me.backgroundImage?($.current.style.setProperty("--background","0 0% 100%"),$.current.style.setProperty("--widget-bg-overlay","transparent")):($.current.style.removeProperty("--background"),$.current.style.removeProperty("--widget-bg-overlay"),ml($.current,me))},[me,H]),z(()=>{const P=()=>{const Ee=window?.innerWidth??0,ve=navigator?.userAgent?.toLowerCase()??"",ke=Ee<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ve);de(ke),Be(ke)};return P(),window.addEventListener("resize",P),()=>window.removeEventListener("resize",P)},[]),dt(()=>{if(!e||!ae||!$.current)return;const P=$.current;let Ee=null,ve=null,ke=null,Ze=window.visualViewport?.offsetTop??0,Le=0;const Ie=2,lt=80;if(window.visualViewport){const pe=()=>{if(P&&window.visualViewport){const He=window.visualViewport.height,nt=window.visualViewport.offsetTop;Ee=requestAnimationFrame(()=>{P.style.transition="none",P.style.top=`${nt}px`,P.style.left="0",P.style.right="0",P.style.bottom="auto",P.style.width="100vw",P.style.height=`${He}px`,P.style.maxHeight=`${He}px`,P.style.minHeight=`${He}px`,ve&&clearTimeout(ve),ve=setTimeout(()=>{P.style.transition=""},100)})}},ct=()=>{pe()},Re=()=>{if(!P||!window.visualViewport)return;const He=window.visualViewport.offsetTop,nt=Date.now();Math.abs(He-Ze)<Ie||nt-Le<lt||(Le=nt,Ze=He,Ee=requestAnimationFrame(()=>{P.style.transition="none",P.style.top=`${He}px`,ke&&clearTimeout(ke),ke=setTimeout(()=>{P.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",ct),window.visualViewport.addEventListener("scroll",Re),pe(),()=>{Ee&&cancelAnimationFrame(Ee),ve&&clearTimeout(ve),ke&&clearTimeout(ke),window.visualViewport?.removeEventListener("resize",ct),window.visualViewport?.removeEventListener("scroll",Re),P&&(P.style.width="",P.style.height="",P.style.maxHeight="",P.style.minHeight="",P.style.transition="")}}else{const pe=()=>{P&&(P.style.transition="none",P.style.top="0",P.style.left="0",P.style.right="0",P.style.bottom="auto",P.style.width="100vw",P.style.height="100svh",P.style.maxHeight="100svh",setTimeout(()=>{P.style.transition=""},100))};return window.addEventListener("resize",pe),pe(),()=>{window.removeEventListener("resize",pe),P&&(P.style.width="",P.style.height="",P.style.maxHeight="",P.style.transition="")}}},[e,ae]),z(()=>{if(e&&!(W&&m==="push")){const P=$.current,Ee=window.scrollY,ve=document.body.style.cssText,ke=document.documentElement.style.overflow,Ze=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ee}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",Ze>0&&!ae&&(document.body.style.paddingRight=`${Ze}px`);let Le=0;const Ie=pe=>{Le=pe.touches[0].clientY},lt=pe=>{if(pe.touches.length!==1)return;const ct=Le-pe.touches[0].clientY;Le=pe.touches[0].clientY;let Re=pe.target;for(;Re&&Re!==P;){const{overflowY:He}=window.getComputedStyle(Re);if((He==="auto"||He==="scroll")&&Re.scrollHeight>Re.clientHeight){const{scrollTop:nt,scrollHeight:yt,clientHeight:Zt}=Re,vn=nt<=0&&ct<0,Jt=nt+Zt>=yt-1&&ct>0;if(!vn&&!Jt)return;break}Re=Re.parentElement}pe.preventDefault()};return P&&(P.addEventListener("touchstart",Ie,{passive:!0}),P.addEventListener("touchmove",lt,{passive:!1})),()=>{P&&(P.removeEventListener("touchstart",Ie),P.removeEventListener("touchmove",lt)),document.body.style.cssText=ve,document.documentElement.style.overflow=ke,window.scrollTo(0,Ee)}}},[e,ae,W,m]),z(()=>{if(!(!W||m!=="push"||!e))return k?.(!0,_??0,y??"right"),()=>{k?.(!1,_??0,y??"right")}},[e,W,m,_,y,k]);const{position:Xe,elementRef:ht}=Ph({enabled:e&&!ae&&!L&&!W});z(()=>{$.current&&(ht.current=$.current)},[ht]);const Et=I("synapse-chat-widget-container","fixed m-0 p-0","box-border",!ae&&!L&&!W?"transition-all duration-300":"",ae?"w-screen h-[100svh]":L?"w-screen h-screen":W?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),mt=I("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",me.backgroundImage?"theme-with-background":"",ae?"rounded-none border-0 flex-col":L?"rounded-none border-0 flex-row":W?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return l("div",{ref:$,"data-mode":H,className:Et,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...L&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...L&&!e&&{display:"none"},...W&&e&&{top:0,bottom:0,[y==="left"?"left":"right"]:0,[y==="left"?"right":"left"]:"auto",width:`${_}px`,height:"100vh"},...W&&!e&&{display:"none"},...!ae&&!L&&!W&&{left:`${Xe.x}px`,top:`${Xe.y}px`,bottom:"auto",right:"auto"},...ae&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:me.backgroundImage?"transparent":"hsl(var(--background))"}},children:[l("style",{children:`
1
+ var Pc=Object.defineProperty;var Dc=(e,t,n)=>t in e?Pc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var O=(e,t,n)=>Dc(e,typeof t!="symbol"?t+"":t,n);var xn,K,_s,Dt,Es,ys,Ss,qr,dr,Cn,vs,Xr,Jr,Zr,bs,ur={},hr=[],Lc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Tn=Array.isArray;function _t(e,t){for(var n in t)e[n]=t[n];return e}function Qr(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function qe(e,t,n){var r,o,i,s={};for(i in t)i=="key"?r=t[i]:i=="ref"?o=t[i]:s[i]=t[i];if(arguments.length>2&&(s.children=arguments.length>3?xn.call(arguments,2):n),typeof e=="function"&&e.defaultProps!=null)for(i in e.defaultProps)s[i]===void 0&&(s[i]=e.defaultProps[i]);return kn(e,s,r,o,null)}function kn(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++_s,__i:-1,__u:0};return o==null&&K.vnode!=null&&K.vnode(i),i}function ws(){return{current:null}}function ue(e){return e.children}function ot(e,t){this.props=e,this.context=t}function tn(e,t){if(t==null)return e.__?tn(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type=="function"?tn(e):null}function Fc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=_t({},t);i.__v=t.__v+1,K.vnode&&K.vnode(i),to(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??tn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Rs(r,i,o),t.__e=t.__=null,i.__e!=n&&Ns(i)}}function Ns(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),Ns(e)}function eo(e){(!e.__d&&(e.__d=!0)&&Dt.push(e)&&!mr.__r++||Es!=K.debounceRendering)&&((Es=K.debounceRendering)||ys)(mr)}function mr(){try{for(var e,t=1;Dt.length;)Dt.length>t&&Dt.sort(Ss),e=Dt.shift(),t=Dt.length,Fc(e)}finally{Dt.length=mr.__r=0}}function xs(e,t,n,r,o,i,s,a,c,d,h){var u,f,E,p,g,S,m,_=r&&r.__k||hr,y=t.length;for(c=Uc(n,t,_,c,y),u=0;u<y;u++)(E=n.__k[u])!=null&&(f=E.__i!=-1&&_[E.__i]||ur,E.__i=u,S=to(e,E,f,o,i,s,a,c,d,h),p=E.__e,E.ref&&f.ref!=E.ref&&(f.ref&&ro(f.ref,null,E),h.push(E.ref,E.__c||p,E)),g==null&&p!=null&&(g=p),(m=!!(4&E.__u))||f.__k===E.__k?(c=Cs(E,c,e,m),m&&f.__e&&(f.__e=null)):typeof E.type=="function"&&S!==void 0?c=S:p&&(c=p.nextSibling),E.__u&=-7);return n.__e=g,c}function Uc(e,t,n,r,o){var i,s,a,c,d,h=n.length,u=h,f=0;for(e.__k=new Array(o),i=0;i<o;i++)(s=t[i])!=null&&typeof s!="boolean"&&typeof s!="function"?(typeof s=="string"||typeof s=="number"||typeof s=="bigint"||s.constructor==String?s=e.__k[i]=kn(null,s,null,null,null):Tn(s)?s=e.__k[i]=kn(ue,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=kn(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,c=i+f,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=Vc(s,n,c,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?f--:o<h&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=c&&(d==c-1?f--:d==c+1?f++:(d>c?f--:f++,s.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<h;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=tn(a)),As(a,a));return r}function Cs(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Cs(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=tn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function wt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Tn(e)?e.some(function(n){wt(n,t)}):t.push(e)),t}function Vc(e,t,n,r){var o,i,s,a=e.key,c=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&c==d.type)return n;if(r>(h?1:0)){for(o=n-1,i=n+1;o>=0||i<t.length;)if((d=t[s=o>=0?o--:i++])!=null&&(2&d.__u)==0&&a==d.key&&c==d.type)return s}return-1}function Ts(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Lc.test(t)?n:n+"px"}function pr(e,t,n,r,o){var i,s;e:if(t=="style")if(typeof n=="string")e.style.cssText=n;else{if(typeof r=="string"&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||Ts(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ts(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(vs,"$1")),s=t.toLowerCase(),t=s in e||t=="onFocusOut"||t=="onFocusIn"?s.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n[Cn]=r[Cn]:(n[Cn]=Xr,e.addEventListener(t,i?Zr:Jr,i)):e.removeEventListener(t,i?Zr:Jr,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function ks(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[dr]==null)t[dr]=Xr++;else if(t[dr]<n[Cn])return;return n(K.event?K.event(t):t)}}}function to(e,t,n,r,o,i,s,a,c,d){var h,u,f,E,p,g,S,m,_,y,k,T,x,N,v,b=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=K.__b)&&h(t);e:if(typeof b=="function")try{if(m=t.props,_=b.prototype&&b.prototype.render,y=(h=b.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?S=(u=t.__c=n.__c).__=u.__E:(_?t.__c=u=new b(m,k):(t.__c=u=new ot(m,k),u.constructor=b,u.render=zc),y&&y.sub(u),u.state||(u.state={}),u.__n=r,f=u.__d=!0,u.__h=[],u._sb=[]),_&&u.__s==null&&(u.__s=u.state),_&&b.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=_t({},u.__s)),_t(u.__s,b.getDerivedStateFromProps(m,u.__s))),E=u.props,p=u.state,u.__v=t,f)_&&b.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),_&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(_&&b.getDerivedStateFromProps==null&&m!==E&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(m,k),t.__v==n.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(m,u.__s,k)===!1){t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(R){R&&(R.__=t)}),hr.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&s.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(m,u.__s,k),_&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(E,p,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,T=K.__r,x=0,_)u.state=u.__s,u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),hr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,T&&T(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++x<25);u.state=u.__s,u.getChildContext!=null&&(r=_t(_t({},r),u.getChildContext())),_&&!f&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(E,p)),N=h!=null&&h.type===ue&&h.key==null?Os(h.props.children):h,a=xs(e,Tn(N)?N:[N],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),S&&(u.__E=u.__=null)}catch(R){if(t.__v=null,c||i!=null)if(R.then){for(t.__u|=c?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(v=i.length;v--;)Qr(i[v]);no(t)}else t.__e=n.__e,t.__k=n.__k,R.then||no(t);K.__e(R,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=jc(n.__e,t,n,r,o,i,s,c,d);return(h=K.diffed)&&h(t),128&t.__u?void 0:a}function no(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(no))}function Rs(e,t,n){for(var r=0;r<n.length;r++)ro(n[r],n[++r],n[++r]);K.__c&&K.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){K.__e(i,o.__v)}})}function Os(e){return typeof e!="object"||e==null||e.__b>0?e:Tn(e)?e.map(Os):e.constructor!==void 0?null:_t({},e)}function jc(e,t,n,r,o,i,s,a,c){var d,h,u,f,E,p,g,S=n.props||ur,m=t.props,_=t.type;if(_=="svg"?o="http://www.w3.org/2000/svg":_=="math"?o="http://www.w3.org/1998/Math/MathML":o||(o="http://www.w3.org/1999/xhtml"),i!=null){for(d=0;d<i.length;d++)if((E=i[d])&&"setAttribute"in E==!!_&&(_?E.localName==_:E.nodeType==3)){e=E,i[d]=null;break}}if(e==null){if(_==null)return document.createTextNode(m);e=document.createElementNS(o,_,m.is&&m),a&&(K.__m&&K.__m(t,i),a=!1),i=null}if(_==null)S===m||a&&e.data==m||(e.data=m);else{if(i=_=="textarea"&&m.defaultValue!=null?null:i&&xn.call(e.childNodes),!a&&i!=null)for(S={},d=0;d<e.attributes.length;d++)S[(E=e.attributes[d]).name]=E.value;for(d in S)E=S[d],d=="dangerouslySetInnerHTML"?u=E:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||pr(e,d,null,E,o);for(d in m)E=m[d],d=="children"?f=E:d=="dangerouslySetInnerHTML"?h=E:d=="value"?p=E:d=="checked"?g=E:a&&typeof E!="function"||S[d]===E||pr(e,d,E,S[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),xs(t.type=="template"?e.content:e,Tn(f)?f:[f],t,n,r,_=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&tn(n,0),a,c),i!=null)for(d=i.length;d--;)Qr(i[d]);a&&_!="textarea"||(d="value",_=="progress"&&p==null?e.removeAttribute("value"):p!=null&&(p!==e[d]||_=="progress"&&!p||_=="option"&&p!=S[d])&&pr(e,d,p,S[d],o),d="checked",g!=null&&g!=e[d]&&pr(e,d,g,S[d],o))}return e}function ro(e,t,n){try{if(typeof e=="function"){var r=typeof e.__u=="function";r&&e.__u(),r&&t==null||(e.__u=e(t))}else e.current=t}catch(o){K.__e(o,n)}}function As(e,t,n){var r,o;if(K.unmount&&K.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ro(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){K.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&As(r[o],t,n||typeof e.type!="function");n||Qr(e.__e),e.__c=e.__=e.__e=void 0}function zc(e,t,n){return this.constructor(e,n)}function Rn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),K.__&&K.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],to(t,e=(!r&&n||t).__k=qe(ue,null,[e]),o||ur,ur,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?xn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Rs(i,e,s)}function Is(e,t){Rn(e,t,Is)}function Yc(e,t,n){var r,o,i,s,a=_t({},e.props);for(i in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)i=="key"?r=t[i]:i=="ref"?o=t[i]:a[i]=t[i]===void 0&&s!=null?s[i]:t[i];return arguments.length>2&&(a.children=arguments.length>3?xn.call(arguments,2):n),kn(e.type,a,r||e.key,o||e.ref,null)}function Nt(e){function t(n){var r,o;return this.getChildContext||(r=new Set,(o={})[t.__c]=this,this.getChildContext=function(){return o},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(i){this.props.value!=i.value&&r.forEach(function(s){s.__e=!0,eo(s)})},this.sub=function(i){r.add(i);var s=i.componentWillUnmount;i.componentWillUnmount=function(){r&&r.delete(i),s&&s.call(i)}}),n.children}return t.__c="__cC"+bs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}xn=hr.slice,K={__e:function(e,t,n,r){for(var o,i,s;t=t.__;)if((o=t.__c)&&!o.__)try{if((i=o.constructor)&&i.getDerivedStateFromError!=null&&(o.setState(i.getDerivedStateFromError(e)),s=o.__d),o.componentDidCatch!=null&&(o.componentDidCatch(e,r||{}),s=o.__d),s)return o.__E=o}catch(a){e=a}throw e}},_s=0,ot.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=_t({},this.state),typeof e=="function"&&(e=e(_t({},n),this.props)),e&&_t(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),eo(this))},ot.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),eo(this))},ot.prototype.render=ue,Dt=[],ys=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Ss=function(e,t){return e.__v.__b-t.__v.__b},mr.__r=0,qr=Math.random().toString(8),dr="__d"+qr,Cn="__a"+qr,vs=/(PointerCapture)$|Capture$/i,Xr=0,Jr=ks(!1),Zr=ks(!0),bs=0;var $c=0;function l(e,t,n,r,o,i){t||(t={});var s,a,c=t;if("ref"in c)for(a in c={},t)a=="ref"?s=t[a]:c[a]=t[a];var d={type:e,props:c,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--$c,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)c[a]===void 0&&(c[a]=s[a]);return K.vnode&&K.vnode(d),d}var xt,me,oo,Ms,nn=0,Ps=[],we=K,Ds=we.__b,Ls=we.__r,Fs=we.diffed,Us=we.__c,Vs=we.unmount,js=we.__;function Bt(e,t){we.__h&&we.__h(me,e,nn||t),nn=0;var n=me.__H||(me.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function F(e){return nn=1,rn(Ys,e)}function rn(e,t,n){var r=Bt(xt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ys(void 0,t),function(a){var c=r.__N?r.__N[0]:r.__[0],d=r.t(c,a);c!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=me,!me.__f)){var o=function(a,c,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(f){return f.__c});if(h.every(function(f){return!f.__N}))return!i||i.call(this,a,c,d);var u=r.__c.props!==a;return h.some(function(f){if(f.__N){var E=f.__[0];f.__=f.__N,f.__N=void 0,E!==f.__[0]&&(u=!0)}}),i&&i.call(this,a,c,d)||u};me.__f=!0;var i=me.shouldComponentUpdate,s=me.componentWillUpdate;me.componentWillUpdate=function(a,c,d){if(this.__e){var h=i;i=void 0,o(a,c,d),i=h}s&&s.call(this,a,c,d)},me.shouldComponentUpdate=o}return r.__N||r.__}function Y(e,t){var n=Bt(xt++,3);!we.__s&&co(n.__H,t)&&(n.__=e,n.u=t,me.__H.__h.push(n))}function dt(e,t){var n=Bt(xt++,4);!we.__s&&co(n.__H,t)&&(n.__=e,n.u=t,me.__h.push(n))}function q(e){return nn=5,ye(function(){return{current:e}},[])}function so(e,t,n){nn=6,dt(function(){if(typeof e=="function"){var r=e(t());return function(){e(null),r&&typeof r=="function"&&r()}}if(e)return e.current=t(),function(){return e.current=null}},n==null?n:n.concat(e))}function ye(e,t){var n=Bt(xt++,7);return co(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function fe(e,t){return nn=8,ye(function(){return e},t)}function Ct(e){var t=me.context[e.__c],n=Bt(xt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(me)),t.props.value):e.__}function io(e,t){we.useDebugValue&&we.useDebugValue(t?t(e):e)}function Hc(e){var t=Bt(xt++,10),n=F();return t.__=e,me.componentDidCatch||(me.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function ao(){var e=Bt(xt++,11);if(!e.__){for(var t=me.__v;t!==null&&!t.__m&&t.__!==null;)t=t.__;var n=t.__m||(t.__m=[0,0]);e.__="P"+n[0]+"-"+n[1]++}return e.__}function Bc(){for(var e;e=Ps.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(fr),t.__h.some(lo),t.__h=[]}catch(n){t.__h=[],we.__e(n,e.__v)}}}we.__b=function(e){me=null,Ds&&Ds(e)},we.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),js&&js(e,t)},we.__r=function(e){Ls&&Ls(e),xt=0;var t=(me=e.__c).__H;t&&(oo===me?(t.__h=[],me.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(fr),t.__h.some(lo),t.__h=[],xt=0)),oo=me},we.diffed=function(e){Fs&&Fs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ps.push(t)!==1&&Ms===we.requestAnimationFrame||((Ms=we.requestAnimationFrame)||Gc)(Bc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),oo=me=null},we.__c=function(e,t){t.some(function(n){try{n.__h.some(fr),n.__h=n.__h.filter(function(r){return!r.__||lo(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],we.__e(r,n.__v)}}),Us&&Us(e,t)},we.unmount=function(e){Vs&&Vs(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{fr(r)}catch(o){t=o}}),n.__H=void 0,t&&we.__e(t,n.__v))};var zs=typeof requestAnimationFrame=="function";function Gc(e){var t,n=function(){clearTimeout(r),zs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);zs&&(t=requestAnimationFrame(n))}function fr(e){var t=me,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),me=t}function lo(e){var t=me;e.__c=e.__(),me=t}function co(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Ys(e,t){return typeof t=="function"?t(e):t}function $s(e,t){for(var n in t)e[n]=t[n];return e}function uo(e,t){for(var n in e)if(n!=="__source"&&!(n in t))return!0;for(var r in t)if(r!=="__source"&&e[r]!==t[r])return!0;return!1}function ho(e,t){var n=t(),r=F({t:{__:n,u:t}}),o=r[0].t,i=r[1];return dt(function(){o.__=n,o.u=t,mo(o)&&i({t:o})},[e,n,t]),Y(function(){return mo(o)&&i({t:o}),e(function(){mo(o)&&i({t:o})})},[e]),n}function mo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function po(e){e()}function fo(e){return e}function go(){return[!1,po]}var _o=dt;function gr(e,t){this.props=e,this.context=t}function Eo(e,t){function n(o){var i=this.props.ref;return i!=o.ref&&i&&(typeof i=="function"?i(null):i.current=null),t?!t(this.props,o)||i!=o.ref:uo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,qe(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(gr.prototype=new ot).isPureReactComponent=!0,gr.prototype.shouldComponentUpdate=function(e,t){return uo(this.props,e)||uo(this.state,t)};var Hs=K.__b;K.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Hs&&Hs(e)};var Wc=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Q(e){function t(n){var r=$s({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Wc,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Bs=function(e,t){return e==null?null:wt(wt(e).map(t))},et={map:Bs,forEach:Bs,count:function(e){return e?wt(e).length:0},only:function(e){var t=wt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:wt},Kc=K.__e;K.__e=function(e,t,n,r){if(e.then){for(var o,i=t;i=i.__;)if((o=i.__c)&&o.__c)return t.__e==null&&(t.__e=n.__e,t.__k=n.__k),o.__c(e,t)}Kc(e,t,n,r)};var Gs=K.unmount;function Ws(e,t,n){return e&&(e.__c&&e.__c.__H&&(e.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),e.__c.__H=null),(e=$s({},e)).__c!=null&&(e.__c.__P===n&&(e.__c.__P=t),e.__c.__e=!0,e.__c=null),e.__k=e.__k&&e.__k.map(function(r){return Ws(r,t,n)})),e}function Ks(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ks(r,t,n)}),e.__c&&e.__c.__P===t&&(e.__e&&n.appendChild(e.__e),e.__c.__e=!0,e.__c.__P=n)),e}function He(){this.__u=0,this.o=null,this.__b=null}function qs(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Xe(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(a){a&&(o=a.default||a),r=!0},function(a){n=a,r=!0}),n)throw n;if(!r)throw t;return o?qe(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function on(){this.i=null,this.l=null}K.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Gs&&Gs(e)},(He.prototype=new ot).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=qs(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(c):c())};n.__R=s;var a=n.__P;n.__P=null;var c=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=Ks(d,d.__c.__P,d.__c.__O)}var h;for(r.setState({__a:r.__b=null});h=r.o.pop();)h.__P=a,h.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},He.prototype.componentWillUnmount=function(){this.o=[]},He.prototype.render=function(e,t){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=Ws(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&qe(ue,null,e.fallback);return o&&(o.__u&=-33),[qe(ue,null,t.__a?null:e.children),o]};var Xs=function(e,t,n){if(++n[1]===n[0]&&e.l.delete(t),e.props.revealOrder&&(e.props.revealOrder[0]!=="t"||!e.l.size))for(n=e.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;e.i=n=n[2]}};function qc(e){return this.getChildContext=function(){return e.context},e.children}function Xc(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Rn(null,t.v),t.v=null,t.h=null},t.h&&t.h!==n&&t.componentWillUnmount(),!t.v){for(var r=t.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;t.h=n,t.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},namespaceURI:n.namespaceURI,insertBefore:function(o,i){this.childNodes.push(o),t.h.insertBefore(o,i)},removeChild:function(o){this.childNodes.splice(this.childNodes.indexOf(o)>>>1,1),t.h.removeChild(o)}}}Rn(qe(qc,{context:t.context},e.__v),t.v)}function Js(e,t){var n=qe(Xc,{__v:e,h:t});return n.containerInfo=t,n}(on.prototype=new ot).__a=function(e){var t=this,n=qs(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Xs(t,e,r)):o()};n?n(i):i()}},on.prototype.render=function(e){this.i=null,this.l=new Map;var t=wt(e.children);e.revealOrder&&e.revealOrder[0]==="b"&&t.reverse();for(var n=t.length;n--;)this.l.set(t[n],this.i=[1,0,this.i]);return e.children},on.prototype.componentDidUpdate=on.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Xs(e,n,t)})};var Zs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Jc=/^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/,Zc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Qc=/[A-Z0-9]/g,ed=typeof document<"u",td=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function yo(e,t,n){return t.__k==null&&(t.textContent=""),Rn(e,t),typeof n=="function"&&n(),e?e.__c:null}function Qs(e,t,n){return Is(e,t),typeof n=="function"&&n(),e?e.__c:null}ot.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(ot.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var ei=K.event;K.event=function(e){return ei&&(e=ei(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var So,nd={configurable:!0,get:function(){return this.class}},ti=K.vnode;K.vnode=function(e){typeof e.type=="string"&&(function(t){var n=t.props,r=t.type,o={},i=r.indexOf("-")==-1;for(var s in n){var a=n[s];if(!(s==="value"&&"defaultValue"in n&&a==null||ed&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var c=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":c==="translate"&&a==="no"?a=!1:c[0]==="o"&&c[1]==="n"?c==="ondoubleclick"?s="ondblclick":c!=="onchange"||r!=="input"&&r!=="textarea"||td(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":Zc.test(s)&&(s=c):c=s="oninput":i&&Jc.test(s)?s=s.replace(Qc,"-$&").toLowerCase():a===null&&(a=void 0),c==="oninput"&&o[s=c]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=wt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=wt(n.children).forEach(function(d){d.props.selected=o.multiple?o.defaultValue.indexOf(d.props.value)!=-1:o.defaultValue==d.props.value}))),n.class&&!n.className?(o.class=n.class,Object.defineProperty(o,"className",nd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=Zs,ti&&ti(e)};var ni=K.__r;K.__r=function(e){ni&&ni(e),So=e.__c};var ri=K.diffed;K.diffed=function(e){ri&&ri(e);var t=e.props,n=e.__e;n!=null&&e.type==="textarea"&&"value"in t&&t.value!==n.value&&(n.value=t.value==null?"":t.value),So=null};var oi={ReactCurrentDispatcher:{current:{readContext:function(e){return So.__n[e.__c].props.value},useCallback:fe,useContext:Ct,useDebugValue:io,useDeferredValue:fo,useEffect:Y,useId:ao,useImperativeHandle:so,useInsertionEffect:_o,useLayoutEffect:dt,useMemo:ye,useReducer:rn,useRef:q,useState:F,useSyncExternalStore:ho,useTransition:go}}},rd="18.3.1";function si(e){return qe.bind(null,e)}function tt(e){return!!e&&e.$$typeof===Zs}function ii(e){return tt(e)&&e.type===ue}function ai(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Lt(e){return tt(e)?Yc.apply(null,arguments):e}function vo(e){return!!e.__k&&(Rn(null,e),!0)}function li(e){return e&&(e.base||e.nodeType===1&&e)||null}var ci=function(e,t){return e(t)},di=function(e,t){var n=K.debounceRendering;K.debounceRendering=function(o){return o()};var r=e(t);return K.debounceRendering=n,r},ui=tt,On={useState:F,useId:ao,useReducer:rn,useEffect:Y,useLayoutEffect:dt,useInsertionEffect:_o,useTransition:go,useDeferredValue:fo,useSyncExternalStore:ho,startTransition:po,useRef:q,useImperativeHandle:so,useMemo:ye,useCallback:fe,useContext:Ct,useDebugValue:io,version:"18.3.1",Children:et,render:yo,hydrate:Qs,unmountComponentAtNode:vo,createPortal:Js,createElement:qe,createContext:Nt,createFactory:si,cloneElement:Lt,createRef:ws,Fragment:ue,isValidElement:tt,isElement:ui,isFragment:ii,isMemo:ai,findDOMNode:li,Component:ot,PureComponent:gr,memo:Eo,forwardRef:Q,flushSync:di,unstable_batchedUpdates:ci,StrictMode:ue,Suspense:He,SuspenseList:on,lazy:Xe,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:oi};const bo=Object.freeze(Object.defineProperty({__proto__:null,Children:et,Component:ot,Fragment:ue,PureComponent:gr,StrictMode:ue,Suspense:He,SuspenseList:on,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:oi,cloneElement:Lt,createContext:Nt,createElement:qe,createFactory:si,createPortal:Js,createRef:ws,default:On,findDOMNode:li,flushSync:di,forwardRef:Q,hydrate:Qs,isElement:ui,isFragment:ii,isMemo:ai,isValidElement:tt,lazy:Xe,memo:Eo,render:yo,startTransition:po,unmountComponentAtNode:vo,unstable_batchedUpdates:ci,useCallback:fe,useContext:Ct,useDebugValue:io,useDeferredValue:fo,useEffect:Y,useErrorBoundary:Hc,useId:ao,useImperativeHandle:so,useInsertionEffect:_o,useLayoutEffect:dt,useMemo:ye,useReducer:rn,useRef:q,useState:F,useSyncExternalStore:ho,useTransition:go,version:rd},Symbol.toStringTag,{value:"Module"}));function od(e){return{render:function(t){yo(t,e)},unmount:function(){vo(e)}}}function hi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function wo(...e){return t=>{let n=!1;const r=e.map(o=>{const i=hi(o,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){const i=r[o];typeof i=="function"?i():hi(e[o],null)}}}}function Ft(...e){return fe(wo(...e),e)}function sd(e){const t=id(e),n=Q((r,o)=>{const{children:i,...s}=r,a=et.toArray(i),c=a.find(ld);if(c){const d=c.props.children,h=a.map(u=>u===c?et.count(d)>1?et.only(null):tt(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:tt(d)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function id(e){const t=Q((n,r)=>{const{children:o,...i}=n;if(tt(o)){const s=dd(o),a=cd(i,o.props);return o.type!==ue&&(a.ref=r?wo(r,s):s),Lt(o,a)}return et.count(o)>1?et.only(null):null});return t.displayName=`${e}.SlotClone`,t}var ad=Symbol("radix.slottable");function ld(e){return tt(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ad}function cd(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function dd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var ud=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],sn=ud.reduce((e,t)=>{const n=sd(`Primitive.${t}`),r=Q((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Gt=globalThis?.document?dt:()=>{};function hd(e,t){return rn((n,r)=>t[n][r]??n,e)}var an=e=>{const{present:t,children:n}=e,r=md(t),o=typeof n=="function"?n({present:r.isPresent}):et.only(n),i=Ft(r.ref,pd(o));return typeof n=="function"||r.isPresent?Lt(o,{ref:i}):null};an.displayName="Presence";function md(e){const[t,n]=F(),r=q(null),o=q(e),i=q("none"),s=e?"mounted":"unmounted",[a,c]=hd(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Y(()=>{const d=_r(r.current);i.current=a==="mounted"?d:"none"},[a]),Gt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,f=_r(d);e?c("MOUNT"):f==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),Gt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=E=>{const p=_r(r.current).includes(CSS.escape(E.animationName));if(E.target===t&&p&&(c("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},f=E=>{E.target===t&&(i.current=_r(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:fe(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function _r(e){return e?.animationName||"none"}function pd(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function mi(e,t=[]){let n=[];function r(i,s){const a=Nt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,S=ye(()=>p,Object.values(p));return l(g.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,fd(o,...t)]}function fd(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Ut(e){const t=q(e);return Y(()=>{t.current=e}),ye(()=>(...n)=>t.current?.(...n),[])}var gd=Nt(void 0);function _d(e){const t=Ct(gd);return e||t||"ltr"}function Ed(e,[t,n]){return Math.min(n,Math.max(t,e))}function Vt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function yd(e,t){return rn((n,r)=>t[n][r]??n,e)}var No="ScrollArea",[pi]=mi(No),[Sd,st]=pi(No),fi=Q((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=F(null),[d,h]=F(null),[u,f]=F(null),[E,p]=F(null),[g,S]=F(null),[m,_]=F(0),[y,k]=F(0),[T,x]=F(!1),[N,v]=F(!1),b=Ft(t,A=>c(A)),R=_d(o);return l(Sd,{scope:n,type:r,dir:R,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:f,scrollbarX:E,onScrollbarXChange:p,scrollbarXEnabled:T,onScrollbarXEnabledChange:x,scrollbarY:g,onScrollbarYChange:S,scrollbarYEnabled:N,onScrollbarYEnabledChange:v,onCornerWidthChange:_,onCornerHeightChange:k,children:l(sn.div,{dir:R,...s,ref:b,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});fi.displayName=No;var gi="ScrollAreaViewport",_i=Q((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=st(gi,n),a=q(null),c=Ft(t,a,s.onViewportChange);return l(ue,{children:[l("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),l(sn.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:l("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});_i.displayName=gi;var Et="ScrollAreaScrollbar",xo=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return Y(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?l(vd,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(bd,{...r,ref:t,forceMount:n}):o.type==="auto"?l(Ei,{...r,ref:t,forceMount:n}):o.type==="always"?l(Co,{...r,ref:t}):null});xo.displayName=Et;var vd=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),[i,s]=F(!1);return Y(()=>{const a=o.scrollArea;let c=0;if(a){const d=()=>{window.clearTimeout(c),s(!0)},h=()=>{c=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(c),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),l(an,{present:n||i,children:l(Ei,{"data-state":i?"visible":"hidden",...r,ref:t})})}),bd=Q((e,t)=>{const{forceMount:n,...r}=e,o=st(Et,e.__scopeScrollArea),i=e.orientation==="horizontal",s=vr(()=>c("SCROLL_END"),100),[a,c]=yd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return Y(()=>{if(a==="idle"){const d=window.setTimeout(()=>c("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,c]),Y(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const f=()=>{const E=d[h];u!==E&&(c("SCROLL"),s()),u=E};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,c,s]),l(an,{present:n||a!=="hidden",children:l(Co,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Vt(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:Vt(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),Ei=Q((e,t)=>{const n=st(Et,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=F(!1),a=e.orientation==="horizontal",c=vr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return ln(n.viewport,c),ln(n.content,c),l(an,{present:r||i,children:l(Co,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Co=Q((e,t)=>{const{orientation:n="vertical",...r}=e,o=st(Et,e.__scopeScrollArea),i=q(null),s=q(0),[a,c]=F({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=wi(a.viewport,a.content),h={...r,sizes:a,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function u(f,E){return kd(f,s.current,a,E)}return n==="horizontal"?l(wd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,E=Ni(f,a,o.dir);i.current.style.transform=`translate3d(${E}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=u(f,o.dir))}}):n==="vertical"?l(Nd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,E=Ni(f,a);i.current.style.transform=`translate3d(0, ${E}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=u(f))}}):null}),wd=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(Et,e.__scopeScrollArea),[s,a]=F(),c=q(null),d=Ft(t,c,i.onScrollbarXChange);return Y(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Si,{"data-orientation":"horizontal",...o,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":Sr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(f),Ci(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:yr(s.paddingLeft),paddingEnd:yr(s.paddingRight)}})}})}),Nd=Q((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(Et,e.__scopeScrollArea),[s,a]=F(),c=q(null),d=Ft(t,c,i.onScrollbarYChange);return Y(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(Si,{"data-orientation":"vertical",...o,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":Sr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const f=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(f),Ci(f,u)&&h.preventDefault()}},onResize:()=>{c.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:yr(s.paddingTop),paddingEnd:yr(s.paddingBottom)}})}})}),[xd,yi]=pi(Et),Si=Q((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:h,onResize:u,...f}=e,E=st(Et,n),[p,g]=F(null),S=Ft(t,b=>g(b)),m=q(null),_=q(""),y=E.viewport,k=r.content-r.viewport,T=Ut(h),x=Ut(c),N=vr(u,10);function v(b){if(m.current){const R=b.clientX-m.current.left,A=b.clientY-m.current.top;d({x:R,y:A})}}return Y(()=>{const b=R=>{const A=R.target;p?.contains(A)&&T(R,k)};return document.addEventListener("wheel",b,{passive:!1}),()=>document.removeEventListener("wheel",b,{passive:!1})},[y,p,k,T]),Y(x,[r,x]),ln(p,N),ln(E.content,N),l(xd,{scope:n,scrollbar:p,hasThumb:o,onThumbChange:Ut(i),onThumbPointerUp:Ut(s),onThumbPositionChange:x,onThumbPointerDown:Ut(a),children:l(sn.div,{...f,ref:S,style:{position:"absolute",...f.style},onPointerDown:Vt(e.onPointerDown,b=>{b.button===0&&(b.target.setPointerCapture(b.pointerId),m.current=p.getBoundingClientRect(),_.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",E.viewport&&(E.viewport.style.scrollBehavior="auto"),v(b))}),onPointerMove:Vt(e.onPointerMove,v),onPointerUp:Vt(e.onPointerUp,b=>{const R=b.target;R.hasPointerCapture(b.pointerId)&&R.releasePointerCapture(b.pointerId),document.body.style.webkitUserSelect=_.current,E.viewport&&(E.viewport.style.scrollBehavior=""),m.current=null})})})}),Er="ScrollAreaThumb",vi=Q((e,t)=>{const{forceMount:n,...r}=e,o=yi(Er,e.__scopeScrollArea);return l(an,{present:n||o.hasThumb,children:l(Cd,{ref:t,...r})})}),Cd=Q((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=st(Er,n),s=yi(Er,n),{onThumbPositionChange:a}=s,c=Ft(t,u=>s.onThumbChange(u)),d=q(void 0),h=vr(()=>{d.current&&(d.current(),d.current=void 0)},100);return Y(()=>{const u=i.viewport;if(u){const f=()=>{if(h(),!d.current){const E=Rd(u,a);d.current=E,a()}};return a(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,h,a]),l(sn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Vt(e.onPointerDownCapture,u=>{const f=u.target.getBoundingClientRect(),E=u.clientX-f.left,p=u.clientY-f.top;s.onThumbPointerDown({x:E,y:p})}),onPointerUp:Vt(e.onPointerUp,s.onThumbPointerUp)})});vi.displayName=Er;var To="ScrollAreaCorner",bi=Q((e,t)=>{const n=st(To,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(Td,{...e,ref:t}):null});bi.displayName=To;var Td=Q((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=st(To,n),[i,s]=F(0),[a,c]=F(0),d=!!(i&&a);return ln(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),ln(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(sn.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function yr(e){return e?parseInt(e,10):0}function wi(e,t){const n=e/t;return isNaN(n)?0:n}function Sr(e){const t=wi(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function kd(e,t,n,r="ltr"){const o=Sr(n),i=o/2,s=t||i,a=o-s,c=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,h=n.content-n.viewport,u=r==="ltr"?[0,h]:[h*-1,0];return xi([c,d],u)(e)}function Ni(e,t,n="ltr"){const r=Sr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,c=n==="ltr"?[0,s]:[s*-1,0],d=Ed(e,c);return xi([0,s],[0,a])(d)}function xi(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Ci(e,t){return e>0&&e<t}var Rd=(e,t=()=>{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return(function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&t(),n=i,r=window.requestAnimationFrame(o)})(),()=>window.cancelAnimationFrame(r)};function vr(e,t){const n=Ut(e),r=q(0);return Y(()=>()=>window.clearTimeout(r.current),[]),fe(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function ln(e,t){const n=Ut(t);Gt(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}var Ti=fi,Od=_i,Ad=bi;function Id(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var o=!1;try{o=this instanceof r}catch{}return o?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}var cn={},An={},ki={},In={},Mn={},Pn={},Ri;function ko(){if(Ri)return Pn;Ri=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.EventEmitter=void 0;let e=class{constructor(){O(this,"eventListeners",new Map)}on(t,n){const r=this.eventListeners.get(t)||new Set;r.add(n),this.eventListeners.set(t,r)}off(t,n){const r=this.eventListeners.get(t);r&&(r.delete(n),r.size===0&&this.eventListeners.delete(t))}emit(t,...n){const r=this.eventListeners.get(t);r&&r.forEach(o=>o(...n))}removeAllListeners(){this.eventListeners.clear()}};return Pn.EventEmitter=e,Pn}var dn={},Oi;function Dn(){return Oi||(Oi=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.DisconnectionReason=dn.ConnectionStatus=void 0,dn.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},dn.DisconnectionReason={CLIENT_CLOSED:"client_closed",SERVER_CLOSED:"server_closed",CONNECTION_ERROR:"connection_error",AUTHENTICATION_ERROR:"authentication_error",MAX_RECONNECT_ATTEMPTS:"max_reconnect_attempts",TIMEOUT:"timeout",NETWORK_ERROR:"network_error"}),dn}var Ai;function Ro(){if(Ai)return Mn;Ai=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.BaseConnection=void 0;const e=ko(),t=Dn();let n=class{constructor(){O(this,"status",t.ConnectionStatus.CONNECTING);O(this,"queue",[]);O(this,"eventEmitter",new e.EventEmitter);O(this,"disconnectionDetails",null);O(this,"onErrorCallback",null);O(this,"onDisconnectCallback",null);O(this,"onMessageCallback",null);O(this,"onOpenCallback",null);O(this,"onStatusChangeCallback",null)}getStatus(){return this.status}onOpen(r){this.onOpenCallback=r}onMessage(r){if(this.onMessageCallback=r,this.queue.length>0){const o=[...this.queue];this.queue.length=0,queueMicrotask(()=>{o.forEach(i=>{this.onMessageCallback?.(i)})})}}onDisconnect(r){this.onDisconnectCallback=r;const o=this.disconnectionDetails;o&&queueMicrotask(()=>{this.onDisconnectCallback?.(o)})}onError(r){this.onErrorCallback=r}on(r,o){this.eventEmitter.on(r,o)}off(r,o){this.eventEmitter.off(r,o)}emit(r,...o){this.eventEmitter.emit(r,...o)}onStatusChange(r){this.onStatusChangeCallback=r,queueMicrotask(()=>{r(this.status)})}disconnect(r){this.disconnectionDetails||(this.disconnectionDetails=r,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.onDisconnectCallback?.(r))}handleMessage(r){this.onMessageCallback?this.onMessageCallback(r):this.queue.push(r)}updateStatus(r){this.status!==r&&(this.status=r,this.onStatusChangeCallback?.(r))}};return Mn.BaseConnection=n,Mn}var Ii={},Mi;function nt(){return Mi||(Mi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValidationError=e.ConfigurationError=e.StoreError=e.MessageError=e.SessionError=e.FileError=e.AuthenticationError=e.RecordingError=e.ConnectionError=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.SynapseErrorCode=void 0,e.normalizeError=T,e.SynapseErrorCode={API:"API_ERROR",CONNECTION:"CONNECTION_ERROR",RECORDING:"RECORDING_ERROR",FILE:"FILE_ERROR",SESSION:"SESSION_ERROR",MESSAGE:"MESSAGE_ERROR",STORE:"STORE_ERROR",CONFIGURATION:"CONFIGURATION_ERROR",VALIDATION:"VALIDATION_ERROR",AUTH:"AUTH_ERROR",UNKNOWN:"UNKNOWN_ERROR"};class t extends Error{constructor(v,b=e.SynapseErrorCode.UNKNOWN,R={}){super(v);O(this,"code");O(this,"timestamp");O(this,"cause");O(this,"context");O(this,"hint");O(this,"displayMessage");O(this,"reason");this.name="SynapseError",this.code=b,this.timestamp=new Date,this.cause=R.cause,this.context=R.context,this.hint=R.hint,this.reason=R.reason,this.displayMessage=R.displayMessage||R?.hint||v,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(v,b,R,A){const $=n.makeMessage(b,R,v);super($,e.SynapseErrorCode.API,{cause:R,context:{status:b,hasBody:!!R},hint:b&&b>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:v||"Something went wrong"});O(this,"status");O(this,"error");O(this,"headers");this.name="APIError",this.status=b,this.error=R,this.headers=A}static makeMessage(v,b,R){const A=b instanceof Error?b.message:R;return v&&A?`HTTP ${v}: ${A}`:v?`${v} status code (no body)`:A||"(no status code or body)"}static generate(v,b,R,A){if(!v)return new r({message:R});const $=b?.error,J=$&&typeof $=="object"&&!Array.isArray($)?$:void 0;switch(v){case 400:return new i(R||"Bad Request",v,J,A);case 401:return new s(R||"Unauthorized",v,J,A);case 403:return new a(R||"Permission Denied",v,J,A);case 404:return new c(R||"Not Found",v,J,A);case 405:return new d(R||"Method Not Allowed",v,J,A);case 429:return new h(R||"Rate Limit Exceeded",v,J,A);case 500:return new u(R||"Internal Server Error",v,J,A);default:return new n(R||"API Error",v,J,A)}}}e.APIError=n;class r extends n{constructor({message:N}={}){super(N||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:N}={}){super(N||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(N,v,b,R){super(N,v,b,R),this.name="InternalServerError"}}e.InternalServerError=u;class f extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.CONNECTION,v),this.name="ConnectionError"}}e.ConnectionError=f;class E extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.RECORDING,v),this.name="RecordingError"}}e.RecordingError=E;class p extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.AUTH,v),this.name="AuthenticationError"}}e.AuthenticationError=p;class g extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.FILE,v),this.name="FileError"}}e.FileError=g;class S extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.SESSION,v),this.name="SessionError"}}e.SessionError=S;class m extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.MESSAGE,v),this.name="MessageError"}}e.MessageError=m;class _ extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.STORE,v),this.name="StoreError"}}e.StoreError=_;class y extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.CONFIGURATION,v),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(N,v={}){super(N,e.SynapseErrorCode.VALIDATION,v),this.name="ValidationError"}}e.ValidationError=k;function T(x,N,v,b={}){if(x instanceof N)return x;const R={...b,context:{...x instanceof t?x.context:void 0,...b.context},hint:b.hint??(x instanceof t?x.hint:void 0),reason:b.reason??(x instanceof t?x.reason:void 0),cause:b.cause??x};if(x instanceof t)return new N(x.message,R);const A=x instanceof Error&&x.message?x.message:v;return new N(A,R)}})(Ii)),Ii}var Pi;function Di(){if(Pi)return In;Pi=1,Object.defineProperty(In,"__esModule",{value:!0}),In.WebSocketConnection=void 0;const e=Ro(),t=Dn(),n=nt();class r extends e.BaseConnection{constructor(s){super();O(this,"conversationId");O(this,"socket",null);O(this,"config");O(this,"authenticated",!1);this.config={...s,reconnect:s.reconnect||!0,reconnectAttempts:s.reconnectAttempts||3,reconnectDelay:s.reconnectDelay||1e3},this.conversationId=s.auth.sessionId,this.connect()}connect(){try{if(this.socket&&this.socket.readyState===WebSocket.OPEN||this.authenticated)return;this.updateStatus(t.ConnectionStatus.CONNECTING);const s=this.buildConnectionUrl();this.socket=new WebSocket(s),this.socket.onopen=this.handleOpen.bind(this),this.socket.onmessage=this.handleSocketMessage.bind(this),this.socket.onerror=this.handleError.bind(this),this.socket.onclose=this.handleClose.bind(this)}catch(s){const a=(0,n.normalizeError)(s,n.ConnectionError,"Failed to establish WebSocket connection",{context:{stage:"connect"}});this.onErrorCallback?.(a),this.disconnect({code:1001,reason:t.DisconnectionReason.CONNECTION_ERROR,message:a.message,timestamp:new Date})}}buildConnectionUrl(){const s=new URL(this.config.serverUrl);return s.pathname=`/reloaded/ws/med-assist/session/${this.config.auth.sessionId}/`,s.toString()}handleOpen(){this.authenticated||this.socket?.readyState!==WebSocket.OPEN||this.onOpenCallback?.()}handleSocketMessage(s){try{const a=JSON.parse(s.data);this.handleMessage(a)}catch(a){const c=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(c)}}handleError(s){}handleClose(s){const a=s.wasClean,c=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(c===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):c===1001||c===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):c===4001||c===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(h=t.DisconnectionReason.TIMEOUT,u="Connection timed out"):(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||"Authentication failed"):c===4401||c===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(c===4401?"Session token expired":"Session credentials rejected")):c===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):c===1013?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Server busy, try again later"):a?(h=t.DisconnectionReason.SERVER_CLOSED,u=d||"Server closed connection"):(h=t.DisconnectionReason.CONNECTION_ERROR,u=d||"Connection closed unexpectedly"),this.disconnect({reason:h,message:u,code:c,timestamp:new Date}))}sendMessage(s){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new n.ConnectionError("Cannot send message: connection not open",{context:{stage:"sendMessage",readyState:this.socket?.readyState},hint:"Ensure the WebSocket is open before sending messages."});try{this.socket.send(JSON.stringify(s))}catch(a){const c=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(c),c}}close(){this.authenticated=!1,this.socket&&(this.updateStatus(t.ConnectionStatus.NOT_CONNECTED),this.socket.close(1e3,"Client closed connection"),this.socket=null)}isConnected(){return this.socket?.readyState===WebSocket.OPEN}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED),this.authenticated=!0}}return In.WebSocketConnection=r,In}var Ln={},Li={},Fi;function Ui(){return Fi||(Fi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=void 0,e.SYNAPSE_CHANNELS={WIDGET:"widget",WEB:"web",SIDE_PANEL:"side_panel"},e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS.WIDGET})(Li)),Li}var Vi;function ji(){if(Vi)return Ln;Vi=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.SSEConnection=void 0;const e=Ro(),t=Dn(),n=Ui(),r=nt();class o extends e.BaseConnection{constructor(a){super();O(this,"conversationId");O(this,"config");O(this,"connected",!1);O(this,"activeStreamController",null);this.config=a,this.conversationId=a.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(a){this.onOpenCallback=a,this.connected&&setTimeout(()=>a(),0)}buildChatUrl(){const a=new URL(this.config.serverUrl);return a.pathname=`${a.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,a.toString()}sendMessage(a){if(!this.connected){const d=new r.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(d);return}this.activeStreamController?.abort();const c=new AbortController;this.activeStreamController=c,this.streamChat(a,c)}postChat(a,c,d){return fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",Authorization:`Bearer ${this.config.auth.getToken()}`,"x-agent-id":this.config.agentId,"x-channel":this.config.channel??n.DEFAULT_CHANNEL},body:JSON.stringify(c),signal:d.signal})}async streamChat(a,c){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,c);if(h.status===401&&this.config.auth.onUnauthorized){const p=await this.config.auth.onUnauthorized();if(c.signal.aborted)return;p&&(h=await this.postChat(d,a,c))}if(!h.ok||!h.body)throw new r.APIError("Failed to send message to http stream",h.status,h.body||{});const u=h.body.getReader(),f=new TextDecoder;let E="";for(;;){const{done:p,value:g}=await u.read();if(p)break;E+=f.decode(g,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(c.signal.aborted)return;const u=h instanceof r.APIError?h:(0,r.normalizeError)(h,r.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(u)}finally{this.activeStreamController===c&&(this.activeStreamController=null)}}extractJsonObjects(a){let c=0;for(;c<a.length;){const d=a.indexOf("{",c);if(d===-1)return"";const h=this.findObjectEnd(a,d);if(h===-1)return a.slice(d);const u=a.slice(d,h+1);try{const f=JSON.parse(u);this.handleMessage(f)}catch(f){const E=(0,r.normalizeError)(f,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(E)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let f=c;f<a.length;f++){const E=a[f];if(h){u?u=!1:E==="\\"?u=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")d++;else if(E==="}"&&(d--,d===0))return f}return-1}close(){this.connected=!1,this.activeStreamController?.abort(),this.activeStreamController=null,this.updateStatus(t.ConnectionStatus.NOT_CONNECTED)}isConnected(){return this.connected}handleConnected(){this.updateStatus(t.ConnectionStatus.CONNECTED)}}return Ln.SSEConnection=o,Ln}var zi;function Yi(){return zi||(zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Di(),n=ji(),r=nt();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(ki)),ki}var Fn={},$i;function Oo(){if($i)return Fn;$i=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix.dev.eka.care",BASE_API_URL:"https://matrix.dev.eka.care"},r=(o="production")=>o==="development"?t:o==="production"?e:o==="staging"?n:e;return Fn.getConfig=r,Fn}var Un={},Vn={},Hi;function br(){if(Hi)return Vn;Hi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.HttpClient=void 0;const e=nt();let t=class{constructor(n){O(this,"baseUrl");O(this,"headers");O(this,"timeout");O(this,"maxRetries");O(this,"onUnauthorized");this.baseUrl=n.baseUrl.replace(/\/$/,""),this.timeout=n.timeout||3e4,this.maxRetries=n.maxRetries||3,this.headers={"Content-Type":"application/json","X-Timezone":Intl.DateTimeFormat?.()?.resolvedOptions?.()?.timeZone||"","x-channel":"widget",...n.headers},n.authorization&&(this.headers.Authorization=n.authorization)}setAuthorization(n){this.headers.Authorization=`Bearer ${n}`}clearAuthorization(){delete this.headers.Authorization}setUnauthorizedHandler(n){this.onUnauthorized=n}async request(n,r,o){try{return await this.requestWithRetries(n,r,o)}catch(i){if(!(i instanceof e.APIError&&i.status===401&&!o?.skipAuthRefresh&&this.onUnauthorized)||!await this.onUnauthorized())throw i;return this.requestWithRetries(n,r,{...o,skipAuthRefresh:!0})}}async requestWithRetries(n,r,o){const i=o?.retries??this.maxRetries;let s;for(let a=0;a<=i;a++)try{const c=this.buildUrl(r,o?.params),d=await fetch(c,{method:n,headers:{...this.headers,...o?.headers},body:o?.body?JSON.stringify(o.body):void 0,signal:AbortSignal.timeout(this.timeout)});return d.ok||await this.handleError(d),d.json()}catch(c){if(s=c,a===i||!(c instanceof TypeError&&c.message==="Failed to fetch"||c instanceof DOMException&&c.name==="AbortError"||c instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(h=>setTimeout(h,d))}throw s?s instanceof TypeError&&s.message==="Failed to fetch"?new e.APIError("Unable to connect to the server. Please check your internet connection.",0,{type:"NETWORK_ERROR",originalError:s.message}):s instanceof DOMException&&s.name==="AbortError"?new e.APIConnectionTimeoutError({message:`Request timed out after ${this.timeout}ms`}):s instanceof SyntaxError?new e.APIError("Invalid response format from server",502,{type:"PARSE_ERROR",originalError:s.message}):s instanceof e.APIError?s:new e.APIError(`Request failed: ${s.message||"Unknown error"}`,500,{type:"UNKNOWN_ERROR",originalError:s}):new e.APIError("Unknown error occurred",500,{type:"UNKNOWN_ERROR"})}async get(n,r,o){return this.request("GET",n,{params:r,...o})}async post(n,r,o){return this.request("POST",n,{body:r,...o})}async put(n,r,o){return this.request("PUT",n,{body:r,...o})}async delete(n,r){return this.request("DELETE",n,{...r})}async patch(n,r,o){return this.request("PATCH",n,{body:r,...o})}buildUrl(n,r){let o=`${this.baseUrl}${n}`;if(r){const i=new URLSearchParams(r).toString();o+=`?${i}`}return o}async handleError(n){let r,o;try{o=await n.json();const i=o,s=i?.error;r=i?.message||i?.msg||s?.msg||s?.message||n.statusText}catch{r=n.statusText}throw e.APIError.generate(n.status,o,r,n.headers)}};return Vn.HttpClient=t,Vn}var jn={},zn={},Bi;function Yn(){if(Bi)return zn;Bi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.BaseResource=void 0;let e=class{constructor(t){O(this,"client");this.client=t}async get(t,n,r){return this.client.get(t,n,r)}async post(t,n,r){return this.client.post(t,n,r)}async put(t,n,r){return this.client.put(t,n,r)}async delete(t,n){return this.client.delete(t,n)}async patch(t,n,r){return this.client.patch(t,n,r)}buildPath(t,n){let r=t;for(const[o,i]of Object.entries(n))r=r.replace(`:${o}`,encodeURIComponent(i));return r}};return zn.BaseResource=e,zn}var Gi;function Wi(){if(Gi)return jn;Gi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.Session=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/session")}async create(r){return this.post(this.basePath,r)}async retrieve(r,o){return this.get(`${this.basePath}/${r}`,o?.includeMessages?{messages:"true"}:void 0)}async feedback({sessionId:r,messageId:o,feedback:i,feedbacks:s,feedbackReason:a,npsBase5:c}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...c&&{nps_base5:c}})}async history(){return this.get(`${this.basePath}`)}async callTool(r,o,i,s){return this.post(`${this.basePath}/${r}/messages/${i}/tools/${o}`,{tool_params:s})}};return jn.Session=t,jn}var $n={},Ki;function Ao(){if(Ki)return $n;Ki=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.Config=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/agent-config")}async retrieve(r){const o=await this.get(`${this.basePath}/${r}`);if(o?.success&&o.data)return o.data}};return $n.Config=t,$n}var qi={},Xi;function Ji(){return Xi||(Xi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=br(),n=Oo(),r=Ao(),o=new Map,i=(c,d)=>`${c.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(c){const d=c.serverUrl||(0,n.getConfig)(c.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,c.agentId),u=o.get(h);if(u)return u;const f=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":c.agentId,...c.channel&&{"x-channel":c.channel}}}),E=new r.Config(f).retrieve(c.agentId);return E.catch(()=>{o.get(h)===E&&o.delete(h)}),o.set(h,E),E}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(qi)),qi}var Hn={},Zi;function Io(){if(Zi)return Hn;Zi=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.Auth=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/auth/token-exchange")}async exchange(r){return this.post(this.basePath,r,{skipAuthRefresh:!0})}async refresh(r){return this.post(this.basePath,r,{params:{type:"refresh"},skipAuthRefresh:!0})}};return Hn.Auth=t,Hn}var Bn={},un={},Qi;function Mo(){return Qi||(Qi=1,Object.defineProperty(un,"__esModule",{value:!0}),un.ErrorType=un.SYNAPSE_RECOVERY_REASON=void 0,un.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},un.ErrorType={NETWORK_ERROR:"NETWORK_ERROR",TIMEOUT_ERROR:"TIMEOUT_ERROR",API_ERROR:"API_ERROR",RATE_LIMIT_ERROR:"RATE_LIMIT_ERROR",SERVER_ERROR:"SERVER_ERROR",PARSE_ERROR:"PARSE_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"}),un}var Gn={},ea;function Po(){if(ea)return Gn;ea=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.ErrorUtils=void 0;const e=nt();class t{static isAPIError(r){return r instanceof e.APIError}static isNetworkError(r){return r instanceof e.APIError&&(r.status===0||r.status===void 0)}static isTimeoutError(r){return r instanceof e.APIConnectionTimeoutError}static isAuthError(r){return r instanceof e.UnauthorizedError||r instanceof e.PermissionDeniedError}static isClientError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=400&&r.status<500}static isServerError(r){return r instanceof e.APIError&&r.status!==void 0&&r.status>=500}static getUserFriendlyMessage(r){return t.isNetworkError(r)?"Unable to connect to the server. Please check your internet connection.":t.isTimeoutError(r)?"Request timed out. Please try again.":t.isAuthError(r)?"Authentication failed. Please log in again.":t.isServerError(r)?"Server error occurred. Please try again later.":t.isAPIError(r)||r instanceof Error?r.message:"An unexpected error occurred."}static getErrorDetails(r){return t.isAPIError(r)?{type:r.name,message:r.message,code:r.code,status:r.status,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof e.SynapseError?{type:r.name,message:r.message,code:r.code,timestamp:r.timestamp,stack:r.stack,context:r.context,hint:r.hint}:r instanceof Error?{type:r.name,message:r.message,stack:r.stack}:{type:"Unknown",message:String(r)}}}return Gn.ErrorUtils=t,Gn}var ta={},na;function ra(){return na||(na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=br(),n=Oo(),r=Po(),o=Io(),i=new Map,s=(d,h,u)=>`${d.replace(/\/$/,"")}|${h}|${u??""}`;e.buildPrefetchKey=s;function a(d){const h=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,u=(0,e.buildPrefetchKey)(h,d.agentId,d.authToken),f=i.get(u);if(f)return f;const E=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),p=new o.Auth(E).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return p.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===p&&i.delete(u)}),i.set(u,p),p}function c(d){const h=i.get(d);return h&&i.delete(d),h}})(ta)),ta}var oa;function Md(){if(oa)return Bn;oa=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.TokenManager=void 0;const e=nt(),t=Mo(),n=Po(),r=ra();let o=class{constructor(i,s,a,c){O(this,"auth");O(this,"httpClient");O(this,"agentId");O(this,"partnerAuthToken");O(this,"refreshToken");O(this,"sessToken");O(this,"_userId");O(this,"_level");O(this,"_expiresAt");O(this,"lastResponse");O(this,"initPromise",null);O(this,"refreshPromise",null);O(this,"prefetchKey");O(this,"onTokenExchange");this.auth=i,this.httpClient=s,this.agentId=a,this.partnerAuthToken=c.partnerAuthToken,this.refreshToken=c.refreshToken,this.onTokenExchange=c.onTokenExchange,this._level=c.level,this._userId=c.userId,c.sessToken&&(this.sessToken=c.sessToken,this.httpClient.setAuthorization(c.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(c.serverUrl,a,c.partnerAuthToken)}getBearer(){return this.sessToken}getSessToken(){return this.sessToken}get userId(){return this._userId}get level(){return this._level}get isExchanged(){return!!this.lastResponse}get expiresAt(){return this._expiresAt}get hasResumableCredentials(){return!!this.sessToken&&!!this.refreshToken}async ensureCredentials(){this.lastResponse||this.hasResumableCredentials||await this.ensureExchanged()}ensureExchanged(){if(this.lastResponse)return Promise.resolve(this.lastResponse);if(!this.initPromise){const i=(0,r.consumePrefetchedExchange)(this.prefetchKey),s=i?i.catch(a=>{if(n.ErrorUtils.isAuthError(a))throw a;return this.exchangeInit()}):this.exchangeInit();this.initPromise=s.then(a=>this.apply(a)).catch(a=>{throw this.tagAuthRejection(a,t.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED,"tokenExchange","Token exchange was rejected")}).finally(()=>{this.initPromise=null})}return this.initPromise}refresh(){if(this.refreshPromise)return this.refreshPromise;const i=this.refreshToken;return i?(this.refreshPromise=this.auth.refresh({refresh_token:i}).then(s=>this.apply(s)).catch(s=>{throw this.tagAuthRejection(s,t.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"tokenRefresh","Token refresh was rejected")}).finally(()=>{this.refreshPromise=null}),this.refreshPromise):Promise.reject(new e.UnauthorizedError("No refresh token available to refresh authentication",401))}tagAuthRejection(i,s,a,c){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,c,{reason:s,context:{stage:a,status:i.status}}):i}clearTokens(){this.resetExchangeState(),this.partnerAuthToken=void 0}clearAll(){this.resetExchangeState(),this._userId=void 0,this._level=void 0}resetExchangeState(){this.sessToken=void 0,this.refreshToken=void 0,this._expiresAt=void 0,this.lastResponse=void 0,this.initPromise=null,this.refreshPromise=null,this.httpClient.clearAuthorization(),(0,r.consumePrefetchedExchange)(this.prefetchKey)}async refreshBearer(){try{return await this.refresh(),this.getBearer()??null}catch{return null}}exchangeInit(){return this.auth.exchange({agent_id:this.agentId,...this.partnerAuthToken&&{auth_token:this.partnerAuthToken},...this.refreshToken&&{refresh_token:this.refreshToken}})}apply(i){return this.sessToken=i.sess_token,this.refreshToken=i.refresh_token,this._userId=i.user_id,this._level=i.level,this._expiresAt=Date.now()+i.expires_in*1e3,this.lastResponse=i,this.httpClient.setAuthorization(i.sess_token),this.onTokenExchange?.(i),i}};return Bn.TokenManager=o,Bn}var Wn={},sa;function Pd(){var n;if(sa)return Wn;sa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.VoiceResource=void 0;const e=Yn();let t=(n=class extends e.BaseResource{async getIceServers(o,i){return this.get(n.ICE_SERVERS_PATH,{session_id:o,token:i})}async sendOffer(o){return this.post(n.OFFER_PATH,o)}},O(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),O(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Wn.VoiceResource=t,Wn}var ia;function aa(){if(ia)return Un;ia=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.ResourceManager=void 0;const e=br(),t=Wi(),n=nt(),r=Ao(),o=Ji(),i=Io(),s=Md(),a=Pd();class c{constructor(h){O(this,"resourceConfig");O(this,"httpClient");O(this,"session");O(this,"config");O(this,"auth");O(this,"tokenManager");O(this,"voiceResource");this.resourceConfig=h,this.httpClient=new e.HttpClient({baseUrl:this.resourceConfig.serverUrl,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":this.resourceConfig.agentId,...this.resourceConfig.channel&&{"x-channel":this.resourceConfig.channel}}}),this.config=new r.Config(this.httpClient),this.session=new t.Session(this.httpClient),this.auth=new i.Auth(this.httpClient),this.tokenManager=new s.TokenManager(this.auth,this.httpClient,this.resourceConfig.agentId,{partnerAuthToken:this.resourceConfig.authToken,refreshToken:this.resourceConfig.refreshToken,sessToken:this.resourceConfig.sessToken,level:this.resourceConfig.level,userId:this.resourceConfig.userId,serverUrl:this.resourceConfig.serverUrl,onTokenExchange:this.resourceConfig.onTokenExchange}),this.httpClient.setUnauthorizedHandler(()=>this.tokenManager.refreshBearer()),this.voiceResource=new a.VoiceResource(this.httpClient)}async exchangeInit(){return await this.tokenManager.ensureExchanged()}async ensureCredentials(){return await this.tokenManager.ensureCredentials()}getLevel(){return this.tokenManager.level}getSessToken(){return this.tokenManager.getSessToken()}getUserId(){return this.tokenManager.userId}refreshBearer(){return this.tokenManager.refreshBearer()}setUnauthorizedHandler(h){this.httpClient.setUnauthorizedHandler(h)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(h,u){try{const{profile:f,intent:E,user_location:p,referer:g,...S}=u||{},m=this.tokenManager.userId||h,_={...m&&{user_id:m},...f&&{user_context:f},...(E||Object.keys(S).length>0)&&{session_context:{...E&&{intent:E},...p&&{user_location:p},...S}},...g&&{referer:g}},y=await this.session.create(_);if(!y?.session_id)throw new n.APIError("Failed to start session.",500,void 0,void 0);return y}catch(f){throw f instanceof n.APIError?f:new n.APIError("Failed to start session.",500,void 0,void 0)}}async getAgentConfig(){this.config||(this.config=new r.Config(this.httpClient));const h=(0,o.consumePrefetchedAgentConfig)((0,o.buildAgentConfigKey)(this.resourceConfig.serverUrl,this.resourceConfig.agentId));if(h)try{return await h}catch{}try{return await this.config.retrieve(this.resourceConfig.agentId)}catch{throw new n.APIError("Failed to get agent config.",500,void 0,void 0)}}async reinitialiseSession(h){return await this.session.retrieve(h)}async getPastSessions(){return await this.session.history()}async getSessionMessages(h){return(await this.session.retrieve(h,{includeMessages:!0}))?.messages??[]}async refreshTokens(){return await this.tokenManager.refresh()}async sendFeedback({sessionId:h,messageId:u,feedback:f,feedbacks:E,feedbackReason:p,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:f,feedbacks:E,feedbackReason:p,npsBase5:g})}async callTool(h,u,f,E){return await this.session.callTool(h,u,f,E)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Un.ResourceManager=c,Un}var Kn={},la={},ca;function Do(){return ca||(ca=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.MULTI_SELECT_ADDITIONAL_OPTION=e.SOCKET_EVENTS=e.SOCKET_CONTENT_TYPES=void 0,e.IsValidSocketMesssage=t,e.SOCKET_CONTENT_TYPES={TEXT:"text",AUDIO:"audio",FILE:"file",TOOL_CALL:"tool",TIPS:"tips",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},e.SOCKET_EVENTS={PING:"ping",PONG:"pong",CHAT:"chat",STREAM:"stream",AUTH:"auth",END_OF_STREAM:"eos",SYNC:"sync",ERROR:"err",CONNECTION_ESTABLISHED:"conn"},e.MULTI_SELECT_ADDITIONAL_OPTION={NOTA:"none_of_the_above",AOTA:"all_of_the_above"};function t(n){return[e.SOCKET_EVENTS.PING,e.SOCKET_EVENTS.PONG,e.SOCKET_EVENTS.ERROR,e.SOCKET_EVENTS.SYNC,e.SOCKET_EVENTS.CONNECTION_ESTABLISHED,e.SOCKET_EVENTS.CHAT,e.SOCKET_EVENTS.STREAM,e.SOCKET_EVENTS.END_OF_STREAM].includes(n.ev)}})(la)),la}var da={},ua;function Dd(){return ua||(ua=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=nt();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){O(this,"pendingFiles",[]);O(this,"pendingMessage","");O(this,"pendingFormats",[])}setFilesForUpload(o,i){this.pendingFiles.length>0&&this.clearPendingFilesState();const s=o.filter(a=>this.validateFile(a));if(s.length===0)throw new t.FileError("File not supported",{context:{stage:"setFilesForUpload"}});this.pendingFiles=s,i&&i.trim()&&(this.pendingMessage=i),this.pendingFormats=s.map(a=>a.type)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.filter(a=>a.url&&a.url.trim());try{if(s.length===0)throw new t.FileError("No valid presigned URLs provided",{context:{stage:"uploadFilesToPresignedUrl"}});if(!this.pendingFiles.length)throw new t.FileError("No files to upload",{context:{stage:"uploadFilesToPresignedUrl"}});for(let a=0;a<s.length;a++){const c=s[a].url,d=await fetch(c,{method:"PUT",body:this.pendingFiles[a],headers:{"Content-Type":this.pendingFiles[a].type,"x-ms-blob-type":"BlockBlob"}});if(!d.ok)throw new t.FileError(`Failed to upload ${this.pendingFiles[a].name} to URL ${a+1}: ${d.status} ${d.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(s[a].id)}return i}catch(a){if(i.length>0)return i;throw(0,t.normalizeError)(a,t.FileError,"Failed to upload files to presigned URL",{context:{stage:"uploadFilesToPresignedUrl"}})}}blobToFile(o,i){return new File([o],i,{type:o.type})}validateFile(o){return["application/pdf","image/jpeg","image/png","image/jpg"].includes(o.type)&&o.size<e.MAX_FILE_SIZE}clearPendingFilesState(){this.pendingFiles=[],this.pendingMessage="",this.pendingFormats=[]}}e.Filemanager=n})(da)),da}var ut={},ha;function wr(){if(ha)return ut;ha=1,Object.defineProperty(ut,"__esModule",{value:!0}),ut.SYNAPSE_REALTIME_RESERVED_EVENTS=ut.SYNAPSE_REALTIME_ERROR_CODES=ut.SYNAPSE_REALTIME_EVENTS=ut.SYNAPSE_MESSAGE_TYPES=void 0;const e=Do();return ut.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,ut.SYNAPSE_REALTIME_EVENTS={CONNECTED:"connected",DISCONNECTED:"disconnected",PROGRESS_MESSAGE:"progress_message",MESSAGE_CHUNK:"message_chunk",TIPS_MESSAGE:"tips_message",END_OF_STREAM:"end_of_stream",ERROR:"error",TOOL_CALL:"tool_call",AUDIO_TRANSCRIPT:"audio_transcript",TOOL_START:"tool_start",TOOL_END:"tool_end"},ut.SYNAPSE_REALTIME_ERROR_CODES={SESSION_INACTIVE:"session_not_found",SESSION_TOKEN_EXPIRED:"sess_token_expired",INVALID_EVENT:"invalid_event",INVALID_CONTENT_TYPE:"invalid_content",PARSING_ERROR:"parsing",FILE_UPLOAD_INPROGRESS:"file_upload_inprogress",TIMEOUT:"timeout",SERVER_ERROR:"server_error",SESSION_TOKEN_MISMATCH:"session_token_mismatch",PROMPT_FETCH_ERROR:"prompt_fetch_error",INVALID_FILE_REQUEST:"invalid_file_request",SESSION_NOT_OWNED:"session_not_owned"},ut.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},ut}var qn={},ma;function Ld(){if(ma)return qn;ma=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.AudioManager=void 0;const e=nt();class t{constructor(r={}){O(this,"mediaRecorder",null);O(this,"mediaStream",null);O(this,"recordingStartTime",0);O(this,"autoPauseTimer",null);O(this,"config");O(this,"onAudioData",null);O(this,"onAudioError",null);O(this,"suppressCallbacks",!1);this.config={mimeType:"audio/webm;codecs=opus",audioBitsPerSecond:128e3,maxRecordingDuration:9e5,autoPauseEnabled:!0,...r}}async checkCurrentPermissionState(){if(!navigator.permissions||!navigator.permissions.query)return"prompt";try{const r=await navigator.permissions.query({name:"microphone"});if(r.state==="denied")throw new e.RecordingError("Microphone permission denied",{context:{permissionState:r.state},hint:"Ensure the browser has microphone access enabled for this site."});return r.state}catch(r){if(r instanceof Error&&r.name==="NotSupportedError")return"prompt"}return"prompt"}async start(r,o){try{if(!navigator.mediaDevices)throw new e.RecordingError("Media devices API is not available. This usually means the page is not served over HTTPS or there are browser restrictions.",{context:{feature:"mediaDevices"},hint:"Serve the app over HTTPS and verify browser/device microphone support.",displayMessage:"Microphone access is unavailable."});if(!window.MediaRecorder)throw new e.RecordingError("MediaRecorder is not supported in this browser",{context:{feature:"MediaRecorder"},hint:"Use a browser that supports the MediaRecorder API.",displayMessage:"Microphone access is unavailable."});const i=["audio/mp3","audio/ogg;codecs=opus","audio/mp4","audio/ogg","audio/wav"].filter(s=>MediaRecorder.isTypeSupported(s));if(i.length===0)throw new e.RecordingError("No supported audio formats found in this browser",{context:{requestedTypes:i},hint:"Verify codec support or adjust the requested MIME types.",displayMessage:"Microphone access is unavailable."});if(this.config.mimeType=i[0],await this.checkCurrentPermissionState(),this.onAudioData=r,this.onAudioError=o??null,this.suppressCallbacks=!1,this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!1,noiseSuppression:!1,autoGainControl:!1,sampleRate:44100,channelCount:1}}),this.mediaRecorder=new MediaRecorder(this.mediaStream,{mimeType:this.config.mimeType,audioBitsPerSecond:this.config.audioBitsPerSecond}),this.mediaRecorder.state!=="inactive")throw new e.RecordingError("MediaRecorder is in an invalid state for start()",{context:{recorderState:this.mediaRecorder.state},displayMessage:"Failed to start recording"});this.setupMediaRecorderEvents(),this.mediaRecorder.start(),this.recordingStartTime=Date.now(),this.config.autoPauseEnabled&&this.setupAutoPauseTimer()}catch(i){throw i instanceof Error&&i.name==="NotAllowedError"?new e.RecordingError("Microphone permission denied",{context:{permissionState:"denied"},hint:"Ensure the browser or device has microphone access enabled for this site/app."}):this.toRecordingError(i,"Failed to start audio recording",{stage:"start"})}}async processAudioChunk(r){try{const o=await this.blobToBase64(r),i=Date.now();if(!this.onAudioData)return;const s={audio:o,format:this.config.mimeType,duration:this.recordingStartTime>0?i-this.recordingStartTime:0,timestamp:this.recordingStartTime>0?this.recordingStartTime:i};this.onAudioData(s)}catch(o){this.handleError(o,{stage:"process_audio_chunk"})}}toRecordingError(r,o,i){if(r instanceof e.RecordingError)return r;if(r instanceof e.SynapseError)return new e.RecordingError(r.message,{cause:r,context:{...r.context,...i},hint:r.hint});const s=r instanceof Error&&r.message?r.message:o;return new e.RecordingError(s,{cause:r,context:i})}handleError(r,o){const i=this.toRecordingError(r,"Unexpected recording error",o);if(this.onAudioError)try{this.onAudioError(i)}catch{}}setupAutoPauseTimer(){this.autoPauseTimer&&clearTimeout(this.autoPauseTimer),this.autoPauseTimer=setTimeout(()=>{this.stop()},this.config.maxRecordingDuration)}setupMediaRecorderEvents(){this.mediaRecorder&&(this.mediaRecorder.ondataavailable=r=>{this.suppressCallbacks||r.data.size<=0||this.processAudioChunk(r.data).catch(o=>this.handleError(o,{stage:"media_recorder_ondataavailable",hasData:r.data.size>0}))},this.mediaRecorder.onstop=async()=>{this.recordingStartTime=0},this.mediaRecorder.onerror=r=>{this.handleError(r.error instanceof Error?r.error:new Error("MediaRecorder encountered an unknown error"),{stage:"media_recorder_onerror"})},this.mediaRecorder.onstart=()=>{})}blobToBase64(r){return new Promise((o,i)=>{const s=new FileReader;s.onload=()=>{if(typeof s.result=="string"){const a=s.result.split(",")[1];o(a)}else i(new e.RecordingError("Failed to convert blob to base64",{context:{stage:"blob_to_base64"}}))},s.onerror=()=>i(new e.RecordingError("FileReader error while converting audio chunk to base64",{cause:s.error??void 0,context:{stage:"blob_to_base64"}})),s.readAsDataURL(r)})}stop(){if(this.mediaRecorder)try{this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to stop audio recording",{stage:"stop"})}}cancel(){if(this.mediaRecorder)try{this.suppressCallbacks=!0,this.autoPauseTimer&&(clearTimeout(this.autoPauseTimer),this.autoPauseTimer=null),this.mediaRecorder.ondataavailable=null,this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to cancel audio recording",{stage:"cancel"})}}destroy(){try{this.cancel(),this.mediaRecorder&&(this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null)}catch(r){throw this.toRecordingError(r,"Failed to destroy audio resources",{stage:"destroy"})}}}return qn.AudioManager=t,qn}var pa;function fa(){if(pa)return Kn;pa=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.MessageManager=void 0;const e=Do(),t=Dd(),n=wr(),r=Ld(),o=nt();let i=class{constructor(s){O(this,"connection",null);O(this,"callbacks",null);O(this,"fileManager",null);O(this,"audioManager",null);O(this,"outgoingBuffer",null);this.callbacks=s||null}setConnection(s){this.connection=s}handleFileUploadProcess({files:s,message:a,urls:c,tool_declined:d,tool_result:h}){this.fileManager||(this.fileManager=new t.Filemanager);let u;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(c&&c.length>0){const f=this.fileManager.getPendingFileState().message;u={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:c,...f&&{text:f},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:c,urls:d,tool_declined:h,tool_id:u,tool_result:f,initial_prompts:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...c&&{audio:c},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...f&&{tool_result:f},...E&&{initial_prompts:E}};return}const p=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const S=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:f})}else s?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...h&&{tool_declined:h},...u&&{tool_id:u},...E&&{initial_prompts:E},...f&&{tool_result:f}}}:c&&c?.audio&&c?.format?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:c?.audio,format:c?.format,...h&&{tool_declined:h},...f&&{tool_result:f}}}:f&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:f}});if(!g){const S=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(S),S}p.sendMessage(g)}handleIncomingSocketChatMessage(s){const a=this.assertConnection("handleIncomingSocketChatMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.FILE:{s?.data?.urls&&s.data.urls?.length>0&&this.fileManager?.uploadFilesToPresignedUrl(s.data.urls).then(c=>{this.sendSocketMessage({urls:c})}).catch(c=>{const d=this.toFileError(c,"Failed to upload files to presigned URL",{stage:"handleIncomingSocketChatMessage",urls:s.data?.urls?.length});this.emitError(d)});break}case e.SOCKET_CONTENT_TYPES.TEXT:if(s.data.text&&s.data.text.trim()===""&&s._id){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,c)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const c={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,c)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const c={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,c)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const u={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,u);return}if(s?.data?.text){const u={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,u)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const u={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const u={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,u);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const c={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,c);break;case e.SOCKET_CONTENT_TYPES.TOOL_END:const d={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_END,d);break;default:const h=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(h),h}}handleDisconnect(s){this.connection?.emit?.(n.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,s)}handleIncomingSocketEndOfStreamMessage(s){this.assertConnection("handleIncomingSocketEndOfStreamMessage").emit(n.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM)}handleIncomingSocketErrorMessage(s){const a=this.assertConnection("handleIncomingSocketErrorMessage");switch(s?.data?.code){case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_EXPIRED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE);break;case n.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:a.emit(n.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,s),a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s);break;default:const c=new o.MessageError(s?.data?.msg||"Socket error received",{context:{stage:"handleIncomingSocketErrorMessage",errorCode:s?.data?.code},hint:s?.data?.msg,cause:s,displayMessage:s?.data?.msg});a.emit(n.SYNAPSE_REALTIME_EVENTS.ERROR,s)}}sendSocketAuthMessage(s){const a=this.assertConnection("sendSocketAuthMessage"),c={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(c)}sendSocketPingMessage(){const s=this.assertConnection("sendSocketPingMessage"),a={ev:e.SOCKET_EVENTS.PING,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}async startRecording({onChunks:s,onError:a}){if(!s){const c=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(c),c}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,c=>{const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(c){const d=this.toRecordingError(c,"Failed to start audio recording",{stage:"startRecording"});throw a?.(d),this.emitError(d),d}}endRecordingWithSocket(){if(!this.audioManager){const s=new o.RecordingError("Audio manager not set. Call startRecording() first.",{context:{stage:"stopRecording"}});throw this.emitError(s),s}try{this.audioManager.stop()}catch(s){const a=this.toRecordingError(s,"Failed to stop audio recording",{stage:"stopRecording"});throw this.emitError(a),a}}sendSocketPongMessage(){const s=this.assertConnection("sendSocketPongMessage"),a={ev:e.SOCKET_EVENTS.PONG,_id:Date.now().toString(),ts:Date.now()};s.sendMessage(a)}handleConnectionEstablished(){this.connection?.handleConnected(),this.connection?.emit(n.SYNAPSE_REALTIME_EVENTS.CONNECTED),this.flushOutgoingBuffer()}flushOutgoingBuffer(){if(!this.connection?.isConnected()||!this.outgoingBuffer)return;const s=this.outgoingBuffer;this.outgoingBuffer=null,this.sendSocketMessage(s)}cleanupMessageServerState(){this.outgoingBuffer=null,this.connection=null,this.fileManager&&(this.fileManager.clearPendingFilesState(),this.fileManager=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null)}emitError(s){this.callbacks?.onError?.(s)}toFileError(s,a,c,d){return(0,o.normalizeError)(s,o.FileError,a,{context:c,hint:d})}toRecordingError(s,a,c,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:c,hint:d})}assertConnection(s){if(!this.connection){const a=new o.ConnectionError("Connection not set. Please ensure the connection is established before calling this method.",{context:{stage:s}});throw this.emitError(a),a}return this.connection}};return Kn.MessageManager=i,Kn}var ga={},_a;function Fd(){return _a||(_a=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.outcomeForHttpStatus=e.outcomeForCloseCode=e.RECOVERY_OUTCOME=void 0,e.RECOVERY_OUTCOME={REFRESH_AND_RETRY:"refresh_and_retry",FORBIDDEN:"forbidden",SESSION_GONE:"session_gone",RETRY_LATER:"retry_later",SESSION_NOT_OWNED:"session_not_owned"};const t={4401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,4403:e.RECOVERY_OUTCOME.FORBIDDEN,4404:e.RECOVERY_OUTCOME.SESSION_GONE,1013:e.RECOVERY_OUTCOME.RETRY_LATER},n={401:e.RECOVERY_OUTCOME.REFRESH_AND_RETRY,403:e.RECOVERY_OUTCOME.FORBIDDEN,404:e.RECOVERY_OUTCOME.SESSION_GONE,429:e.RECOVERY_OUTCOME.RETRY_LATER,503:e.RECOVERY_OUTCOME.RETRY_LATER},r=i=>i===void 0?void 0:t[i];e.outcomeForCloseCode=r;const o=i=>i===void 0?void 0:n[i];e.outcomeForHttpStatus=o})(ga)),ga}var Xn={},Jn={},Ea;function Ud(){if(Ea)return Jn;Ea=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){O(this,"audioCtx",null);O(this,"animFrame",null)}start(n,r,o){const i=new AudioContext;this.audioCtx=i;const s=i.createAnalyser();s.fftSize=e,i.createMediaStreamSource(n).connect(s);const a=new Uint8Array(s.frequencyBinCount),c=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(c)};c()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return Jn.VoiceAudioAnalyser=t,Jn}var hn={},ya;function Sa(){return ya||(ya=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.VOICE_AGENT_EVENTS=hn.VOICE_AGENT_STATE=void 0,hn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},hn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),hn}var va;function Vd(){if(va)return Xn;va=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.VoiceAgent=void 0;const e=ko(),t=Ud(),n=nt(),r=Sa(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(f=>{if(h.iceGatheringState==="complete"){f();return}const E=setTimeout(f,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(E),f())}})}let d=class{constructor(h,u,f){O(this,"config");O(this,"resourceManager");O(this,"getCredentials");O(this,"emitter",new e.EventEmitter);O(this,"remoteAnalyser",new t.VoiceAudioAnalyser);O(this,"localAnalyser",new t.VoiceAudioAnalyser);O(this,"pc",null);O(this,"pcId",null);O(this,"dataChannel",null);O(this,"localStream",null);O(this,"remoteAudio",null);O(this,"_state",r.VOICE_AGENT_STATE.IDLE);O(this,"_isMuted",!1);O(this,"manuallyDisconnected",!1);O(this,"_hasConnectionFailureNotified",!1);O(this,"_userSpeaking",!1);O(this,"_silenceTimer",null);O(this,"_cachedIceServers",null);O(this,"_iceServersCachedAt",0);this.config=h,this.resourceManager=u,this.getCredentials=f}get state(){return this._state}get isMuted(){return this._isMuted}on(h,u){this.emitter.on(h,u)}off(h,u){this.emitter.off(h,u)}async connect(){const h=await this.getCredentials();this.setState(r.VOICE_AGENT_STATE.CONNECTING),this._hasConnectionFailureNotified=!1;try{if(!navigator.mediaDevices?.getUserMedia)throw new Error("Microphone access is not available. Please ensure you are using a secure (HTTPS) connection.");const u=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=u;const f=await this.fetchIceServers(h),E=new RTCPeerConnection({iceServers:f,iceTransportPolicy:"all"});this.pc=E,this.dataChannel=E.createDataChannel("pipecat-events",{ordered:!0}),this.dataChannel.onopen=()=>{},this.dataChannel.onclose=()=>this.handleConnectionFailure(new Error("Data channel closed"),"Voice connection failed"),this.dataChannel.onerror=()=>this.handleConnectionFailure(new Error("Data channel error"),"Voice connection failed"),u.getAudioTracks().forEach(_=>E.addTrack(_,u)),E.ontrack=_=>this.handleRemoteTrack(_),E.onconnectionstatechange=()=>{E.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(E.connectionState==="failed"||E.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},E.oniceconnectionstatechange=()=>{(E.iceConnectionState==="connected"||E.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):E.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const p=await E.createOffer();await E.setLocalDescription(p);const g=this.config.iceGatheringTimeoutMs??o;await c(E,g);const S=_=>({sdp:E.localDescription.sdp,type:E.localDescription.type,pc_id:this.pcId,request_data:{session_id:_.sessionId,token:_.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(S(h))}catch(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(S(y))}else throw _}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,E.signalingState==="closed")return;await E.setRemoteDescription(new RTCSessionDescription({sdp:m.sdp,type:m.type}))}catch(u){this.handleConnectionFailure(u)}}disconnect(){this.manuallyDisconnected=!0,this.setState(r.VOICE_AGENT_STATE.DISCONNECTING),this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE)}toggleMute(){if(!this.localStream)return;const h=this.localStream.getAudioTracks()[0];if(!h)return;const u=h.enabled;this.localStream.getAudioTracks().forEach(f=>{f.enabled=!u}),this._isMuted=u,this.clearSilenceTimer(),this._userSpeaking=!1,this.setState(u?r.VOICE_AGENT_STATE.MUTED:r.VOICE_AGENT_STATE.LISTENING)}reset(){this.setState(r.VOICE_AGENT_STATE.IDLE)}destroy(){this.releaseResources(),this.emitter.removeAllListeners(),this._state=r.VOICE_AGENT_STATE.IDLE}async fetchIceServers(h){if(this.config.iceServers)return this.config.iceServers;const u=Date.now();if(this._cachedIceServers&&u-this._iceServersCachedAt<s)return this._cachedIceServers;let f;try{f=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const p=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(p.sessionId)}else throw E}if(!Array.isArray(f?.ice_servers)||f.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=f.ice_servers,this._iceServersCachedAt=Date.now(),this._cachedIceServers}setState(h){this._state=h,this.emitter.emit(r.VOICE_AGENT_EVENTS.STATE_CHANGED,h)}clearSilenceTimer(){this._silenceTimer!==null&&(clearTimeout(this._silenceTimer),this._silenceTimer=null)}handleConnectionFailure(h,u="Voice connection failed"){if(this._hasConnectionFailureNotified||this._state===r.VOICE_AGENT_STATE.DISCONNECTING||this.manuallyDisconnected)return;this._hasConnectionFailureNotified=!0,this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.ERROR);const f={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,f)}releaseResources(){this.remoteAnalyser.stop(),this.localAnalyser.stop(),this.clearSilenceTimer(),this._userSpeaking=!1,this.localStream&&(this.localStream.getTracks().forEach(h=>h.stop()),this.localStream=null),this.dataChannel&&(this.dataChannel.close(),this.dataChannel=null),this.pc&&(this.pc.onconnectionstatechange=null,this.pc.oniceconnectionstatechange=null,this.pc.ontrack=null,this.pc.onicecandidate=null,this.pc.ondatachannel=null,this.pc.close(),this.pc=null),this.pcId=null,this._isMuted=!1,this.remoteAudio&&(this.remoteAudio.srcObject=null)}startLocalAudioAnalysis(h){const u=this.config.speakingThreshold??i;this.localAnalyser.start(h,u,f=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(f?(this._userSpeaking=!0,this.clearSilenceTimer(),this._state===r.VOICE_AGENT_STATE.THINKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)):this._userSpeaking&&this._silenceTimer===null&&(this._silenceTimer=setTimeout(()=>{this._silenceTimer=null,this._userSpeaking&&this._state===r.VOICE_AGENT_STATE.LISTENING&&(this._userSpeaking=!1,this.setState(r.VOICE_AGENT_STATE.THINKING))},a)))})}handleRemoteTrack(h){this.remoteAudio||(this.remoteAudio=new Audio,this.remoteAudio.autoplay=!0);const u=h.streams[0];this.remoteAudio.srcObject=u;const f=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,f,E=>{E?(this.clearSilenceTimer(),this._userSpeaking=!1,this._state!==r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.SPEAKING)):this._state===r.VOICE_AGENT_STATE.SPEAKING&&this.setState(r.VOICE_AGENT_STATE.LISTENING)})}};return Xn.VoiceAgent=d,Xn}var ba;function jd(){if(ba)return An;ba=1,Object.defineProperty(An,"__esModule",{value:!0}),An.SynapseSDK=void 0;const e=Yi(),t=Dn(),n=Oo(),r=aa(),o=fa(),i=wr(),s=ko(),a=nt(),c=Mo(),d=Fd(),h=Do(),u=Vd();class f{constructor(p){O(this,"connection",null);O(this,"messageManager");O(this,"resourceManager");O(this,"sessionConfig",null);O(this,"config");O(this,"connectionType");O(this,"isRefreshingSession",!1);O(this,"isRecovering",!1);O(this,"forceConsumed",!1);O(this,"connectionAttempts",0);O(this,"sdkEventEmitter",new s.EventEmitter);O(this,"_voice",null);O(this,"pendingNetworkReconnect",!1);O(this,"boundOnlineHandler",null);O(this,"isReconnecting",!1);O(this,"reconnectTimer",null);O(this,"boundVisibilityHandler",null);O(this,"isSessionNotOwned",!1);this.config={...p,environment:p.environment||"production"},this.connectionType=p.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:S=>this.config.callbacks?.onTokenExchange?.(S)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const p=await this.resourceManager.refreshBearer();if(!p)return null;if(this.connectionType===e.ConnectionType.SOCKET&&this.sessionConfig?.session_id&&this.connection?.isConnected())try{this.closeConnection(),await this.initializeConnection(this.sessionConfig),this.setupEventHandlers()}catch(g){this.emitError(this.toConnectionError(g,"Failed to reset connection after auth refresh",{stage:"onRestUnauthorized"}))}return p}async startSession(p){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,p=void 0),await this.resourceManager.ensureCredentials();const g=p?.session_id?p:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:p,files:g,audio:S,tool_declined:m,tool_id:_,initial_prompts:y,tool_result:k}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{this.messageManager.sendSocketMessage({message:p,files:g,audio:S,...m&&{tool_declined:m},..._&&{tool_id:_},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(x){this.emitError(x)}break;default:const T=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(T),T}}async sendMessageFeedback(p,g,S){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:p,feedback:g,feedbackReason:S});break}}async sendSessionFeedback(p,g){if(!this.connection){const S=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(S),S}if(!this.sessionConfig?.session_id){const S=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(S),S}if(!p?.length&&!g){const S=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(S),S}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:p,npsBase5:g});break}}on(p,g){this.sdkEventEmitter.on(p,g)}off(p,g){this.sdkEventEmitter.off(p,g)}getSessionConfig(){if(!this.sessionConfig?.session_id)throw new a.SessionError("Session ID not found",{context:{stage:"getSessionConfig"},hint:"Ensure the session API returns a session ID."});return this.sessionConfig}async getPastSessions(){return await this.resourceManager.getPastSessions()}async getSessionMessages(p){return await this.resourceManager.getSessionMessages(p)}async callTool(p,g,S){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,p,g,S);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let _={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,_);break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(y),y}}async startRecording({onChunks:p,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:p,onError:g})}catch(m){throw m}break;default:const S=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(S),S}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const p=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(p),p}}async getAgentConfig(){return this.resourceManager.getAgentConfig()}isConnected(){return this.connection?.isConnected()??!1}clearTokens(){this.resourceManager.clearTokens()}get voice(){return this._voice||(this._voice=new u.VoiceAgent(this.buildVoiceConfig(),this.resourceManager,async()=>(await this.resourceManager.exchangeInit(),{sessionId:(await this.resourceManager.createSession()).session_id,sessionToken:this.resourceManager.getSessToken()||""}))),this._voice}endSession(){this._voice?.destroy(),this._voice=null,this.closeConnection(),this.cleanup()}buildVoiceConfig(){return{offerUrl:`${this.config.serverUrl||(0,n.getConfig)(this.config.environment).BASE_API_URL}/med-assist/voice/offer`,handleRefresh:async()=>{await this.resourceManager.refreshTokens()}}}toClientError(p){if(p instanceof a.APIError){const g=p.reason??(p.status===401||p.status===403?c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:p.error?.msg||p.message,error:p.error,code:p.code,...g&&{reason:g},status:p.status,context:p.context}}return p instanceof a.SynapseError?{message:p.displayMessage||p.message,code:p.code,...p.reason&&{reason:p.reason},context:p.context}:p instanceof Error?{message:p.message}:{message:"An unexpected error occurred"}}emitError(p){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(p))}toSessionError(p,g,S,m){return(0,a.normalizeError)(p,a.SessionError,g,{context:S,hint:m})}async initializeConnection(p){if(this.closeConnection(),!p.session_id||!this.resourceManager.getSessToken())throw new a.SessionError("Session ID or sess token not found",{context:{stage:"initializeConnection"},hint:"Ensure the token exchange and session API completed successfully."});this.sessionConfig=p;const g=(0,n.getConfig)(this.config?.environment),S=this.connectionType===e.ConnectionType.SOCKET,m=S?g.WEBSOCKET_URL:g.BASE_API_URL,_=this.config.serverUrl?S?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:_||m,auth:{sessionId:p.session_id,getToken:()=>this.resourceManager.getSessToken()||"",onUnauthorized:()=>this.resourceManager.refreshBearer()},agentId:this.config.agentId,userId:this.config.userId,overrides:this.config.overrides,...this.config.channel&&{channel:this.config.channel}}),this.connectionAttempts++,this.messageManager.setConnection(this.connection);const y=this.connection.emit.bind(this.connection);this.connection.emit=(k,...T)=>{y(k,...T),this.sdkEventEmitter.emit(k,...T)}}async createNewSession(){return await this.resourceManager.createSession(this.config.userId,this.config.context)}setupEventHandlers(){if(!this.connection)return;this.connection.onOpen(()=>{switch(this.connectionType){case e.ConnectionType.SOCKET:this.onSocketConnectionOpen();break;case e.ConnectionType.HTTP_STREAM:this.messageManager.handleConnectionEstablished();break}}),this.connection.onMessage(g=>{this.onIncomingSocketMessage(g)}),this.connection.onError(g=>{this.onRealtimeConnectionError(g)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_TOKEN_EXPIRED,()=>{this.handleAuthExpiry()}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_NOT_OWNED,()=>{this.handleRecovery(d.RECOVERY_OUTCOME.SESSION_NOT_OWNED)}),this.connection.on(i.SYNAPSE_REALTIME_RESERVED_EVENTS.SESSION_INACTIVE,()=>{this.handleSessionInactiveMessage()});const p=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==p||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const S=(0,d.outcomeForCloseCode)(g.code);if(S){await this.handleRecovery(S,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(p){if(p instanceof a.APIError){const S=(0,d.outcomeForHttpStatus)(p.status);if(S){this.handleRecovery(S,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:p.message,code:p.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,p);const g=p instanceof a.APIError?p:this.toConnectionError(p,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const p=this.resourceManager.getSessToken();if(!p){const g=new a.SessionError("Sess token not set. Call startSession() first.",{context:{stage:"onSocketConnectionOpen"},hint:"Ensure startSession() completes successfully before socket opens."});throw this.emitError(g),g}this.messageManager.sendSocketAuthMessage(p)}onIncomingSocketMessage(p){switch(p.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(p);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(p);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(p);break;case h.SOCKET_EVENTS.PING:this.messageManager.sendSocketPongMessage();break;case h.SOCKET_EVENTS.PONG:this.messageManager.sendSocketPingMessage();break;case h.SOCKET_EVENTS.SYNC:break;case h.SOCKET_EVENTS.ERROR:this.messageManager.handleIncomingSocketErrorMessage(p);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:p.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const p=this.resourceManager.getLevel();return p?p==="user":!!this.config.authToken}statusOf(p){if(p instanceof a.APIError)return p.status;if(p instanceof a.SynapseError&&typeof p.context?.status=="number")return p.context.status}emitRecoveryError(p,g,S){this.emitError(new a.SessionError(g,{reason:p,cause:S,context:{stage:"connectionRecovery",reason:p}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(p,g){if(p===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(p){case d.RECOVERY_OUTCOME.REFRESH_AND_RETRY:await this.recoverExpiredCredentials();break;case d.RECOVERY_OUTCOME.SESSION_GONE:if(this.isSessionNotOwned){this.isSessionNotOwned=!1;break}await this.recoverMissingSession();break;case d.RECOVERY_OUTCOME.FORBIDDEN:this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected");break;case d.RECOVERY_OUTCOME.SESSION_NOT_OWNED:this.isSessionNotOwned=!0,this.sessionConfig=null;break}}finally{this.isRecovering=!1}}}async recoverExpiredCredentials(){try{this.closeConnection(),await this.resourceManager.refreshTokens(),await this.reconnectCurrentSession()}catch(p){const g=this.statusOf(p);if(g!==403&&g!==401){this.emitError(this.toSessionError(p,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",p)}}async recoverMissingSession(){const p=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!p){this.closeConnection(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(p);await this.connectTo(g);return}catch(g){const S=this.statusOf(g);if(S===401||S===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);return}try{await this.connectTo(await this.createNewSession())}catch(m){const _=this.statusOf(m);if(_===401||_===403){this.clearUser(),this.emitRecoveryError(c.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",m);return}this.emitError(this.toSessionError(m,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(p){await this.initializeConnection(p),this.setupEventHandlers()}async handleAuthExpiry(){if(!(this.isRefreshingSession||this.isRecovering)){this.isRefreshingSession=!0,this.isRecovering=!0;try{await this.recoverExpiredCredentials()}finally{this.isRefreshingSession=!1,this.isRecovering=!1}}}async handleSessionInactiveMessage(){if(!this.isRecovering){this.isRecovering=!0;try{await this.recoverMissingSession()}finally{this.isRecovering=!1}}}toConnectionError(p,g,S,m){return(0,a.normalizeError)(p,a.ConnectionError,g,{context:S,hint:m})}scheduleReconnect(p){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(p);return}const g=Math.min(1e3*Math.pow(2,this.connectionAttempts),16e3);this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout(async()=>{if(this.reconnectTimer=null,!!this.sessionConfig?.session_id&&!(typeof navigator<"u"&&!navigator.onLine)){this.isReconnecting=!0;try{await this.startSession({session_id:this.sessionConfig.session_id}),this.isReconnecting=!1,this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1}catch{this.isReconnecting=!1,this.connectionAttempts>=5&&this.messageManager.handleDisconnect(p)}}},g)}registerVisibilityReconnect(){this.boundVisibilityHandler||typeof document>"u"||(this.boundVisibilityHandler=()=>{document.visibilityState==="visible"&&(this.connection?.isConnected()||!this.sessionConfig?.session_id||(this.connectionAttempts=0,this.isReconnecting=!1,this.scheduleReconnect({reason:t.DisconnectionReason.NETWORK_ERROR,message:"Reconnecting after wake",code:1006,timestamp:new Date})))},document.addEventListener("visibilitychange",this.boundVisibilityHandler))}removeVisibilityReconnectListener(){this.boundVisibilityHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.boundVisibilityHandler),this.boundVisibilityHandler=null)}registerNetworkReconnect(){this.pendingNetworkReconnect||(this.pendingNetworkReconnect=!0,this.boundOnlineHandler=async()=>{if(this.removeNetworkReconnectListener(),this.pendingNetworkReconnect=!1,this.sessionConfig?.session_id){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.connectionAttempts=0,this.isReconnecting=!1;try{await this.startSession({session_id:this.sessionConfig.session_id})}catch{this.registerNetworkReconnect()}}},typeof window<"u"&&window.addEventListener("online",this.boundOnlineHandler))}removeNetworkReconnectListener(){this.boundOnlineHandler&&typeof window<"u"&&(window.removeEventListener("online",this.boundOnlineHandler),this.boundOnlineHandler=null)}closeConnection(){this.connection&&(this.connection.close(),this.connection=null)}cleanup(){this.connectionAttempts=0,this.isReconnecting=!1,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.pendingNetworkReconnect=!1,this.removeNetworkReconnectListener(),this.removeVisibilityReconnectListener(),this.sdkEventEmitter?.removeAllListeners?.(),this.messageManager?.cleanupMessageServerState?.()}}return An.SynapseSDK=f,An}var wa={},Na;function zd(){return Na||(Na=1,Object.defineProperty(wa,"__esModule",{value:!0})),wa}var Nr={},xa;function Yd(){return xa||(xa=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.USER_FEEDBACK=void 0,Nr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Nr}var Ca={},Ta;function $d(){return Ta||(Ta=1,Object.defineProperty(Ca,"__esModule",{value:!0})),Ca}var Zn={},ka;function Hd(){if(ka)return Zn;ka=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.ToolCall=void 0;const e=Yn();let t=class extends e.BaseResource{constructor(){super(...arguments);O(this,"basePath","/med-assist/api-call-tool")}async callTool(r,o,i){return this.post(`${this.basePath}?session_id=${r}&tool_name=${o}`,{tool_params:i})}};return Zn.ToolCall=t,Zn}var Be={},Ra;function Bd(){if(Ra)return Be;Ra=1,Object.defineProperty(Be,"__esModule",{value:!0}),Be.SYNAPSE_EICITATION_STATUS=Be.SYNAPSE_CTA_ACTIONS=Be.SYNAPSE_TOOL_FORMATS=Be.SYNAPSE_TOOL_CALLBACK_NAME=Be.SYNAPSE_COMPONENTS=Be.SYNAPSE_TOOL_NAME=void 0;var e;(function(s){s.MOBILE_VERIFICATION="mobile_verification",s.AVAILABILITY_DATES="availability_dates",s.AVAILABILITY_SLOTS="availability_slots",s.DOCTOR_AVAILABILITY="doctor_availability",s.DOCTOR_DETAILS="doctor_details",s.GET_LOCATION="get_location"})(e||(Be.SYNAPSE_TOOL_NAME=e={}));var t;(function(s){s.MOBILE="mobile_number",s.OTP="otp",s.EMAIL="email_address",s.PILL="pills",s.MULTI="multi",s.DOCTOR_CARD="doctor_card",s.CARD="card",s.MEDIA_CARD="media_card"})(t||(Be.SYNAPSE_COMPONENTS=t={}));var n;(function(s){s.DOCTOR_AVAILABILITY="get_doctor_availability",s.AVAILABILITY_DATES="get_available_dates",s.AVAILABILITY_SLOTS="get_available_slots",s.MOBILE_VERIFICATION="verify_mobile_number",s.DOCTOR_DETAILS="get_doctor_details"})(n||(Be.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Be.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Be.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Be.SYNAPSE_EICITATION_STATUS=i={})),Be}var Oa={},Aa;function Gd(){return Aa||(Aa=1,Object.defineProperty(Oa,"__esModule",{value:!0})),Oa}var Ia={},Ma;function Wd(){return Ma||(Ma=1,Object.defineProperty(Ia,"__esModule",{value:!0})),Ia}var Qn={},Pa;function Kd(){if(Pa)return Qn;Pa=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(Qn.SYNAPSE_CONVERSATION=e={})),Qn}var mn={},Da;function qd(){return Da||(Da=1,(function(e){var t=mn&&mn.__createBinding||(Object.create?(function(r,o,i,s){s===void 0&&(s=i);var a=Object.getOwnPropertyDescriptor(o,i);(!a||("get"in a?!o.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return o[i]}}),Object.defineProperty(r,s,a)}):(function(r,o,i,s){s===void 0&&(s=i),r[s]=o[i]})),n=mn&&mn.__exportStar||function(r,o){for(var i in r)i!=="default"&&!Object.prototype.hasOwnProperty.call(o,i)&&t(o,r,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(Sa(),e)})(mn)),mn}var La;function Xd(){return La||(La=1,(function(e){var t=cn&&cn.__createBinding||(Object.create?(function(x,N,v,b){b===void 0&&(b=v);var R=Object.getOwnPropertyDescriptor(N,v);(!R||("get"in R?!N.__esModule:R.writable||R.configurable))&&(R={enumerable:!0,get:function(){return N[v]}}),Object.defineProperty(x,b,R)}):(function(x,N,v,b){b===void 0&&(b=v),x[b]=N[v]})),n=cn&&cn.__exportStar||function(x,N){for(var v in x)v!=="default"&&!Object.prototype.hasOwnProperty.call(N,v)&&t(N,x,v)};Object.defineProperty(e,"__esModule",{value:!0}),e.SYNAPSE_MESSAGE_TYPES=e.DEFAULT_CHANNEL=e.SYNAPSE_CHANNELS=e.ErrorUtils=e.SYNAPSE_RECOVERY_REASON=e.ErrorType=e.SynapseErrorCode=e.InternalServerError=e.RateLimitError=e.MethodNotAllowedError=e.NotFoundError=e.PermissionDeniedError=e.UnauthorizedError=e.BadRequestError=e.APIConnectionTimeoutError=e.APIUserAbortError=e.APIError=e.SynapseError=e.HttpClient=e.MessageManager=e.ToolCall=e.prefetchAgentConfig=e.Config=e.prefetchTokenExchange=e.Auth=e.Session=e.ResourceManager=e.ConnectionType=e.ConnectionFactory=e.SSEConnection=e.WebSocketConnection=e.BaseConnection=e.SynapseSDK=void 0;var r=jd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Ro();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Di();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=ji();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Yi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Dn(),e);var c=aa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(zd(),e);var d=Wi();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(Yd(),e);var h=Io();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=ra();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n($d(),e);var f=Ao();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var E=Ji();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return E.prefetchAgentConfig}});var p=Hd();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return p.ToolCall}}),n(Bd(),e);var g=fa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(wr(),e),n(Gd(),e);var S=br();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return S.HttpClient}});var m=nt();Object.defineProperty(e,"SynapseError",{enumerable:!0,get:function(){return m.SynapseError}}),Object.defineProperty(e,"APIError",{enumerable:!0,get:function(){return m.APIError}}),Object.defineProperty(e,"APIUserAbortError",{enumerable:!0,get:function(){return m.APIUserAbortError}}),Object.defineProperty(e,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return m.APIConnectionTimeoutError}}),Object.defineProperty(e,"BadRequestError",{enumerable:!0,get:function(){return m.BadRequestError}}),Object.defineProperty(e,"UnauthorizedError",{enumerable:!0,get:function(){return m.UnauthorizedError}}),Object.defineProperty(e,"PermissionDeniedError",{enumerable:!0,get:function(){return m.PermissionDeniedError}}),Object.defineProperty(e,"NotFoundError",{enumerable:!0,get:function(){return m.NotFoundError}}),Object.defineProperty(e,"MethodNotAllowedError",{enumerable:!0,get:function(){return m.MethodNotAllowedError}}),Object.defineProperty(e,"RateLimitError",{enumerable:!0,get:function(){return m.RateLimitError}}),Object.defineProperty(e,"InternalServerError",{enumerable:!0,get:function(){return m.InternalServerError}}),Object.defineProperty(e,"SynapseErrorCode",{enumerable:!0,get:function(){return m.SynapseErrorCode}});var _=Mo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return _.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return _.SYNAPSE_RECOVERY_REASON}});var y=Po();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(Wd(),e);var k=Ui();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return k.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return k.DEFAULT_CHANNEL}});var T=wr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return T.SYNAPSE_MESSAGE_TYPES}}),n(Kd(),e),n(qd(),e)})(cn)),cn}var I=Xd();function Fa(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(n=Fa(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ua(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Fa(e))&&(r&&(r+=" "),r+=t);return r}const Jd=(e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},Zd=(e,t)=>({classGroupId:e,validator:t}),Va=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),xr="-",ja=[],Qd="arbitrary..",eu=e=>{const t=nu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return tu(o);const i=o.split(xr),s=i[0]===""&&i.length>1?1:0;return za(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?Jd(a,s):s:a||ja}return n[o]||ja}}},za=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=za(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(xr):e.slice(t).join(xr),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},tu=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?Qd+r:void 0})(),nu=e=>{const{theme:t,classGroups:n}=e;return ru(n,t)},ru=(e,t)=>{const n=Va();for(const r in e){const o=e[r];Lo(o,n,r,t)}return n},Lo=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];ou(s,t,n,r)}},ou=(e,t,n,r)=>{if(typeof e=="string"){su(e,t,n);return}if(typeof e=="function"){iu(e,t,n,r);return}au(e,t,n,r)},su=(e,t,n)=>{const r=e===""?t:Ya(t,e);r.classGroupId=n},iu=(e,t,n,r)=>{if(lu(e)){Lo(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Zd(n,e))},au=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];Lo(c,Ya(t,a),n,r)}},Ya=(e,t)=>{let n=e;const r=t.split(xr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Va(),n.nextPart.set(s,a)),n=a}return n},lu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,cu=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const o=(i,s)=>{n[i]=s,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(i){let s=n[i];if(s!==void 0)return s;if((s=r[i])!==void 0)return o(i,s),s},set(i,s){i in n?n[i]=s:o(i,s)}}},Fo="!",$a=":",du=[],Ha=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),uu=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,c=0,d;const h=o.length;for(let g=0;g<h;g++){const S=o[g];if(s===0&&a===0){if(S===$a){i.push(o.slice(c,g)),c=g+1;continue}if(S==="/"){d=g;continue}}S==="["?s++:S==="]"?s--:S==="("?a++:S===")"&&a--}const u=i.length===0?o:o.slice(c);let f=u,E=!1;u.endsWith(Fo)?(f=u.slice(0,-1),E=!0):u.startsWith(Fo)&&(f=u.slice(1),E=!0);const p=d&&d>c?d-c:void 0;return Ha(i,E,f,p)};if(t){const o=t+$a,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Ha(du,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},hu=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((n,r)=>{t.set(n,1e6+r)}),n=>{const r=[];let o=[];for(let i=0;i<n.length;i++){const s=n[i],a=s[0]==="[",c=t.has(s);a||c?(o.length>0&&(o.sort(),r.push(...o),o=[]),r.push(s)):o.push(s)}return o.length>0&&(o.sort(),r.push(...o)),r}},mu=e=>({cache:cu(e.cacheSize),parseClassName:uu(e),sortModifiers:hu(e),...eu(e)}),pu=/\s+/,fu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(pu);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:f,hasImportantModifier:E,baseClassName:p,maybePostfixModifierPosition:g}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let S=!!g,m=r(S?p.substring(0,g):p);if(!m){if(!S){c=h+(c.length>0?" "+c:c);continue}if(m=r(p),!m){c=h+(c.length>0?" "+c:c);continue}S=!1}const _=f.length===0?"":f.length===1?f[0]:i(f).join(":"),y=E?_+Fo:_,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const T=o(m,S);for(let x=0;x<T.length;++x){const N=T[x];s.push(y+N)}c=h+(c.length>0?" "+c:c)}return c},gu=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ba(n))&&(o&&(o+=" "),o+=r);return o},Ba=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ba(e[r]))&&(n&&(n+=" "),n+=t);return n},_u=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=mu(d),r=n.cache.get,o=n.cache.set,i=a,a(c)},a=c=>{const d=r(c);if(d)return d;const h=fu(c,n);return o(c,h),h};return i=s,(...c)=>i(gu(...c))},Eu=[],Me=e=>{const t=n=>n[e]||Eu;return t.isThemeGetter=!0,t},Ga=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Wa=/^\((?:(\w[\w-]*):)?(.+)\)$/i,yu=/^\d+\/\d+$/,Su=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,vu=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,bu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,wu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Nu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,pn=e=>yu.test(e),te=e=>!!e&&!Number.isNaN(Number(e)),jt=e=>!!e&&Number.isInteger(Number(e)),Uo=e=>e.endsWith("%")&&te(e.slice(0,-1)),Tt=e=>Su.test(e),xu=()=>!0,Cu=e=>vu.test(e)&&!bu.test(e),Ka=()=>!1,Tu=e=>wu.test(e),ku=e=>Nu.test(e),Ru=e=>!j(e)&&!z(e),Ou=e=>fn(e,Qa,Ka),j=e=>Ga.test(e),Wt=e=>fn(e,el,Cu),Vo=e=>fn(e,Du,te),qa=e=>fn(e,Ja,Ka),Au=e=>fn(e,Za,ku),Cr=e=>fn(e,tl,Tu),z=e=>Wa.test(e),er=e=>gn(e,el),Iu=e=>gn(e,Lu),Xa=e=>gn(e,Ja),Mu=e=>gn(e,Qa),Pu=e=>gn(e,Za),Tr=e=>gn(e,tl,!0),fn=(e,t,n)=>{const r=Ga.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},gn=(e,t,n=!1)=>{const r=Wa.exec(e);return r?r[1]?t(r[1]):n:!1},Ja=e=>e==="position"||e==="percentage",Za=e=>e==="image"||e==="url",Qa=e=>e==="length"||e==="size"||e==="bg-size",el=e=>e==="length",Du=e=>e==="number",Lu=e=>e==="family-name",tl=e=>e==="shadow",Fu=()=>{const e=Me("color"),t=Me("font"),n=Me("text"),r=Me("font-weight"),o=Me("tracking"),i=Me("leading"),s=Me("breakpoint"),a=Me("container"),c=Me("spacing"),d=Me("radius"),h=Me("shadow"),u=Me("inset-shadow"),f=Me("text-shadow"),E=Me("drop-shadow"),p=Me("blur"),g=Me("perspective"),S=Me("aspect"),m=Me("ease"),_=Me("animate"),y=()=>["auto","avoid","all","avoid-page","page","left","right","column"],k=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],T=()=>[...k(),z,j],x=()=>["auto","hidden","clip","visible","scroll"],N=()=>["auto","contain","none"],v=()=>[z,j,c],b=()=>[pn,"full","auto",...v()],R=()=>[jt,"none","subgrid",z,j],A=()=>["auto",{span:["full",jt,z,j]},jt,z,j],$=()=>[jt,"auto",z,j],J=()=>["auto","min","max","fr",z,j],oe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],_e=()=>["start","end","center","stretch","center-safe","end-safe"],ie=()=>["auto",...v()],he=()=>[pn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],U=()=>[e,z,j],Te=()=>[...k(),Xa,qa,{position:[z,j]}],de=()=>["no-repeat",{repeat:["","x","y","space","round"]}],V=()=>["auto","cover","contain",Mu,Ou,{size:[z,j]}],H=()=>[Uo,er,Wt],D=()=>["","none","full",d,z,j],B=()=>["",te,er,Wt],Ee=()=>["solid","dashed","dotted","double"],Ne=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],se=()=>[te,Uo,Xa,qa],ne=()=>["","none",p,z,j],$e=()=>["none",te,z,j],Ge=()=>["none",te,z,j],We=()=>[te,z,j],Je=()=>[pn,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Tt],breakpoint:[Tt],color:[xu],container:[Tt],"drop-shadow":[Tt],ease:["in","out","in-out"],font:[Ru],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Tt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Tt],shadow:[Tt],spacing:["px",te],text:[Tt],"text-shadow":[Tt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",pn,j,z,S]}],container:["container"],columns:[{columns:[te,j,z,a]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:T()}],overflow:[{overflow:x()}],"overflow-x":[{"overflow-x":x()}],"overflow-y":[{"overflow-y":x()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:b()}],"inset-x":[{"inset-x":b()}],"inset-y":[{"inset-y":b()}],start:[{start:b()}],end:[{end:b()}],top:[{top:b()}],right:[{right:b()}],bottom:[{bottom:b()}],left:[{left:b()}],visibility:["visible","invisible","collapse"],z:[{z:[jt,"auto",z,j]}],basis:[{basis:[pn,"full","auto",a,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[te,pn,"auto","initial","none",j]}],grow:[{grow:["",te,z,j]}],shrink:[{shrink:["",te,z,j]}],order:[{order:[jt,"first","last","none",z,j]}],"grid-cols":[{"grid-cols":R()}],"col-start-end":[{col:A()}],"col-start":[{"col-start":$()}],"col-end":[{"col-end":$()}],"grid-rows":[{"grid-rows":R()}],"row-start-end":[{row:A()}],"row-start":[{"row-start":$()}],"row-end":[{"row-end":$()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":J()}],"auto-rows":[{"auto-rows":J()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:[...oe(),"normal"]}],"justify-items":[{"justify-items":[..._e(),"normal"]}],"justify-self":[{"justify-self":["auto",..._e()]}],"align-content":[{content:["normal",...oe()]}],"align-items":[{items:[..._e(),{baseline:["","last"]}]}],"align-self":[{self:["auto",..._e(),{baseline:["","last"]}]}],"place-content":[{"place-content":oe()}],"place-items":[{"place-items":[..._e(),"baseline"]}],"place-self":[{"place-self":["auto",..._e()]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:ie()}],mx:[{mx:ie()}],my:[{my:ie()}],ms:[{ms:ie()}],me:[{me:ie()}],mt:[{mt:ie()}],mr:[{mr:ie()}],mb:[{mb:ie()}],ml:[{ml:ie()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:he()}],w:[{w:[a,"screen",...he()]}],"min-w":[{"min-w":[a,"screen","none",...he()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...he()]}],h:[{h:["screen","lh",...he()]}],"min-h":[{"min-h":["screen","lh","none",...he()]}],"max-h":[{"max-h":["screen","lh",...he()]}],"font-size":[{text:["base",n,er,Wt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,z,Vo]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Uo,j]}],"font-family":[{font:[Iu,j,t]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,z,j]}],"line-clamp":[{"line-clamp":[te,"none",z,Vo]}],leading:[{leading:[i,...v()]}],"list-image":[{"list-image":["none",z,j]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",z,j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:U()}],"text-color":[{text:U()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Ee(),"wavy"]}],"text-decoration-thickness":[{decoration:[te,"from-font","auto",z,Wt]}],"text-decoration-color":[{decoration:U()}],"underline-offset":[{"underline-offset":[te,"auto",z,j]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",z,j]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",z,j]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:Te()}],"bg-repeat":[{bg:de()}],"bg-size":[{bg:V()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},jt,z,j],radial:["",z,j],conic:[jt,z,j]},Pu,Au]}],"bg-color":[{bg:U()}],"gradient-from-pos":[{from:H()}],"gradient-via-pos":[{via:H()}],"gradient-to-pos":[{to:H()}],"gradient-from":[{from:U()}],"gradient-via":[{via:U()}],"gradient-to":[{to:U()}],rounded:[{rounded:D()}],"rounded-s":[{"rounded-s":D()}],"rounded-e":[{"rounded-e":D()}],"rounded-t":[{"rounded-t":D()}],"rounded-r":[{"rounded-r":D()}],"rounded-b":[{"rounded-b":D()}],"rounded-l":[{"rounded-l":D()}],"rounded-ss":[{"rounded-ss":D()}],"rounded-se":[{"rounded-se":D()}],"rounded-ee":[{"rounded-ee":D()}],"rounded-es":[{"rounded-es":D()}],"rounded-tl":[{"rounded-tl":D()}],"rounded-tr":[{"rounded-tr":D()}],"rounded-br":[{"rounded-br":D()}],"rounded-bl":[{"rounded-bl":D()}],"border-w":[{border:B()}],"border-w-x":[{"border-x":B()}],"border-w-y":[{"border-y":B()}],"border-w-s":[{"border-s":B()}],"border-w-e":[{"border-e":B()}],"border-w-t":[{"border-t":B()}],"border-w-r":[{"border-r":B()}],"border-w-b":[{"border-b":B()}],"border-w-l":[{"border-l":B()}],"divide-x":[{"divide-x":B()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":B()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Ee(),"hidden","none"]}],"divide-style":[{divide:[...Ee(),"hidden","none"]}],"border-color":[{border:U()}],"border-color-x":[{"border-x":U()}],"border-color-y":[{"border-y":U()}],"border-color-s":[{"border-s":U()}],"border-color-e":[{"border-e":U()}],"border-color-t":[{"border-t":U()}],"border-color-r":[{"border-r":U()}],"border-color-b":[{"border-b":U()}],"border-color-l":[{"border-l":U()}],"divide-color":[{divide:U()}],"outline-style":[{outline:[...Ee(),"none","hidden"]}],"outline-offset":[{"outline-offset":[te,z,j]}],"outline-w":[{outline:["",te,er,Wt]}],"outline-color":[{outline:U()}],shadow:[{shadow:["","none",h,Tr,Cr]}],"shadow-color":[{shadow:U()}],"inset-shadow":[{"inset-shadow":["none",u,Tr,Cr]}],"inset-shadow-color":[{"inset-shadow":U()}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:U()}],"ring-offset-w":[{"ring-offset":[te,Wt]}],"ring-offset-color":[{"ring-offset":U()}],"inset-ring-w":[{"inset-ring":B()}],"inset-ring-color":[{"inset-ring":U()}],"text-shadow":[{"text-shadow":["none",f,Tr,Cr]}],"text-shadow-color":[{"text-shadow":U()}],opacity:[{opacity:[te,z,j]}],"mix-blend":[{"mix-blend":[...Ne(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ne()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[te]}],"mask-image-linear-from-pos":[{"mask-linear-from":se()}],"mask-image-linear-to-pos":[{"mask-linear-to":se()}],"mask-image-linear-from-color":[{"mask-linear-from":U()}],"mask-image-linear-to-color":[{"mask-linear-to":U()}],"mask-image-t-from-pos":[{"mask-t-from":se()}],"mask-image-t-to-pos":[{"mask-t-to":se()}],"mask-image-t-from-color":[{"mask-t-from":U()}],"mask-image-t-to-color":[{"mask-t-to":U()}],"mask-image-r-from-pos":[{"mask-r-from":se()}],"mask-image-r-to-pos":[{"mask-r-to":se()}],"mask-image-r-from-color":[{"mask-r-from":U()}],"mask-image-r-to-color":[{"mask-r-to":U()}],"mask-image-b-from-pos":[{"mask-b-from":se()}],"mask-image-b-to-pos":[{"mask-b-to":se()}],"mask-image-b-from-color":[{"mask-b-from":U()}],"mask-image-b-to-color":[{"mask-b-to":U()}],"mask-image-l-from-pos":[{"mask-l-from":se()}],"mask-image-l-to-pos":[{"mask-l-to":se()}],"mask-image-l-from-color":[{"mask-l-from":U()}],"mask-image-l-to-color":[{"mask-l-to":U()}],"mask-image-x-from-pos":[{"mask-x-from":se()}],"mask-image-x-to-pos":[{"mask-x-to":se()}],"mask-image-x-from-color":[{"mask-x-from":U()}],"mask-image-x-to-color":[{"mask-x-to":U()}],"mask-image-y-from-pos":[{"mask-y-from":se()}],"mask-image-y-to-pos":[{"mask-y-to":se()}],"mask-image-y-from-color":[{"mask-y-from":U()}],"mask-image-y-to-color":[{"mask-y-to":U()}],"mask-image-radial":[{"mask-radial":[z,j]}],"mask-image-radial-from-pos":[{"mask-radial-from":se()}],"mask-image-radial-to-pos":[{"mask-radial-to":se()}],"mask-image-radial-from-color":[{"mask-radial-from":U()}],"mask-image-radial-to-color":[{"mask-radial-to":U()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":k()}],"mask-image-conic-pos":[{"mask-conic":[te]}],"mask-image-conic-from-pos":[{"mask-conic-from":se()}],"mask-image-conic-to-pos":[{"mask-conic-to":se()}],"mask-image-conic-from-color":[{"mask-conic-from":U()}],"mask-image-conic-to-color":[{"mask-conic-to":U()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:Te()}],"mask-repeat":[{mask:de()}],"mask-size":[{mask:V()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",z,j]}],filter:[{filter:["","none",z,j]}],blur:[{blur:ne()}],brightness:[{brightness:[te,z,j]}],contrast:[{contrast:[te,z,j]}],"drop-shadow":[{"drop-shadow":["","none",E,Tr,Cr]}],"drop-shadow-color":[{"drop-shadow":U()}],grayscale:[{grayscale:["",te,z,j]}],"hue-rotate":[{"hue-rotate":[te,z,j]}],invert:[{invert:["",te,z,j]}],saturate:[{saturate:[te,z,j]}],sepia:[{sepia:["",te,z,j]}],"backdrop-filter":[{"backdrop-filter":["","none",z,j]}],"backdrop-blur":[{"backdrop-blur":ne()}],"backdrop-brightness":[{"backdrop-brightness":[te,z,j]}],"backdrop-contrast":[{"backdrop-contrast":[te,z,j]}],"backdrop-grayscale":[{"backdrop-grayscale":["",te,z,j]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[te,z,j]}],"backdrop-invert":[{"backdrop-invert":["",te,z,j]}],"backdrop-opacity":[{"backdrop-opacity":[te,z,j]}],"backdrop-saturate":[{"backdrop-saturate":[te,z,j]}],"backdrop-sepia":[{"backdrop-sepia":["",te,z,j]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",z,j]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[te,"initial",z,j]}],ease:[{ease:["linear","initial",m,z,j]}],delay:[{delay:[te,z,j]}],animate:[{animate:["none",_,z,j]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,z,j]}],"perspective-origin":[{"perspective-origin":T()}],rotate:[{rotate:$e()}],"rotate-x":[{"rotate-x":$e()}],"rotate-y":[{"rotate-y":$e()}],"rotate-z":[{"rotate-z":$e()}],scale:[{scale:Ge()}],"scale-x":[{"scale-x":Ge()}],"scale-y":[{"scale-y":Ge()}],"scale-z":[{"scale-z":Ge()}],"scale-3d":["scale-3d"],skew:[{skew:We()}],"skew-x":[{"skew-x":We()}],"skew-y":[{"skew-y":We()}],transform:[{transform:[z,j,"","none","gpu","cpu"]}],"transform-origin":[{origin:T()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Je()}],"translate-x":[{"translate-x":Je()}],"translate-y":[{"translate-y":Je()}],"translate-z":[{"translate-z":Je()}],"translate-none":["translate-none"],accent:[{accent:U()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:U()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",z,j]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",z,j]}],fill:[{fill:["none",...U()]}],"stroke-w":[{stroke:[te,er,Wt,Vo]}],stroke:[{stroke:["none",...U()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},Uu=_u(Fu);function M(...e){return Uu(Ua(e))}function Kt(e){if(!e&&e!==0)return"";const t=e instanceof Date?e:new Date(typeof e=="number"?e:Number(e)||e);return Number.isNaN(t.getTime())?"":t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}const Vu=e=>{switch(e){case I.SYNAPSE_COMPONENTS.DOCTOR_CARD:case I.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},ju=e=>new Promise(t=>setTimeout(t,e)),nl=Q(({className:e,children:t,...n},r)=>l(Ti,{ref:r,className:M("relative overflow-hidden",e),...n,children:[l(Od,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(rl,{}),l(Ad,{})]}));nl.displayName=Ti.displayName;const rl=Q(({className:e,orientation:t="vertical",...n},r)=>l(xo,{ref:r,orientation:t,className:M("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:l(vi,{className:"relative flex-1 rounded-full bg-border"})}));rl.displayName=xo.displayName;var zu=Symbol.for("react.lazy"),kr=bo[" use ".trim().toString()];function Yu(e){return typeof e=="object"&&e!==null&&"then"in e}function ol(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===zu&&"_payload"in e&&Yu(e._payload)}function sl(e){const t=Hu(e),n=Q((r,o)=>{let{children:i,...s}=r;ol(i)&&typeof kr=="function"&&(i=kr(i._payload));const a=et.toArray(i),c=a.find(Gu);if(c){const d=c.props.children,h=a.map(u=>u===c?et.count(d)>1?et.only(null):tt(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:tt(d)?Lt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var $u=sl("Slot");function Hu(e){const t=Q((n,r)=>{let{children:o,...i}=n;if(ol(o)&&typeof kr=="function"&&(o=kr(o._payload)),tt(o)){const s=Ku(o),a=Wu(i,o.props);return o.type!==ue&&(a.ref=r?wo(r,s):s),Lt(o,a)}return et.count(o)>1?et.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Bu=Symbol("radix.slottable");function Gu(e){return tt(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Bu}function Wu(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...s)=>{const a=i(...s);return o(...s),a}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}function Ku(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}const il=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,al=Ua,qu=(e,t)=>n=>{var r;if(t?.variants==null)return al(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n?.[d],u=i?.[d];if(h===null)return null;const f=il(h)||il(u);return o[d][f]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,f]=h;return f===void 0||(d[u]=f),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:f,...E}=h;return Object.entries(E).every(p=>{let[g,S]=p;return Array.isArray(S)?S.includes({...i,...a}[g]):{...i,...a}[g]===S})?[...d,u,f]:d},[]);return al(e,s,c,n?.class,n?.className)},Xu=qu("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),ce=Q(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?$u:"button",{className:M(Xu({variant:t,size:n,className:e})),ref:i,...o}));ce.displayName="Button";const Ju=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Zu=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),ll=e=>{const t=Zu(e);return t.charAt(0).toUpperCase()+t.slice(1)},cl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Qu=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var eh={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const th=Q(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>qe("svg",{ref:c,...eh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:cl("lucide",o),...!i&&!Qu(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>qe(d,h)),...Array.isArray(i)?i:[i]])),Fe=(e,t)=>{const n=Q(({className:r,...o},i)=>qe(th,{ref:i,iconNode:t,className:cl(`lucide-${Ju(ll(e))}`,`lucide-${e}`,r),...o}));return n.displayName=ll(e),n},nh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],jo=Fe("chevron-down",nh),rh=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],oh=Fe("ellipsis-vertical",rh),sh=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],dl=Fe("file-text",sh),ih=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],ul=Fe("info",ih),ah=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],lh=Fe("maximize-2",ah),ch=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],dh=Fe("menu",ch),uh=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],tr=Fe("message-square-plus",uh),hh=[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]],zo=Fe("mic",hh),mh=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],ph=Fe("minimize-2",mh),fh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],hl=Fe("plus",fh),gh=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],_h=Fe("rotate-ccw",gh),Eh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ml=Fe("square",Eh),yh=[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]],Rr=Fe("thumbs-up",yh),Sh=[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]],Or=Fe("thumbs-down",Sh),vh=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],bh=Fe("triangle-alert",vh),wh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],_n=Fe("x",wh),Nh=[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]],xh=Fe("zoom-in",Nh),pl=e=>{let t;const n=new Set,r=(a,c)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=c??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(u=>u(t,h))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>s,subscribe:a=>(n.add(a),()=>n.delete(a))},s=t=e(r,o,i);return i},Ch=(e=>e?pl(e):pl),Th=e=>e;function kh(e,t=Th){const n=On.useSyncExternalStore(e.subscribe,On.useCallback(()=>t(e.getState()),[e,t]),On.useCallback(()=>t(e.getInitialState()),[e,t]));return On.useDebugValue(n),n}const Rh=e=>{const t=Ch(e),n=r=>kh(t,r);return Object.assign(n,t),n},Oh=(e=>Rh);function fl(e,t){let n;try{n=e()}catch{return}return{getItem:r=>{var o;const i=a=>a===null?null:JSON.parse(a,void 0),s=(o=n.getItem(r))!=null?o:null;return s instanceof Promise?s.then(i):i(s)},setItem:(r,o)=>n.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>n.removeItem(r)}}const Yo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Yo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Yo(r)(n)}}}},Ah=(e,t)=>(n,r,o)=>{let i={storage:fl(()=>localStorage),partialize:g=>g,version:0,merge:(g,S)=>({...S,...g}),...t},s=!1;const a=new Set,c=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,S)=>(u(g,S),h());const f=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>f;let E;const p=()=>{var g,S;if(!d)return;s=!1,a.forEach(_=>{var y;return _((y=r())!=null?y:f)});const m=((S=i.onRehydrateStorage)==null?void 0:S.call(i,(g=r())!=null?g:f))||void 0;return Yo(d.getItem.bind(d))(i.name).then(_=>{if(_)if(typeof _.version=="number"&&_.version!==i.version){if(i.migrate){const y=i.migrate(_.state,_.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,_.state];return[!1,void 0]}).then(_=>{var y;const[k,T]=_;if(E=i.merge(T,(y=r())!=null?y:f),n(E,!0),k)return h()}).then(()=>{m?.(E,void 0),E=r(),s=!0,c.forEach(_=>_(E))}).catch(_=>{m?.(void 0,_)})};return o.persist={setOptions:g=>{i={...i,...g},g.storage&&(d=g.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>p(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(c.add(g),()=>{c.delete(g)})},i.skipHydration||p(),E||f},Ih=Ah,Pe={USER:"user",ASSISTANT:"assistant"};var Se=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Se||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let kt="";const nr=e=>`med-assist-store-${e}`,Mh=e=>{kt=nr(e)},gl={sessionId:"",isStreaming:!1,recordingStatus:Se.IDLE,isWaitingForResponse:!1,error:null,isTimeoutError:!1,startNewConnection:!1,showRetryButton:!1,chats:{},inlineText:null,connectionStatus:ge.CONNECTING,streamingTimeoutId:null,responseTimeoutId:null,lastStreamingActivity:null,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},_l={...gl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},W=Oh()(Ih((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:ge.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:Se.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),inlineText:null,setInlineText:n=>e({inlineText:n}),isBotIconAnimating:!1,setIsBotIconAnimating:n=>e({isBotIconAnimating:n}),isMobile:!1,setIsMobile:n=>e({isMobile:n}),displayMode:"widget",setDisplayMode:n=>e({displayMode:n}),toggleDisplayMode:()=>e({displayMode:t().displayMode==="full"?"widget":"full"}),initialDisplayMode:"widget",setInitialDisplayMode:n=>e({initialDisplayMode:n}),chats:{},addMessageToSession:(n,r)=>{e(o=>({chats:{...o.chats,[n]:[...o.chats[n]||[],r]}}))},updateMessageInSession:(n,r,o)=>e(i=>({chats:{...i.chats,[n]:(i.chats[n]||[]).map(s=>s.id===r?{...s,...o}:s)}})),getMessagesForSession:n=>t().chats[n]||[],setMessagesForSession:(n,r)=>e(o=>({chats:{...o.chats,[n]:r}})),clearMessagesForSession:n=>e(r=>({chats:{...r.chats,[n]:[]}})),clearAllChats:()=>e({chats:{}}),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,isTimeoutError:!1,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),isTimeoutError:!1,setTimeoutError:n=>e({isTimeoutError:n}),clearSession:async()=>{e(gl),await sessionStorage.removeItem(kt||nr(t().agentId))},clearUser:()=>{e(_l),sessionStorage.removeItem(kt||nr(t().agentId))},streamingTimeoutId:null,setStreamingTimeoutId:n=>e({streamingTimeoutId:n}),clearStreamingTimeout:()=>{const n=t();n.streamingTimeoutId&&(clearTimeout(n.streamingTimeoutId),e({streamingTimeoutId:null}))},responseTimeoutId:null,setResponseTimeoutId:n=>e({responseTimeoutId:n}),clearResponseTimeout:()=>{const n=t();n.responseTimeoutId&&(clearTimeout(n.responseTimeoutId),e({responseTimeoutId:null}))},lastStreamingActivity:null,setLastStreamingActivity:n=>e({lastStreamingActivity:n})}),{name:"med-assist-store",storage:fl(()=>({getItem:()=>kt?sessionStorage.getItem(kt):null,setItem:(e,t)=>{kt&&sessionStorage.setItem(kt,t)},removeItem:()=>{kt&&sessionStorage.removeItem(kt)}})),partialize:e=>({agentId:e.agentId,userId:e.userId,context:e.context,chats:e.chats,sessionId:e.sessionId,refreshToken:e.refreshToken,sessToken:e.sessToken,level:e.level,initialMessage:e.initialMessage,sessionInitialMessages:e.sessionInitialMessages,connectionStatus:e.connectionStatus,elicitationState:e.elicitationState})})),Ph=e=>{const t=nr(e);let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}W.setState(_l),n&&W.setState(n)},$o=Nt(null),Dh=({children:e})=>{const[t,n]=F(null);return l($o.Provider,{value:{synapse:t,setSynapse:n},children:e})},Lh=()=>{const e=Ct($o);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Fh=()=>{const e=Ct($o);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},Uh=()=>{const[e,t]=F(I.VOICE_AGENT_STATE.IDLE),[n,r]=F(!1),o=Lh(),{setError:i}=W();Y(()=>{if(!o)return;const h=o.voice,u=E=>{t(E)},f=()=>{i({title:"Voice connection failed. Please try again."})};return h.on(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.on(I.VOICE_AGENT_EVENTS.ERROR,f),()=>{h.off(I.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(I.VOICE_AGENT_EVENTS.ERROR,f)}},[o,i]);const s=fe(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=fe(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),c=fe(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=fe(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:c,toggleMute:d}},qt=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));qt.displayName="Card";const El=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("flex flex-col space-y-1.5 p-6",e),...t}));El.displayName="CardHeader";const yl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("font-semibold leading-none tracking-tight",e),...t}));yl.displayName="CardTitle";const Vh=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("text-sm text-muted-foreground",e),...t}));Vh.displayName="CardDescription";const Sl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("p-6 pt-0",e),...t}));Sl.displayName="CardContent";const vl=Q(({className:e,...t},n)=>l("div",{ref:n,className:M("flex items-center p-6 pt-0",e),...t}));vl.displayName="CardFooter";const Ho=5,jh=10*1024*1024,Ar={width:384,height:600},Ir=20,zh=400,Yh=320,$h=560,Hh=150;function Bh({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=fe(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Ar.width-Ir,y:window.innerHeight-Ar.height-Ir},[]),[i,s]=F(()=>e??o()),[a,c]=F(!1),d=q({x:0,y:0}),h=q(null),u=q(!1);Y(()=>{t||(u.current=!1)},[t]),dt(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),Y(()=>{if(!t||typeof window>"u")return;let g=null;const S=()=>{s(_=>{const y=Math.max(0,window.innerWidth-Ar.width-Ir),k=Math.max(0,window.innerHeight-Ar.height-Ir),T=Math.max(0,Math.min(_.x,y)),x=Math.max(0,Math.min(_.y,k));return T===_.x&&x===_.y?_:{x:T,y:x}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(S,Hh)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const f=fe(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){c(!1);return}g.preventDefault(),c(!0);const S=h.current;if(S){const m=S.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),E=fe(g=>{if(!t||!a)return;const S=g.clientX-d.current.x,m=g.clientY-d.current.y,_=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(S,_)),T=Math.max(0,Math.min(m,y));s({x:k,y:T})},[a,t]),p=fe(()=>{!t||!a||(c(!1),r?.())},[a,r]);return Y(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",f),()=>{g.removeEventListener("mousedown",f)}},[t,f]),Y(()=>{if(a)return document.addEventListener("mousemove",E),document.addEventListener("mouseup",p),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""}},[a,E,p]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Bo="#6B5CE0",Gh="#F0F0F0",Mr={background:Gh,backgroundImage:void 0,primary:Bo,textColor:"black"},Wh="rgba(0, 0, 0, 0.4)",Kh="24px";function qh(e){if(e==="dark")return"white";if(e==="light")return"black"}function Xh(e){const t=e?.primary??e?.primaryColor??Mr.primary,n=e?.textColor??qh(e?.mode);return{background:e?.background??Mr.background,backgroundImage:e?.backgroundImage??Mr.backgroundImage,primary:t,primaryColor:t,textColor:n??Mr.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Jh(e){e=e.replace("#","");const t=parseInt(e.substring(0,2),16)/255,n=parseInt(e.substring(2,4),16)/255,r=parseInt(e.substring(4,6),16)/255,o=Math.max(t,n,r),i=Math.min(t,n,r);let s=0,a=0;const c=(o+i)/2;if(o!==i){const h=o-i;switch(a=c>.5?h/(2-o-i):h/(o+i),o){case t:s=((n-r)/h+(n<r?6:0))/6;break;case n:s=((r-t)/h+2)/6;break;case r:s=((t-n)/h+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(c*100);return`${s} ${a}% ${d}%`}function Zh(e){const t=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(!t)throw new Error("Invalid RGB format");const n=parseInt(t[1],10)/255,r=parseInt(t[2],10)/255,o=parseInt(t[3],10)/255,i=Math.max(n,r,o),s=Math.min(n,r,o);let a=0,c=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(c=d>.5?u/(2-i-s):u/(i+s),i){case n:a=((r-o)/u+(r<o?6:0))/6;break;case r:a=((o-n)/u+2)/6;break;case o:a=((n-r)/u+4)/6;break}}a=Math.round(a*360),c=Math.round(c*100);const h=Math.round(d*100);return`${a} ${c}% ${h}%`}function Qh(e){const t=e.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);if(!t)throw new Error("Invalid HSL format");return`${t[1]} ${t[2]}% ${t[3]}%`}function Go(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return Jh(t);if(t.startsWith("rgb"))return Zh(t);if(t.startsWith("hsl"))return Qh(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function bl(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Wo(e){return bl(e)>.5?"0 0% 9%":"0 0% 98%"}function em(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return"0 0% 96%";const n=t[1],r=Math.max(0,parseInt(t[2],10)-5);return`${n} ${r}% 96%`}function tm(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);if(!t)return{50:"262 83% 98%",100:"262 83% 96%",200:"262 83% 92%",300:"262 83% 85%",400:"262 83% 75%",500:"262 83% 58%",600:"262 83% 50%",700:"262 83% 40%",800:"262 83% 30%",900:"262 83% 20%"};const n=parseInt(t[1],10),r=parseInt(t[2],10),o=parseInt(t[3],10);return{50:`${n} ${Math.max(0,r-20)}% ${Math.min(98,o+40)}%`,100:`${n} ${Math.max(0,r-15)}% ${Math.min(96,o+35)}%`,200:`${n} ${Math.max(0,r-10)}% ${Math.min(92,o+30)}%`,300:`${n} ${Math.max(0,r-5)}% ${Math.min(85,o+20)}%`,400:`${n} ${r}% ${Math.min(75,o+10)}%`,500:`${n} ${r}% ${o}%`,600:`${n} ${Math.min(100,r+5)}% ${Math.max(50,o-10)}%`,700:`${n} ${Math.min(100,r+10)}% ${Math.max(40,o-20)}%`,800:`${n} ${Math.min(100,r+15)}% ${Math.max(30,o-30)}%`,900:`${n} ${Math.min(100,r+20)}% ${Math.max(20,o-40)}%`}}function wl(e,t){const n=t.primary??Bo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(E,p)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(E,p)};let c;try{c=Go(n)}catch{c=Go(Bo)}a("--primary",c),a("--primary-foreground",Wo(c)),a("--ring",c),a("--border-primary",c);const d=tm(c);for(const[E,p]of Object.entries(d))a(`--primary-${E}`,p);const h=Wo(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const E=i?"#191919":"#F0F0F0";try{a("--background",Go(E))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${c} / ${s?.05:.1})`)}if(i?a("--bot-message-bg","var(--black-600)"):a("--bot-message-bg","var(--white-600)"),i?a("--card","0 0% 0% / 0.6"):a("--card","0 0% 100% / 0.6"),a("--bot-message-border",em(i?"0 0% 100%":"0 0% 9%")),i?(a("--foreground","0 0% 100%"),a("--card-foreground","0 0% 100%"),a("--popover-foreground","0 0% 100%"),a("--muted-foreground","0 0% 70%"),a("--normal-text-color","var(--white-1000)")):(a("--foreground","0 0% 0%"),a("--card-foreground","0 0% 0%"),a("--popover-foreground","0 0% 0%"),a("--muted-foreground","0 0% 30%"),a("--normal-text-color","var(--black-1000)")),o?(a("--header-bg","transparent"),a("--header-stroke",i?"var(--white-200)":"var(--black-200)")):s?(a("--header-bg",`hsl(${c})`),a("--header-stroke",`hsl(${c} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${c} / 0.3)`)),o?(a("--footer-bg","transparent"),a("--footer-stroke",i?"var(--white-200)":"var(--black-200)")):(a("--footer-bg",i?"var(--black-700)":"var(--white-700)"),a("--footer-stroke",`hsl(${c} / 0.3)`)),s&&!o){const E=bl(h)>.5;a("--header-tagline",E?"var(--white-600)":"var(--black-600)")}else a("--header-tagline",i?"var(--white-600)":"var(--black-600)");a("--elicitation-bg",i?"var(--black-1000)":"var(--white-1000)"),a("--input-box-bg",i?"var(--white-100)":"var(--black-100)");const u=e instanceof ShadowRoot?e.host:e;u instanceof HTMLElement&&(u.setAttribute("data-text-color",r),u.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",c):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const f=i?"white":"black";for(const E of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${E}`,`var(--${f}-${E})`);a("--secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--surface-secondary",i?"0 0% 15%":"0 0% 96.1%"),a("--secondary-foreground",i?"0 0% 98%":"0 0% 9%"),a("--muted",i?"0 0% 15%":"0 0% 96.1%"),a("--accent",c),a("--accent-foreground",Wo(c)),o?a("--surface",i?"0 0% 0% / 0.6":"0 0% 100% / 0.6"):a("--surface",i?"0 0% 10%":"0 0% 94.1%"),a("--surface-tertiary",i?"0 0% 12%":"0 0% 98%"),a("--border-subtle",i?"0 0% 20%":"0 0% 89.8%"),a("--border-medium",i?"0 0% 30%":"0 0% 80%"),a("--text-primary",i?"0 0% 100%":"0 0% 3.9%"),a("--text-secondary",i?"0 0% 70%":"0 0% 45.1%"),a("--text-tertiary",i?"0 0% 60%":"0 0% 63.9%"),a("--text-muted",i?"0 0% 70%":"0 0% 45.1%"),a("--border",i?"0 0% 20%":"0 0% 89.8%"),a("--input",i?"0 0% 20%":"0 0% 89.8%"),o?(a("--theme-background-image",`url(${t.backgroundImage})`),a("--theme-background-blur",Kh),a("--theme-background-overlay",Wh),u instanceof HTMLElement&&u.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),u instanceof HTMLElement&&u.classList.remove("theme-with-background"))}function Xt({className:e,style:t}){return l("div",{className:M("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_ease-in-out_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e),style:t})}function Ko(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Nl(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Ko,{}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[l("div",{className:"px-2 pt-2 pb-1",children:l(Xt,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Xt,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Xt,{className:"h-9 w-9 rounded-full"}),l(Xt,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function nm(){return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(Ko,{}),[{role:"assistant",size:"h-16 w-[70%]"},{role:"user",size:"h-9 w-[45%]"},{role:"assistant",size:"h-24 w-[75%]"},{role:"user",size:"h-9 w-[35%]"},{role:"assistant",size:"h-16 w-[65%]"}].map((e,t)=>l("div",{className:M("flex",e.role==="user"?"justify-end":"justify-start"),children:l(Xt,{className:M("rounded-lg",e.size)})},t))]})}function rm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return l("div",{"aria-hidden":"true",children:[l(Ko,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Xt,{className:M("h-5 rounded-md",t[r%t.length])}),l(Xt,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function om(e,t=[]){let n=[];function r(i,s){const a=Nt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:E,...p}=u,g=f?.[e]?.[c]||a,S=ye(()=>p,Object.values(p));return l(g.Provider,{value:S,children:E})};d.displayName=i+"Provider";function h(u,f){const E=f?.[e]?.[c]||a,p=Ct(E);if(p)return p;if(s!==void 0)return s;throw new Error(`\`${u}\` must be used within \`${i}\``)}return[d,h]}const o=()=>{const i=n.map(s=>Nt(s));return function(s){const a=s?.[e]||i;return ye(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,sm(o,...t)]}function sm(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(o){const i=r.reduce((s,{useScope:a,scopeName:c})=>{const d=a(o)[`__scope${c}`];return{...s,...d}},{});return ye(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var im=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],qo=im.reduce((e,t)=>{const n=sl(`Primitive.${t}`),r=Q((o,i)=>{const{asChild:s,...a}=o,c=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l(c,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),xl={exports:{}},Xo={};const am=Id(bo);var Cl;function lm(){if(Cl)return Xo;Cl=1;var e=am;function t(u,f){return u===f&&(u!==0||1/u===1/f)||u!==u&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,f){var E=f(),p=r({inst:{value:E,getSnapshot:f}}),g=p[0].inst,S=p[1];return i(function(){g.value=E,g.getSnapshot=f,c(g)&&S({inst:g})},[u,E,f]),o(function(){return c(g)&&S({inst:g}),u(function(){c(g)&&S({inst:g})})},[u]),s(E),E}function c(u){var f=u.getSnapshot;u=u.value;try{var E=f();return!n(u,E)}catch{return!0}}function d(u,f){return f()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return Xo.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,Xo}var Tl;function cm(){return Tl||(Tl=1,xl.exports=lm()),xl.exports}var dm=cm();function um(){return dm.useSyncExternalStore(hm,()=>!0,()=>!1)}function hm(){return()=>{}}var Jo="Avatar",[mm]=om(Jo),[pm,kl]=mm(Jo),Rl=Q((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=F("idle");return l(pm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(qo.span,{...r,ref:t})})});Rl.displayName=Jo;var Ol="AvatarImage",Al=Q((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=kl(Ol,n),a=fm(r,i),c=Ut(d=>{o(d),s.onImageLoadingStatusChange(d)});return Gt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(qo.img,{...i,ref:t,src:r}):null});Al.displayName=Ol;var Il="AvatarFallback",Ml=Q((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=kl(Il,n),[s,a]=F(r===void 0);return Y(()=>{if(r!==void 0){const c=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(c)}},[r]),s&&i.imageLoadingStatus!=="loaded"?l(qo.span,{...o,ref:t}):null});Ml.displayName=Il;function Pl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function fm(e,{referrerPolicy:t,crossOrigin:n}){const r=um(),o=q(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=F(()=>Pl(i,e));return Gt(()=>{a(Pl(i,e))},[i,e]),Gt(()=>{const c=u=>()=>{a(u)};if(!i)return;const d=c("loaded"),h=c("error");return i.addEventListener("load",d),i.addEventListener("error",h),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",h)}},[i,n,t]),s}var Dl=Rl,Ll=Al,Fl=Ml;const Zo=Q(({className:e,...t},n)=>l(Dl,{ref:n,className:M("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));Zo.displayName=Dl.displayName;const Ul=Q(({className:e,...t},n)=>l(Ll,{ref:n,className:M("aspect-square h-full w-full",e),...t}));Ul.displayName=Ll.displayName;const Qo=Q(({className:e,...t},n)=>l(Fl,{ref:n,className:M("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));Qo.displayName=Fl.displayName;const Vl=Nt(!1);function gm({enabled:e,children:t}){return l(Vl.Provider,{value:e,children:t})}function _m(){return Ct(Vl)}const jl="(max-width: 768px), (pointer: coarse)",zl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Em(){if(typeof window>"u")return!1;const e=window.matchMedia?.(jl)?.matches??!1,t=zl.test(navigator?.userAgent??"");return e||t}function Yl(){const[e,t]=F(Em);return Y(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(jl),r=zl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function ym({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:c=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h,historyEnabled:u=!1}){const f=Yl(),E=_m(),p=W(A=>A.displayMode)==="side_panel",g=E&&!f&&!p,S=W(A=>A.displayMode)==="full",m=W(A=>A.initialDisplayMode)==="full",_=!S&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",y=W(A=>A.connectionStatus),k=W(A=>A.level)==="user",[T,x]=F(!1),N=q(null),v=ye(()=>a==="connected"||a==="connecting"||a==="listening"||a==="speaking"||a==="thinking",[a]),b=fe(()=>{T||(x(!0),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{N.current=null,x(!1)},6e3),s())},[T,s]);Y(()=>{y===ge.CONNECTED&&(x(!1),N.current&&clearTimeout(N.current))},[y]);const R=(()=>{switch(y){case ge.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case ge.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case ge.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return l("div",{className:"px-6 py-3",children:l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center gap-3",children:[l("div",{className:"relative flex-shrink-0",children:[l(Zo,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(Qo,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?l("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):l("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),l("div",{className:M("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",R.dotColor,y===ge.CONNECTING&&"animate-pulse")})]}),l("div",{className:"flex flex-col",children:[r?l("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):l("p",{className:M("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",_),children:n||"Health Assist"}),l("div",{className:"flex items-center gap-1.5",children:l("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:R.text})})]})]}),l("div",{className:M("flex items-center",!g&&"gap-1"),children:[!v&&(!k||!u)&&l(ce,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:b,disabled:T,className:M("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200 disabled:opacity-60 disabled:pointer-events-none",_),children:l(tr,{className:"w-5 h-5"})}),h&&k&&l(ce,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:M("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(oh,{className:"w-5 h-5"})}),g&&l(ce,{onClick:d,type:"button",variant:"ghost",size:"icon",title:S?"Exit fullscreen":"Enter fullscreen",className:M("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:S?l(ph,{className:"w-8 h-8"}):l(lh,{className:"w-8 h-8"})}),(t||!m)&&l(ce,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:M("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",_),children:l(_n,{className:"w-8 h-8"})})]})]})})}const es=Q(({className:e,...t},n)=>l("textarea",{className:M("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:n,...t}));es.displayName="Textarea";function $l({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=F(!1),[s,a]=F(""),c=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";Y(()=>{if(c){const f=URL.createObjectURL(e);return a(f),()=>URL.revokeObjectURL(f)}},[e,c]),Y(()=>{i(!1)},[e]);const h=()=>c?"text-green-600":"text-text-secondary",u=f=>{if(f===0)return"0 B";const E=1024,p=["B","KB","MB","GB"],g=Math.floor(Math.log(f)/Math.log(E));return`${(f/Math.pow(E,g)).toFixed(1)} ${p[g]}`.toLowerCase()};return!c||o?l("div",{className:`relative group inline-flex flex-shrink-0 bg-white border border-neutral-300 rounded-lg flex items-center gap-3 px-3 py-2.5 max-w-full ${n?"hover:bg-neutral-50":""} ${r}`,children:[l("div",{className:`flex-shrink-0 ${h()}`,children:l(dl,{className:"h-5 w-5"})}),l("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&l("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&l("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute -top-2 -right-2 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10",children:l(_n,{className:"h-3 w-3"})})]}):l("div",{className:`relative group flex-shrink-0 ${r}`,children:[l("div",{className:`w-20 h-20 bg-white border border-neutral-300 rounded-lg flex items-center justify-center overflow-hidden ${n?"hover:bg-neutral-100 cursor-pointer":""}`,children:s&&l("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&l("button",{onClick:t,"aria-label":`Remove ${e.name}`,className:"absolute top-0 right-0 bg-white border border-neutral-300 text-[var(--color-foreground)] rounded-full w-5 h-5 flex items-center justify-center shadow-sm hover:bg-neutral-50 transition-colors z-10 transform translate-x-1 -translate-y-1",children:l(_n,{className:"h-3 w-3"})})]})}function ts({files:e,onRemoveFile:t,isPreview:n=!0,className:r=""}){if(e.length===0)return null;const o=e.filter(s=>s.type?.startsWith("image/")),i=e.filter(s=>!s.type?.startsWith("image/"));return l("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return l($l,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&l("div",{className:"flex gap-2 overflow-x-auto max-w-full p-1 scrollbar-hide",children:o.map(s=>{const a=e.indexOf(s);return l($l,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const ns=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M1.46875 0.09375L16.3125 6.9375C16.75 7.125 17 7.53125 17 8C17 8.46875 16.75 8.875 16.3125 9.0625L1.46875 15.9062C1.3125 15.9688 1.1875 16 1.03125 16C0.46875 16 0 15.5312 0 14.9688C0 14.8125 0.03125 14.6875 0.09375 14.5625L2.34375 9.5C2.5 9.15625 2.8125 8.9375 3.15625 8.90625L8.0625 8.46875C8.3125 8.46875 8.5 8.25 8.5 8C8.5 7.75 8.3125 7.5625 8.0625 7.53125L3.15625 7.09375C2.8125 7.0625 2.5 6.84375 2.34375 6.5L0.09375 1.4375C0.03125 1.3125 0 1.1875 0 1.03125C0 0.46875 0.46875 0 1.03125 0C1.1875 0 1.3125 0.03125 1.46875 0.09375Z",fill:"currentColor"})}),Hl=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),Sm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Bl=({className:e})=>l("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:l("path",{d:"M6.875 0C7.375 0 7.75 0.40625 7.75 0.875V14.875C7.75 15.375 7.375 15.75 6.875 15.75C6.40625 15.75 6 15.375 6 14.875V0.875C6 0.40625 6.40625 0 6.875 0ZM12.875 2C13.375 2 13.75 2.40625 13.75 2.875V12.875C13.75 13.375 13.375 13.75 12.875 13.75C12.4062 13.75 12 13.375 12 12.875V2.875C12 2.40625 12.4062 2 12.875 2ZM3.875 3C4.375 3 4.75 3.40625 4.75 3.875V11.875C4.75 12.375 4.375 12.75 3.875 12.75C3.40625 12.75 3 12.375 3 11.875V3.875C3 3.40625 3.40625 3 3.875 3ZM9.875 4C10.375 4 10.75 4.40625 10.75 4.875V10.875C10.75 11.375 10.375 11.75 9.875 11.75C9.40625 11.75 9 11.375 9 10.875V4.875C9 4.40625 9.40625 4 9.875 4ZM0.875 6C1.375 6 1.75 6.40625 1.75 6.875V8.875C1.75 9.375 1.375 9.75 0.875 9.75C0.40625 9.75 0 9.375 0 8.875V6.875C0 6.40625 0.40625 6 0.875 6ZM15.875 6C16.375 6 16.75 6.40625 16.75 6.875V8.875C16.75 9.375 16.375 9.75 15.875 9.75C15.4062 9.75 15 9.375 15 8.875V6.875C15 6.40625 15.4062 6 15.875 6Z",fill:"currentColor"})}),vm=Xe(()=>Hl().then(e=>({default:e.ElicitationInput})));function bm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:c,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:f,theme:E,allowed:p,showStartNewChatButton:g,onStartNewChat:S,isVoiceAgentActive:m,handleVoiceMode:_,isAuthComponent:y,activeElicitationState:k,isFullScreen:T}){const x=q(null),N=q(null),v=e.trim().length>0||a,b=!p||p.includes(I.SYNAPSE_CONVERSATION.AUDIO),R=!p||p.includes(I.SYNAPSE_CONVERSATION.VOICE),A=v||!b,$=v,J=!p||p.includes(I.SYNAPSE_CONVERSATION.FILE),oe=(d||f!==Se.IDLE)&&!s,_e=M("rounded-full transition-all duration-200 ",s?"bg-gradient-to-r from-rose-400 via-primary to-indigo-500 text-white ring-2 ring-white/60 animate-pulse shadow-[0_0_20px_rgba(139,92,246,0.45)]":oe?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),ie=V=>{const H=Array.from(V.target.files||[]);H.length>0&&r(H)},he=()=>{d||(x.current&&(x.current.value=""),x.current?.click())},U=V=>{V.key==="Enter"&&!V.shiftKey&&$&&!d&&(V.preventDefault(),n())},Te=V=>{V.style.height="auto",V.style.overflow="hidden";const H=V.scrollHeight,D=T?20:28,B=120,Ee=Math.max(D,Math.min(H,B));V.style.height=Ee+"px",H>B?V.style.overflow="auto":V.style.overflow="hidden"},de=V=>{Te(V.currentTarget)};return Y(()=>{N.current&&Te(N.current)},[e]),Y(()=>{!d&&!u&&N.current?.focus()},[d]),g&&S?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:S,className:M("px-6 py-3 bg-primary text-primary-foreground text-sm font-semibold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-60 disabled:pointer-events-none w-full",!u&&"hover:bg-primary/90"),children:[l("span",{children:"Start new chat"}),l(tr,{className:"w-5 h-5","aria-hidden":!0})]})}):l(ue,{children:y?l(He,{fallback:l(Nl,{}),children:l(vm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:E,isMobile:u,onSend:n})}):T?l("div",{className:"mx-3 mb-3","data-name":"reply-box",children:l("div",{className:"flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ts,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:x,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:l(es,{ref:N,onInput:de,placeholder:h,value:e,onChange:V=>t(V.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"20px",maxHeight:"120px",fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:14,lineHeight:"20px",fontWeight:400,padding:0},onKeyPress:U,title:"Enter your message","aria-label":"Enter your message",className:M("flex-1 min-w-0 shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","bg-transparent disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap","text-foreground resize-none placeholder:text-muted-foreground")})}),l("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[l("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:J&&f===Se.IDLE&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:he,disabled:d,className:M("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(hl,{className:"w-6 h-6",strokeWidth:1.5})})}),l("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,className:M("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(ml,{className:"w-4 h-4"})}):b&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:oe,className:M("h-10 w-10 shrink-0 p-2",_e),title:"Start recording","aria-label":"Start recording",children:l(zo,{className:"w-6 h-6",strokeWidth:1.5})}),A&&!s?l(ce,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!$,variant:"ghost",className:M("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",$?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:$?"Send message":"Type a message to send","aria-label":$?"Send message":"Type a message to send",children:l(ns,{className:"w-4 h-4 text-primary-foreground"})}):b&&R&&!s&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100 p-2",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(Bl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:x,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:ie,disabled:d,title:"Attach file","aria-label":"Attach file"}),l("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[a&&c.length>0&&l("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:l(ts,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(es,{ref:N,onInput:de,placeholder:h,value:e,onChange:V=>t(V.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:U,title:"Enter your message","aria-label":"Enter your message",className:M("w-full shadow-none border-0 outline-none focus-visible:ring-0 focus-visible:ring-offset-0","text-base placeholder:text-muted-foreground bg-transparent","disabled:cursor-not-allowed rounded-none break-words whitespace-pre-wrap text-foreground resize-none")})}),l("div",{className:"flex items-center justify-between",children:[l("div",{className:"flex items-center shrink-0",children:J&&f===Se.IDLE&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:he,disabled:d,className:M("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!u&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:l(hl,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,className:M("h-10 w-10 rounded-full bg-gradient-to-r from-red-400 to-rose-500 text-white shadow-lg transition-all duration-200 active:scale-95 shrink-0",!u&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:l(ml,{className:"w-4 h-4"})}):A?l(ce,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!$,variant:"ghost",className:M("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",$?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:$?"Send message":"Type a message to send","aria-label":$?"Send message":"Type a message to send",children:l(ns,{className:"w-4 h-4 text-primary-foreground"})}):b&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:oe,className:M("h-10 w-10 shrink-0",_e),title:"Start recording","aria-label":"Start recording",children:l(zo,{className:"w-5 h-5",strokeWidth:1.5})}),b&&R&&!s&&l(ce,{type:"button",variant:"ghost",size:"icon",onClick:_,disabled:d||m,className:"h-10 w-10 bg-primary text-primary-foreground hover:bg-primary/90 rounded-full transition-all duration-200 shadow-lg hover:shadow-xl hover:scale-105 active:scale-95 shrink-0 disabled:opacity-50 disabled:pointer-events-none disabled:hover:scale-100",title:"Enter voice mode","aria-label":"Enter voice mode",children:l(Bl,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}function wm({message:e,onDismiss:t}){return l(ue,{children:[l("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),l("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:l("div",{role:"alertdialog","aria-modal":"true","aria-labelledby":"synapse-disp-toast-msg",className:"pointer-events-auto flex w-full flex-row items-center gap-3 rounded-lg border border-border bg-surface p-3 text-left text-foreground opacity-100",onClick:n=>n.stopPropagation(),children:[l("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),l("button",{type:"button",onClick:t,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Close",children:l(_n,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Nm(){const e=W(r=>r.toastMessage),t=W(r=>r.setToastMessage),n=fe(()=>{t(null)},[t]);return Y(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(wm,{message:e,onDismiss:n}):null}function rs({isOpen:e,children:t,align:n="center",onClose:r}){return e?l("div",{className:`absolute inset-0 z-[60] flex ${n==="bottom"?"items-end justify-center pb-4":"items-center justify-center"}`,style:{backgroundColor:"rgba(0, 0, 0, 0.7)"},onClick:r,children:l("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const xm="Before we begin",Cm=e=>`A quick note on how ${e} works and handles your information.`,Tm=e=>[`This assistant is powered by AI. Replies are generated automatically and can be wrong, so please check anything important before you act on it. Don't use it in an urgent or emergency situation \u2014 contact ${e} directly or call your local emergency number.`,`To help you, ${e} and our authorised technology partners process what you share here \u2014 your contact details and your messages \u2014 under contractual and security safeguards, on secure servers. We use it only to provide this service, and keep it only as long as needed or as the law requires.`];function km(e,t){return(Array.isArray(e)?e:e.split(/\n\s*\n|\n/)).map(n=>String(n??"").replace(/\{\{\s*name\s*\}\}/gi,t).trim()).filter(Boolean)}const Gl=(e,t)=>{if(t){const n=km(t,e);if(n.length)return n}return Tm(e)},Rm="I agree and consent",Om="By continuing, you consent to the above.",Am="Continue";function Wl({botName:e,consentContent:t,isFullScreen:n}){return l(ue,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:M("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:xm}),l("p",{className:M("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Cm(e)})]}),l("div",{className:M("overflow-y-auto rounded-lg border border-border-subtle flex flex-col",n?"max-h-[340px] p-4 gap-4":"max-h-[180px] p-3 gap-3"),tabIndex:0,role:"region","aria-label":"Consent details",children:Gl(e,t).map((r,o)=>l("p",{className:M("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function Im({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(rs,{isOpen:e,onClose:t,children:l("div",{className:M("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",s?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?l(Wl,{botName:n,consentContent:o,isFullScreen:s}):l("div",{className:"flex flex-col gap-2",children:[l("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),Gl(n,o).map((a,c)=>l("p",{className:M("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(ce,{onClick:t,className:M("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Mm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=F(!1);return e?l(rs,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:M("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",o?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[l(Wl,{botName:t,consentContent:n,isFullScreen:o}),l("div",{className:"flex flex-col gap-1.5",children:[l("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[l("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),l("div",{"aria-hidden":"true",className:M("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",o?"w-5 h-5":"w-4 h-4",i?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:i&&l("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),l("span",{className:M("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Rm})]}),l("p",{className:M("text-muted-foreground text-left text-pretty cursor-pointer",o?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>s(a=>!a),children:Om})]}),l(ce,{disabled:!i,onClick:()=>i&&r(),className:M("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Am})]})}):null}const Pm=Xe(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),Dm=Xe(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),Lm=Xe(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),Fm=Xe(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),Um=Xe(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),Vm=[{label:"Took longer than expected",value:"took_longer"},{label:"Asking too many questions",value:"too_many_questions"},{label:"Irrelevant response",value:"irrelevant_response"},{label:"Other",value:"other"}],jm=[{Icon:Pm,label:"Bad",score:1},{Icon:Dm,label:"Poor",score:2},{Icon:Lm,label:"Okay",score:3},{Icon:Fm,label:"Good",score:4},{Icon:Um,label:"Great!",score:5}];function zm(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Ym({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=F(null),[d,h]=F(new Set),[u,f]=F(!1),E=s&&a!==null?zm(a,t):t.form?.default?.length?t.form.default:Vm,p=_=>{h(y=>{const k=new Set(y);return k.has(_)?k.delete(_):k.add(_),k})},g=_=>{c(_),h(new Set)},S=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(rs,{isOpen:e,onClose:o,children:l("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[l("button",{onClick:r,className:"text-sm text-white/70 hover:text-white transition-colors bg-transparent border-none cursor-pointer p-0 pr-1",children:"Skip"}),l("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[l("div",{className:"flex flex-col gap-1",children:[t.title&&l("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&l("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&l("div",{className:"flex items-center justify-between gap-1",children:jm.map(({Icon:_,label:y,score:k})=>{const T=a===k,x=a!==null&&!T;return l("button",{onClick:()=>g(k),title:y,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[l("div",{className:`rounded-xl p-1 transition-all ${T?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${x?"opacity-50":""}`,style:T?{filter:"brightness(1.25)"}:void 0,children:l(He,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(_,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${T?"text-primary/50 font-medium":x?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&E.length>0&&l("div",{className:"flex flex-col gap-2",children:E.map(_=>l("div",{onClick:()=>p(_.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(_.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:_.label},_.value))}),l(ce,{disabled:!S,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),l("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>f(_=>!_),children:[l("div",{className:"relative w-3 h-3 shrink-0",children:l("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${u?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:u&&l("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:l("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),l("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function Kl({isOpen:e,onClose:t,showCloseButton:n=!0,iconUrl:r,onStartNewSession:o,showStartNewChatButton:i,children:s,sidebar:a,sessionDrawer:c,fullScreenEmptyState:d,title:h,titleImg:u,tagline:f,sessionId:E,chatComposer:p,environment:g,mode:S,sidePanelMode:m,sidePanelWidth:_,side:y,onSidePanelPushChange:k,onToggleDisplayMode:T,onOpenSessionDrawer:x,historyEnabled:N=!1,isAuthComponent:v,activeElicitation:b,voiceAgentState:R,theme:A,feedbackModal:$,consentModal:J}){const[oe,_e]=F(!1),[ie,he]=F(!1),[U,Te]=F(!1),de=q(null),V=W(L=>L.level),H=S,D=H==="full",B=H==="side_panel",Ee=q(null),[Ne,se]=F("");Y(()=>{Ee.current!==null&&Ee.current!==H&&se(H==="full"?"Switched to fullscreen mode":H==="side_panel"?"Switched to side panel mode":H==="widget"?"Switched to widget mode":"Switched to mobile layout"),Ee.current=H},[H]);const ne=ye(()=>Xh(A),[A]),{setIsMobile:$e}=W(L=>L),Ge=!!v,We=async L=>{if(!(!p?.onSend||ie)){he(!0);try{await p.onSend(L)}finally{he(!1)}}};dt(()=>{if(!de.current)return;const L=H==="full"?{...ne,headerTinted:!1}:ne;wl(de.current,L),H==="full"&&!ne.backgroundImage?(de.current.style.setProperty("--background","0 0% 100%"),de.current.style.setProperty("--widget-bg-overlay","transparent")):(de.current.style.removeProperty("--background"),de.current.style.removeProperty("--widget-bg-overlay"),wl(de.current,ne))},[ne,H]),Y(()=>{const L=()=>{const Oe=window?.innerWidth??0,le=navigator?.userAgent?.toLowerCase()??"",Re=Oe<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(le);_e(Re),$e(Re)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),dt(()=>{if(!e||!oe||!de.current)return;const L=de.current;let Oe=null,le=null,Re=null,Ze=window.visualViewport?.offsetTop??0,rt=0;const xe=2,at=80;if(window.visualViewport){const Ae=()=>{if(L&&window.visualViewport){const Ie=window.visualViewport.height,lt=window.visualViewport.offsetTop;Oe=requestAnimationFrame(()=>{L.style.transition="none",L.style.top=`${lt}px`,L.style.left="0",L.style.right="0",L.style.bottom="auto",L.style.width="100vw",L.style.height=`${Ie}px`,L.style.maxHeight=`${Ie}px`,L.style.minHeight=`${Ie}px`,le&&clearTimeout(le),le=setTimeout(()=>{L.style.transition=""},100)})}},De=()=>{Ae()},Ue=()=>{if(!L||!window.visualViewport)return;const Ie=window.visualViewport.offsetTop,lt=Date.now();Math.abs(Ie-Ze)<xe||lt-rt<at||(rt=lt,Ze=Ie,Oe=requestAnimationFrame(()=>{L.style.transition="none",L.style.top=`${Ie}px`,Re&&clearTimeout(Re),Re=setTimeout(()=>{L.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",De),window.visualViewport.addEventListener("scroll",Ue),Ae(),()=>{Oe&&cancelAnimationFrame(Oe),le&&clearTimeout(le),Re&&clearTimeout(Re),window.visualViewport?.removeEventListener("resize",De),window.visualViewport?.removeEventListener("scroll",Ue),L&&(L.style.width="",L.style.height="",L.style.maxHeight="",L.style.minHeight="",L.style.transition="")}}else{const Ae=()=>{L&&(L.style.transition="none",L.style.top="0",L.style.left="0",L.style.right="0",L.style.bottom="auto",L.style.width="100vw",L.style.height="100svh",L.style.maxHeight="100svh",setTimeout(()=>{L.style.transition=""},100))};return window.addEventListener("resize",Ae),Ae(),()=>{window.removeEventListener("resize",Ae),L&&(L.style.width="",L.style.height="",L.style.maxHeight="",L.style.transition="")}}},[e,oe]),Y(()=>{if(e&&!(B&&m==="push")){const L=de.current,Oe=window.scrollY,le=document.body.style.cssText,Re=document.documentElement.style.overflow,Ze=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Oe}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",document.body.style.overflow="hidden",document.documentElement.style.overflow="hidden",Ze>0&&!oe&&(document.body.style.paddingRight=`${Ze}px`);let rt=0;const xe=Ae=>{rt=Ae.touches[0].clientY},at=Ae=>{if(Ae.touches.length!==1)return;const De=rt-Ae.touches[0].clientY;rt=Ae.touches[0].clientY;let Ue=Ae.target;for(;Ue&&Ue!==L;){const{overflowY:Ie}=window.getComputedStyle(Ue);if((Ie==="auto"||Ie==="scroll")&&Ue.scrollHeight>Ue.clientHeight){const{scrollTop:lt,scrollHeight:en,clientHeight:yn}=Ue,St=lt<=0&&De<0,ct=lt+yn>=en-1&&De>0;if(!St&&!ct)return;break}Ue=Ue.parentElement}Ae.preventDefault()};return L&&(L.addEventListener("touchstart",xe,{passive:!0}),L.addEventListener("touchmove",at,{passive:!1})),()=>{L&&(L.removeEventListener("touchstart",xe),L.removeEventListener("touchmove",at)),document.body.style.cssText=le,document.documentElement.style.overflow=Re,window.scrollTo(0,Oe)}}},[e,oe,B,m]),Y(()=>{if(!(!B||m!=="push"||!e))return k?.(!0,_??0,y??"right"),()=>{k?.(!1,_??0,y??"right")}},[e,B,m,_,y,k]);const{position:Je,elementRef:Ot}=Bh({enabled:e&&!oe&&!D&&!B});Y(()=>{de.current&&(Ot.current=de.current)},[Ot]);const mt=M("synapse-chat-widget-container","fixed m-0 p-0","box-border",!oe&&!D&&!B?"transition-all duration-300":"",oe?"w-screen h-[100svh]":D?"w-screen h-screen":B?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),it=M("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",ne.backgroundImage?"theme-with-background":"",oe?"rounded-none border-0 flex-col":D?"rounded-none border-0 flex-row":B?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return l("div",{ref:de,"data-mode":H,className:mt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...D&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...D&&!e&&{display:"none"},...B&&e&&{top:0,bottom:0,[y==="left"?"left":"right"]:0,[y==="left"?"right":"left"]:"auto",width:`${_}px`,height:"100vh"},...B&&!e&&{display:"none"},...!oe&&!D&&!B&&{left:`${Je.x}px`,top:`${Je.y}px`,bottom:"auto",right:"auto"},...oe&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:ne.backgroundImage?"transparent":"hsl(var(--background))"}},children:[l("style",{children:`
2
2
  /* Isolate widget from host website styles */
3
3
  .synapse-chat-widget-container,
4
4
  .synapse-chat-widget-container *,
@@ -35,23 +35,23 @@ var wc=Object.defineProperty;var Nc=(e,t,n)=>t in e?wc(e,t,{enumerable:!0,config
35
35
  .synapse-chat-widget-container [data-radix-scroll-area-viewport] {
36
36
  overscroll-behavior: contain;
37
37
  }
38
- `}),l(Gt,{className:mt,"data-text-color":me.textColor,style:ae?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[l("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:je}),!me.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),me.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${me.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),me.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:me.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(vm,{isOpen:F,onClose:()=>Ce(!1),botName:h,explicitDisclaimer:A?.explicitDisclaimer,consentContent:A?.consentContent,isFullScreen:L}),q?.isOpen&&l(Sm,{isOpen:!0,botName:h,consentContent:A?.consentContent,onAccept:q.onAccept,isFullScreen:L}),Y?.isOpen&&l(Am,{isOpen:Y.isOpen,config:Y.config,onSubmit:Y.onSubmit,onSkip:Y.onSkip,onClose:Y.onClose,onDontShowAgain:Y.onDontShowAgain}),L&&a,B==="user"&&!L&&c,l("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[l("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...L?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!ae&&!L&&!W&&{cursor:e?"grab":"default"}},children:l(lm,{onClose:t,showCloseButton:n,title:h,titleImg:u,tagline:f,iconUrl:r,startNewConversation:o,voiceAgentState:N,headerTinted:L?!1:me.headerTinted,onToggleDisplayMode:T,onOpenSessionDrawer:L?void 0:S,historyEnabled:x})}),(()=>{const P=L&&!!d,Ee=p&&N===M.VOICE_AGENT_STATE.IDLE?l($e,{fallback:l(pl,{}),children:l(um,{value:p.value,onChange:p.onChange,onSend:ze?tt:p.onSend,onFileChange:p.onFileChange,onRemoveFile:p.onRemoveFile,onRecording:p.onRecording,isRecording:p.isRecording,hasAttachment:p.hasAttachment,attachmentFiles:p.attachmentFiles,isDisabled:p.isDisabled||ze&&le,isMobile:ae,placeholder:p.placeholder,recordingStatus:p.recordingStatus,theme:me,onStartNewChat:o,showStartNewChatButton:i,isVoiceAgentActive:p.isVoiceAgentActive,handleVoiceMode:p.handleVoiceMode,allowed:p.allowed,isAuthComponent:v,activeElicitationState:w,isFullScreen:L&&!P})}):null,ve={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},ke=l(ce,{children:[E&&g==="development"&&l("div",{className:"px-6 flex justify-center items-center",children:l("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",E]})}),L?l("div",{onClick:()=>Ce(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:l("span",{className:"text-[10px] leading-[14px]",style:ve,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):A?.explicitDisclaimer?l("div",{onClick:()=>Ce(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[A?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:ve,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ve,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:ve,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>Ce(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[A?.hideWatermark!==!0&&l(ce,{children:[l("span",{className:"text-[10px] leading-[14px]",style:ve,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ve,children:"Eka Care"})]}),l(tl,{className:"w-3 h-3"})]})]}),Ze=d&&L?d({composer:P?Ee:null,composerFooter:P?ke:null}):null;return l(ce,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Ze??s,l(mm,{})]}),p&&!P&&l("div",{className:I("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:I(L&&"max-w-2xl mx-auto w-full"),children:Ee}),ke]})]})})()]})]})]})}function Im(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Mm(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),o=new Date(e.getFullYear(),e.getMonth(),e.getDate());return o.getTime()===n.getTime()?"Today":o.getTime()===r.getTime()?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}function Pm({sessions:e,activeSessionId:t,onSelectSession:n,onNewChat:r,isCollapsed:o,onToggle:i,isLoading:s=!1}){return l("div",{id:"synapse-session-sidebar","data-collapsed":o,className:I("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",o?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:I("flex items-center w-full",o?"justify-center":"justify-between"),children:[!o&&l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{type:"button",onClick:i,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:o?"Expand chats":"Collapse chats","aria-label":o?"Expand chats":"Collapse chats","aria-expanded":!o,"aria-controls":"synapse-session-list",children:l(Qu,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:o?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:o?l("button",{type:"button",onClick:r,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:l(tr,{className:"w-6 h-6"})}):l("button",{type:"button",onClick:r,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[l("div",{className:"pr-2 shrink-0",children:l(tr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!o&&l("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:s&&e.length===0?l(Gh,{}):e.length===0?l("div",{className:"flex items-center justify-center h-full px-4 text-center",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):e.map(a=>{const c=a.session_id===t,d=new Date(a.c_at),h=Mm(d),u=Im(d);return l("button",{type:"button",onClick:()=>n(a.session_id),"aria-current":c?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:c?{backgroundImage:"linear-gradient(hsl(var(--primary) / 0.1), hsl(var(--primary) / 0.1))"}:void 0,children:[l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:a.title||`Chat at ${u}`}),l("div",{className:"flex items-center gap-2 w-full min-w-0",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:a.title?`${h}, ${u}`:h}),c&&l(Dm,{})]})]},a.session_id)})})]})}function Dm(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function Lm(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(r.getTime()-864e5),i=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return i.getTime()===r.getTime()?`Today, ${s}`:i.getTime()===o.getTime()?`Yesterday, ${s}`:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}, ${s}`}function Um({isOpen:e,onClose:t,sessions:n,activeSessionId:r,onSelectSession:o,onNewChat:i}){return l(ce,{children:[l("div",{className:I("absolute inset-0 z-[60] transition-opacity duration-200",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:t}),l("div",{className:I("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",e?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:"flex items-center justify-between",children:[l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{onClick:t,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:l(yn,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("button",{onClick:()=>{i(),t()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[l("div",{className:"pr-2 shrink-0",children:l(tr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),l("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:n.length===0?l("div",{className:"flex items-center justify-center h-full px-4",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):n.map(s=>{const a=s.session_id===r,c=!!s.title,d=`Chat on ${Lm(s.c_at)}`;return l("button",{onClick:()=>{o(s.session_id),t()},className:"flex flex-col gap-2 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:a?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:c?l(ce,{children:[l("div",{className:"flex flex-col gap-0.5 w-full",children:l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:s.title})}),l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:d}),a&&l(Vl,{})]})]}):l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-sm font-medium leading-5 truncate text-foreground",children:d}),a&&l(Vl,{})]})},s.session_id)})})]})]})}function Vl(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function Fm(){const e=new Date().getHours();return e>=5&&e<12?"Good morning. How are you feeling today?":e>=12&&e<17?"Good afternoon. How are you feeling right now?":e>=17&&e<21?"Good evening. How are you doing this evening?":"Up late? I'm here whenever you need me."}const Vm=180;function jm({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=c=>{const d=c.label||c.value||"";d&&n({message:c.value||d,messageId:Date.now().toString()})};return l("div",{className:"flex-1 flex flex-col overflow-y-auto",children:l("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[l("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=Vm&&l("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:Fm()}),e&&l("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&l("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((c,d)=>{const h=c.label||c.value||"";return h?l("button",{type:"button",onClick:()=>a(c),disabled:r,className:I("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&l("div",{children:[o,i]})]})})}function zm(e,t={}){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`medassist:${e}`,{detail:t}))}catch{}}function jl(){const[e,t]=D(typeof navigator<"u"?navigator.onLine:!0);return z(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const zl=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),$m=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Ym=e=>{const t=new Date(e),n=t.toLocaleDateString(void 0,{weekday:"short"}),r=t.toLocaleDateString(void 0,{day:"2-digit"}),o=t.toLocaleDateString(void 0,{month:"short"});return{weekday:n,dayNum:r,month:o}},Bm=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},$l=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Hm=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===M.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),c=n||a,d=n&&r?Km(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:$l(c,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const c=a.date?s.findIndex(d=>d.date===a.date):-1;if(c===-1)s.push({...a});else{const d=s[c];s[c]={...d,...zl(a),slots:a.slots??d.slots}}}return s},Gm=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,c=s.end_date||o.end_date;r[i]={...s,...zl(o),availability:Hm({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},Yl=e=>!!e&&Array.isArray(e.doctors),Wm=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!Yl(e)||!Yl(t))return e;const r=e.format||t.format;return{...t,doctors:Gm(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Km=(e,t)=>{const n=new Date(e),r=new Date(t),o=Math.round((r.getTime()-n.getTime())/(1e3*60*60*24));return o>=0?o+1:3},Bl=(e,t)=>`${e}::${t}`,qm=e=>e<1e12?e*1e3:e,Xm=(e,t)=>`${e}::${t}::answer`,Zm=e=>!!e?.tool_id&&!!e?.component;function Jm(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(Zm),i=r.timestamp?Ht(qm(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Ve.USER?Ve.USER:Ve.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>Bl(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[Bl(r.id,s.tool_id)]={tool_id:s.tool_id,messageId:r.id,component:s.component,input:s.input,active:!1,disabled:!0,...s.answer&&{answer:s.answer}},s.answer&&t.push({id:Xm(r.id,s.tool_id),content:s.answer,role:Ve.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Kt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Qm=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=D([]),d=J([]),[h,u]=D(!1),[f,E]=D(!1),p=J(new Map),g=J(0),[b,m]=D(!1),_=J([]),y=J(null),k=J(null),T=Ch(),S=J(null),{isOnline:x}=jl(),v=J(!1),w=G(R=>R.agentId),N=G(R=>R.sessionId),A=G(R=>R.isStreaming),Y=G(R=>R.isWaitingForResponse),q=G(R=>R.initialMessage),ae=G(R=>R.userId),de=G(R=>R.fileUploadPerSession),{setSessionId:le,setRefreshToken:ue,setSessToken:F,setLevel:Ce,setError:$,setConnectionStatus:B,setShowRetryButton:H,setStartNewConnection:L,setIsStreaming:W,setIsWaitingForResponse:oe,setProgressMessage:je,setRecordingStatus:K,clearSession:me,clearUser:Be,addMessageToSession:ze,getMessagesForSession:tt,setMessagesForSession:Xe,updateMessageInSession:ht,setUserId:Et,setFileUploadPerSession:mt,setToastMessage:P,upsertElicitationState:Ee,setElicitationState:ve,setInitialMessage:ke,setSessionInitialMessage:Ze}=G.getState();z(()=>{if(!x)$({title:"No internet connection",description:"Please check your internet connection."}),B(_e.NOT_CONNECTED);else if(!b)B(_e.CONNECTING);else if(pe())B(_e.CONNECTED),Re();else{const{showRetryButton:R,startNewConnection:C,error:U}=G.getState();(R||C||U)&&!pe()&&Re()}},[x,b]),z(()=>{N&&(c(R=>{const C=new Set(R.map(U=>U.id));return[...R,...(tt(N)||[]).filter(U=>!C.has(U.id))]}),_.current=[])},[N]),z(()=>{if(m(!1),!w)return;const R=new M.SynapseSDK({agentId:w,...o&&{authToken:o},...G.getState().refreshToken&&{refreshToken:G.getState().refreshToken},...G.getState().sessToken&&{sessToken:G.getState().sessToken},...G.getState().level&&{level:G.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:ae,callbacks:{onError:C=>{if(typeof navigator<"u"&&!navigator.onLine){B(_e.NOT_CONNECTED),$({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(C.reason)switch(C.reason){case M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{G.getState().level!=="user"?(Be(),y.current?.clearTokens(),Sn()):ar();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:ar();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:$(null),B(_e.NOT_CONNECTED),L(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:B(_e.CONNECTING);return}switch(C.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const U=C;U.status===404||U?.context?.status===404?L(!0):(B(_e.NOT_CONNECTED),$({title:"Something went wrong!",description:Kt(C)}),H(!0));break}case M.SynapseErrorCode.RECORDING:$({title:"Recording failed",description:Kt(C)});break;case M.SynapseErrorCode.CONNECTION:pe()||(B(_e.NOT_CONNECTED),g.current<2?(g.current=g.current+1,Le(N)):(H(!0),$({title:"Trying to connect...",description:Kt(C)})));break;default:$({title:"Something went wrong",description:Kt(C)}),H(!0);break}},onTokenExchange:C=>{const U=G.getState().userId;(C?.user_id&&U&&C.user_id!==U||C?.userid_change_detected)&&me(),C?.refresh_token&&ue(C.refresh_token),C?.sess_token&&F(C.sess_token),C?.level&&Ce(C.level),C?.user_id&&Et(C.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=R,T(R),m(!0),()=>{m(!1),ct(),y.current=null,T(null),S.current&&(clearTimeout(S.current),S.current=null)}},[w,e,o]),z(()=>{d.current=a},[a]),z(()=>{const R=d.current[d.current.length-1];!R?.role||!N||(R?.role===Ve.USER&&!R.isStored?ze(N,{...R,isStored:!0}):!A&&!R.isStored&&(c(C=>{const U=[...C];return U[U.length-1]={...R,isStored:!0},U}),ze(N,{...R,isStored:!0})))},[a,A]),z(()=>()=>{const R=d.current[d.current.length-1];R&&!R?.isStored&&N&&ze(N,{...R,isStored:!0})},[]),z(()=>(S.current&&(clearTimeout(S.current),S.current=null),Y&&!A?S.current=setTimeout(()=>{oe(!1),S.current=null},3e4):A&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[Y,A,oe]);const Le=async R=>{try{const C=await y.current?.startSession(R?{session_id:R}:void 0);if(C?.session_id&&le(C.session_id),C?.user_id&&Et(C.user_id),C?.initial_message){ke(C.initial_message);const U=C.session_id||R;U&&Ze(U,C.initial_message)}C?.error?.msg&&P(C.error.msg)}catch(C){if(C?.reason)return;const U=C;U.status===404||U.context?.status==404?($(null),B(_e.NOT_CONNECTED),L(!0)):($({title:"Connection Lost!",description:Kt(C)}),H(!0))}},Ie=async R=>{const C=G.getState().chats[R];if(C?.length)return c(C),C;const U=p.current.get(R);if(U)return U;const X=(async()=>{try{const se=await y.current?.getSessionMessages(R);if(!se?.length)return[];const{messages:re,elicitations:Ne}=Jm(se);return Object.keys(Ne).length&&ve({...G.getState().elicitationState,...Ne}),Xe(R,re),c(re),re}catch{return[]}finally{p.current.delete(R)}})();p.current.set(R,X),E(!0);try{return await X}finally{E(!1)}},lt=async({forceNewSession:R=!1,sessionId:C}={})=>{try{if(!y.current){$({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),R){B(_e.CONNECTING),c([]),await me(),await y?.current?.endSession(),Re(),await Le(),nt();return}const U=G.getState()?.sessionId,X=C||U||void 0;X!==U&&(ct(),c([]),X&&await Ie(X)),await Le(X),nt()}catch{}finally{u(!1)}},pe=()=>y.current?.isConnected()??!1,ct=()=>{y.current?.endSession()},Re=()=>{g.current=0,H(!1),L(!1),$(null)},He=()=>{let R;try{R=y.current?.getSessionConfig()?.session_id}catch{R=void 0}R||(R=G.getState().sessionId||void 0),!(!R||k.current===R)&&(k.current=R,zm("ready",{sessionId:R}))},nt=()=>{y.current?.on(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,R=>{const C=R;if(C.data?.text&&C.messageId){A||(oe(!1),W(!0)),pe()&&B(_e.CONNECTED),Re();const U=C.data.text,X=C.messageId,se=v.current;v.current=!1,c(re=>{const Ne=re[re.length-1];if(Ne&&Ne.id===X&&Ne.role===Ve.ASSISTANT){const Ue=[...re],rt=se&&Ne.content.length>0&&!/\s$/.test(Ne.content)&&!/^\s/.test(U)?`
38
+ `}),l(qt,{className:it,"data-text-color":ne.textColor,style:oe?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[l("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0,0,0,0)",whiteSpace:"nowrap",border:0},children:Ne}),!ne.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),ne.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${ne.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),ne.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:ne.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(Im,{isOpen:U,onClose:()=>Te(!1),botName:h,explicitDisclaimer:A?.explicitDisclaimer,consentContent:A?.consentContent,isFullScreen:D}),J?.isOpen&&l(Mm,{isOpen:!0,botName:h,consentContent:A?.consentContent,onAccept:J.onAccept,isFullScreen:D}),$?.isOpen&&l(Ym,{isOpen:$.isOpen,config:$.config,onSubmit:$.onSubmit,onSkip:$.onSkip,onClose:$.onClose,onDontShowAgain:$.onDontShowAgain}),D&&a,V==="user"&&!D&&c,l("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[l("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...D?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!oe&&!D&&!B&&{cursor:e?"grab":"default"}},children:l(ym,{onClose:t,showCloseButton:n,title:h,titleImg:u,tagline:f,iconUrl:r,startNewConversation:o,voiceAgentState:R,headerTinted:D?!1:ne.headerTinted,onToggleDisplayMode:T,onOpenSessionDrawer:D?void 0:x,historyEnabled:N})}),(()=>{const L=D&&!!d,Oe=p&&R===I.VOICE_AGENT_STATE.IDLE?l(He,{fallback:l(Nl,{}),children:l(bm,{value:p.value,onChange:p.onChange,onSend:Ge?We:p.onSend,onFileChange:p.onFileChange,onRemoveFile:p.onRemoveFile,onRecording:p.onRecording,isRecording:p.isRecording,hasAttachment:p.hasAttachment,attachmentFiles:p.attachmentFiles,isDisabled:p.isDisabled||Ge&&ie,isMobile:oe,placeholder:p.placeholder,recordingStatus:p.recordingStatus,theme:ne,onStartNewChat:o,showStartNewChatButton:i,isVoiceAgentActive:p.isVoiceAgentActive,handleVoiceMode:p.handleVoiceMode,allowed:p.allowed,isAuthComponent:v,activeElicitationState:b,isFullScreen:D&&!L})}):null,le={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Re=l(ue,{children:[E&&g==="development"&&l("div",{className:"px-6 flex justify-center items-center",children:l("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",E]})}),D?l("div",{onClick:()=>Te(!0),className:"px-6 py-1 flex justify-center items-center text-center text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:l("span",{className:"text-[10px] leading-[14px]",style:le,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):A?.explicitDisclaimer?l("div",{onClick:()=>Te(!0),className:"px-6 py-1 flex flex-col justify-center items-center gap-0.5 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[A?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>Te(!0),className:"px-6 py-1 flex justify-center items-center gap-1 text-foreground opacity-50 hover:opacity-70 transition-opacity cursor-pointer bg-transparent border-none rounded","aria-label":"Open disclaimer",children:[A?.hideWatermark!==!0&&l(ue,{children:[l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:le,children:"Eka Care"})]}),l(ul,{className:"w-3 h-3"})]})]}),Ze=d&&D?d({composer:L?Oe:null,composerFooter:L?Re:null}):null;return l(ue,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Ze??s,l(Nm,{})]}),p&&!L&&l("div",{className:M("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:M(D&&"max-w-2xl mx-auto w-full"),children:Oe}),Re]})]})})()]})]})]})}function $m(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Hm(e){const t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n.getTime()-864e5),o=new Date(e.getFullYear(),e.getMonth(),e.getDate());return o.getTime()===n.getTime()?"Today":o.getTime()===r.getTime()?"Yesterday":e.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}function Bm({sessions:e,activeSessionId:t,onSelectSession:n,onNewChat:r,isCollapsed:o,onToggle:i,isLoading:s=!1}){return l("div",{id:"synapse-session-sidebar","data-collapsed":o,className:M("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",o?"w-[72px]":"w-[280px]"),style:{borderRight:"1px solid hsl(var(--border-subtle))",backgroundImage:"linear-gradient(hsl(var(--primary) / 0.02), hsl(var(--primary) / 0.02))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:M("flex items-center w-full",o?"justify-center":"justify-between"),children:[!o&&l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{type:"button",onClick:i,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:o?"Expand chats":"Collapse chats","aria-label":o?"Expand chats":"Collapse chats","aria-expanded":!o,"aria-controls":"synapse-session-list",children:l(dh,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:o?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:o?l("button",{type:"button",onClick:r,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:"Start new chat","aria-label":"Start new chat",children:l(tr,{className:"w-6 h-6"})}):l("button",{type:"button",onClick:r,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[l("div",{className:"pr-2 shrink-0",children:l(tr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!o&&l("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:s&&e.length===0?l(rm,{}):e.length===0?l("div",{className:"flex items-center justify-center h-full px-4 text-center",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):e.map(a=>{const c=a.session_id===t,d=new Date(a.c_at),h=Hm(d),u=$m(d);return l("button",{type:"button",onClick:()=>n(a.session_id),"aria-current":c?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:c?{backgroundImage:"linear-gradient(hsl(var(--primary) / 0.1), hsl(var(--primary) / 0.1))"}:void 0,children:[l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:a.title||`Chat at ${u}`}),l("div",{className:"flex items-center gap-2 w-full min-w-0",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:a.title?`${h}, ${u}`:h}),c&&l(Gm,{})]})]},a.session_id)})})]})}function Gm(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function Wm(e){const t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()),o=new Date(r.getTime()-864e5),i=new Date(t.getFullYear(),t.getMonth(),t.getDate()),s=t.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0});return i.getTime()===r.getTime()?`Today, ${s}`:i.getTime()===o.getTime()?`Yesterday, ${s}`:`${t.toLocaleDateString("en-GB",{day:"numeric",month:"short",year:"2-digit"})}, ${s}`}function Km({isOpen:e,onClose:t,sessions:n,activeSessionId:r,onSelectSession:o,onNewChat:i}){return l(ue,{children:[l("div",{className:M("absolute inset-0 z-[60] transition-opacity duration-200",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:t}),l("div",{className:M("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",e?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("div",{className:"flex items-center justify-between",children:[l("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),l("button",{onClick:t,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:l(_n,{className:"w-6 h-6"})})]})}),l("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:l("button",{onClick:()=>{i(),t()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[l("div",{className:"pr-2 shrink-0",children:l(tr,{className:"w-4 h-4 text-primary-foreground"})}),l("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),l("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:n.length===0?l("div",{className:"flex items-center justify-center h-full px-4",children:l("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):n.map(s=>{const a=s.session_id===r,c=!!s.title,d=`Chat on ${Wm(s.c_at)}`;return l("button",{onClick:()=>{o(s.session_id),t()},className:"flex flex-col gap-2 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:a?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:c?l(ue,{children:[l("div",{className:"flex flex-col gap-0.5 w-full",children:l("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:s.title})}),l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:d}),a&&l(ql,{})]})]}):l("div",{className:"flex items-center gap-2 w-full",children:[l("span",{className:"text-sm font-medium leading-5 truncate text-foreground",children:d}),a&&l(ql,{})]})},s.session_id)})})]})]})}function ql(){return l("span",{className:"shrink-0 px-2 py-0.5 rounded-full text-[8px] font-semibold leading-3 tracking-[0.4px] bg-primary text-primary-foreground",children:"CURRENT CHAT"})}function qm(){const e=new Date().getHours();return e>=5&&e<12?"Good morning. How are you feeling today?":e>=12&&e<17?"Good afternoon. How are you feeling right now?":e>=17&&e<21?"Good evening. How are you doing this evening?":"Up late? I'm here whenever you need me."}const Xm=180;function Jm({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=c=>{const d=c.label||c.value||"";d&&n({message:c.value||d,messageId:Date.now().toString()})};return l("div",{className:"flex-1 flex flex-col overflow-y-auto",children:l("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[l("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=Xm&&l("h2",{className:"text-text-primary",style:{fontFamily:"Inter, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontSize:36,lineHeight:"40px",fontWeight:500,letterSpacing:"-0.025em",margin:0},children:qm()}),e&&l("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&l("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((c,d)=>{const h=c.label||c.value||"";return h?l("button",{type:"button",onClick:()=>a(c),disabled:r,className:M("inline-flex items-center bg-white border border-primary text-primary","rounded-lg overflow-clip whitespace-nowrap transition-colors shrink-0","supports-[hover:hover]:hover:bg-primary supports-[hover:hover]:hover:text-primary-foreground",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:500,padding:"8px 12px",WebkitTapHighlightColor:"transparent",outline:"none"},children:h},`${h}-${d}`):null})}),s,o&&l("div",{children:[o,i]})]})})}const ht={AUTH_FAILED:"auth_failed",SESSION_FAILED:"session_failed",CONNECTION_FAILED:"connection_failed",CONNECTION_ESTABLISHED:"connection_established",READY:"ready",TYPING_STARTED:"typing_started",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"};function Xl(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function Jl(){const[e,t]=F(typeof navigator<"u"?navigator.onLine:!0);return Y(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const Zl=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Zm=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Qm=e=>{const t=new Date(e),n=t.toLocaleDateString(void 0,{weekday:"short"}),r=t.toLocaleDateString(void 0,{day:"2-digit"}),o=t.toLocaleDateString(void 0,{month:"short"});return{weekday:n,dayNum:r,month:o}},ep=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},Ql=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},tp=({prev:e=[],next:t=[],startDate:n,endDate:r,format:o})=>{const i=o===I.SYNAPSE_TOOL_FORMATS?.DEFAULT;if(!e.length&&!t.length){const a=new Date().toISOString().slice(0,10),c=n||a,d=n&&r?op(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:Ql(c,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const c=a.date?s.findIndex(d=>d.date===a.date):-1;if(c===-1)s.push({...a});else{const d=s[c];s[c]={...d,...Zl(a),slots:a.slots??d.slots}}}return s},np=(e=[],t=[],n)=>{if(!e.length)return t;if(!t.length)return e;const r=e.map(o=>({...o}));for(const o of t){const i=o.doctor_id?r.findIndex(s=>s.doctor_id===o.doctor_id):-1;if(i===-1)r.push({...o});else{const s=r[i],a=s.start_date||o.start_date||s.preferred_date||o.preferred_date,c=s.end_date||o.end_date;r[i]={...s,...Zl(o),availability:tp({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},ec=e=>!!e&&Array.isArray(e.doctors),rp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!ec(e)||!ec(t))return e;const r=e.format||t.format;return{...t,doctors:np(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},op=(e,t)=>{const n=new Date(e),r=new Date(t),o=Math.round((r.getTime()-n.getTime())/(1e3*60*60*24));return o>=0?o+1:3},tc=(e,t)=>`${e}::${t}`,sp=e=>e<1e12?e*1e3:e,ip=(e,t)=>`${e}::${t}::answer`,ap=e=>!!e?.tool_id&&!!e?.component;function lp(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(ap),i=r.timestamp?Kt(sp(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Pe.USER?Pe.USER:Pe.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>tc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[tc(r.id,s.tool_id)]={tool_id:s.tool_id,messageId:r.id,component:s.component,input:s.input,active:!1,disabled:!0,...s.answer&&{answer:s.answer}},s.answer&&t.push({id:ip(r.id,s.tool_id),content:s.answer,role:Pe.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const nc="initial-bot-message",Jt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},cp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=F([]),d=q([]),[h,u]=F(!1),[f,E]=F(!1),p=q(new Map),g=q(0),[S,m]=F(!1),_=q([]),y=q(null),k=q({}),T=q(null),x=Fh(),N=q(null),{isOnline:v}=Jl(),b=q(!1),R=W(C=>C.agentId),A=W(C=>C.sessionId),$=W(C=>C.isStreaming),J=W(C=>C.isWaitingForResponse),oe=W(C=>C.initialMessage),_e=W(C=>C.userId),ie=W(C=>C.fileUploadPerSession),{setSessionId:he,setRefreshToken:U,setSessToken:Te,setLevel:de,setError:V,setConnectionStatus:H,setShowRetryButton:D,setStartNewConnection:B,setIsStreaming:Ee,setIsWaitingForResponse:Ne,setProgressMessage:se,setRecordingStatus:ne,clearSession:$e,clearUser:Ge,addMessageToSession:We,getMessagesForSession:Je,setMessagesForSession:Ot,updateMessageInSession:mt,setUserId:it,setFileUploadPerSession:L,setToastMessage:Oe,upsertElicitationState:le,setElicitationState:Re,setInitialMessage:Ze,setSessionInitialMessage:rt}=W.getState();Y(()=>{if(!v)V({title:"No internet connection",description:"Please check your internet connection."}),H(ge.NOT_CONNECTED);else if(!S)H(ge.CONNECTING);else if(De())H(ge.CONNECTED),Ie();else{const{showRetryButton:C,startNewConnection:w,error:P}=W.getState();(C||w||P)&&!De()&&Ie(),T.current!==null&&!w&&!yn()&&xe(W.getState().sessionId||void 0)}},[v,S]),Y(()=>{A&&(c(C=>{const w=new Set(C.map(P=>P.id));return[...C,...(Je(A)||[]).filter(P=>!w.has(P.id))]}),_.current=[])},[A]),Y(()=>{if(m(!1),!R)return;const C=new I.SynapseSDK({agentId:R,...o&&{authToken:o},...W.getState().refreshToken&&{refreshToken:W.getState().refreshToken},...W.getState().sessToken&&{sessToken:W.getState().sessToken},...W.getState().level&&{level:W.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:_e,callbacks:{onError:w=>{if(ir(w),typeof navigator<"u"&&!navigator.onLine){H(ge.NOT_CONNECTED),V({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(w.reason)switch(w.reason){case I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{W.getState().level!=="user"?(Ge(),y.current?.clearTokens(),bn()):lr();return}case I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:lr();return;case I.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:V(null),H(ge.NOT_CONNECTED),B(!0);return;case I.SYNAPSE_RECOVERY_REASON.RETRY_LATER:H(ge.CONNECTING);return}switch(w.code){case I.SynapseErrorCode.API:case I.SynapseErrorCode.SESSION:{const P=w;P.status===404||P?.context?.status===404?B(!0):(H(ge.NOT_CONNECTED),V({title:"Something went wrong!",description:Jt(w)}),D(!0));break}case I.SynapseErrorCode.RECORDING:V({title:"Recording failed",description:Jt(w)});break;case I.SynapseErrorCode.CONNECTION:De()||(H(ge.NOT_CONNECTED),g.current<2?(g.current=g.current+1,xe(W.getState().sessionId||void 0)):(D(!0),V({title:"Trying to connect...",description:Jt(w)})));break;default:V({title:"Something went wrong",description:Jt(w)}),D(!0);break}},onTokenExchange:w=>{const P=W.getState().userId;(w?.user_id&&P&&w.user_id!==P||w?.userid_change_detected)&&$e(),w?.refresh_token&&U(w.refresh_token),w?.sess_token&&Te(w.sess_token),w?.level&&de(w.level),w?.user_id&&it(w.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=C,x(C),m(!0),()=>{m(!1),Ue(),y.current=null,x(null),N.current&&(clearTimeout(N.current),N.current=null)}},[R,e,o]),Y(()=>{d.current=a},[a]),Y(()=>{const C=d.current[d.current.length-1];!C?.role||!A||(C?.role===Pe.USER&&!C.isStored?We(A,{...C,isStored:!0}):!$&&!C.isStored&&(c(w=>{const P=[...w];return P[P.length-1]={...C,isStored:!0},P}),We(A,{...C,isStored:!0})))},[a,$]),Y(()=>()=>{const C=d.current[d.current.length-1];C&&!C?.isStored&&A&&We(A,{...C,isStored:!0})},[]),Y(()=>(N.current&&(clearTimeout(N.current),N.current=null),J&&!$?N.current=setTimeout(()=>{Ne(!1),N.current=null},3e4):$&&N.current&&(clearTimeout(N.current),N.current=null),()=>{N.current&&(clearTimeout(N.current),N.current=null)}),[J,$,Ne]);const xe=async C=>{T.current=performance.now();try{const w=await y.current?.startSession(C?{session_id:C}:void 0);if(w?.session_id&&he(w.session_id),w?.user_id&&it(w.user_id),w?.initial_message){Ze(w.initial_message);const P=w.session_id||C;P&&rt(P,w.initial_message)}w?.error?.msg&&Oe(w.error.msg)}catch(w){if(w?.reason)return;const P=w;P.status===404||P.context?.status==404?(V(null),H(ge.NOT_CONNECTED),B(!0)):(V({title:"Connection Lost!",description:Jt(w)}),D(!0))}},at=async C=>{const w=W.getState().chats[C];if(w?.length)return c(w),w;const P=p.current.get(C);if(P)return P;const G=(async()=>{try{const X=await y.current?.getSessionMessages(C);if(!X?.length)return[];const{messages:Z,elicitations:pe}=lp(X);return Object.keys(pe).length&&Re({...W.getState().elicitationState,...pe}),Ot(C,Z),c(Z),Z}catch{return[]}finally{p.current.delete(C)}})();p.current.set(C,G),E(!0);try{return await G}finally{E(!1)}},Ae=async({forceNewSession:C=!1,sessionId:w}={})=>{try{if(!y.current){V({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),C){H(ge.CONNECTING),c([]),await $e(),await y?.current?.endSession(),Ie(),await xe(),At();return}const P=W.getState()?.sessionId,G=w||P||void 0;G!==P&&(Ue(),c([]),G&&await at(G)),await xe(G),At()}catch{}finally{u(!1)}},De=()=>y.current?.isConnected()??!1,Ue=()=>{y.current?.endSession()},Ie=()=>{g.current=0,D(!1),B(!1),V(null)},lt=()=>{St(ht.READY)},en=()=>{let C;try{C=y.current?.getSessionConfig()?.session_id}catch{C=void 0}return C||W.getState().sessionId||void 0},yn=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},St=(C,w={})=>{const P=en();!P||k.current[C]===P||(k.current[C]=P,Xl(C,{sessionId:P,...w}))},ct=(C,w={})=>{const P=en();Xl(C,{...P&&{sessionId:P},...w})},ir=C=>{if(De())return;const w=C?.code,P=[I.SynapseErrorCode.RECORDING,I.SynapseErrorCode.FILE,I.SynapseErrorCode.MESSAGE,I.SynapseErrorCode.VALIDATION,I.SynapseErrorCode.CONFIGURATION,I.SynapseErrorCode.STORE];if(w&&P.includes(w))return;const G=typeof C?.status=="number"?C.status:void 0,X=C?.error,Z=typeof X?.code=="string"?X.code:typeof X?.type=="string"?X.type:void 0,pe={...G!==void 0&&{status:G}};if(C?.reason===I.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||C?.reason===I.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||w===I.SynapseErrorCode.AUTH||G===401||G===403){ct(ht.AUTH_FAILED,{reason:C?.reason??Z??w??"auth_error",...pe});return}const ve=w===I.SynapseErrorCode.API&&G===void 0;if(w===I.SynapseErrorCode.CONNECTION||G===0||ve){ct(ht.CONNECTION_FAILED,{reason:C?.reason??Z??(ve?"timeout":w)??"connection_error",...pe});return}ct(ht.SESSION_FAILED,{reason:C?.reason??Z??w??"session_error",...pe})},zr=C=>{switch(C){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:ct(ht.SESSION_FAILED,{reason:C});return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:ct(ht.CONNECTION_FAILED,{reason:C});return}},Yr=()=>{ct(ht.CONNECTION_ESTABLISHED,{...T.current!==null&&{elapsedMs:Math.max(0,Math.round(performance.now()-T.current))}})},$r=()=>{St(ht.TYPING_STARTED)},Sn=()=>{d.current.some(C=>C.role===Pe.USER)||St(ht.FIRST_MESSAGE_SENT)},vn=C=>{d.current.some(w=>w.role===Pe.ASSISTANT&&w.id!==nc)||St(ht.FIRST_BOT_REPLY,{messageId:C})},At=()=>{y.current?.on(I.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,C=>{const w=C;if(w.data?.text&&w.messageId){$||(Ne(!1),Ee(!0)),De()&&H(ge.CONNECTED),Ie();const P=w.data.text,G=w.messageId,X=b.current;b.current=!1;const Z=d.current[d.current.length-1];!(Z&&Z.id===G&&Z.role===Pe.ASSISTANT)&&vn(G),c(pe=>{const ve=pe[pe.length-1];if(ve&&ve.id===G&&ve.role===Pe.ASSISTANT){const Ke=[...pe],It=X&&ve.content.length>0&&!/\s$/.test(ve.content)&&!/^\s/.test(P)?`
39
39
 
40
- `:"";return Ue[Ue.length-1]={...Ne,content:Ne.content+rt+U},Ue}else return[...re,{id:X,content:U,role:Ve.ASSISTANT,timestamp:Ht(Date.now()),isStored:!1}]})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{v.current=!1,W(!1),je(null),oe(!1)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{Re(),B(_e.CONNECTED),He()}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,R=>{v.current=!0;const C=R;if(!C?.messageId||!C?.data||!C?.data?.details?.component||!C?.data?.tool_id)return;Y&&oe(!1);const{messageId:U,data:X}=C,se=X.tool_id,re=`${U}::${se}`,Ne=G.getState().elicitationState[re],Ue=X.details?.component,rt=C?.data?.details?._meta?.tool_result,Qt=X.details?.input,Vt=Wm(Ne?.input,Qt,Ue);let Fe=C.data.details?._meta?.disp_toast_msg;const ot=X?.details?._meta?.schema?.required||[];switch(X?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Oe=C?.data?.details?.input||{},Me=ot.reduce((bt,vt)=>(Oe[vt]!==void 0&&(bt[vt]=Oe[vt]),bt),{}),ee={...Ne?.server_input||{},...Me},jt=ot.filter(bt=>!ee[bt]),zt=C.data.details?._meta?.mcp_meta_fields||[];Ee(re,{tool_id:se,active:!0,disabled:!1,input:Vt,server_input:ee,messageId:U,required:ot,component:Ue,pattern:C.data.details?._meta?.schema?.properties?.[C.data.details?.component]?.pattern,minLength:C.data.details?._meta?.schema?.properties?.[C.data.details?.component]?.minLength,maxLength:C.data.details?._meta?.schema?.properties?.[C.data.details?.component]?.maxLength,type:C.data.details?._meta?.schema?.properties?.[C.data.details?.component]?.type,disp_toast_msg:C.data.details?._meta?.disp_toast_msg,description:C.data.details?._meta?.schema?.properties?.[C.data.details?.component]?.description,tool_result:rt,orientation:C.data.details?._meta?.orientation,...zt.length&&{mcp_meta_fields:zt},...jt?{toolSelectionNames:jt}:{},...Ne?.hide_show_more!==void 0?{hide_show_more:Ne.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ee(re,{...Ne||{},tool_id:se,disabled:!0,active:ku(Ue),messageId:U,component:Ue,input:Vt,tool_result:rt,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{Ee(re,{...Ne||{},tool_id:se,active:!1,messageId:U,response_value:{label:X?.details?._meta?.disp_message||"Tool call failed"},tool_result:rt,disabled:!0});break}default:Ee(re,{tool_id:se,disabled:!1,active:!1,messageId:U,tool_result:rt,input:Vt,component:Ue})}Fe&&P(Fe);const pt=C?.data?.details?._meta?.user_hint;c(Oe=>{let Me=Oe[Oe.length-1]?.id===U?Oe.length-1:Oe.findIndex?.(ee=>ee.id===U);if(Me==-1){const ee={id:U,content:C.data?.details?.input?.text||"",role:Ve.ASSISTANT,tool_keys:[re],isResponseFromTool:!0,isStored:!1,...pt?{userHint:pt}:{}};return[...Oe,ee]}else{const ee={...Oe[Me],isResponseFromTool:!0,tool_keys:[...new Set([...Oe[Me].tool_keys||[],re])],...pt?{userHint:pt}:{}};Oe[Me]=ee,ht(N,U,ee)}return[...Oe]});const Ot=C?.data?.details?._meta?.disp_message,st=G.getState().elicitationState;if((!st[re]?.active||st[re]?.send_to_llm)&&(Ot||Object.keys(rt||{}).length))try{yt({message:Ot||"",tool_result:rt,toolCalled:!0,tool_key:re})}catch{}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,R=>{if(R?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const C=typeof navigator<"u"&&!navigator.onLine;if(B(_e.NOT_CONNECTED),C){$({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),H(!1);return}g.current<2?(g.current=g.current+1,H(!0),$({title:"Something went wrong!",description:"Please try again."})):($({title:"Something went wrong!",description:"Please start a new Chat."}),L(!0))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.ERROR,R=>{switch(R?.data?.code){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:L(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:$({title:"Session not found",description:"Please start a new chat from onError callback"}),L(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Sn();return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case M.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(g.current<1){g.current++,wn();return}$({title:"Error parsing request",description:"please try again"}),H(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:$({title:"Request timed out",description:"please try again"}),H(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:$({title:"Something went wrong",description:"please try again"}),H(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:$({title:"Something went wrong",description:"please try again"}),H(!0),K(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:$({title:"Something went wrong",description:"please try again"}),H(!0),K(be.IDLE);return;default:$({title:"Something went wrong",description:"please try again"}),H(!0),K(be.IDLE);return}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async R=>{const C=R;C?.data?.text&&(c(U=>[...U,{id:Date.now().toString(),content:C.data.text||"",role:Ve.USER,timestamp:Ht(Date.now()),isStored:!0}]),K(be.IDLE)),W(!1),oe(!1),je(null)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,R=>{v.current=!0;const C=R;C.data?.text&&(oe(!1),je(C.data.text))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,R=>{v.current=!0;const C=R;if(C.data?.name&&C.messageId){const U=C.messageId;c(X=>{const se=X[X.length-1];if(se&&se.id===U&&se.role===Ve.ASSISTANT){const re=[...X];return re[re.length-1]={...se,toolCallStatus:`Calling tool: ${C.data.name}...`},N&&ht(N,U,{toolCallStatus:`Calling tool: ${C.data.name}...`}),re}return X})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,R=>{v.current=!0;const C=R;if(C.data?.name&&C.messageId){const U=C.messageId;c(X=>{const se=X[X.length-1];if(se&&se.id===U&&se.role===Ve.ASSISTANT){const re=[...X];return re[re.length-1]={...se,toolCallStatus:"Tool call completed."},N&&ht(N,U,{toolCallStatus:"Tool call completed."}),re}return X})}})},yt=async({message:R,files:C,audio:U,toolCalled:X,selectedComponent:se,resend:re,tool_declined:Ne,tool_result:Ue,tool_key:rt})=>{const Qt=G.getState().elicitationState,Vt=Object.values(Qt).some(Fe=>Fe.active);if(!(!X&&(!C||C.length===0)&&!R?.trim()&&!U?.audio&&!se&&!Vt&&!Ue&&!Object.keys(Ue||{}).length)){if(C&&C.length>3){$({title:"Maximum 3 files are allowed to be sent at a time",description:"Please try again"});return}if(C&&C.length>0&&C.reduce((Fe,ot)=>Fe+ot.size,0)>10*1024*1024){$({title:"Total file size limit of 10MB exceeded",description:"Please reduce the size of the files or try again with less files"});return}if(C&&C.length>0&&C.length+de>Do){const Fe=Do-de;$({title:`You can only upload up to ${Do} files per session`,description:`${Fe<=0?"Maximum file upload limit reached":`You have ${Fe} file${Fe===1?"":"s"} upload${Fe===1?"":"s"} left`}`});return}else C&&C.length&&mt(de+C.length);$(null),H(!1),pe()&&B(_e.CONNECTED);try{const Fe=a.length<=2&&_.current.length==1?_.current:null;let ot=null,pt=null;const Ot=a.length-1,st=Ot>=0?a[Ot]:null,Oe=G.getState().elicitationState,Me=rt||null,ee=Me?Oe[Me]:void 0,jt=ee?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===M.SYNAPSE_COMPONENTS.CARD?!!ee&&!Ue&&!!ee.active:!!ee?.active,zt=!!(C||[]).length||!!U?.audio||!!Ne||!jt||!X,bt=se?se.label:void 0,vt=ee?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof bt=="string"?bt:null;if(!zt&&jt&&Me&&ee?.messageId){const xe=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(Se=>!ee.server_input?.[Se])??[],Ge=xe.reduce((Se,fe)=>{if(se){const ne=se[fe];ne!==void 0&&(Se[fe]=ne)}else xe.length===1&&(Se[fe]=R);return Se},{}),St=ee.mcp_meta_fields?.reduce((Se,fe)=>(xe.includes(fe)?Se[fe]=Ge[fe]:ee.server_input?.[fe]&&(Se[fe]=ee.server_input[fe]),re&&!Se.is_resend&&(Se.is_resend=re),Se),{}),en=Object.keys(ee.server_input||{})?.reduce((Se,fe)=>{const ne=!Object.keys(St||{})?.includes(fe),Te=!!ee.server_input?.[fe];return(re?ne&&Te:ne&&ee.required?.includes(fe)&&Te)&&(Se[fe]=ee.server_input?.[fe]),Se},{}),tn=re?{}:(ee.required||xe).reduce((Se,fe)=>(Object.keys(St||{}).includes(fe)||(Ge[fe]!==void 0?Se[fe]=Ge[fe]:se&&se[fe]!==void 0&&(Se[fe]=se[fe])),Se),{}),At={...en||{},...tn,...Object.keys(St||{}).length&&{mcp_meta_fields:St}};if(!Object.keys(At).length)return;await Ee(Me,{...ee,server_input:{...ee.server_input||{},...At}});try{await ir(ee.tool_id,ee.messageId,At),ot=!0}catch(Se){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Kt(Se)}`}}),pt="Tool call failed",Ee(Me,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Kt(Se)}`}})}}else{const xe=st?.id,Ge=xe?Object.entries(Qt).filter(([en,tn])=>{const[At]=en.split("::");return At===xe&&tn.active}):[],St=Ue??ee?.tool_result;await y.current?.sendMessage({message:R??"",files:C,audio:U,...Fe&&{initial_prompts:Fe},...Ne||Ge.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...St&&{tool_result:St}})}(R||C&&C.length>0||U?.audio||vt||pt)&&(c(xe=>{if(ot)return xe;const Ge=xe.length===0&&q?.text?[{id:"initial-bot-message",content:q.text,role:Ve.ASSISTANT,timestamp:Ht(Date.now()),isStored:!1}]:[];return[...xe,...Ge,{id:Date.now().toString(),content:vt||pt||R||"",files:C||[],audio:U,role:Ve.USER,timestamp:Ht(Date.now()),isStored:!1}]}),ot||oe(!0),ot=null);const Vr=G.getState().elicitationState,Nn=new Set;Me&&Nn.add(Me),st?.tool_keys?.forEach(xe=>Nn.add(xe)),Nn.forEach(xe=>{const Ge=Vr[xe];Ge&&Ee(xe,{...Ge,...zt&&{active:!1,disabled:!0},...xe===Me?{response_value:{...Ge?.response_value||{},label:vt||R||""}}:{}})})}catch{}}},Zt=R=>R.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(R.type)?($({title:`File type not supported: ${R.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):R.size>3*1024*1024?($({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,vn=async()=>{try{await y.current?.startRecording({onChunks:async R=>{K(be.PROCESSING),await yt({audio:R}),K(be.TRANSCRIBING)},onError(R){K(be.IDLE)}}),K(be.LISTENING)}catch(R){throw K(be.IDLE),R}},Jt=()=>{y.current?.endRecording()},ir=async(R,C,U)=>{try{if(!pe())throw new Error("Not connected to the server");await y.current?.callTool(R,C,U)}catch(X){throw X}},Sn=async()=>{Re(),await me(),await lt({forceNewSession:!0})},ar=()=>{Be(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),B(_e.NOT_CONNECTED),$({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},wn=async()=>{if(pe()){B(_e.CONNECTED);const R=d.current[d.current.length-1];if(R&&R.role===Ve.USER)try{y.current?.sendMessage({message:R.content,files:R.files||[],messageId:R.id,audio:R.audio})}catch{}}else if(B(_e.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:R}=G.getState();await Le(R)}else g.current===2?(g.current++,H(!0),$({title:"Trying to connect..."})):($({title:"Something went wrong!",description:"Please start a new chat."}),L(!0))};return{sendMessage:yt,startSession:lt,incomingMessages:a,loading:h,isLoadingSessionMessages:f,endSession:ct,isReady:b,startRecording:vn,stopRecording:Jt,getPastSessions:async()=>{try{const R=await y.current?.getPastSessions();return!R||!R?.data?.length?[]:R.data}catch{return[]}},handleRetry:wn,isValidFile:Zt,handleStartNewConnection:Sn,callTool:ir,handleInitialTaskClick:async R=>{const{message:C}=R;if(!q?.suggestions?.length||!C)return;const U=q.suggestions.find(X=>X.value===C);if(_.current=[{role:"assistant",text:`${q.text} ${U?.response||""}`}],!U||!U.response){await yt(R);return}c(X=>[...X,{id:Date.now().toString(),content:C,role:Ve.USER,timestamp:Ht(Date.now()),isStored:!1}]),oe(!0),await Ru(1e3),oe(!1),c(X=>[...X,{id:Date.now().toString(),content:U.response||"Please try again",role:Ve.ASSISTANT,timestamp:Ht(Date.now()),isStored:!1}])},sendMessageFeedback:async(R,C,U)=>{if(pe())try{await y.current?.sendMessageFeedback(C,R,U)}catch{}},sendSessionFeedback:async(R,C)=>{if(!(!pe()||!R?.length&&!C))try{await y.current?.sendSessionFeedback(R,C)}catch{}},clearElicitationState:async(R,C)=>{const U=G.getState().elicitationState,X=R?U[R]:void 0;try{await yt({message:C||"User aborted elicitation",tool_declined:!0,tool_result:X?.tool_result,tool_key:R})}catch{}finally{R&&X&&Ee(R,{...X,active:!1,disabled:!0})}}}};function ep(e){return e==="full"?M.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?M.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":M.SYNAPSE_CHANNELS?.WIDGET??"widget"}const tp=32,np=100,rp=320;function op(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function sp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=J(null),i=J(null),[s,a]=D(!1),c=J(null),d=J(!1),h=J("auto"),u=J(!0),f=ge(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=ge(b=>op()?"auto":b,[]),p=ge(b=>{const m=f();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(b)}),a(!1))},[f,E]),g=ge(b=>{d.current=!0,h.current=b,c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null,d.current&&(d.current=!1,p(h.current))}))},[p]);return z(()=>()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),d.current=!1},[]),z(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),z(()=>{if(!e||!u.current)return;const b=setTimeout(()=>g("auto"),rp);return()=>clearTimeout(b)},[r,e,g]),z(()=>{let b=!1,m=null,_=null,y=0;const k=()=>{if(b)return;const T=f(),S=i.current?.parentElement;if(!T||!S){requestAnimationFrame(k);return}const x=()=>{const{scrollTop:N,scrollHeight:A,clientHeight:Y}=T;return A-N-Y<=tp};u.current=!0;let v=0;const w=()=>{if(v>0){v--;return}u.current=x()};T.addEventListener("scroll",w,{passive:!0}),_=()=>T.removeEventListener("scroll",w),m=new ResizeObserver(()=>{if(!u.current)return;const N=Date.now();N-y<np||(y=N,v++,g("auto"))}),m.observe(S)};return k(),()=>{b=!0,m?.disconnect(),_?.()}},[f,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:p,scheduleScrollToBottom:g}}const qo="eka-medassist-agent-config",Hl="feedback_hidden",Xo="upfront_consent_accepted";function Zo(e,t){try{const n=localStorage.getItem(qo);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function Gl(e,t){try{const n=localStorage.getItem(qo),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(qo,JSON.stringify(r))}catch{}}function ip({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=Th(),d=()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()},h=r!==M.VOICE_AGENT_STATE.IDLE,[u,f]=D(""),[E,p]=D(!1),g=G(ne=>ne.setDisplayMode),[b,m]=D(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),_=()=>m(ne=>ne==="full"?"widget":"full"),y=Il()?"mobile":b,k=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),T=Math.min(Math.max(n.sidePanelWidth??Oh,Ah),Ih),S=n.sidePanelMode??"push",[x,v]=D([]),w=J(!1),[N,A]=D(!1),[Y,q]=D(!1),[ae,de]=D(()=>!!n.theme?.upfrontConsent&&!Zo(t,Xo)),le=J(null),{setAgentId:ue,startNewConnection:F,showRetryButton:Ce,clearError:$,error:B,connectionStatus:H,recordingStatus:L,isWaitingForResponse:W,isStreaming:oe,setError:je,sessionId:K,setContext:me,initialMessage:Be,setInitialMessage:ze,sessionInitialMessages:tt,setInitialDisplayMode:Xe,clearSession:ht}=G(),Et=G(ne=>ne.elicitationState),mt=G(ne=>ne.level),{incomingMessages:P,loading:Ee,isLoadingSessionMessages:ve,sendMessage:ke,handleInitialTaskClick:Ze,startSession:Le,isReady:Ie,startRecording:lt,stopRecording:pe,handleRetry:ct,isValidFile:Re,sendMessageFeedback:He,clearElicitationState:nt,sendSessionFeedback:yt,getPastSessions:Zt}=Qm({environment:n.environment,connectionType:n.connectionType,baseUrl:n.baseUrl?n.baseUrl:void 0,context:n?.context,...n?.authToken&&{authToken:n.authToken},...n?.force&&{force:n.force},channel:ep(n.displayMode)}),[vn,Jt]=D(!1),[ir,Sn]=D([]),[ar,wn]=D(!0),R=J(Zt);z(()=>{R.current=Zt});const C=ge(async()=>{wn(!0);try{const ne=await R.current();Sn(ne)}catch{}finally{wn(!1)}},[]),U=ge(async()=>{Jt(!0),await C()},[C]),X=ge(()=>{Jt(!1)},[]),[se,re]=D(!1),Ne=ge(()=>re(ne=>!ne),[]);z(()=>{y!=="full"||mt!=="user"||C()},[y,mt,K,C]),z(()=>{t&&(le.current!==t&&(Sh(t),wh(t),ue(t),n.force&&ht(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(g(n.displayMode),Xe(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&me(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&ze(n.initialMessage),le.current=t),e&&Ie&&!w.current&&(w.current=!0,Le({forceNewSession:!1})))},[e,Ie,t]),z(()=>{cm([Pl])},[]),z(()=>()=>{s()},[]),z(()=>{!n.theme?.upfrontConsent||!t||Zo(t,Xo)||de(!0)},[n.theme?.upfrontConsent,t]);const Ue=ge(()=>{Gl(t,Xo),de(!1)},[t]),rt=()=>{n.feedback&&!Zo(t,Hl)?q(!0):n.onClose()},Qt=async(ne,Te)=>{await yt(ne,Te),q(!1),n.onClose()},Vt=()=>{q(!1),n.onClose()},Fe=()=>{Gl(t,Hl),q(!1),n.onClose()},ot=()=>{q(!1)},pt=P.length>0,Ot=P.length===1,st=ye(()=>{const ne=P[P.length-1],Te=ne?.tool_keys?.[ne.tool_keys.length-1];if(!Te)return null;const We=Et[Te];return We?.active?{...We,tool_key:Te}:null},[P,Et]),Oe=ye(()=>(K?tt[K]:void 0)??Be??n?.initialMessage??null,[K,tt,Be,n?.initialMessage]),Me=ye(()=>!!Oe?.text||!!Oe?.suggestions?.length,[Oe]),ee=ye(()=>Me&&P?.length===0&&!ve,[P,Me,ve]),jt=ye(()=>st?st.component===M.SYNAPSE_COMPONENTS.MOBILE||st.component===M.SYNAPSE_COMPONENTS.OTP||st.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[st]),{scrollAreaRef:zt,messagesEndRef:bt,showScrollButton:vt,scrollToBottom:Vr}=sp({messageCount:P.length,isStreaming:oe,isFirstMessage:Ot,resolvedMode:y}),Nn=H===_e.CONNECTED,xe=W||oe,Ge=ye(()=>L===be.IDLE?null:L===be.LISTENING?"Listening...":L===be.PROCESSING?"Processing...":L===be.TRANSCRIBING?"Transcribing...":null,[L]),St=Ge&&L!==be.IDLE?Ge:W||oe?"Please wait for the response...":"Type a reply\u2026",en=async(ne,Te)=>{if(xe)return;const We=Te?Ze:ke,nn=ne?.message??u;x.length>0?(await We({files:x,message:nn.trim()}),v([]),A(!1)):nn.trim()?await We({...ne,message:nn.trim()}):ne?.resend?await We(ne):ne&&await We(ne),f(""),p(!1),A(!1)},tn=ne=>{if(ne&&ne.length>0){const Te=ne.filter(We=>!!Re(We));if(Te?.length+x.length>3){je({title:"You can only upload up to 3 files at a time",description:"Please remove some files and try again."});return}if(Te?.length>0&&Te.reduce((We,nn)=>We+nn.size,0)>10*1024*1024){je({title:`Total file size limit of ${Rh} MB exceeded`,description:"Please reduce the size of the files or try again with less files"});return}if(Te?.length>0)ne=Te;else return}v(Te=>(A((Te?.length??0)+(ne?.length??0)>0),[...Te,...ne]))},At=ne=>{v(Te=>{const We=Te.filter((nn,Sc)=>Sc!==ne);return A(We.length>0),We})},Se=async()=>{if(E)await pe(),p(!1);else{if(xe)return;try{await lt(),p(!0)}catch{}}},fe={value:u,onChange:f,onSend:en,onFileChange:tn,onRemoveFile:At,onRecording:Se,isRecording:E,hasAttachment:N,attachmentFiles:x,isDisabled:xe,placeholder:St,recordingStatus:L,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d};return{inputValue:u,setInputValue:f,isRecording:E,hasAttachment:N,attachmentFiles:x,showScrollButton:vt,displayMode:b,setDisplayMode:m,toggleDisplayMode:_,resolvedMode:y,currentDisplayMode:b,setCurrentDisplayMode:m,sidePanelMode:S,sidePanelWidth:T,side:k,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:zt,messagesEndRef:bt,startNewConnection:F,showRetryButton:Ce,clearError:$,error:B,connectionStatus:H,isStreaming:oe,sessionId:K,activeElicitation:st,inConversation:pt,isFirstMessage:Ot,isEmptyChat:ee,isAuthComponent:jt,isConnected:Nn,isComposerDisabled:xe,loading:Ee,isLoadingSessionMessages:ve,initialMessage:Oe,incomingMessages:P,sendMessage:ke,startSession:Le,sendMessageFeedback:He,clearElicitationState:nt,handleRetry:ct,handleSendMessage:en,handleFileChange:tn,handleRemoveFile:At,handleRecording:Se,scrollToBottom:Vr,handleClose:rt,showFeedbackModal:Y,handleSessionFeedbackSubmit:Qt,handleSessionFeedbackSkip:Vt,handleDontShowAgain:Fe,handleCloseModal:ot,showConsentModal:ae,handleConsentAccept:Ue,chatComposerProps:fe,isSessionDrawerOpen:vn,pastSessions:ir,isLoadingPastSessions:ar,openSessionDrawer:U,closeSessionDrawer:X,refreshPastSessions:C,userLevel:mt,isSidebarCollapsed:se,toggleSidebar:Ne,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,connectVoiceAgent:i,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c,handleVoiceAgentClick:d}}function qt(){return qt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},qt.apply(this,arguments)}const ap=["children","options"],Wl=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce((e,t)=>(e[t.toLowerCase()]=t,e),{class:"className",for:"htmlFor"}),Kl={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},lp=["style","script","pre"],cp=["src","href","data","formAction","srcDoc","action"],dp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,up=/\n{2,}$/,ql=/^(\s*>[\s\S]*?)(?=\n\n|$)/,hp=/^ *> ?/gm,mp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,pp=/^ {2,}\n/,fp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Xl=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Zl=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,gp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,_p=/^(?:\n *)*\n/,Ep=/\r\n?/g,yp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,bp=/^\[\^([^\]]+)]/,vp=/\f/g,Sp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,wp=/^\s*?\[(x|\s)\]/,Jl=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Ql=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,ec=/^([^\n]+)\n *(=|-)\2{2,} *\n/,Jo=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Np=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,tc=/^<!--[\s\S]*?(?:-->)/,xp=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,Qo=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Cp=/^\{.*\}$/,Tp=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,kp=/^<([^ >]+[:@\/][^ >]+)>/,Rp=/-([a-z])?/gi,nc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,Op=/^[^\n]+(?: \n|\n{2,})/,Ap=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,Ip=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Mp=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Pp=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Dp=/\t/g,Lp=/(^ *\||\| *$)/g,Up=/^ *:-+: *$/,Fp=/^ *:-+ *$/,Vp=/^ *-+: *$/,Ir=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Mr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",jp=RegExp(`^([*_])\\1${Ir(1)}${Mr}\\1\\1(?!\\1)`),zp=RegExp(`^([*_])${Ir(0)}${Mr}\\1(?!\\1)`),$p=RegExp(`^(==)${Ir(0)}${Mr}\\1`),Yp=RegExp(`^(~~)${Ir(0)}${Mr}\\1`),Bp=/^(:[a-zA-Z0-9-_]+:)/,Hp=/^\\([^0-9A-Za-z\s])/,Gp=/\\([^0-9A-Za-z\s])/g,Wp=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Kp=/^\n+/,qp=/^([ \t]*)/,Xp=/(?:^|\n)( *)$/,es="(?:\\d+\\.)",ts="(?:[*+-])";function rc(e){return"( *)("+(e===1?es:ts)+") +"}const oc=rc(1),sc=rc(2);function ic(e){return RegExp("^"+(e===1?oc:sc))}const Zp=ic(1),Jp=ic(2);function ac(e){return RegExp("^"+(e===1?oc:sc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?es:ts)+" )[^\\n]*)*(\\n|$)","gm")}const Qp=ac(1),ef=ac(2);function lc(e){const t=e===1?es:ts;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const cc=lc(1),dc=lc(2);function uc(e,t){const n=t===1,r=n?cc:dc,o=n?Qp:ef,i=n?Zp:Jp;return{t:s=>i.test(s),o:bn(function(s,a){const c=Xp.exec(a.prevCapture);return c&&(a.list||!a.inline&&!a.simple)?r.exec(s=c[1]+s):null}),i:1,u(s,a,c){const d=n?+s[2]:void 0,h=s[0].replace(up,`
41
- `).match(o);let u=!1;return{items:h.map(function(f,E){const p=i.exec(f)[0].length,g=RegExp("^ {1,"+p+"}","gm"),b=f.replace(g,"").replace(i,""),m=E===h.length-1,_=b.indexOf(`
40
+ `:"";return Ke[Ke.length-1]={...ve,content:ve.content+It+P},Ke}else return[...pe,{id:G,content:P,role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}]})}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{b.current=!1,Ee(!1),se(null),Ne(!1)}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{Ie(),H(ge.CONNECTED),Yr(),lt()}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,C=>{b.current=!0;const w=C;if(!w?.messageId||!w?.data||!w?.data?.details?.component||!w?.data?.tool_id)return;J&&Ne(!1);const{messageId:P,data:G}=w,X=G.tool_id,Z=`${P}::${X}`,pe=W.getState().elicitationState[Z],ve=G.details?.component,Ke=w?.data?.details?._meta?.tool_result,It=G.details?.input,$t=rp(pe?.input,It,ve);let Ye=w.data.details?._meta?.disp_toast_msg;const Qe=G?.details?._meta?.schema?.required||[];switch(G?.details?.status){case I.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Ve=w?.data?.details?.input||{},je=Qe.reduce((gt,vt)=>(Ve[vt]!==void 0&&(gt[vt]=Ve[vt]),gt),{}),ee={...pe?.server_input||{},...je},Mt=Qe.filter(gt=>!ee[gt]),Pt=w.data.details?._meta?.mcp_meta_fields||[];le(Z,{tool_id:X,active:!0,disabled:!1,input:$t,server_input:ee,messageId:P,required:Qe,component:ve,pattern:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.pattern,minLength:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.minLength,maxLength:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.maxLength,type:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.type,disp_toast_msg:w.data.details?._meta?.disp_toast_msg,description:w.data.details?._meta?.schema?.properties?.[w.data.details?.component]?.description,tool_result:Ke,orientation:w.data.details?._meta?.orientation,...Pt.length&&{mcp_meta_fields:Pt},...Mt?{toolSelectionNames:Mt}:{},...pe?.hide_show_more!==void 0?{hide_show_more:pe.hide_show_more}:{}});break}case I.SYNAPSE_EICITATION_STATUS.SUCCESS:{le(Z,{...pe||{},tool_id:X,disabled:!0,active:Vu(ve),messageId:P,component:ve,input:$t,tool_result:Ke,send_to_llm:!0});break}case I.SYNAPSE_EICITATION_STATUS.FAILURE:{le(Z,{...pe||{},tool_id:X,active:!1,messageId:P,response_value:{label:G?.details?._meta?.disp_message||"Tool call failed"},tool_result:Ke,disabled:!0});break}default:le(Z,{tool_id:X,disabled:!1,active:!1,messageId:P,tool_result:Ke,input:$t,component:ve})}Ye&&Oe(Ye);const pt=w?.data?.details?._meta?.user_hint;c(Ve=>{let je=Ve[Ve.length-1]?.id===P?Ve.length-1:Ve.findIndex?.(ee=>ee.id===P);if(je==-1){const ee={id:P,content:w.data?.details?.input?.text||"",role:Pe.ASSISTANT,tool_keys:[Z],isResponseFromTool:!0,isStored:!1,...pt?{userHint:pt}:{}};return[...Ve,ee]}else{const ee={...Ve[je],isResponseFromTool:!0,tool_keys:[...new Set([...Ve[je].tool_keys||[],Z])],...pt?{userHint:pt}:{}};Ve[je]=ee,mt(A,P,ee)}return[...Ve]});const Ht=w?.data?.details?._meta?.disp_message,ft=W.getState().elicitationState;if((!ft[Z]?.active||ft[Z]?.send_to_llm)&&(Ht||Object.keys(Ke||{}).length))try{Yt({message:Ht||"",tool_result:Ke,toolCalled:!0,tool_key:Z})}catch{}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,C=>{if(C?.reason===I.DisconnectionReason.CLIENT_CLOSED)return;const w=C;ct(ht.CONNECTION_FAILED,{reason:w?.reason??"unknown",...typeof w?.code=="number"&&{closeCode:w.code}}),T.current=performance.now();const P=typeof navigator<"u"&&!navigator.onLine;if(H(ge.NOT_CONNECTED),P){V({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),D(!1);return}g.current<2?(g.current=g.current+1,D(!0),V({title:"Something went wrong!",description:"Please try again."})):(V({title:"Something went wrong!",description:"Please start a new Chat."}),B(!0))}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.ERROR,C=>{const w=C?.data?.code;switch(zr(w),w){case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:B(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:V({title:"Session not found",description:"Please start a new chat from onError callback"}),B(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:bn();return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_EVENT:return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_CONTENT_TYPE:return;case I.SYNAPSE_REALTIME_ERROR_CODES.PARSING_ERROR:if(g.current<1){g.current++,cr();return}V({title:"Error parsing request",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:V({title:"Request timed out",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;case I.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return;default:V({title:"Something went wrong",description:"please try again"}),D(!0),ne(Se.IDLE);return}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async C=>{const w=C;w?.data?.text&&(c(P=>[...P,{id:Date.now().toString(),content:w.data.text||"",role:Pe.USER,timestamp:Kt(Date.now()),isStored:!0}]),ne(Se.IDLE)),Ee(!1),Ne(!1),se(null)}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,C=>{b.current=!0;const w=C;w.data?.text&&(Ne(!1),se(w.data.text))}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_START,C=>{b.current=!0;const w=C;if(w.data?.name&&w.messageId){const P=w.messageId;c(G=>{const X=G[G.length-1];if(X&&X.id===P&&X.role===Pe.ASSISTANT){const Z=[...G];return Z[Z.length-1]={...X,toolCallStatus:`Calling tool: ${w.data.name}...`},A&&mt(A,P,{toolCallStatus:`Calling tool: ${w.data.name}...`}),Z}return G})}}),y.current?.on(I.SYNAPSE_REALTIME_EVENTS.TOOL_END,C=>{b.current=!0;const w=C;if(w.data?.name&&w.messageId){const P=w.messageId;c(G=>{const X=G[G.length-1];if(X&&X.id===P&&X.role===Pe.ASSISTANT){const Z=[...G];return Z[Z.length-1]={...X,toolCallStatus:"Tool call completed."},A&&mt(A,P,{toolCallStatus:"Tool call completed."}),Z}return G})}})},Yt=async({message:C,files:w,audio:P,toolCalled:G,selectedComponent:X,resend:Z,tool_declined:pe,tool_result:ve,tool_key:Ke})=>{const It=W.getState().elicitationState,$t=Object.values(It).some(Ye=>Ye.active);if(!(!G&&(!w||w.length===0)&&!C?.trim()&&!P?.audio&&!X&&!$t&&!ve&&!Object.keys(ve||{}).length)){if(w&&w.length>3){V({title:"Maximum 3 files are allowed to be sent at a time",description:"Please try again"});return}if(w&&w.length>0&&w.reduce((Ye,Qe)=>Ye+Qe.size,0)>10*1024*1024){V({title:"Total file size limit of 10MB exceeded",description:"Please reduce the size of the files or try again with less files"});return}if(w&&w.length>0&&w.length+ie>Ho){const Ye=Ho-ie;V({title:`You can only upload up to ${Ho} files per session`,description:`${Ye<=0?"Maximum file upload limit reached":`You have ${Ye} file${Ye===1?"":"s"} upload${Ye===1?"":"s"} left`}`});return}else w&&w.length&&L(ie+w.length);V(null),D(!1),De()&&H(ge.CONNECTED);try{const Ye=a.length<=2&&_.current.length==1?_.current:null;let Qe=null,pt=null;const Ht=a.length-1,ft=Ht>=0?a[Ht]:null,Ve=W.getState().elicitationState,je=Ke||null,ee=je?Ve[je]:void 0,Mt=ee?.component===I.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===I.SYNAPSE_COMPONENTS.CARD?!!ee&&!ve&&!!ee.active:!!ee?.active,Pt=!!(w||[]).length||!!P?.audio||!!pe||!Mt||!G,gt=X?X.label:void 0,vt=ee?.component===I.SYNAPSE_COMPONENTS.PILL&&typeof gt=="string"?gt:null;if(!Pt&&Mt&&je&&ee?.messageId){const ae=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(ke=>!ee.server_input?.[ke])??[],Le=ae.reduce((ke,be)=>{if(X){const Nn=X[be];Nn!==void 0&&(ke[be]=Nn)}else ae.length===1&&(ke[be]=C);return ke},{}),bt=ee.mcp_meta_fields?.reduce((ke,be)=>(ae.includes(be)?ke[be]=Le[be]:ee.server_input?.[be]&&(ke[be]=ee.server_input[be]),Z&&!ke.is_resend&&(ke.is_resend=Z),ke),{}),Wr=Object.keys(ee.server_input||{})?.reduce((ke,be)=>{const Nn=!Object.keys(bt||{})?.includes(be),gs=!!ee.server_input?.[be];return(Z?Nn&&gs:Nn&&ee.required?.includes(be)&&gs)&&(ke[be]=ee.server_input?.[be]),ke},{}),Kr=Z?{}:(ee.required||ae).reduce((ke,be)=>(Object.keys(bt||{}).includes(be)||(Le[be]!==void 0?ke[be]=Le[be]:X&&X[be]!==void 0&&(ke[be]=X[be])),ke),{}),wn={...Wr||{},...Kr,...Object.keys(bt||{}).length&&{mcp_meta_fields:bt}};if(!Object.keys(wn).length)return;await le(je,{...ee,server_input:{...ee.server_input||{},...wn}});try{await ar(ee.tool_id,ee.messageId,wn),Qe=!0}catch(ke){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Jt(ke)}`}}),pt="Tool call failed",le(je,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Jt(ke)}`}})}}else{const ae=ft?.id,Le=ae?Object.entries(It).filter(([Wr,Kr])=>{const[wn]=Wr.split("::");return wn===ae&&Kr.active}):[],bt=ve??ee?.tool_result;await y.current?.sendMessage({message:C??"",files:w,audio:P,...Ye&&{initial_prompts:Ye},...pe||Le.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...bt&&{tool_result:bt}})}(C||w&&w.length>0||P?.audio||vt||pt)&&(Qe||Sn(),c(ae=>{if(Qe)return ae;const Le=ae.length===0&&oe?.text?[{id:nc,content:oe.text,role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}]:[];return[...ae,...Le,{id:Date.now().toString(),content:vt||pt||C||"",files:w||[],audio:P,role:Pe.USER,timestamp:Kt(Date.now()),isStored:!1}]}),Qe||Ne(!0),Qe=null);const re=W.getState().elicitationState,Ce=new Set;je&&Ce.add(je),ft?.tool_keys?.forEach(ae=>Ce.add(ae)),Ce.forEach(ae=>{const Le=re[ae];Le&&le(ae,{...Le,...Pt&&{active:!1,disabled:!0},...ae===je?{response_value:{...Le?.response_value||{},label:vt||C||""}}:{}})})}catch{}}},Hr=C=>C.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(C.type)?(V({title:`File type not supported: ${C.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):C.size>3*1024*1024?(V({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,Br=async()=>{try{await y.current?.startRecording({onChunks:async C=>{ne(Se.PROCESSING),await Yt({audio:C}),ne(Se.TRANSCRIBING)},onError(C){ne(Se.IDLE)}}),ne(Se.LISTENING)}catch(C){throw ne(Se.IDLE),C}},Gr=()=>{y.current?.endRecording()},ar=async(C,w,P)=>{try{if(!De())throw new Error("Not connected to the server");await y.current?.callTool(C,w,P)}catch(G){throw G}},bn=async()=>{Ie(),await $e(),await Ae({forceNewSession:!0})},lr=()=>{Ge(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),H(ge.NOT_CONNECTED),V({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},cr=async()=>{if(De()){H(ge.CONNECTED);const C=d.current[d.current.length-1];if(C&&C.role===Pe.USER)try{y.current?.sendMessage({message:C.content,files:C.files||[],messageId:C.id,audio:C.audio})}catch{}}else if(H(ge.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:C}=W.getState();await xe(C)}else g.current===2?(g.current++,D(!0),V({title:"Trying to connect..."})):(V({title:"Something went wrong!",description:"Please start a new chat."}),B(!0))};return{sendMessage:Yt,startSession:Ae,incomingMessages:a,loading:h,isLoadingSessionMessages:f,endSession:Ue,isReady:S,startRecording:Br,stopRecording:Gr,getPastSessions:async()=>{try{const C=await y.current?.getPastSessions();return!C||!C?.data?.length?[]:C.data}catch{return[]}},handleRetry:cr,isValidFile:Hr,handleStartNewConnection:bn,callTool:ar,handleInitialTaskClick:async C=>{const{message:w}=C;if(!oe?.suggestions?.length||!w)return;const P=oe.suggestions.find(X=>X.value===w);if(_.current=[{role:"assistant",text:`${oe.text} ${P?.response||""}`}],!P||!P.response){await Yt(C);return}Sn(),c(X=>[...X,{id:Date.now().toString(),content:w,role:Pe.USER,timestamp:Kt(Date.now()),isStored:!1}]),Ne(!0),await ju(1e3),Ne(!1);const G=Date.now().toString();vn(G),c(X=>[...X,{id:G,content:P.response||"Please try again",role:Pe.ASSISTANT,timestamp:Kt(Date.now()),isStored:!1}])},sendMessageFeedback:async(C,w,P)=>{if(De())try{await y.current?.sendMessageFeedback(w,C,P)}catch{}},sendSessionFeedback:async(C,w)=>{if(!(!De()||!C?.length&&!w))try{await y.current?.sendSessionFeedback(C,w)}catch{}},clearElicitationState:async(C,w)=>{const P=W.getState().elicitationState,G=C?P[C]:void 0;try{await Yt({message:w||"User aborted elicitation",tool_declined:!0,tool_result:G?.tool_result,tool_key:C})}catch{}finally{C&&G&&le(C,{...G,active:!1,disabled:!0})}},notifyTypingStarted:$r}};function dp(e){return e==="full"?I.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?I.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":I.SYNAPSE_CHANNELS?.WIDGET??"widget"}const up=32,hp=100,mp=320;function pp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function fp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=q(null),i=q(null),[s,a]=F(!1),c=q(null),d=q(!1),h=q("auto"),u=q(!0),f=fe(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),E=fe(S=>pp()?"auto":S,[]),p=fe(S=>{const m=f();m&&(m.scrollTo({top:m.scrollHeight,behavior:E(S)}),a(!1))},[f,E]),g=fe(S=>{d.current=!0,h.current=S,c.current===null&&(c.current=requestAnimationFrame(()=>{c.current=null,d.current&&(d.current=!1,p(h.current))}))},[p]);return Y(()=>()=>{c.current!==null&&(cancelAnimationFrame(c.current),c.current=null),d.current=!1},[]),Y(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),Y(()=>{if(!e||!u.current)return;const S=setTimeout(()=>g("auto"),mp);return()=>clearTimeout(S)},[r,e,g]),Y(()=>{let S=!1,m=null,_=null,y=0;const k=()=>{if(S)return;const T=f(),x=i.current?.parentElement;if(!T||!x){requestAnimationFrame(k);return}const N=()=>{const{scrollTop:R,scrollHeight:A,clientHeight:$}=T;return A-R-$<=up};u.current=!0;let v=0;const b=()=>{if(v>0){v--;return}u.current=N()};T.addEventListener("scroll",b,{passive:!0}),_=()=>T.removeEventListener("scroll",b),m=new ResizeObserver(()=>{if(!u.current)return;const R=Date.now();R-y<hp||(y=R,v++,g("auto"))}),m.observe(x)};return k(),()=>{S=!0,m?.disconnect(),_?.()}},[f,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:p,scheduleScrollToBottom:g}}const os="eka-medassist-agent-config",rc="feedback_hidden",ss="upfront_consent_accepted";function is(e,t){try{const n=localStorage.getItem(os);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function oc(e,t){try{const n=localStorage.getItem(os),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(os,JSON.stringify(r))}catch{}}function gp({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=Uh(),d=()=>{r===I.VOICE_AGENT_STATE.IDLE&&i()},h=r!==I.VOICE_AGENT_STATE.IDLE,[u,f]=F(""),[E,p]=F(!1),g=W(re=>re.setDisplayMode),[S,m]=F(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),_=()=>m(re=>re==="full"?"widget":"full"),y=Yl()?"mobile":S,k=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),T=Math.min(Math.max(n.sidePanelWidth??zh,Yh),$h),x=n.sidePanelMode??"push",[N,v]=F([]),b=q(!1),[R,A]=F(!1),[$,J]=F(!1),[oe,_e]=F(()=>!!n.theme?.upfrontConsent&&!is(t,ss)),ie=q(null),{setAgentId:he,startNewConnection:U,showRetryButton:Te,clearError:de,error:V,connectionStatus:H,recordingStatus:D,isWaitingForResponse:B,isStreaming:Ee,setError:Ne,sessionId:se,setContext:ne,initialMessage:$e,setInitialMessage:Ge,sessionInitialMessages:We,setInitialDisplayMode:Je,clearSession:Ot}=W(),mt=W(re=>re.elicitationState),it=W(re=>re.level),{incomingMessages:L,loading:Oe,isLoadingSessionMessages:le,sendMessage:Re,handleInitialTaskClick:Ze,notifyTypingStarted:rt,startSession:xe,isReady:at,startRecording:Ae,stopRecording:De,handleRetry:Ue,isValidFile:Ie,sendMessageFeedback:lt,clearElicitationState:en,sendSessionFeedback:yn,getPastSessions:St}=cp({environment:n.environment,connectionType:n.connectionType,baseUrl:n.baseUrl?n.baseUrl:void 0,context:n?.context,...n?.authToken&&{authToken:n.authToken},...n?.force&&{force:n.force},channel:dp(n.displayMode)}),[ct,ir]=F(!1),[zr,Yr]=F([]),[$r,Sn]=F(!0),vn=q(St);Y(()=>{vn.current=St});const At=fe(async()=>{Sn(!0);try{const re=await vn.current();Yr(re)}catch{}finally{Sn(!1)}},[]),Yt=fe(async()=>{ir(!0),await At()},[At]),Hr=fe(()=>{ir(!1)},[]),[Br,Gr]=F(!1),ar=fe(()=>Gr(re=>!re),[]);Y(()=>{y!=="full"||it!=="user"||At()},[y,it,se,At]),Y(()=>{t&&(ie.current!==t&&(Mh(t),Ph(t),he(t),n.force&&Ot(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(g(n.displayMode),Je(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&ne(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&Ge(n.initialMessage),ie.current=t),e&&at&&!b.current&&(b.current=!0,xe({forceNewSession:!1})))},[e,at,t]),Y(()=>{Sm([Hl])},[]),Y(()=>()=>{s()},[]),Y(()=>{!n.theme?.upfrontConsent||!t||is(t,ss)||_e(!0)},[n.theme?.upfrontConsent,t]);const bn=fe(()=>{oc(t,ss),_e(!1)},[t]),lr=()=>{n.feedback&&!is(t,rc)?J(!0):n.onClose()},cr=async(re,Ce)=>{await yn(re,Ce),J(!1),n.onClose()},C=()=>{J(!1),n.onClose()},w=()=>{oc(t,rc),J(!1),n.onClose()},P=()=>{J(!1)},G=L.length>0,X=L.length===1,Z=ye(()=>{const re=L[L.length-1],Ce=re?.tool_keys?.[re.tool_keys.length-1];if(!Ce)return null;const ae=mt[Ce];return ae?.active?{...ae,tool_key:Ce}:null},[L,mt]),pe=ye(()=>(se?We[se]:void 0)??$e??n?.initialMessage??null,[se,We,$e,n?.initialMessage]),ve=ye(()=>!!pe?.text||!!pe?.suggestions?.length,[pe]),Ke=ye(()=>ve&&L?.length===0&&!le,[L,ve,le]),It=ye(()=>Z?Z.component===I.SYNAPSE_COMPONENTS.MOBILE||Z.component===I.SYNAPSE_COMPONENTS.OTP||Z.component===I.SYNAPSE_COMPONENTS.EMAIL:!1,[Z]),{scrollAreaRef:$t,messagesEndRef:Ye,showScrollButton:Qe,scrollToBottom:pt}=fp({messageCount:L.length,isStreaming:Ee,isFirstMessage:X,resolvedMode:y}),Ht=H===ge.CONNECTED,ft=B||Ee,Ve=ye(()=>D===Se.IDLE?null:D===Se.LISTENING?"Listening...":D===Se.PROCESSING?"Processing...":D===Se.TRANSCRIBING?"Transcribing...":null,[D]),je=Ve&&D!==Se.IDLE?Ve:B||Ee?"Please wait for the response...":"Type a reply\u2026",ee=async(re,Ce)=>{if(ft)return;const ae=Ce?Ze:Re,Le=re?.message??u;N.length>0?(await ae({files:N,message:Le.trim()}),v([]),A(!1)):Le.trim()?await ae({...re,message:Le.trim()}):re?.resend?await ae(re):re&&await ae(re),f(""),p(!1),A(!1)},Mt=re=>{if(re&&re.length>0){const Ce=re.filter(ae=>!!Ie(ae));if(Ce?.length+N.length>3){Ne({title:"You can only upload up to 3 files at a time",description:"Please remove some files and try again."});return}if(Ce?.length>0&&Ce.reduce((ae,Le)=>ae+Le.size,0)>10*1024*1024){Ne({title:`Total file size limit of ${jh} MB exceeded`,description:"Please reduce the size of the files or try again with less files"});return}if(Ce?.length>0)re=Ce;else return}v(Ce=>(A((Ce?.length??0)+(re?.length??0)>0),[...Ce,...re]))},Pt=re=>{v(Ce=>{const ae=Ce.filter((Le,bt)=>bt!==re);return A(ae.length>0),ae})},gt=async()=>{if(E)await De(),p(!1);else{if(ft)return;try{await Ae(),p(!0)}catch{}}},vt={value:u,onChange:re=>{re.trim()&&rt(),f(re)},onSend:ee,onFileChange:Mt,onRemoveFile:Pt,onRecording:gt,isRecording:E,hasAttachment:R,attachmentFiles:N,isDisabled:ft,placeholder:je,recordingStatus:D,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d};return{inputValue:u,setInputValue:f,isRecording:E,hasAttachment:R,attachmentFiles:N,showScrollButton:Qe,displayMode:S,setDisplayMode:m,toggleDisplayMode:_,resolvedMode:y,currentDisplayMode:S,setCurrentDisplayMode:m,sidePanelMode:x,sidePanelWidth:T,side:k,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:$t,messagesEndRef:Ye,startNewConnection:U,showRetryButton:Te,clearError:de,error:V,connectionStatus:H,isStreaming:Ee,sessionId:se,activeElicitation:Z,inConversation:G,isFirstMessage:X,isEmptyChat:Ke,isAuthComponent:It,isConnected:Ht,isComposerDisabled:ft,loading:Oe,isLoadingSessionMessages:le,initialMessage:pe,incomingMessages:L,sendMessage:Re,startSession:xe,sendMessageFeedback:lt,clearElicitationState:en,handleRetry:Ue,handleSendMessage:ee,handleFileChange:Mt,handleRemoveFile:Pt,handleRecording:gt,scrollToBottom:pt,handleClose:lr,showFeedbackModal:$,handleSessionFeedbackSubmit:cr,handleSessionFeedbackSkip:C,handleDontShowAgain:w,handleCloseModal:P,showConsentModal:oe,handleConsentAccept:bn,chatComposerProps:vt,isSessionDrawerOpen:ct,pastSessions:zr,isLoadingPastSessions:$r,openSessionDrawer:Yt,closeSessionDrawer:Hr,refreshPastSessions:At,userLevel:it,isSidebarCollapsed:Br,toggleSidebar:ar,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,connectVoiceAgent:i,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c,handleVoiceAgentClick:d}}function Zt(){return Zt=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Zt.apply(this,arguments)}const _p=["children","options"],sc=["allowFullScreen","allowTransparency","autoComplete","autoFocus","autoPlay","cellPadding","cellSpacing","charSet","classId","colSpan","contentEditable","contextMenu","crossOrigin","encType","formAction","formEncType","formMethod","formNoValidate","formTarget","frameBorder","hrefLang","inputMode","keyParams","keyType","marginHeight","marginWidth","maxLength","mediaGroup","minLength","noValidate","radioGroup","readOnly","rowSpan","spellCheck","srcDoc","srcLang","srcSet","tabIndex","useMap"].reduce((e,t)=>(e[t.toLowerCase()]=t,e),{class:"className",for:"htmlFor"}),ic={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Ep=["style","script","pre"],yp=["src","href","data","formAction","srcDoc","action"],Sp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,vp=/\n{2,}$/,ac=/^(\s*>[\s\S]*?)(?=\n\n|$)/,bp=/^ *> ?/gm,wp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Np=/^ {2,}\n/,xp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,lc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,cc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Cp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,Tp=/^(?:\n *)*\n/,kp=/\r\n?/g,Rp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,Op=/^\[\^([^\]]+)]/,Ap=/\f/g,Ip=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,Mp=/^\s*?\[(x|\s)\]/,dc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,uc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,hc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,as=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Pp=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,mc=/^<!--[\s\S]*?(?:-->)/,Dp=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,ls=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Lp=/^\{.*\}$/,Fp=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,Up=/^<([^ >]+[:@\/][^ >]+)>/,Vp=/-([a-z])?/gi,pc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,jp=/^[^\n]+(?: \n|\n{2,})/,zp=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,Yp=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,$p=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Hp=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Bp=/\t/g,Gp=/(^ *\||\| *$)/g,Wp=/^ *:-+: *$/,Kp=/^ *:-+ *$/,qp=/^ *-+: *$/,Pr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Dr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Xp=RegExp(`^([*_])\\1${Pr(1)}${Dr}\\1\\1(?!\\1)`),Jp=RegExp(`^([*_])${Pr(0)}${Dr}\\1(?!\\1)`),Zp=RegExp(`^(==)${Pr(0)}${Dr}\\1`),Qp=RegExp(`^(~~)${Pr(0)}${Dr}\\1`),ef=/^(:[a-zA-Z0-9-_]+:)/,tf=/^\\([^0-9A-Za-z\s])/,nf=/\\([^0-9A-Za-z\s])/g,rf=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,of=/^\n+/,sf=/^([ \t]*)/,af=/(?:^|\n)( *)$/,cs="(?:\\d+\\.)",ds="(?:[*+-])";function fc(e){return"( *)("+(e===1?cs:ds)+") +"}const gc=fc(1),_c=fc(2);function Ec(e){return RegExp("^"+(e===1?gc:_c))}const lf=Ec(1),cf=Ec(2);function yc(e){return RegExp("^"+(e===1?gc:_c)+"[^\\n]*(?:\\n(?!\\1"+(e===1?cs:ds)+" )[^\\n]*)*(\\n|$)","gm")}const df=yc(1),uf=yc(2);function Sc(e){const t=e===1?cs:ds;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const vc=Sc(1),bc=Sc(2);function wc(e,t){const n=t===1,r=n?vc:bc,o=n?df:uf,i=n?lf:cf;return{t:s=>i.test(s),o:En(function(s,a){const c=af.exec(a.prevCapture);return c&&(a.list||!a.inline&&!a.simple)?r.exec(s=c[1]+s):null}),i:1,u(s,a,c){const d=n?+s[2]:void 0,h=s[0].replace(vp,`
41
+ `).match(o);let u=!1;return{items:h.map(function(f,E){const p=i.exec(f)[0].length,g=RegExp("^ {1,"+p+"}","gm"),S=f.replace(g,"").replace(i,""),m=E===h.length-1,_=S.indexOf(`
42
42
 
43
- `)!==-1||m&&u;u=_;const y=c.inline,k=c.list;let T;c.list=!0,_?(c.inline=!1,T=rr(b)+`
43
+ `)!==-1||m&&u;u=_;const y=c.inline,k=c.list;let T;c.list=!0,_?(c.inline=!1,T=rr(S)+`
44
44
 
45
- `):(c.inline=!0,T=rr(b));const S=a(T,c);return c.inline=y,c.list=k,S}),ordered:n,start:d}},l:(s,a,c)=>e(s.ordered?"ol":"ul",{key:c.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,c))}))}}const tf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),nf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function hc(e){return typeof e=="string"}function rr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Pr(e,t){return e.startsWith(t)}function rf(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Pr(e,n[r]))return!0;return!1}return n(e,t)}function or(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function of(e){return Vp.test(e)?"right":Up.test(e)?"center":Fp.test(e)?"left":null}function mc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const c=i[i.length-1];c.push.apply(c,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((c,d,h)=>{c.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=c}),a(),n.inTable=o,i}function sf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(Lp,"").split("|").map(of):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
- `).map(function(d){return mc(d,a,c,!0)})})(e[3],t,n):[],i=mc(e[1],t,n,!!o.length);return n.inline=!1,o.length?{align:r,cells:o,header:i,type:"25"}:{children:i,type:"21"}}function pc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function bn(e){return e.inline=1,e}function Xt(e){return bn(function(t,n){return n.inline?e.exec(t):null})}function Ft(e){return bn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Rt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Dr(e){return bn(function(t){return e.exec(t)})}const af=/(javascript|vbscript|data(?!:image)):/i;function lf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(af.test(t))return null}catch{return null}return e}function _t(e){return e&&e.replace(Gp,"$1")}function Lr(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!0,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function cf(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!1,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function df(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const ns=(e,t,n)=>({children:Lr(t,e[2],n)});function rs(){return{}}function os(){return null}function uf(...e){return e.filter(Boolean).join(" ")}function ss(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function hf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?qt({},Kl,t.namedCodesToUnicode):Kl;const n=t.slugify||or,r=t.sanitizer||lf,o=t.createElement||Ke,i=[ql,Xl,Zl,t.enforceAtxHeadings?Ql:Jl,ec,nc,cc,dc],s=[...i,Op,Jo,tc,Qo];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function c(m,_,...y){const k=ss(t.overrides,m+".props",{});return o((function(T,S){const x=ss(S,T);return x?typeof x=="function"||typeof x=="object"&&"render"in x?x:ss(S,T+".component",T):T})(m,t.overrides),qt({},_,k,{className:uf(_?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(Sp,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=Pp.test(m)===!1);const y=g(p(_?m:rr(m).replace(Kp,"")+`
45
+ `):(c.inline=!0,T=rr(S));const x=a(T,c);return c.inline=y,c.list=k,x}),ordered:n,start:d}},l:(s,a,c)=>e(s.ordered?"ol":"ul",{key:c.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,c))}))}}const hf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),mf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function Nc(e){return typeof e=="string"}function rr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Lr(e,t){return e.startsWith(t)}function pf(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Lr(e,n[r]))return!0;return!1}return n(e,t)}function or(e){return e.replace(/[ÀÁÂÃÄÅàáâãä忯]/g,"a").replace(/[çÇ]/g,"c").replace(/[ðÐ]/g,"d").replace(/[ÈÉÊËéèêë]/g,"e").replace(/[ÏïÎîÍíÌì]/g,"i").replace(/[Ññ]/g,"n").replace(/[øØœŒÕõÔôÓóÒò]/g,"o").replace(/[ÜüÛûÚúÙù]/g,"u").replace(/[ŸÿÝý]/g,"y").replace(/[^a-z0-9- ]/gi,"").replace(/ /gi,"-").toLowerCase()}function ff(e){return qp.test(e)?"right":Wp.test(e)?"center":Kp.test(e)?"left":null}function xc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const c=i[i.length-1];c.push.apply(c,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((c,d,h)=>{c.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=c}),a(),n.inTable=o,i}function gf(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(Gp,"").split("|").map(ff):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
+ `).map(function(d){return xc(d,a,c,!0)})})(e[3],t,n):[],i=xc(e[1],t,n,!!o.length);return n.inline=!1,o.length?{align:r,cells:o,header:i,type:"25"}:{children:i,type:"21"}}function Cc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function En(e){return e.inline=1,e}function Qt(e){return En(function(t,n){return n.inline?e.exec(t):null})}function zt(e){return En(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Rt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Fr(e){return En(function(t){return e.exec(t)})}const _f=/(javascript|vbscript|data(?!:image)):/i;function Ef(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(_f.test(t))return null}catch{return null}return e}function yt(e){return e&&e.replace(nf,"$1")}function Ur(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!0,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function yf(e,t,n){const r=n.inline||!1,o=n.simple||!1;n.inline=!1,n.simple=!0;const i=e(t,n);return n.inline=r,n.simple=o,i}function Sf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const us=(e,t,n)=>({children:Ur(t,e[2],n)});function hs(){return{}}function ms(){return null}function vf(...e){return e.filter(Boolean).join(" ")}function ps(e,t,n){let r=e;const o=t.split(".");for(;o.length&&(r=r[o[0]],r!==void 0);)o.shift();return r||n}function bf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?Zt({},ic,t.namedCodesToUnicode):ic;const n=t.slugify||or,r=t.sanitizer||Ef,o=t.createElement||qe,i=[ac,lc,cc,t.enforceAtxHeadings?uc:dc,hc,pc,vc,bc],s=[...i,jp,as,mc,ls];function a(m,_){for(let y=0;y<m.length;y++)if(m[y].test(_))return!0;return!1}function c(m,_,...y){const k=ps(t.overrides,m+".props",{});return o((function(T,x){const N=ps(x,T);return N?typeof N=="function"||typeof N=="object"&&"render"in N?N:ps(x,T+".component",T):T})(m,t.overrides),Zt({},_,k,{className:vf(_?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(Ip,"");let _=!1;t.forceInline?_=!0:t.forceBlock||(_=Hp.test(m)===!1);const y=g(p(_?m:rr(m).replace(of,"")+`
47
47
 
48
- `,{inline:_}));for(;hc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(_?"span":"div");let T;if(y.length>1||t.forceWrapper)T=y;else{if(y.length===1)return T=y[0],typeof T=="string"?c("span",{key:"outer"},T):T;T=null}return o(k,{key:"outer"},T)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(dp);return y?y.reduce(function(k,T){const S=T.indexOf("=");if(S!==-1){const x=(function(A){return A.indexOf("-")!==-1&&A.match(xp)===null&&(A=A.replace(Rp,function(Y,q){return q.toUpperCase()})),A})(T.slice(0,S)).trim(),v=(function(A){const Y=A[0];return(Y==='"'||Y==="'")&&A.length>=2&&A[A.length-1]===Y?A.slice(1,-1):A})(T.slice(S+1).trim()),w=Wl[x]||x;if(w==="ref")return k;const N=k[w]=(function(A,Y,q,ae){return Y==="style"?(function(de){const le=[];let ue="",F=!1,Ce=!1,$="";if(!de)return le;for(let H=0;H<de.length;H++){const L=de[H];if(L!=='"'&&L!=="'"||F||(Ce?L===$&&(Ce=!1,$=""):(Ce=!0,$=L)),L==="("&&ue.endsWith("url")?F=!0:L===")"&&F&&(F=!1),L!==";"||Ce||F)ue+=L;else{const W=ue.trim();if(W){const oe=W.indexOf(":");if(oe>0){const je=W.slice(0,oe).trim(),K=W.slice(oe+1).trim();le.push([je,K])}}ue=""}}const B=ue.trim();if(B){const H=B.indexOf(":");if(H>0){const L=B.slice(0,H).trim(),W=B.slice(H+1).trim();le.push([L,W])}}return le})(q).reduce(function(de,[le,ue]){return de[le.replace(/(-[a-z])/g,F=>F[1].toUpperCase())]=ae(ue,A,le),de},{}):cp.indexOf(Y)!==-1?ae(_t(q),A,Y):(q.match(Cp)&&(q=_t(q.slice(1,q.length-1))),q==="true"||q!=="false"&&q)})(m,x,v,r);typeof N=="string"&&(Jo.test(N)||Qo.test(N))&&(k[w]=d(N.trim()))}else T!=="style"&&(k[Wl[T]||T]=!0);return k},{}):null}const u=[],f={},E={0:{t:[">"],o:Rt(ql),i:1,u(m,_,y){const[,k,T]=m[0].replace(hp,"").match(mp);return{alert:k,children:_(T,y)}},l(m,_,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),or),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,_(m.children,y))}},1:{t:[" "],o:Dr(pp),i:1,u:rs,l:(m,_,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Rt(fp),i:1,u:rs,l:(m,_,y)=>c("hr",{key:y.key})},3:{t:[" "],o:Rt(Zl),i:0,u:m=>({lang:void 0,text:_t(rr(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>c("pre",{key:y.key},c("code",qt({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Rt(Xl),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Ft(gp),i:3,u:m=>({text:_t(m[2])}),l:(m,_,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:Rt(yp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:os},7:{t:["[^"],o:Xt(bp),i:1,u:m=>({target:"#"+n(m[1],or),text:m[1]}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href")},c("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:Xt(wp),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,_,y)=>c("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Rt(t.enforceAtxHeadings?Ql:Jl),i:1,u:(m,_,y)=>({children:Lr(_,m[2],y),id:n(m[2],or),level:m[1].length}),l:(m,_,y)=>c("h"+m.level,{id:m.id,key:y.key},_(m.children,y))},10:{t:m=>{const _=m.indexOf(`
49
- `);return _>0&&_<m.length-1&&(m[_+1]==="="||m[_+1]==="-")},o:Rt(ec),i:1,u:(m,_,y)=>({children:Lr(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Dr(Jo),i:1,u(m,_,y){const[,k]=m[3].match(qp),T=RegExp("^"+k,"gm"),S=m[3].replace(T,""),x=a(s,S)?df:Lr,v=m[1].toLowerCase(),w=lp.indexOf(v)!==-1,N=(w?v:m[1]).trim(),A={attrs:h(N,m[2]),noInnerParse:w,tag:N};if(y.inAnchor=y.inAnchor||v==="a",w)A.text=m[3];else{const Y=y.inHTML;y.inHTML=!0,A.children=x(_,S,y),y.inHTML=Y}return y.inAnchor=!1,A},l:(m,_,y)=>c(m.tag,qt({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:Dr(Qo),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>c(m.tag,qt({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Dr(tc),i:1,u:()=>({}),l:os},14:{t:["!["],o:Ft(nf),i:1,u:m=>({alt:_t(m[1]),target:_t(m[2]),title:_t(m[3])}),l:(m,_,y)=>c("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:Xt(tf),i:3,u:(m,_,y)=>({children:cf(_,m[1],y),target:_t(m[2]),title:_t(m[3])}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},_(m.children,y))},16:{t:["<"],o:Xt(kp),i:0,u(m){let _=m[1],y=!1;return _.indexOf("@")!==-1&&_.indexOf("//")===-1&&(y=!0,_=_.replace("mailto:","")),{children:[{text:_,type:"27"}],target:y?"mailto:"+_:_,type:"15"}}},17:{t:(m,_)=>!_.inAnchor&&!t.disableAutoLink&&(Pr(m,"http://")||Pr(m,"https://")),o:Xt(Tp),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:uc(c,1),33:uc(c,2),19:{t:[`
50
- `],o:Rt(_p),i:3,u:rs,l:()=>`
51
- `},21:{o:bn(function(m,_){if(_.inline||_.simple||_.inHTML&&m.indexOf(`
48
+ `,{inline:_}));for(;Nc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(_?"span":"div");let T;if(y.length>1||t.forceWrapper)T=y;else{if(y.length===1)return T=y[0],typeof T=="string"?c("span",{key:"outer"},T):T;T=null}return o(k,{key:"outer"},T)}function h(m,_){if(!_||!_.trim())return null;const y=_.match(Sp);return y?y.reduce(function(k,T){const x=T.indexOf("=");if(x!==-1){const N=(function(A){return A.indexOf("-")!==-1&&A.match(Dp)===null&&(A=A.replace(Vp,function($,J){return J.toUpperCase()})),A})(T.slice(0,x)).trim(),v=(function(A){const $=A[0];return($==='"'||$==="'")&&A.length>=2&&A[A.length-1]===$?A.slice(1,-1):A})(T.slice(x+1).trim()),b=sc[N]||N;if(b==="ref")return k;const R=k[b]=(function(A,$,J,oe){return $==="style"?(function(_e){const ie=[];let he="",U=!1,Te=!1,de="";if(!_e)return ie;for(let H=0;H<_e.length;H++){const D=_e[H];if(D!=='"'&&D!=="'"||U||(Te?D===de&&(Te=!1,de=""):(Te=!0,de=D)),D==="("&&he.endsWith("url")?U=!0:D===")"&&U&&(U=!1),D!==";"||Te||U)he+=D;else{const B=he.trim();if(B){const Ee=B.indexOf(":");if(Ee>0){const Ne=B.slice(0,Ee).trim(),se=B.slice(Ee+1).trim();ie.push([Ne,se])}}he=""}}const V=he.trim();if(V){const H=V.indexOf(":");if(H>0){const D=V.slice(0,H).trim(),B=V.slice(H+1).trim();ie.push([D,B])}}return ie})(J).reduce(function(_e,[ie,he]){return _e[ie.replace(/(-[a-z])/g,U=>U[1].toUpperCase())]=oe(he,A,ie),_e},{}):yp.indexOf($)!==-1?oe(yt(J),A,$):(J.match(Lp)&&(J=yt(J.slice(1,J.length-1))),J==="true"||J!=="false"&&J)})(m,N,v,r);typeof R=="string"&&(as.test(R)||ls.test(R))&&(k[b]=d(R.trim()))}else T!=="style"&&(k[sc[T]||T]=!0);return k},{}):null}const u=[],f={},E={0:{t:[">"],o:Rt(ac),i:1,u(m,_,y){const[,k,T]=m[0].replace(bp,"").match(wp);return{alert:k,children:_(T,y)}},l(m,_,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),or),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,_(m.children,y))}},1:{t:[" "],o:Fr(Np),i:1,u:hs,l:(m,_,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Rt(xp),i:1,u:hs,l:(m,_,y)=>c("hr",{key:y.key})},3:{t:[" "],o:Rt(cc),i:0,u:m=>({lang:void 0,text:yt(rr(m[0].replace(/^ {4}/gm,"")))}),l:(m,_,y)=>c("pre",{key:y.key},c("code",Zt({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Rt(lc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:zt(Cp),i:3,u:m=>({text:yt(m[2])}),l:(m,_,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:Rt(Rp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:ms},7:{t:["[^"],o:Qt(Op),i:1,u:m=>({target:"#"+n(m[1],or),text:m[1]}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href")},c("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:Qt(Mp),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,_,y)=>c("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Rt(t.enforceAtxHeadings?uc:dc),i:1,u:(m,_,y)=>({children:Ur(_,m[2],y),id:n(m[2],or),level:m[1].length}),l:(m,_,y)=>c("h"+m.level,{id:m.id,key:y.key},_(m.children,y))},10:{t:m=>{const _=m.indexOf(`
49
+ `);return _>0&&_<m.length-1&&(m[_+1]==="="||m[_+1]==="-")},o:Rt(hc),i:1,u:(m,_,y)=>({children:Ur(_,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Fr(as),i:1,u(m,_,y){const[,k]=m[3].match(sf),T=RegExp("^"+k,"gm"),x=m[3].replace(T,""),N=a(s,x)?Sf:Ur,v=m[1].toLowerCase(),b=Ep.indexOf(v)!==-1,R=(b?v:m[1]).trim(),A={attrs:h(R,m[2]),noInnerParse:b,tag:R};if(y.inAnchor=y.inAnchor||v==="a",b)A.text=m[3];else{const $=y.inHTML;y.inHTML=!0,A.children=N(_,x,y),y.inHTML=$}return y.inAnchor=!1,A},l:(m,_,y)=>c(m.tag,Zt({key:y.key},m.attrs),m.text||(m.children?_(m.children,y):""))},13:{t:["<"],o:Fr(ls),i:1,u(m){const _=m[1].trim();return{attrs:h(_,m[2]||""),tag:_}},l:(m,_,y)=>c(m.tag,Zt({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Fr(mc),i:1,u:()=>({}),l:ms},14:{t:["!["],o:zt(mf),i:1,u:m=>({alt:yt(m[1]),target:yt(m[2]),title:yt(m[3])}),l:(m,_,y)=>c("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:Qt(hf),i:3,u:(m,_,y)=>({children:yf(_,m[1],y),target:yt(m[2]),title:yt(m[3])}),l:(m,_,y)=>c("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},_(m.children,y))},16:{t:["<"],o:Qt(Up),i:0,u(m){let _=m[1],y=!1;return _.indexOf("@")!==-1&&_.indexOf("//")===-1&&(y=!0,_=_.replace("mailto:","")),{children:[{text:_,type:"27"}],target:y?"mailto:"+_:_,type:"15"}}},17:{t:(m,_)=>!_.inAnchor&&!t.disableAutoLink&&(Lr(m,"http://")||Lr(m,"https://")),o:Qt(Fp),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:wc(c,1),33:wc(c,2),19:{t:[`
50
+ `],o:Rt(Tp),i:3,u:hs,l:()=>`
51
+ `},21:{o:En(function(m,_){if(_.inline||_.simple||_.inHTML&&m.indexOf(`
52
52
 
53
53
  `)===-1&&_.prevCapture.indexOf(`
54
54
 
55
- `)===-1)return null;let y="",k=0;for(;;){const S=m.indexOf(`
56
- `,k),x=m.slice(k,S===-1?void 0:S+1);if(a(i,x)||(y+=x,S===-1||!x.trim()))break;k=S+1}const T=rr(y);return T===""?null:[y,,T]}),i:3,u:ns,l:(m,_,y)=>c("p",{key:y.key},_(m.children,y))},22:{t:["["],o:Xt(Ap),i:0,u:m=>(f[m[1]]={target:m[2],title:m[4]},{}),l:os},23:{t:["!["],o:Ft(Ip),i:0,u:m=>({alt:m[1]?_t(m[1]):void 0,ref:m[2]}),l:(m,_,y)=>f[m.ref]?c("img",{key:y.key,alt:m.alt,src:r(f[m.ref].target,"img","src"),title:f[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:Xt(Mp),i:0,u:(m,_,y)=>({children:_(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,_,y)=>f[m.ref]?c("a",{key:y.key,href:r(f[m.ref].target,"a","href"),title:f[m.ref].title},_(m.children,y)):c("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Rt(nc),i:1,u:sf,l(m,_,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(T,S){return c("th",{key:S,style:pc(k,S)},_(T,y))}))),c("tbody",null,k.cells.map(function(T,S){return c("tr",{key:S},T.map(function(x,v){return c("td",{key:v,style:pc(k,v)},_(x,y))}))})))}},27:{o:bn(function(m,_){let y;return Pr(m,":")&&(y=Bp.exec(m)),y||Wp.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(Np,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Ft(jp),i:2,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("strong",{key:y.key},_(m.children,y))},29:{t:m=>{const _=m[0];return(_==="*"||_==="_")&&m[1]!==_},o:Ft(zp),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:Ft(Hp),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Ft($p),i:3,u:ns,l:(m,_,y)=>c("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:Ft(Yp),i:3,u:ns,l:(m,_,y)=>c("del",{key:y.key},_(m.children,y))}};t.disableParsingRawHTML===!0&&(delete E[11],delete E[13]);const p=(function(m){var _=Object.keys(m);function y(k,T){var S=[];if(T.prevCapture=T.prevCapture||"",k.trim())for(;k;)for(var x=0;x<_.length;){var v=_[x],w=m[v];if(!w.t||rf(k,T,w.t)){var N=w.o(k,T);if(N&&N[0]){k=k.substring(N[0].length);var A=w.u(N,y,T);T.prevCapture+=N[0],A.type||(A.type=v),S.push(A);break}x++}else x++}return T.prevCapture="",S}return _.sort(function(k,T){return m[k].i-m[T].i||(k<T?-1:1)}),function(k,T){return y((function(S){return S.replace(Ep,`
57
- `).replace(vp,"").replace(Dp," ")})(k),T)}})(E),g=(function(m,_){return function y(k,T={}){if(Array.isArray(k)){const S=T.key,x=[];let v=!1;for(let w=0;w<k.length;w++){T.key=w;const N=y(k[w],T),A=hc(N);A&&v?x[x.length-1]+=N:N!==null&&x.push(N),v=A}return T.key=S,x}return(function(S,x,v){const w=m[S.type].l;return _?_(()=>w(S,x,v),S,x,v):w(S,x,v)})(k,y,T)}})(E,t.renderRule),b=d(e);return u.length?c("div",null,b,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,or),key:m.identifier},m.identifier,g(p(m.footnote,{inline:!0})))}))):b}const mf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,c={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(c[s]=o[s]);return c})(e,ap);return Mt(hf(t??"",n),r)},pf={disableParsingRawHTML:!0,forceBlock:!0};function Ur({children:e}){return l(mf,{options:pf,children:e})}function fc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?l("div",{onClick:i?void 0:o,className:I("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&l("span",{className:s?"text-primary-foreground":"text-primary",children:r}),l("span",{className:"block whitespace-normal",children:e})]}):null}const ff=qe(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),gf=qe(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),_f=qe(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),Ef=qe(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),yf=qe(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function De({className:e}){return l("div",{className:I("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function sr({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(Fr,{}),l(De,{className:"h-8 w-20 rounded-full"}),l(De,{className:"h-8 w-24 rounded-full"}),l(De,{className:"h-8 w-16 rounded-full"})]}):e==="media"?l("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[l(Fr,{}),l(De,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(De,{className:"h-3 w-3/4 rounded"}),l(De,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?l("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[l(Fr,{}),l(De,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(De,{className:"h-9 w-full rounded-lg"}),l(De,{className:"h-9 w-full rounded-lg"}),l(De,{className:"h-9 w-full rounded-lg"})]}),l(De,{className:"mt-4 h-9 w-full rounded-lg"})]}):l("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[l(Fr,{}),l("div",{className:"flex items-center gap-3",children:[l(De,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(De,{className:"h-3 w-3/4 rounded"}),l(De,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(De,{className:"h-3 w-full rounded"}),l(De,{className:"h-3 w-5/6 rounded"})]}),l(De,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Fr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function bf({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=D([]),[a,c]=D({}),[d,h]=D(!1),[u,f]=D(5),E=n.component,p=n.disabled,g=ye(()=>n.input,[n.input]);z(()=>{E===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&c(g.doctor_details)},[E,g?.doctor_details]),z(()=>{n.disabled||(h(!1),f(5),s([]))},[g,n.disabled]);const b=async w=>{h(!0),await r({message:w.value,messageId:e,toolCalled:!0,selectedComponent:w,tool_key:t})},m=async(w,N,A,Y=!0)=>{await r({toolCalled:Y,selectedComponent:w,selected_id:w.doctor_id,message:N,tool_key:t,messageId:e,...A&&{tool_result:A}})},_=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const w=E===M.SYNAPSE_COMPONENTS.MULTI&&g?.options;return w?Array.isArray(w)?w.map((N,A)=>({id:`option-${A}`,label:N.label,value:N.value})):Object.keys(w).map((N,A)=>({id:`option-${A}`,label:N,value:N})):[]},T=ye(()=>{if(E===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(w=>!!w&&!!w.doctor_id)},[E,g?.doctors]);if(!E)return null;const S=E===M.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,x=E===M.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,v=E===M.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return l("div",{className:"flex justify-end",children:[S&&l("div",{className:`flex ${S.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[S.slice(0,u).map((w,N)=>l(fc,{disabled:p||o||d,text:w?.label||"",onClick:()=>b(w),className:"cursor-pointer"},N)),S.length>u&&l("button",{type:"button",disabled:p||o||d,onClick:()=>f(w=>w+5),className:I("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[l(Ao,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,S.length-u)," more"]})]}),E===M.SYNAPSE_COMPONENTS.MULTI&&g?.options&&l($e,{fallback:l(sr,{variant:"input"}),children:l("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[l("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),l(ff,{options:k(),selectedValues:i,onSelectionChange:s,disabled:p||o}),l(ie,{onClick:y,disabled:i.length===0||p||o,className:I("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),T&&T.length>0?l($e,{fallback:l(sr,{variant:"card"}),children:l(gf,{count:T.length>1?T.length+1:T.length,renderItem:(w,N)=>{if(T.length>1&&w===T.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:_,disabled:o||p,className:I("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[l("span",{className:I("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(ph,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const A=T[w];return l($e,{fallback:l(sr,{variant:"card"}),children:l(_f,{doctor:A,doctorDetails:a?.[A.doctor_id],disabled:o,onSelect:m,isActive:N})},A.doctor_id)}})}):null,x&&l($e,{fallback:l(sr,{variant:"card"}),children:l(Ef,{cards:x,onSelect:async w=>{await r({...w,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:p||o})}),v&&l($e,{fallback:l(sr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(yf,{card:v})})})]})}function vf({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:c,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:f,onClearElicitationState:E,isAuthComponent:p,isFullScreen:g}){const b=t==="user",[m,_]=D(M.USER_FEEDBACK.NONE),y=G(S=>S.isStreaming),k=S=>{_(S),u(S)},T=!!(n?.trim()||r&&r.length>0||d||i||a);return l(ce,{children:[T&&l("div",{className:I("flex",b?"justify-end":"justify-start"),children:l("div",{className:I("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(Gt,{className:I("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":I("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:I("markdown-content",g&&!b?"text-base leading-6":"text-sm"),children:l(Ur,{children:`${n} ${!b&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l(Go,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!y&&o&&n&&m===M.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(M.USER_FEEDBACK.LIKE),children:l(Tr,{className:"h-3 w-3"})}),l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(M.USER_FEEDBACK.DISLIKE),children:l(kr,{className:"h-3 w-3"})})]})}),!a&&!b&&!y&&o&&m===M.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Tr,{className:"h-3 w-3"})})}),!a&&!b&&!y&&o&&m===M.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(kr,{className:"h-3 w-3"})})}),p&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ie,{variant:"link",size:"sm",className:"h-6 px-0 text-[12px] font-medium text-primary border-b border-dashed border-primary rounded-none bg-transparent no-underline hover:no-underline hover:bg-transparent active:bg-transparent focus-visible:bg-transparent rounded-none",onClick:()=>{const S=s[s.length-1];S&&c[S]?.active&&E(S,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(S=>{const x=c[S];return x?l(bf,{messageId:e,tool_key:S,entry:x,onSendMessage:h,disabled:f||x.disabled},S):null}),a&&!b&&l("div",{className:"flex justify-start",children:l("div",{className:I("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(Gt,{className:I("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",g&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:l("div",{className:I("markdown-content",g?"text-base leading-6":"text-sm"),children:l(Ur,{children:a})})}),!y&&o&&m===M.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(M.USER_FEEDBACK.LIKE),children:l(Tr,{className:"h-3 w-3"})}),l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(M.USER_FEEDBACK.DISLIKE),children:l(kr,{className:"h-3 w-3"})})]})}),!y&&o&&m===M.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Tr,{className:"h-3 w-3"})})}),!y&&o&&m===M.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ie,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(kr,{className:"h-3 w-3"})})})]})})})]})}function Sf({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){if(!e&&!t?.length)return null;const i=s=>{const a=s.value||s.label||"";a&&n({message:a})};return l(ce,{children:[e&&l("div",{className:"flex justify-start",children:l("div",{className:I("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l(Gt,{className:I("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",o&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:l("div",{className:I("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Ur,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:I("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(fc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}function wf({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const c=G(u=>u.isWaitingForResponse),d=G(u=>u.elicitationState),h=G(u=>u.progressMessage);return e.length===0&&!h?l(Sf,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):l(ce,{children:[(e&&e.length>0||h)&&l(ce,{children:e.map((u,f)=>l("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:f===e.length-1?"last-message":void 0,children:l(vf,{id:u.id,role:u.role,content:u.content,files:u.files||[],toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,timestamp:u.timestamp,onSendMessage:t,isLastMessage:f===e.length-1,progressMessage:h,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:E=>n(E,u.id),onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),c&&l(Nf,{})]})}function Nf(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(Gt,{className:"px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",children:l("div",{className:"flex items-center gap-1.5","aria-label":"Bot is typing",children:[0,1,2].map(e=>l("span",{className:"w-2 h-2 rounded-full bg-foreground animate-pulse",style:{animationDelay:`${e*150}ms`}},e))})})})})})}function gc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=jl(),[c,d]=D(!0);return z(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?l("div",{className:I("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:l("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?l("div",{className:I("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),l("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),l("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[l("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!c||!s&&!i?.title&&a?null:l("div",{className:I("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),l("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&l("div",{className:"flex-shrink-0",children:l("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const xf=qe(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function Cf({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:c,showRetryButton:d,clearError:h,error:u,sessionId:f,activeElicitation:E,isAuthComponent:p,isConnected:g,inConversation:b,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:T,startSession:S,sendMessageFeedback:x,clearElicitationState:v,handleRetry:w,scrollToBottom:N,chatComposerProps:A,isComposerDisabled:Y,voiceAgentState:q,isMuted:ae,isVoiceAgentActive:de,disconnectVoiceAgent:le,resetVoiceAgent:ue,toggleMute:F,handleClose:Ce,isSessionDrawerOpen:$,pastSessions:B,isLoadingPastSessions:H,openSessionDrawer:L,closeSessionDrawer:W,userLevel:oe,isSidebarCollapsed:je,toggleSidebar:K,showFeedbackModal:me,handleSessionFeedbackSubmit:Be,handleSessionFeedbackSkip:ze,handleDontShowAgain:tt,handleCloseModal:Xe,showConsentModal:ht,handleConsentAccept:Et,handleSendMessage:mt,sidePanelMode:P,sidePanelWidth:Ee,side:ve,onSidePanelPushChange:ke}=ip({isOpen:e,agentId:t,config:n});z(()=>{T.length||N("auto")},[T.length,N]);const Ze=ye(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=o==="full"&&oe==="user"?l(Pm,{sessions:B,activeSessionId:f,onSelectSession:Ie=>S({sessionId:Ie}),onNewChat:()=>S({forceNewSession:!0}),isCollapsed:je,onToggle:K,isLoading:H}):void 0;return l(sm,{enabled:!!n.resize,children:l(Fl,{isOpen:e,onClose:Ce,feedbackModal:n.feedback?{isOpen:me,config:n.feedback,onSubmit:Be,onSkip:ze,onClose:Xe,onDontShowAgain:tt}:void 0,consentModal:n.theme?.upfrontConsent?{isOpen:ht,onAccept:Et}:void 0,showCloseButton:n.showCloseButton,title:n.title,showStartNewChatButton:c,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:()=>S({forceNewSession:!0}),sessionId:f,environment:n.environment,mode:o,sidePanelMode:P,sidePanelWidth:Ee,side:ve,onSidePanelPushChange:ke,onToggleDisplayMode:n.resize?r:void 0,theme:n.theme,isAuthComponent:p,activeElicitation:E,voiceAgentState:q,chatComposer:A,onOpenSessionDrawer:L,sessionDrawer:l(Um,{isOpen:$,onClose:W,sessions:B,activeSessionId:f,onSelectSession:Ie=>{S({sessionId:Ie})},onNewChat:()=>S({forceNewSession:!0})}),sidebar:Le,fullScreenEmptyState:_?Ie=>l(jm,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:lt=>mt(lt,!0),disabled:Y,composer:Ie.composer,composerFooter:Ie.composerFooter,connectionBanner:l(gc,{onRetry:w,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})}):void 0,children:de?l($e,{fallback:l(_c,{}),children:l(xf,{state:q,isMuted:ae,onEndCall:le,onClose:ue,onToggleMute:F,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l($e,{fallback:l(_c,{}),children:l("div",{className:I("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[l("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:l(Ga,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[l("div",{className:"flex-1"}),l("div",{className:I("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?l(Hh,{}):l(ce,{children:[m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:Ze}),l(wf,{messages:T,onSendMessage:Ie=>mt(Ie,_),iconUrl:n.iconUrl,onToggleFeedback:x,onClearElicitationState:v,isAuthComponent:p,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),l("div",{ref:s})]})]})}),a&&l("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:l(ie,{onClick:()=>N("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:l(Ao,{className:"w-5 h-5 text-text-primary"})})}),l(gc,{className:"mt-2",onRetry:w,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})]})})})})}function _c(){return l("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[l("div",{className:"flex-1 p-6 space-y-4",children:[l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),l("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Ec(e){return!!e&&e.startsWith("ResizeObserver loop")}function is(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);try{return new Error(JSON.stringify(e))}catch{return new Error("Unknown error")}}class Tf extends it{constructor(){super(...arguments);O(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:is(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(Of,{error:this.state.error,componentStack:this.state.componentStack,title:this.props.title,titleImg:this.props.titleImg,iconUrl:this.props.iconUrl,onClose:this.props.onClose,showCloseButton:this.props.showCloseButton,environment:this.props.environment,displayMode:this.props.displayMode,theme:this.props.theme}):this.props.children}}function kf({error:e}){throw e}function Rf(e){const[t,n]=D(null);return z(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Ec(i?.message)||Ec(i?.error?.message)||(i?.error?n(is(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(is(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(Tf,{...e,children:t?l(kf,{error:t}):e.children})}function Of({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:c}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",f=ye(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]);return l(Fl,{isOpen:!0,onClose:o??(()=>{}),showCloseButton:i??!1,onStartNewSession:d,title:h,titleImg:n,iconUrl:r,environment:u,mode:a??"widget",theme:c,children:l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:l("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:l("div",{className:"w-full max-w-[320px] text-center",children:[l("div",{className:"mx-auto mb-4 grid place-items-center",children:l("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:l(uh,{className:"h-8 w-8",style:{color:c?.primary??"hsl(var(--primary))"}})})}),l("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),l("div",{className:["mt-2 text-sm",f].join(" "),children:"Something went wrong. Please try again."}),l("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",f].join(" "),children:e?.message||String(e)}),l("div",{className:"mt-5 flex items-center justify-center gap-3",children:l(ie,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(ih,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})}function Af({agentId:e,config:t}){const[n,r]=D(t.displayMode==="full");z(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(Rf,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:l(Nh,{children:l(Cf,{isOpen:n,agentId:e,config:{...t,environment:t.environment??"production",onClose:o,title:t.title??"Medi Clinic",iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",theme:t.theme}})})})}const yc=(e,t,n)=>{const r=n||{},o=Wc(e);return o.render(l(ce,{children:l(Af,{agentId:t,config:r})})),o},If=e=>{try{const t=sessionStorage.getItem(nr(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},bc=e=>{const{refreshToken:t,sessToken:n}=If(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},vc=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=yc,window.fetchAgentConfig=vc,window.prefetchAuth=bc);export{J as A,ie as B,Ao as C,Q as D,el as F,tl as I,Io as M,lo as N,ln as P,mo as R,Wo as S,ye as T,yn as X,dt as _,M as a,I as b,Pe as c,D as d,ce as e,Yt as f,vc as fetchAgentConfig,ri as g,cn as h,Pt as i,Lt as j,Ym as k,ll as l,Yo as m,kl as n,Bo as o,$m as p,bc as prefetchAuth,ge as q,dl as r,yc as renderMedAssist,Ur as s,$l as t,l as u,Gt as v,Bm as w,cl as x,z as y,ul as z};
55
+ `)===-1)return null;let y="",k=0;for(;;){const x=m.indexOf(`
56
+ `,k),N=m.slice(k,x===-1?void 0:x+1);if(a(i,N)||(y+=N,x===-1||!N.trim()))break;k=x+1}const T=rr(y);return T===""?null:[y,,T]}),i:3,u:us,l:(m,_,y)=>c("p",{key:y.key},_(m.children,y))},22:{t:["["],o:Qt(zp),i:0,u:m=>(f[m[1]]={target:m[2],title:m[4]},{}),l:ms},23:{t:["!["],o:zt(Yp),i:0,u:m=>({alt:m[1]?yt(m[1]):void 0,ref:m[2]}),l:(m,_,y)=>f[m.ref]?c("img",{key:y.key,alt:m.alt,src:r(f[m.ref].target,"img","src"),title:f[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:Qt($p),i:0,u:(m,_,y)=>({children:_(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,_,y)=>f[m.ref]?c("a",{key:y.key,href:r(f[m.ref].target,"a","href"),title:f[m.ref].title},_(m.children,y)):c("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Rt(pc),i:1,u:gf,l(m,_,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(T,x){return c("th",{key:x,style:Cc(k,x)},_(T,y))}))),c("tbody",null,k.cells.map(function(T,x){return c("tr",{key:x},T.map(function(N,v){return c("td",{key:v,style:Cc(k,v)},_(N,y))}))})))}},27:{o:En(function(m,_){let y;return Lr(m,":")&&(y=ef.exec(m)),y||rf.exec(m)}),i:4,u(m){const _=m[0];return{text:_.indexOf("&")===-1?_:_.replace(Pp,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:zt(Xp),i:2,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("strong",{key:y.key},_(m.children,y))},29:{t:m=>{const _=m[0];return(_==="*"||_==="_")&&m[1]!==_},o:zt(Jp),i:3,u:(m,_,y)=>({children:_(m[2],y)}),l:(m,_,y)=>c("em",{key:y.key},_(m.children,y))},30:{t:["\\"],o:zt(tf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:zt(Zp),i:3,u:us,l:(m,_,y)=>c("mark",{key:y.key},_(m.children,y))},32:{t:["~~"],o:zt(Qp),i:3,u:us,l:(m,_,y)=>c("del",{key:y.key},_(m.children,y))}};t.disableParsingRawHTML===!0&&(delete E[11],delete E[13]);const p=(function(m){var _=Object.keys(m);function y(k,T){var x=[];if(T.prevCapture=T.prevCapture||"",k.trim())for(;k;)for(var N=0;N<_.length;){var v=_[N],b=m[v];if(!b.t||pf(k,T,b.t)){var R=b.o(k,T);if(R&&R[0]){k=k.substring(R[0].length);var A=b.u(R,y,T);T.prevCapture+=R[0],A.type||(A.type=v),x.push(A);break}N++}else N++}return T.prevCapture="",x}return _.sort(function(k,T){return m[k].i-m[T].i||(k<T?-1:1)}),function(k,T){return y((function(x){return x.replace(kp,`
57
+ `).replace(Ap,"").replace(Bp," ")})(k),T)}})(E),g=(function(m,_){return function y(k,T={}){if(Array.isArray(k)){const x=T.key,N=[];let v=!1;for(let b=0;b<k.length;b++){T.key=b;const R=y(k[b],T),A=Nc(R);A&&v?N[N.length-1]+=R:R!==null&&N.push(R),v=A}return T.key=x,N}return(function(x,N,v){const b=m[x.type].l;return _?_(()=>b(x,N,v),x,N,v):b(x,N,v)})(k,y,T)}})(E,t.renderRule),S=d(e);return u.length?c("div",null,S,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,or),key:m.identifier},m.identifier,g(p(m.footnote,{inline:!0})))}))):S}const wf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,c={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(c[s]=o[s]);return c})(e,_p);return Lt(bf(t??"",n),r)},Nf={disableParsingRawHTML:!0,forceBlock:!0};function Vr({children:e}){return l(wf,{options:Nf,children:e})}function Tc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?l("div",{onClick:i?void 0:o,className:M("inline-flex items-center gap-2 rounded-lg border border-primary px-3 py-2 shadow-sm text-xs cursor-pointer transition-colors",s?"bg-primary text-primary-foreground":"bg-elicitationBg text-primary",n,i?"opacity-50 cursor-not-allowed":""),style:{maxWidth:t,WebkitTapHighlightColor:"transparent",outline:"none"},title:e,children:[r&&l("span",{className:s?"text-primary-foreground":"text-primary",children:r}),l("span",{className:"block whitespace-normal",children:e})]}):null}const xf=Xe(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Cf=Xe(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),Tf=Xe(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),kf=Xe(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Rf=Xe(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function ze({className:e}){return l("div",{className:M("relative overflow-hidden bg-surface-secondary","before:absolute before:inset-0","before:-translate-x-full before:animate-[shimmer_1.4s_infinite]","before:bg-gradient-to-r before:from-transparent before:via-white/40 before:to-transparent",e)})}function sr({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(jr,{}),l(ze,{className:"h-8 w-20 rounded-full"}),l(ze,{className:"h-8 w-24 rounded-full"}),l(ze,{className:"h-8 w-16 rounded-full"})]}):e==="media"?l("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[l(jr,{}),l(ze,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(ze,{className:"h-3 w-3/4 rounded"}),l(ze,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?l("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[l(jr,{}),l(ze,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(ze,{className:"h-9 w-full rounded-lg"}),l(ze,{className:"h-9 w-full rounded-lg"}),l(ze,{className:"h-9 w-full rounded-lg"})]}),l(ze,{className:"mt-4 h-9 w-full rounded-lg"})]}):l("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[l(jr,{}),l("div",{className:"flex items-center gap-3",children:[l(ze,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(ze,{className:"h-3 w-3/4 rounded"}),l(ze,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(ze,{className:"h-3 w-full rounded"}),l(ze,{className:"h-3 w-5/6 rounded"})]}),l(ze,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function jr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Of({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=F([]),[a,c]=F({}),[d,h]=F(!1),[u,f]=F(5),E=n.component,p=n.disabled,g=ye(()=>n.input,[n.input]);Y(()=>{E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&c(g.doctor_details)},[E,g?.doctor_details]),Y(()=>{n.disabled||(h(!1),f(5),s([]))},[g,n.disabled]);const S=async b=>{h(!0),await r({message:b.value,messageId:e,toolCalled:!0,selectedComponent:b,tool_key:t})},m=async(b,R,A,$=!0)=>{await r({toolCalled:$,selectedComponent:b,selected_id:b.doctor_id,message:R,tool_key:t,messageId:e,...A&&{tool_result:A}})},_=async()=>{await r({message:"show more",tool_declined:!0})},y=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},k=()=>{const b=E===I.SYNAPSE_COMPONENTS.MULTI&&g?.options;return b?Array.isArray(b)?b.map((R,A)=>({id:`option-${A}`,label:R.label,value:R.value})):Object.keys(b).map((R,A)=>({id:`option-${A}`,label:R,value:R})):[]},T=ye(()=>{if(E===I.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(b=>!!b&&!!b.doctor_id)},[E,g?.doctors]);if(!E)return null;const x=E===I.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,N=E===I.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,v=E===I.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return l("div",{className:"flex justify-end",children:[x&&l("div",{className:`flex ${x.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[x.slice(0,u).map((b,R)=>l(Tc,{disabled:p||o||d,text:b?.label||"",onClick:()=>S(b),className:"cursor-pointer"},R)),x.length>u&&l("button",{type:"button",disabled:p||o||d,onClick:()=>f(b=>b+5),className:M("inline-flex items-center justify-center gap-1.5 w-full max-w-[200px] rounded-lg border border-dashed border-primary","bg-elicitationBg px-3 py-2 text-xs font-semibold text-primary","transition-colors cursor-pointer","disabled:opacity-50 disabled:cursor-not-allowed"),children:[l(jo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,x.length-u)," more"]})]}),E===I.SYNAPSE_COMPONENTS.MULTI&&g?.options&&l(He,{fallback:l(sr,{variant:"input"}),children:l("div",{className:"mt-3 space-y-3 break-words overflow-wrap-anywhere whitespace-pre-wrap bg-elicitationBg border border-primary/40 rounded-xl p-4",children:[l("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),l(xf,{options:k(),selectedValues:i,onSelectionChange:s,disabled:p||o}),l(ce,{onClick:y,disabled:i.length===0||p||o,className:M("w-full rounded-lg px-4 py-2 text-sm font-medium transition-all","bg-primary hover:bg-primary/90 text-primary-foreground","disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-primary/50 disabled:text-primary-foreground","shadow-sm hover:shadow-md active:scale-[0.98] "),children:"Confirm"})]})}),T&&T.length>0?l(He,{fallback:l(sr,{variant:"card"}),children:l(Cf,{count:T.length>1?T.length+1:T.length,renderItem:(b,R)=>{if(T.length>1&&b===T.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:_,disabled:o||p,className:M("max-w-md w-full h-full flex flex-col items-center justify-center gap-2 px-4","rounded-xl border-2 border-dashed border-black-200 dark:border-white-200 bg-primary/[10%]","transition-colors disabled:opacity-60 disabled:cursor-not-allowed"),children:[l("span",{className:M("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(xh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const A=T[b];return l(He,{fallback:l(sr,{variant:"card"}),children:l(Tf,{doctor:A,doctorDetails:a?.[A.doctor_id],disabled:o,onSelect:m,isActive:R})},A.doctor_id)}})}):null,N&&l(He,{fallback:l(sr,{variant:"card"}),children:l(kf,{cards:N,onSelect:async b=>{await r({...b,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:p||o})}),v&&l(He,{fallback:l(sr,{variant:"media"}),children:l("div",{className:"mt-3",children:l(Rf,{card:v})})})]})}function Af({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:c,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:f,onClearElicitationState:E,isAuthComponent:p,isFullScreen:g}){const S=t==="user",[m,_]=F(I.USER_FEEDBACK.NONE),y=W(x=>x.isStreaming),k=x=>{_(x),u(x)},T=!!(n?.trim()||r&&r.length>0||d||i||a);return l(ue,{children:[T&&l("div",{className:M("flex",S?"justify-end":"justify-start"),children:l("div",{className:M("flex gap-3",S?"flex-row-reverse":"flex-row",S?"max-w-[60%]":g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(qt,{className:M("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",S?"bg-primary text-primary-foreground shadow-sm":M("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!S&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!S&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:M("markdown-content",g&&!S?"text-base leading-6":"text-sm"),children:l(Vr,{children:`${n} ${!S&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l(ts,{files:r,isPreview:!1,className:""})}),i&&!S&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!S&&!y&&o&&n&&m===I.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(I.USER_FEEDBACK.LIKE),children:l(Rr,{className:"h-3 w-3"})}),l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(I.USER_FEEDBACK.DISLIKE),children:l(Or,{className:"h-3 w-3"})})]})}),!a&&!S&&!y&&o&&m===I.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Rr,{className:"h-3 w-3"})})}),!a&&!S&&!y&&o&&m===I.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Or,{className:"h-3 w-3"})})}),p&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"link",size:"sm",className:"h-6 px-0 text-[12px] font-medium text-primary border-b border-dashed border-primary rounded-none bg-transparent no-underline hover:no-underline hover:bg-transparent active:bg-transparent focus-visible:bg-transparent rounded-none",onClick:()=>{const x=s[s.length-1];x&&c[x]?.active&&E(x,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(x=>{const N=c[x];return N?l(Of,{messageId:e,tool_key:x,entry:N,onSendMessage:h,disabled:f||N.disabled},x):null}),a&&!S&&l("div",{className:"flex justify-start",children:l("div",{className:M("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l(qt,{className:M("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap","text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",g&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:l("div",{className:M("markdown-content",g?"text-base leading-6":"text-sm"),children:l(Vr,{children:a})})}),!y&&o&&m===I.USER_FEEDBACK.NONE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l("div",{className:"flex items-center gap-1",children:[l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(I.USER_FEEDBACK.LIKE),children:l(Rr,{className:"h-3 w-3"})}),l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-black-500 dark:text-white-500 hover:text-foreground",onClick:()=>k(I.USER_FEEDBACK.DISLIKE),children:l(Or,{className:"h-3 w-3"})})]})}),!y&&o&&m===I.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Rr,{className:"h-3 w-3"})})}),!y&&o&&m===I.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(ce,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Or,{className:"h-3 w-3"})})})]})})})]})}function If({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){if(!e&&!t?.length)return null;const i=s=>{const a=s.value||s.label||"";a&&n({message:a})};return l(ue,{children:[e&&l("div",{className:"flex justify-start",children:l("div",{className:M("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l(qt,{className:M("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200",o&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:l("div",{className:M("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Vr,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:M("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(Tc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}function Mf({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const c=W(u=>u.isWaitingForResponse),d=W(u=>u.elicitationState),h=W(u=>u.progressMessage);return e.length===0&&!h?l(If,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):l(ue,{children:[(e&&e.length>0||h)&&l(ue,{children:e.map((u,f)=>l("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:f===e.length-1?"last-message":void 0,children:l(Af,{id:u.id,role:u.role,content:u.content,files:u.files||[],toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,timestamp:u.timestamp,onSendMessage:t,isLastMessage:f===e.length-1,progressMessage:h,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:E=>n(E,u.id),onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),c&&l(Pf,{})]})}function Pf(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l(qt,{className:"px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",children:l("div",{className:"flex items-center gap-1.5","aria-label":"Bot is typing",children:[0,1,2].map(e=>l("span",{className:"w-2 h-2 rounded-full bg-foreground animate-pulse",style:{animationDelay:`${e*150}ms`}},e))})})})})})}function kc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=Jl(),[c,d]=F(!0);return Y(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?l("div",{className:M("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:l("p",{className:"text-text-secondary text-sm max-w-sm mx-auto text-center w-250 mx-4 text-balance",children:"The conversation is now closed. Start a new session to continue."})}):n&&i?.title?l("div",{className:M("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),l("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),l("button",{onClick:()=>{o(),t?.()},className:"px-4 py-2 bg-primary text-primary-foreground text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors flex items-center gap-2 flex-shrink-0",children:[l("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry"]})]})}):s&&a&&!i?.title||!r&&!n&&!c||!s&&!i?.title&&a?null:l("div",{className:M("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:l("div",{className:"flex items-center gap-3",children:[l("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:l("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),l("div",{className:"flex-1",children:[l("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),l("div",{className:"text-text-secondary text-xs mt-1",children:a?i?.description??"Please wait while we try to connect":"Please check your internet connection"})]}),!a&&l("div",{className:"flex-shrink-0",children:l("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const Df=Xe(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function Lf({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:c,showRetryButton:d,clearError:h,error:u,sessionId:f,activeElicitation:E,isAuthComponent:p,isConnected:g,inConversation:S,isFirstMessage:m,isEmptyChat:_,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:T,startSession:x,sendMessageFeedback:N,clearElicitationState:v,handleRetry:b,scrollToBottom:R,chatComposerProps:A,isComposerDisabled:$,voiceAgentState:J,isMuted:oe,isVoiceAgentActive:_e,disconnectVoiceAgent:ie,resetVoiceAgent:he,toggleMute:U,handleClose:Te,isSessionDrawerOpen:de,pastSessions:V,isLoadingPastSessions:H,openSessionDrawer:D,closeSessionDrawer:B,userLevel:Ee,isSidebarCollapsed:Ne,toggleSidebar:se,showFeedbackModal:ne,handleSessionFeedbackSubmit:$e,handleSessionFeedbackSkip:Ge,handleDontShowAgain:We,handleCloseModal:Je,showConsentModal:Ot,handleConsentAccept:mt,handleSendMessage:it,sidePanelMode:L,sidePanelWidth:Oe,side:le,onSidePanelPushChange:Re}=gp({isOpen:e,agentId:t,config:n});Y(()=>{T.length||R("auto")},[T.length,R]);const Ze=ye(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),rt=o==="full"&&Ee==="user"?l(Bm,{sessions:V,activeSessionId:f,onSelectSession:xe=>x({sessionId:xe}),onNewChat:()=>x({forceNewSession:!0}),isCollapsed:Ne,onToggle:se,isLoading:H}):void 0;return l(gm,{enabled:!!n.resize,children:l(Kl,{isOpen:e,onClose:Te,feedbackModal:n.feedback?{isOpen:ne,config:n.feedback,onSubmit:$e,onSkip:Ge,onClose:Je,onDontShowAgain:We}:void 0,consentModal:n.theme?.upfrontConsent?{isOpen:Ot,onAccept:mt}:void 0,showCloseButton:n.showCloseButton,title:n.title,showStartNewChatButton:c,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:()=>x({forceNewSession:!0}),sessionId:f,environment:n.environment,mode:o,sidePanelMode:L,sidePanelWidth:Oe,side:le,onSidePanelPushChange:Re,onToggleDisplayMode:n.resize?r:void 0,theme:n.theme,isAuthComponent:p,activeElicitation:E,voiceAgentState:J,chatComposer:A,onOpenSessionDrawer:D,sessionDrawer:l(Km,{isOpen:de,onClose:B,sessions:V,activeSessionId:f,onSelectSession:xe=>{x({sessionId:xe})},onNewChat:()=>x({forceNewSession:!0})}),sidebar:rt,fullScreenEmptyState:_?xe=>l(Jm,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:at=>it(at,!0),disabled:$,composer:xe.composer,composerFooter:xe.composerFooter,connectionBanner:l(kc,{onRetry:b,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})}):void 0,children:_e?l(He,{fallback:l(Rc,{}),children:l(Df,{state:J,isMuted:oe,onEndCall:ie,onClose:he,onToggleMute:U,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l(He,{fallback:l(Rc,{}),children:l("div",{className:M("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[l("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:l(nl,{ref:i,className:"flex-1 min-h-0 [&>[data-radix-scroll-area-viewport]>div]:!flex [&>[data-radix-scroll-area-viewport]>div]:flex-col [&>[data-radix-scroll-area-viewport]>div]:min-h-full",children:[l("div",{className:"flex-1"}),l("div",{className:M("min-w-0 overflow-x-hidden",S?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?l(nm,{}):l(ue,{children:[m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&l("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:Ze}),l(Mf,{messages:T,onSendMessage:xe=>it(xe,_),iconUrl:n.iconUrl,onToggleFeedback:N,onClearElicitationState:v,isAuthComponent:p,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),l("div",{ref:s})]})]})}),a&&l("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:l(ce,{onClick:()=>R("smooth"),size:"icon",className:"h-10 w-10 rounded-full bg-surface/90 backdrop-blur-sm shadow-lg border border-border-subtle hover:bg-surface hover:shadow-xl transition-all duration-200",children:l(jo,{className:"w-5 h-5 text-text-primary"})})}),l(kc,{className:"mt-2",onRetry:b,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})]})})})})}function Rc(){return l("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[l("div",{className:"flex-1 p-6 space-y-4",children:[l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),l("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),l("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Oc(e){return!!e&&e.startsWith("ResizeObserver loop")}function fs(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);try{return new Error(JSON.stringify(e))}catch{return new Error("Unknown error")}}class Ff extends ot{constructor(){super(...arguments);O(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:fs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(jf,{error:this.state.error,componentStack:this.state.componentStack,title:this.props.title,titleImg:this.props.titleImg,iconUrl:this.props.iconUrl,onClose:this.props.onClose,showCloseButton:this.props.showCloseButton,environment:this.props.environment,displayMode:this.props.displayMode,theme:this.props.theme}):this.props.children}}function Uf({error:e}){throw e}function Vf(e){const[t,n]=F(null);return Y(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Oc(i?.message)||Oc(i?.error?.message)||(i?.error?n(fs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(fs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(Ff,{...e,children:t?l(Uf,{error:t}):e.children})}function jf({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:c}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",f=ye(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]);return l(Kl,{isOpen:!0,onClose:o??(()=>{}),showCloseButton:i??!1,onStartNewSession:d,title:h,titleImg:n,iconUrl:r,environment:u,mode:a??"widget",theme:c,children:l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:l("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:l("div",{className:"w-full max-w-[320px] text-center",children:[l("div",{className:"mx-auto mb-4 grid place-items-center",children:l("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:l(bh,{className:"h-8 w-8",style:{color:c?.primary??"hsl(var(--primary))"}})})}),l("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),l("div",{className:["mt-2 text-sm",f].join(" "),children:"Something went wrong. Please try again."}),l("div",{className:["mt-4 rounded-2xl border border-border-subtle/60 bg-surface/60 backdrop-blur px-4 py-3","text-left text-[11px] leading-relaxed font-mono whitespace-pre-wrap break-words",f].join(" "),children:e?.message||String(e)}),l("div",{className:"mt-5 flex items-center justify-center gap-3",children:l(ce,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(_h,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})}function zf({agentId:e,config:t}){const[n,r]=F(t.displayMode==="full");Y(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(Vf,{title:t.title??"Medi Clinic",titleImg:t.theme?.titleImg,iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",onClose:o,showCloseButton:t.showCloseButton,environment:t.environment??"production",displayMode:t.displayMode,theme:t.theme,children:l(Dh,{children:l(Lf,{isOpen:n,agentId:e,config:{...t,environment:t.environment??"production",onClose:o,title:t.title??"Medi Clinic",iconUrl:t.iconUrl??"https://cdn.eka.care/bot-icon.svg",theme:t.theme}})})})}const Ac=(e,t,n)=>{const r=n||{},o=od(e);return o.render(l(ue,{children:l(zf,{agentId:t,config:r})})),o},Yf=e=>{try{const t=sessionStorage.getItem(nr(e)),n=t?JSON.parse(t)?.state:void 0;return{refreshToken:typeof n?.refreshToken=="string"&&n.refreshToken?n.refreshToken:void 0,sessToken:typeof n?.sessToken=="string"&&n.sessToken?n.sessToken:void 0}}catch{return{}}},Ic=e=>{const{refreshToken:t,sessToken:n}=Yf(e.agentId);return t&&n?Promise.resolve(null):I.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Mc=e=>I.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Ac,window.fetchAgentConfig=Mc,window.prefetchAuth=Ic);export{q as A,ce as B,jo as C,Q as D,dl as F,ul as I,zo as M,Eo as N,sn as P,bo as R,ns as S,ye as T,_n as X,dt as _,I as a,M as b,Fe as c,F as d,ue as e,Gt as f,Mc as fetchAgentConfig,mi as g,an as h,Ft as i,Vt as j,Qm as k,El as l,Zo as m,Ul as n,Qo as o,Zm as p,Ic as prefetchAuth,fe as q,Sl as r,Ac as renderMedAssist,Vr as s,Ql as t,l as u,qt as v,ep as w,yl as x,Y as y,vl as z};