@eka-care/medassist-widget 0.1.128-dev.0 → 0.1.129

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 yc=Object.defineProperty;var vc=(e,t,n)=>t in e?yc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>vc(e,typeof t!="symbol"?t+"":t,n);var vn,q,os,kt,ss,is,as,Fr,rr,bn,ls,Ur,Vr,jr,cs,or={},sr=[],bc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Sn=Array.isArray;function pt(e,t){for(var n in t)e[n]=t[n];return e}function zr(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Ge(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?vn.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 wn(e,s,r,o,null)}function wn(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??++os,__i:-1,__u:0};return o==null&&q.vnode!=null&&q.vnode(i),i}function ds(){return{current:null}}function ce(e){return e.children}function ot(e,t){this.props=e,this.context=t}function Qt(e,t){if(t==null)return e.__?Qt(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"?Qt(e):null}function Sc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=pt({},t);i.__v=t.__v+1,q.vnode&&q.vnode(i),$r(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Qt(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,gs(r,i,o),t.__e=t.__=null,i.__e!=n&&us(i)}}function us(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}),us(e)}function Br(e){(!e.__d&&(e.__d=!0)&&kt.push(e)&&!ir.__r++||ss!=q.debounceRendering)&&((ss=q.debounceRendering)||is)(ir)}function ir(){try{for(var e,t=1;kt.length;)kt.length>t&&kt.sort(as),e=kt.shift(),t=kt.length,Sc(e)}finally{kt.length=ir.__r=0}}function hs(e,t,n,r,o,i,s,a,c,d,h){var u,f,_,p,g,v,m,E=r&&r.__k||sr,y=t.length;for(c=wc(n,t,E,c,y),u=0;u<y;u++)(_=n.__k[u])!=null&&(f=_.__i!=-1&&E[_.__i]||or,_.__i=u,v=$r(e,_,f,o,i,s,a,c,d,h),p=_.__e,_.ref&&f.ref!=_.ref&&(f.ref&&Yr(f.ref,null,_),h.push(_.ref,_.__c||p,_)),g==null&&p!=null&&(g=p),(m=!!(4&_.__u))||f.__k===_.__k?(c=ms(_,c,e,m),m&&f.__e&&(f.__e=null)):typeof _.type=="function"&&v!==void 0?c=v:p&&(c=p.nextSibling),_.__u&=-7);return n.__e=g,c}function wc(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]=wn(null,s,null,null,null):Sn(s)?s=e.__k[i]=wn(ce,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=wn(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=Nc(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=Qt(a)),Es(a,a));return r}function ms(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=ms(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Qt(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function yt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Sn(e)?e.some(function(n){yt(n,t)}):t.push(e)),t}function Nc(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 ps(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||bc.test(t)?n:n+"px"}function ar(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||ps(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ps(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ls,"$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[bn]=r[bn]:(n[bn]=Ur,e.addEventListener(t,i?jr:Vr,i)):e.removeEventListener(t,i?jr:Vr,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 fs(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[rr]==null)t[rr]=Ur++;else if(t[rr]<n[bn])return;return n(q.event?q.event(t):t)}}}function $r(e,t,n,r,o,i,s,a,c,d){var h,u,f,_,p,g,v,m,E,y,k,w,N,T,b,S=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=q.__b)&&h(t);e:if(typeof S=="function")try{if(m=t.props,E=S.prototype&&S.prototype.render,y=(h=S.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?v=(u=t.__c=n.__c).__=u.__E:(E?t.__c=u=new S(m,k):(t.__c=u=new ot(m,k),u.constructor=S,u.render=Tc),y&&y.sub(u),u.state||(u.state={}),u.__n=r,f=u.__d=!0,u.__h=[],u._sb=[]),E&&u.__s==null&&(u.__s=u.state),E&&S.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=pt({},u.__s)),pt(u.__s,S.getDerivedStateFromProps(m,u.__s))),_=u.props,p=u.state,u.__v=t,f)E&&S.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),E&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(E&&S.getDerivedStateFromProps==null&&m!==_&&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(x){x&&(x.__=t)}),sr.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),E&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(_,p,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,w=q.__r,N=0,E)u.state=u.__s,u.__d=!1,w&&w(t),h=u.render(u.props,u.state,u.context),sr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,w&&w(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++N<25);u.state=u.__s,u.getChildContext!=null&&(r=pt(pt({},r),u.getChildContext())),E&&!f&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(_,p)),T=h!=null&&h.type===ce&&h.key==null?_s(h.props.children):h,a=hs(e,Sn(T)?T:[T],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),v&&(u.__E=u.__=null)}catch(x){if(t.__v=null,c||i!=null)if(x.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(b=i.length;b--;)zr(i[b]);Hr(t)}else t.__e=n.__e,t.__k=n.__k,x.then||Hr(t);q.__e(x,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=xc(n.__e,t,n,r,o,i,s,c,d);return(h=q.diffed)&&h(t),128&t.__u?void 0:a}function Hr(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Hr))}function gs(e,t,n){for(var r=0;r<n.length;r++)Yr(n[r],n[++r],n[++r]);q.__c&&q.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){q.__e(i,o.__v)}})}function _s(e){return typeof e!="object"||e==null||e.__b>0?e:Sn(e)?e.map(_s):e.constructor!==void 0?null:pt({},e)}function xc(e,t,n,r,o,i,s,a,c){var d,h,u,f,_,p,g,v=n.props||or,m=t.props,E=t.type;if(E=="svg"?o="http://www.w3.org/2000/svg":E=="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((_=i[d])&&"setAttribute"in _==!!E&&(E?_.localName==E:_.nodeType==3)){e=_,i[d]=null;break}}if(e==null){if(E==null)return document.createTextNode(m);e=document.createElementNS(o,E,m.is&&m),a&&(q.__m&&q.__m(t,i),a=!1),i=null}if(E==null)v===m||a&&e.data==m||(e.data=m);else{if(i=E=="textarea"&&m.defaultValue!=null?null:i&&vn.call(e.childNodes),!a&&i!=null)for(v={},d=0;d<e.attributes.length;d++)v[(_=e.attributes[d]).name]=_.value;for(d in v)_=v[d],d=="dangerouslySetInnerHTML"?u=_:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||ar(e,d,null,_,o);for(d in m)_=m[d],d=="children"?f=_:d=="dangerouslySetInnerHTML"?h=_:d=="value"?p=_:d=="checked"?g=_:a&&typeof _!="function"||v[d]===_||ar(e,d,_,v[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=""),hs(t.type=="template"?e.content:e,Sn(f)?f:[f],t,n,r,E=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&Qt(n,0),a,c),i!=null)for(d=i.length;d--;)zr(i[d]);a&&E!="textarea"||(d="value",E=="progress"&&p==null?e.removeAttribute("value"):p!=null&&(p!==e[d]||E=="progress"&&!p||E=="option"&&p!=v[d])&&ar(e,d,p,v[d],o),d="checked",g!=null&&g!=e[d]&&ar(e,d,g,v[d],o))}return e}function Yr(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){q.__e(o,n)}}function Es(e,t,n){var r,o;if(q.unmount&&q.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Yr(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){q.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Es(r[o],t,n||typeof e.type!="function");n||zr(e.__e),e.__c=e.__=e.__e=void 0}function Tc(e,t,n){return this.constructor(e,n)}function Nn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),q.__&&q.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],$r(t,e=(!r&&n||t).__k=Ge(ce,null,[e]),o||or,or,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?vn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),gs(i,e,s)}function ys(e,t){Nn(e,t,ys)}function Cc(e,t,n){var r,o,i,s,a=pt({},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?vn.call(arguments,2):n),wn(e.type,a,r||e.key,o||e.ref,null)}function vt(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,Br(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"+cs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}vn=sr.slice,q={__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}},os=0,ot.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=pt({},this.state),typeof e=="function"&&(e=e(pt({},n),this.props)),e&&pt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Br(this))},ot.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Br(this))},ot.prototype.render=ce,kt=[],is=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,as=function(e,t){return e.__v.__b-t.__v.__b},ir.__r=0,Fr=Math.random().toString(8),rr="__d"+Fr,bn="__a"+Fr,ls=/(PointerCapture)$|Capture$/i,Ur=0,Vr=fs(!1),jr=fs(!0),cs=0;var kc=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:--kc,__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 q.vnode&&q.vnode(d),d}var bt,he,Gr,vs,en=0,bs=[],be=q,Ss=be.__b,ws=be.__r,Ns=be.diffed,xs=be.__c,Ts=be.unmount,Cs=be.__;function Vt(e,t){be.__h&&be.__h(he,e,en||t),en=0;var n=he.__H||(he.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function L(e){return en=1,tn(Rs,e)}function tn(e,t,n){var r=Vt(bt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Rs(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 _=f.__[0];f.__=f.__N,f.__N=void 0,_!==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=Vt(bt++,3);!be.__s&&Zr(n.__H,t)&&(n.__=e,n.u=t,he.__H.__h.push(n))}function at(e,t){var n=Vt(bt++,4);!be.__s&&Zr(n.__H,t)&&(n.__=e,n.u=t,he.__h.push(n))}function X(e){return en=5,_e(function(){return{current:e}},[])}function Wr(e,t,n){en=6,at(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 _e(e,t){var n=Vt(bt++,7);return Zr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function fe(e,t){return en=8,_e(function(){return e},t)}function St(e){var t=he.context[e.__c],n=Vt(bt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(he)),t.props.value):e.__}function Kr(e,t){be.useDebugValue&&be.useDebugValue(t?t(e):e)}function Rc(e){var t=Vt(bt++,10),n=L();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 qr(){var e=Vt(bt++,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 Oc(){for(var e;e=bs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(lr),t.__h.some(Xr),t.__h=[]}catch(n){t.__h=[],be.__e(n,e.__v)}}}be.__b=function(e){he=null,Ss&&Ss(e)},be.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Cs&&Cs(e,t)},be.__r=function(e){ws&&ws(e),bt=0;var t=(he=e.__c).__H;t&&(Gr===he?(t.__h=[],he.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(lr),t.__h.some(Xr),t.__h=[],bt=0)),Gr=he},be.diffed=function(e){Ns&&Ns(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(bs.push(t)!==1&&vs===be.requestAnimationFrame||((vs=be.requestAnimationFrame)||Ac)(Oc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Gr=he=null},be.__c=function(e,t){t.some(function(n){try{n.__h.some(lr),n.__h=n.__h.filter(function(r){return!r.__||Xr(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],be.__e(r,n.__v)}}),xs&&xs(e,t)},be.unmount=function(e){Ts&&Ts(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{lr(r)}catch(o){t=o}}),n.__H=void 0,t&&be.__e(t,n.__v))};var ks=typeof requestAnimationFrame=="function";function Ac(e){var t,n=function(){clearTimeout(r),ks&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ks&&(t=requestAnimationFrame(n))}function lr(e){var t=he,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),he=t}function Xr(e){var t=he;e.__c=e.__(),he=t}function Zr(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Rs(e,t){return typeof t=="function"?t(e):t}function Os(e,t){for(var n in t)e[n]=t[n];return e}function Jr(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 Qr(e,t){var n=t(),r=L({t:{__:n,u:t}}),o=r[0].t,i=r[1];return at(function(){o.__=n,o.u=t,eo(o)&&i({t:o})},[e,n,t]),z(function(){return eo(o)&&i({t:o}),e(function(){eo(o)&&i({t:o})})},[e]),n}function eo(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 to(e){e()}function no(e){return e}function ro(){return[!1,to]}var oo=at;function cr(e,t){this.props=e,this.context=t}function so(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:Jr(this.props,o)}function r(o){return this.shouldComponentUpdate=n,Ge(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(cr.prototype=new ot).isPureReactComponent=!0,cr.prototype.shouldComponentUpdate=function(e,t){return Jr(this.props,e)||Jr(this.state,t)};var As=q.__b;q.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),As&&As(e)};var Ic=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=Os({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Ic,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Is=function(e,t){return e==null?null:yt(yt(e).map(t))},Xe={map:Is,forEach:Is,count:function(e){return e?yt(e).length:0},only:function(e){var t=yt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:yt},Mc=q.__e;q.__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)}Mc(e,t,n,r)};var Ms=q.unmount;function Ps(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=Os({},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 Ps(r,t,n)})),e}function Ds(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ds(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 Ls(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function We(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?Ge(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function nn(){this.i=null,this.l=null}q.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Ms&&Ms(e)},($e.prototype=new ot).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=Ls(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]=Ds(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]=Ps(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&Ge(ce,null,e.fallback);return o&&(o.__u&=-33),[Ge(ce,null,t.__a?null:e.children),o]};var Fs=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 Pc(e){return this.getChildContext=function(){return e.context},e.children}function Dc(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Nn(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)}}}Nn(Ge(Pc,{context:t.context},e.__v),t.v)}function Us(e,t){var n=Ge(Dc,{__v:e,h:t});return n.containerInfo=t,n}(nn.prototype=new ot).__a=function(e){var t=this,n=Ls(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Fs(t,e,r)):o()};n?n(i):i()}},nn.prototype.render=function(e){this.i=null,this.l=new Map;var t=yt(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},nn.prototype.componentDidUpdate=nn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Fs(e,n,t)})};var Vs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Lc=/^(?: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]/,Fc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Uc=/[A-Z0-9]/g,Vc=typeof document<"u",jc=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function io(e,t,n){return t.__k==null&&(t.textContent=""),Nn(e,t),typeof n=="function"&&n(),e?e.__c:null}function js(e,t,n){return ys(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 zs=q.event;q.event=function(e){return zs&&(e=zs(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var ao,zc={configurable:!0,get:function(){return this.class}},Bs=q.vnode;q.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||Vc&&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"||jc(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":Fc.test(s)&&(s=c):c=s="oninput":i&&Lc.test(s)?s=s.replace(Uc,"-$&").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=yt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=yt(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",zc)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=Vs,Bs&&Bs(e)};var $s=q.__r;q.__r=function(e){$s&&$s(e),ao=e.__c};var Hs=q.diffed;q.diffed=function(e){Hs&&Hs(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),ao=null};var Ys={ReactCurrentDispatcher:{current:{readContext:function(e){return ao.__n[e.__c].props.value},useCallback:fe,useContext:St,useDebugValue:Kr,useDeferredValue:no,useEffect:z,useId:qr,useImperativeHandle:Wr,useInsertionEffect:oo,useLayoutEffect:at,useMemo:_e,useReducer:tn,useRef:X,useState:L,useSyncExternalStore:Qr,useTransition:ro}}},Bc="18.3.1";function Gs(e){return Ge.bind(null,e)}function Ze(e){return!!e&&e.$$typeof===Vs}function Ws(e){return Ze(e)&&e.type===ce}function Ks(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Rt(e){return Ze(e)?Cc.apply(null,arguments):e}function lo(e){return!!e.__k&&(Nn(null,e),!0)}function qs(e){return e&&(e.base||e.nodeType===1&&e)||null}var Xs=function(e,t){return e(t)},Zs=function(e,t){var n=q.debounceRendering;q.debounceRendering=function(o){return o()};var r=e(t);return q.debounceRendering=n,r},Js=Ze,xn={useState:L,useId:qr,useReducer:tn,useEffect:z,useLayoutEffect:at,useInsertionEffect:oo,useTransition:ro,useDeferredValue:no,useSyncExternalStore:Qr,startTransition:to,useRef:X,useImperativeHandle:Wr,useMemo:_e,useCallback:fe,useContext:St,useDebugValue:Kr,version:"18.3.1",Children:Xe,render:io,hydrate:js,unmountComponentAtNode:lo,createPortal:Us,createElement:Ge,createContext:vt,createFactory:Gs,cloneElement:Rt,createRef:ds,Fragment:ce,isValidElement:Ze,isElement:Js,isFragment:Ws,isMemo:Ks,findDOMNode:qs,Component:ot,PureComponent:cr,memo:so,forwardRef:J,flushSync:Zs,unstable_batchedUpdates:Xs,StrictMode:ce,Suspense:$e,SuspenseList:nn,lazy:We,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ys};const co=Object.freeze(Object.defineProperty({__proto__:null,Children:Xe,Component:ot,Fragment:ce,PureComponent:cr,StrictMode:ce,Suspense:$e,SuspenseList:nn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ys,cloneElement:Rt,createContext:vt,createElement:Ge,createFactory:Gs,createPortal:Us,createRef:ds,default:xn,findDOMNode:qs,flushSync:Zs,forwardRef:J,hydrate:js,isElement:Js,isFragment:Ws,isMemo:Ks,isValidElement:Ze,lazy:We,memo:so,render:io,startTransition:to,unmountComponentAtNode:lo,unstable_batchedUpdates:Xs,useCallback:fe,useContext:St,useDebugValue:Kr,useDeferredValue:no,useEffect:z,useErrorBoundary:Rc,useId:qr,useImperativeHandle:Wr,useInsertionEffect:oo,useLayoutEffect:at,useMemo:_e,useReducer:tn,useRef:X,useState:L,useSyncExternalStore:Qr,useTransition:ro,version:Bc},Symbol.toStringTag,{value:"Module"}));function $c(e){return{render:function(t){io(t,e)},unmount:function(){lo(e)}}}function Qs(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function uo(...e){return t=>{let n=!1;const r=e.map(o=>{const i=Qs(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():Qs(e[o],null)}}}}function Ot(...e){return fe(uo(...e),e)}function Hc(e){const t=Yc(e),n=J((r,o)=>{const{children:i,...s}=r,a=Xe.toArray(i),c=a.find(Wc);if(c){const d=c.props.children,h=a.map(u=>u===c?Xe.count(d)>1?Xe.only(null):Ze(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Ze(d)?Rt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Yc(e){const t=J((n,r)=>{const{children:o,...i}=n;if(Ze(o)){const s=qc(o),a=Kc(i,o.props);return o.type!==ce&&(a.ref=r?uo(r,s):s),Rt(o,a)}return Xe.count(o)>1?Xe.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Gc=Symbol("radix.slottable");function Wc(e){return Ze(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Gc}function Kc(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 Xc=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rn=Xc.reduce((e,t)=>{const n=Hc(`Primitive.${t}`),r=J((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}},{}),jt=globalThis?.document?at:()=>{};function Zc(e,t){return tn((n,r)=>t[n][r]??n,e)}var on=e=>{const{present:t,children:n}=e,r=Jc(t),o=typeof n=="function"?n({present:r.isPresent}):Xe.only(n),i=Ot(r.ref,Qc(o));return typeof n=="function"||r.isPresent?Rt(o,{ref:i}):null};on.displayName="Presence";function Jc(e){const[t,n]=L(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,c]=Zc(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return z(()=>{const d=dr(r.current);i.current=a==="mounted"?d:"none"},[a]),jt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,f=dr(d);e?c("MOUNT"):f==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),jt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=_=>{const p=dr(r.current).includes(CSS.escape(_.animationName));if(_.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=_=>{_.target===t&&(i.current=dr(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 dr(e){return e?.animationName||"none"}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)}function ei(e,t=[]){let n=[];function r(i,s){const a=vt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:_,...p}=u,g=f?.[e]?.[c]||a,v=_e(()=>p,Object.values(p));return l(g.Provider,{value:v,children:_})};d.displayName=i+"Provider";function h(u,f){const _=f?.[e]?.[c]||a,p=St(_);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=>vt(s));return function(s){const a=s?.[e]||i;return _e(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,ed(o,...t)]}function ed(...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 _e(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function At(e){const t=X(e);return z(()=>{t.current=e}),_e(()=>(...n)=>t.current?.(...n),[])}var td=vt(void 0);function nd(e){const t=St(td);return e||t||"ltr"}function rd(e,[t,n]){return Math.min(n,Math.max(t,e))}function It(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function od(e,t){return tn((n,r)=>t[n][r]??n,e)}var ho="ScrollArea",[ti]=ei(ho),[sd,st]=ti(ho),ni=J((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=L(null),[d,h]=L(null),[u,f]=L(null),[_,p]=L(null),[g,v]=L(null),[m,E]=L(0),[y,k]=L(0),[w,N]=L(!1),[T,b]=L(!1),S=Ot(t,I=>c(I)),x=nd(o);return l(sd,{scope:n,type:r,dir:x,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:f,scrollbarX:_,onScrollbarXChange:p,scrollbarXEnabled:w,onScrollbarXEnabledChange:N,scrollbarY:g,onScrollbarYChange:v,scrollbarYEnabled:T,onScrollbarYEnabledChange:b,onCornerWidthChange:E,onCornerHeightChange:k,children:l(rn.div,{dir:x,...s,ref:S,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});ni.displayName=ho;var ri="ScrollAreaViewport",oi=J((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=st(ri,n),a=X(null),c=Ot(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(rn.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})})]})});oi.displayName=ri;var ft="ScrollAreaScrollbar",mo=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,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(id,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(ad,{...r,ref:t,forceMount:n}):o.type==="auto"?l(si,{...r,ref:t,forceMount:n}):o.type==="always"?l(po,{...r,ref:t}):null});mo.displayName=ft;var id=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,e.__scopeScrollArea),[i,s]=L(!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(on,{present:n||i,children:l(si,{"data-state":i?"visible":"hidden",...r,ref:t})})}),ad=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,e.__scopeScrollArea),i=e.orientation==="horizontal",s=pr(()=>c("SCROLL_END"),100),[a,c]=od("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 _=d[h];u!==_&&(c("SCROLL"),s()),u=_};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,c,s]),l(on,{present:n||a!=="hidden",children:l(po,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:It(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:It(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),si=J((e,t)=>{const n=st(ft,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=L(!1),a=e.orientation==="horizontal",c=pr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return sn(n.viewport,c),sn(n.content,c),l(on,{present:r||i,children:l(po,{"data-state":i?"visible":"hidden",...o,ref:t})})}),po=J((e,t)=>{const{orientation:n="vertical",...r}=e,o=st(ft,e.__scopeScrollArea),i=X(null),s=X(0),[a,c]=L({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=di(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,_){return md(f,s.current,a,_)}return n==="horizontal"?l(ld,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,_=ui(f,a,o.dir);i.current.style.transform=`translate3d(${_}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(cd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,_=ui(f,a);i.current.style.transform=`translate3d(0, ${_}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=u(f))}}):null}),ld=J((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(ft,e.__scopeScrollArea),[s,a]=L(),c=X(null),d=Ot(t,c,i.onScrollbarXChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(ai,{"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":mr(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),mi(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:hr(s.paddingLeft),paddingEnd:hr(s.paddingRight)}})}})}),cd=J((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(ft,e.__scopeScrollArea),[s,a]=L(),c=X(null),d=Ot(t,c,i.onScrollbarYChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(ai,{"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":mr(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),mi(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:hr(s.paddingTop),paddingEnd:hr(s.paddingBottom)}})}})}),[dd,ii]=ti(ft),ai=J((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,_=st(ft,n),[p,g]=L(null),v=Ot(t,S=>g(S)),m=X(null),E=X(""),y=_.viewport,k=r.content-r.viewport,w=At(h),N=At(c),T=pr(u,10);function b(S){if(m.current){const x=S.clientX-m.current.left,I=S.clientY-m.current.top;d({x,y:I})}}return z(()=>{const S=x=>{const I=x.target;p?.contains(I)&&w(x,k)};return document.addEventListener("wheel",S,{passive:!1}),()=>document.removeEventListener("wheel",S,{passive:!1})},[y,p,k,w]),z(N,[r,N]),sn(p,T),sn(_.content,T),l(dd,{scope:n,scrollbar:p,hasThumb:o,onThumbChange:At(i),onThumbPointerUp:At(s),onThumbPositionChange:N,onThumbPointerDown:At(a),children:l(rn.div,{...f,ref:v,style:{position:"absolute",...f.style},onPointerDown:It(e.onPointerDown,S=>{S.button===0&&(S.target.setPointerCapture(S.pointerId),m.current=p.getBoundingClientRect(),E.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",_.viewport&&(_.viewport.style.scrollBehavior="auto"),b(S))}),onPointerMove:It(e.onPointerMove,b),onPointerUp:It(e.onPointerUp,S=>{const x=S.target;x.hasPointerCapture(S.pointerId)&&x.releasePointerCapture(S.pointerId),document.body.style.webkitUserSelect=E.current,_.viewport&&(_.viewport.style.scrollBehavior=""),m.current=null})})})}),ur="ScrollAreaThumb",li=J((e,t)=>{const{forceMount:n,...r}=e,o=ii(ur,e.__scopeScrollArea);return l(on,{present:n||o.hasThumb,children:l(ud,{ref:t,...r})})}),ud=J((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=st(ur,n),s=ii(ur,n),{onThumbPositionChange:a}=s,c=Ot(t,u=>s.onThumbChange(u)),d=X(void 0),h=pr(()=>{d.current&&(d.current(),d.current=void 0)},100);return z(()=>{const u=i.viewport;if(u){const f=()=>{if(h(),!d.current){const _=pd(u,a);d.current=_,a()}};return a(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,h,a]),l(rn.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:It(e.onPointerDownCapture,u=>{const f=u.target.getBoundingClientRect(),_=u.clientX-f.left,p=u.clientY-f.top;s.onThumbPointerDown({x:_,y:p})}),onPointerUp:It(e.onPointerUp,s.onThumbPointerUp)})});li.displayName=ur;var fo="ScrollAreaCorner",ci=J((e,t)=>{const n=st(fo,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(hd,{...e,ref:t}):null});ci.displayName=fo;var hd=J((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=st(fo,n),[i,s]=L(0),[a,c]=L(0),d=!!(i&&a);return sn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),sn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(rn.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 hr(e){return e?parseInt(e,10):0}function di(e,t){const n=e/t;return isNaN(n)?0:n}function mr(e){const t=di(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function md(e,t,n,r="ltr"){const o=mr(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 hi([c,d],u)(e)}function ui(e,t,n="ltr"){const r=mr(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=rd(e,c);return hi([0,s],[0,a])(d)}function hi(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 mi(e,t){return e>0&&e<t}var pd=(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 pr(e,t){const n=At(e),r=X(0);return z(()=>()=>window.clearTimeout(r.current),[]),fe(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sn(e,t){const n=At(t);jt(()=>{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 pi=ni,fd=oi,gd=ci;function _d(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 an={},Tn={},fi={},Cn={},kn={},Rn={},gi;function go(){if(gi)return Rn;gi=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.EventEmitter=void 0;let e=class{constructor(){R(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 Rn.EventEmitter=e,Rn}var ln={},_i;function On(){return _i||(_i=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.DisconnectionReason=ln.ConnectionStatus=void 0,ln.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},ln.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"}),ln}var Ei;function _o(){if(Ei)return kn;Ei=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.BaseConnection=void 0;const e=go(),t=On();let n=class{constructor(){R(this,"status",t.ConnectionStatus.CONNECTING);R(this,"queue",[]);R(this,"eventEmitter",new e.EventEmitter);R(this,"disconnectionDetails",null);R(this,"onErrorCallback",null);R(this,"onDisconnectCallback",null);R(this,"onMessageCallback",null);R(this,"onOpenCallback",null);R(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 kn.BaseConnection=n,kn}var yi={},vi;function Je(){return vi||(vi=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=w,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(b,S=e.SynapseErrorCode.UNKNOWN,x={}){super(b);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=S,this.timestamp=new Date,this.cause=x.cause,this.context=x.context,this.hint=x.hint,this.reason=x.reason,this.displayMessage=x.displayMessage||x?.hint||b,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(b,S,x,I){const H=n.makeMessage(S,x,b);super(H,e.SynapseErrorCode.API,{cause:x,context:{status:S,hasBody:!!x},hint:S&&S>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:b||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=S,this.error=x,this.headers=I}static makeMessage(b,S,x){const I=S instanceof Error?S.message:x;return b&&I?`HTTP ${b}: ${I}`:b?`${b} status code (no body)`:I||"(no status code or body)"}static generate(b,S,x,I){if(!b)return new r({message:x});const H=S?.error,ne=H&&typeof H=="object"&&!Array.isArray(H)?H:void 0;switch(b){case 400:return new i(x||"Bad Request",b,ne,I);case 401:return new s(x||"Unauthorized",b,ne,I);case 403:return new a(x||"Permission Denied",b,ne,I);case 404:return new c(x||"Not Found",b,ne,I);case 405:return new d(x||"Method Not Allowed",b,ne,I);case 429:return new h(x||"Rate Limit Exceeded",b,ne,I);case 500:return new u(x||"Internal Server Error",b,ne,I);default:return new n(x||"API Error",b,ne,I)}}}e.APIError=n;class r extends n{constructor({message:T}={}){super(T||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:T}={}){super(T||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="InternalServerError"}}e.InternalServerError=u;class f extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.CONNECTION,b),this.name="ConnectionError"}}e.ConnectionError=f;class _ extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.RECORDING,b),this.name="RecordingError"}}e.RecordingError=_;class p extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.AUTH,b),this.name="AuthenticationError"}}e.AuthenticationError=p;class g extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.FILE,b),this.name="FileError"}}e.FileError=g;class v extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.SESSION,b),this.name="SessionError"}}e.SessionError=v;class m extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.MESSAGE,b),this.name="MessageError"}}e.MessageError=m;class E extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.STORE,b),this.name="StoreError"}}e.StoreError=E;class y extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.CONFIGURATION,b),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.VALIDATION,b),this.name="ValidationError"}}e.ValidationError=k;function w(N,T,b,S={}){if(N instanceof T)return N;const x={...S,context:{...N instanceof t?N.context:void 0,...S.context},hint:S.hint??(N instanceof t?N.hint:void 0),reason:S.reason??(N instanceof t?N.reason:void 0),cause:S.cause??N};if(N instanceof t)return new T(N.message,x);const I=N instanceof Error&&N.message?N.message:b;return new T(I,x)}})(yi)),yi}var bi;function Si(){if(bi)return Cn;bi=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.WebSocketConnection=void 0;const e=_o(),t=On(),n=Je();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(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 Cn.WebSocketConnection=r,Cn}var An={},wi={},Ni;function xi(){return Ni||(Ni=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})(wi)),wi}var Ti;function Ci(){if(Ti)return An;Ti=1,Object.defineProperty(An,"__esModule",{value:!0}),An.SSEConnection=void 0;const e=_o(),t=On(),n=xi(),r=Je();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(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 _="";for(;;){const{done:p,value:g}=await u.read();if(p)break;_+=f.decode(g,{stream:!0}),_=this.extractJsonObjects(_)}_.trim().length>0&&this.extractJsonObjects(_)}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 _=(0,r.normalizeError)(f,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(_)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let f=c;f<a.length;f++){const _=a[f];if(h){u?u=!1:_==="\\"?u=!0:_==='"'&&(h=!1);continue}if(_==='"')h=!0;else if(_==="{")d++;else if(_==="}"&&(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 An.SSEConnection=o,An}var ki;function Ri(){return ki||(ki=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Si(),n=Ci(),r=Je();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})(fi)),fi}var In={},Oi;function Eo(){if(Oi)return In;Oi=1,Object.defineProperty(In,"__esModule",{value:!0}),In.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 In.getConfig=r,In}var Mn={},Pn={},Ai;function fr(){if(Ai)return Pn;Ai=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.HttpClient=void 0;const e=Je();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(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 Pn.HttpClient=t,Pn}var Dn={},Ln={},Ii;function Fn(){if(Ii)return Ln;Ii=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.BaseResource=void 0;let e=class{constructor(t){R(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 Ln.BaseResource=e,Ln}var Mi;function Pi(){if(Mi)return Dn;Mi=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.Session=void 0;const e=Fn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Dn.Session=t,Dn}var Un={},Di;function yo(){if(Di)return Un;Di=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.Config=void 0;const e=Fn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Un.Config=t,Un}var Li={},Fi;function Ui(){return Fi||(Fi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=fr(),n=Eo(),r=yo(),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}}}),_=new r.Config(f).retrieve(c.agentId);return _.catch(()=>{o.get(h)===_&&o.delete(h)}),o.set(h,_),_}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(Li)),Li}var Vn={},Vi;function vo(){if(Vi)return Vn;Vi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.Auth=void 0;const e=Fn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Vn.Auth=t,Vn}var jn={},cn={},ji;function bo(){return ji||(ji=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.ErrorType=cn.SYNAPSE_RECOVERY_REASON=void 0,cn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},cn.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"}),cn}var zn={},zi;function So(){if(zi)return zn;zi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.ErrorUtils=void 0;const e=Je();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 zn.ErrorUtils=t,zn}var Bi={},$i;function Hi(){return $i||($i=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=fr(),n=Eo(),r=So(),o=vo(),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 _=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(_).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}})(Bi)),Bi}var Yi;function Ed(){if(Yi)return jn;Yi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.TokenManager=void 0;const e=Je(),t=bo(),n=So(),r=Hi();let o=class{constructor(i,s,a,c){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(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 jn.TokenManager=o,jn}var Bn={},Gi;function yd(){var n;if(Gi)return Bn;Gi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.VoiceResource=void 0;const e=Fn();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)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Bn.VoiceResource=t,Bn}var Wi;function Ki(){if(Wi)return Mn;Wi=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.ResourceManager=void 0;const e=fr(),t=Pi(),n=Je(),r=yo(),o=Ui(),i=vo(),s=Ed(),a=yd();class c{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(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:_,user_location:p,referer:g,...v}=u||{},m=this.tokenManager.userId||h,E={...m&&{user_id:m},...f&&{user_context:f},...(_||Object.keys(v).length>0)&&{session_context:{..._&&{intent:_},...p&&{user_location:p},...v}},...g&&{referer:g}},y=await this.session.create(E);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:_,feedbackReason:p,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:f,feedbacks:_,feedbackReason:p,npsBase5:g})}async callTool(h,u,f,_){return await this.session.callTool(h,u,f,_)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Mn.ResourceManager=c,Mn}var $n={},qi={},Xi;function wo(){return Xi||(Xi=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)}})(qi)),qi}var Zi={},Ji;function vd(){return Ji||(Ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=Je();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(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})(Zi)),Zi}var lt={},Qi;function gr(){if(Qi)return lt;Qi=1,Object.defineProperty(lt,"__esModule",{value:!0}),lt.SYNAPSE_REALTIME_RESERVED_EVENTS=lt.SYNAPSE_REALTIME_ERROR_CODES=lt.SYNAPSE_REALTIME_EVENTS=lt.SYNAPSE_MESSAGE_TYPES=void 0;const e=wo();return lt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,lt.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"},lt.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"},lt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},lt}var Hn={},ea;function bd(){if(ea)return Hn;ea=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.AudioManager=void 0;const e=Je();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(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 Hn.AudioManager=t,Hn}var ta;function na(){if(ta)return $n;ta=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.MessageManager=void 0;const e=wo(),t=vd(),n=gr(),r=bd(),o=Je();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(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:_}){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},..._&&{initial_prompts:_}};return}const p=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const v=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(v),v}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},..._&&{initial_prompts:_},...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 v=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(v),v}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 $n.MessageManager=i,$n}var ra={},oa;function Sd(){return oa||(oa=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})(ra)),ra}var Yn={},Gn={},sa;function wd(){if(sa)return Gn;sa=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(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 Gn.VoiceAudioAnalyser=t,Gn}var dn={},ia;function aa(){return ia||(ia=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.VOICE_AGENT_EVENTS=dn.VOICE_AGENT_STATE=void 0,dn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},dn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),dn}var la;function Nd(){if(la)return Yn;la=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.VoiceAgent=void 0;const e=go(),t=wd(),n=Je(),r=aa(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(f=>{if(h.iceGatheringState==="complete"){f();return}const _=setTimeout(f,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(_),f())}})}let d=class{constructor(h,u,f){R(this,"config");R(this,"resourceManager");R(this,"getCredentials");R(this,"emitter",new e.EventEmitter);R(this,"remoteAnalyser",new t.VoiceAudioAnalyser);R(this,"localAnalyser",new t.VoiceAudioAnalyser);R(this,"pc",null);R(this,"pcId",null);R(this,"dataChannel",null);R(this,"localStream",null);R(this,"remoteAudio",null);R(this,"_state",r.VOICE_AGENT_STATE.IDLE);R(this,"_isMuted",!1);R(this,"manuallyDisconnected",!1);R(this,"_hasConnectionFailureNotified",!1);R(this,"_userSpeaking",!1);R(this,"_silenceTimer",null);R(this,"_cachedIceServers",null);R(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),_=new RTCPeerConnection({iceServers:f,iceTransportPolicy:"all"});this.pc=_,this.dataChannel=_.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(E,u)),_.ontrack=E=>this.handleRemoteTrack(E),_.onconnectionstatechange=()=>{_.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(_.connectionState==="failed"||_.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},_.oniceconnectionstatechange=()=>{(_.iceConnectionState==="connected"||_.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):_.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const p=await _.createOffer();await _.setLocalDescription(p);const g=this.config.iceGatheringTimeoutMs??o;await c(_,g);const v=E=>({sdp:_.localDescription.sdp,type:_.localDescription.type,pc_id:this.pcId,request_data:{session_id:E.sessionId,token:E.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(v(h))}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(v(y))}else throw E}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,_.signalingState==="closed")return;await _.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(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const p=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(p.sessionId)}else throw _}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,_=>{_?(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 Yn.VoiceAgent=d,Yn}var ca;function xd(){if(ca)return Tn;ca=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.SynapseSDK=void 0;const e=Ri(),t=On(),n=Eo(),r=Ki(),o=na(),i=gr(),s=go(),a=Je(),c=bo(),d=Sd(),h=wo(),u=Nd();class f{constructor(p){R(this,"connection",null);R(this,"messageManager");R(this,"resourceManager");R(this,"sessionConfig",null);R(this,"config");R(this,"connectionType");R(this,"isRefreshingSession",!1);R(this,"isRecovering",!1);R(this,"forceConsumed",!1);R(this,"connectionAttempts",0);R(this,"sdkEventEmitter",new s.EventEmitter);R(this,"_voice",null);R(this,"pendingNetworkReconnect",!1);R(this,"boundOnlineHandler",null);R(this,"isReconnecting",!1);R(this,"reconnectTimer",null);R(this,"boundVisibilityHandler",null);R(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:v=>this.config.callbacks?.onTokenExchange?.(v)}),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:v,tool_declined:m,tool_id:E,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:v,...m&&{tool_declined:m},...E&&{tool_id:E},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(N){this.emitError(N)}break;default:const w=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(w),w}}async sendMessageFeedback(p,g,v){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:v});break}}async sendSessionFeedback(p,g){if(!this.connection){const v=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(v),v}if(!this.sessionConfig?.session_id){const v=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(v),v}if(!p?.length&&!g){const v=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(v),v}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,v){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,v);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let E={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,E);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 v=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(v),v}}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,v,m){return(0,a.normalizeError)(p,a.SessionError,g,{context:v,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),v=this.connectionType===e.ConnectionType.SOCKET,m=v?g.WEBSOCKET_URL:g.BASE_API_URL,E=this.config.serverUrl?v?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:E||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,...w)=>{y(k,...w),this.sdkEventEmitter.emit(k,...w)}}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 v=(0,d.outcomeForCloseCode)(g.code);if(v){await this.handleRecovery(v,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(p){if(p instanceof a.APIError){const v=(0,d.outcomeForHttpStatus)(p.status);if(v){this.handleRecovery(v,{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,v){this.emitError(new a.SessionError(g,{reason:p,cause:v,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 v=this.statusOf(g);if(v===401||v===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 E=this.statusOf(m);if(E===401||E===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,v,m){return(0,a.normalizeError)(p,a.ConnectionError,g,{context:v,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 Tn.SynapseSDK=f,Tn}var da={},ua;function Td(){return ua||(ua=1,Object.defineProperty(da,"__esModule",{value:!0})),da}var _r={},ha;function Cd(){return ha||(ha=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.USER_FEEDBACK=void 0,_r.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),_r}var ma={},pa;function kd(){return pa||(pa=1,Object.defineProperty(ma,"__esModule",{value:!0})),ma}var Wn={},fa;function Rd(){if(fa)return Wn;fa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ToolCall=void 0;const e=Fn();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Wn.ToolCall=t,Wn}var He={},ga;function Od(){if(ga)return He;ga=1,Object.defineProperty(He,"__esModule",{value:!0}),He.SYNAPSE_EICITATION_STATUS=He.SYNAPSE_CTA_ACTIONS=He.SYNAPSE_TOOL_FORMATS=He.SYNAPSE_TOOL_CALLBACK_NAME=He.SYNAPSE_COMPONENTS=He.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||(He.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||(He.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||(He.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(He.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(He.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(He.SYNAPSE_EICITATION_STATUS=i={})),He}var _a={},Ea;function Ad(){return Ea||(Ea=1,Object.defineProperty(_a,"__esModule",{value:!0})),_a}var ya={},va;function Id(){return va||(va=1,Object.defineProperty(ya,"__esModule",{value:!0})),ya}var Kn={},ba;function Md(){if(ba)return Kn;ba=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(Kn.SYNAPSE_CONVERSATION=e={})),Kn}var un={},Sa;function Pd(){return Sa||(Sa=1,(function(e){var t=un&&un.__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=un&&un.__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(aa(),e)})(un)),un}var wa;function Dd(){return wa||(wa=1,(function(e){var t=an&&an.__createBinding||(Object.create?(function(N,T,b,S){S===void 0&&(S=b);var x=Object.getOwnPropertyDescriptor(T,b);(!x||("get"in x?!T.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return T[b]}}),Object.defineProperty(N,S,x)}):(function(N,T,b,S){S===void 0&&(S=b),N[S]=T[b]})),n=an&&an.__exportStar||function(N,T){for(var b in N)b!=="default"&&!Object.prototype.hasOwnProperty.call(T,b)&&t(T,N,b)};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=xd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=_o();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Si();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Ci();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Ri();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(On(),e);var c=Ki();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(Td(),e);var d=Pi();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(Cd(),e);var h=vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=Hi();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(kd(),e);var f=yo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var _=Ui();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return _.prefetchAgentConfig}});var p=Rd();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return p.ToolCall}}),n(Od(),e);var g=na();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(gr(),e),n(Ad(),e);var v=fr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return v.HttpClient}});var m=Je();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 E=bo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return E.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return E.SYNAPSE_RECOVERY_REASON}});var y=So();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(Id(),e);var k=xi();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 w=gr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return w.SYNAPSE_MESSAGE_TYPES}}),n(Md(),e),n(Pd(),e)})(an)),an}var M=Dd();function Na(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=Na(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function xa(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Na(e))&&(r&&(r+=" "),r+=t);return r}const Ld=(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},Fd=(e,t)=>({classGroupId:e,validator:t}),Ta=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Er="-",Ca=[],Ud="arbitrary..",Vd=e=>{const t=zd(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return jd(o);const i=o.split(Er),s=i[0]===""&&i.length>1?1:0;return ka(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?Ld(a,s):s:a||Ca}return n[o]||Ca}}},ka=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=ka(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(Er):e.slice(t).join(Er),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},jd=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?Ud+r:void 0})(),zd=e=>{const{theme:t,classGroups:n}=e;return Bd(n,t)},Bd=(e,t)=>{const n=Ta();for(const r in e){const o=e[r];No(o,n,r,t)}return n},No=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];$d(s,t,n,r)}},$d=(e,t,n,r)=>{if(typeof e=="string"){Hd(e,t,n);return}if(typeof e=="function"){Yd(e,t,n,r);return}Gd(e,t,n,r)},Hd=(e,t,n)=>{const r=e===""?t:Ra(t,e);r.classGroupId=n},Yd=(e,t,n,r)=>{if(Wd(e)){No(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Fd(n,e))},Gd=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];No(c,Ra(t,a),n,r)}},Ra=(e,t)=>{let n=e;const r=t.split(Er),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Ta(),n.nextPart.set(s,a)),n=a}return n},Wd=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Kd=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)}}},xo="!",Oa=":",qd=[],Aa=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Xd=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 v=o[g];if(s===0&&a===0){if(v===Oa){i.push(o.slice(c,g)),c=g+1;continue}if(v==="/"){d=g;continue}}v==="["?s++:v==="]"?s--:v==="("?a++:v===")"&&a--}const u=i.length===0?o:o.slice(c);let f=u,_=!1;u.endsWith(xo)?(f=u.slice(0,-1),_=!0):u.startsWith(xo)&&(f=u.slice(1),_=!0);const p=d&&d>c?d-c:void 0;return Aa(i,_,f,p)};if(t){const o=t+Oa,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Aa(qd,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Zd=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}},Jd=e=>({cache:Kd(e.cacheSize),parseClassName:Xd(e),sortModifiers:Zd(e),...Vd(e)}),Qd=/\s+/,eu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Qd);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:f,hasImportantModifier:_,baseClassName:p,maybePostfixModifierPosition:g}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let v=!!g,m=r(v?p.substring(0,g):p);if(!m){if(!v){c=h+(c.length>0?" "+c:c);continue}if(m=r(p),!m){c=h+(c.length>0?" "+c:c);continue}v=!1}const E=f.length===0?"":f.length===1?f[0]:i(f).join(":"),y=_?E+xo:E,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const w=o(m,v);for(let N=0;N<w.length;++N){const T=w[N];s.push(y+T)}c=h+(c.length>0?" "+c:c)}return c},tu=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ia(n))&&(o&&(o+=" "),o+=r);return o},Ia=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ia(e[r]))&&(n&&(n+=" "),n+=t);return n},nu=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=Jd(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=eu(c,n);return o(c,h),h};return i=s,(...c)=>i(tu(...c))},ru=[],Oe=e=>{const t=n=>n[e]||ru;return t.isThemeGetter=!0,t},Ma=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Pa=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ou=/^\d+\/\d+$/,su=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,iu=/\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$/,au=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,lu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,cu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,hn=e=>ou.test(e),te=e=>!!e&&!Number.isNaN(Number(e)),Mt=e=>!!e&&Number.isInteger(Number(e)),To=e=>e.endsWith("%")&&te(e.slice(0,-1)),wt=e=>su.test(e),du=()=>!0,uu=e=>iu.test(e)&&!au.test(e),Da=()=>!1,hu=e=>lu.test(e),mu=e=>cu.test(e),pu=e=>!V(e)&&!j(e),fu=e=>mn(e,ja,Da),V=e=>Ma.test(e),zt=e=>mn(e,za,uu),Co=e=>mn(e,vu,te),La=e=>mn(e,Ua,Da),gu=e=>mn(e,Va,mu),yr=e=>mn(e,Ba,hu),j=e=>Pa.test(e),qn=e=>pn(e,za),_u=e=>pn(e,bu),Fa=e=>pn(e,Ua),Eu=e=>pn(e,ja),yu=e=>pn(e,Va),vr=e=>pn(e,Ba,!0),mn=(e,t,n)=>{const r=Ma.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},pn=(e,t,n=!1)=>{const r=Pa.exec(e);return r?r[1]?t(r[1]):n:!1},Ua=e=>e==="position"||e==="percentage",Va=e=>e==="image"||e==="url",ja=e=>e==="length"||e==="size"||e==="bg-size",za=e=>e==="length",vu=e=>e==="number",bu=e=>e==="family-name",Ba=e=>e==="shadow",Su=()=>{const e=Oe("color"),t=Oe("font"),n=Oe("text"),r=Oe("font-weight"),o=Oe("tracking"),i=Oe("leading"),s=Oe("breakpoint"),a=Oe("container"),c=Oe("spacing"),d=Oe("radius"),h=Oe("shadow"),u=Oe("inset-shadow"),f=Oe("text-shadow"),_=Oe("drop-shadow"),p=Oe("blur"),g=Oe("perspective"),v=Oe("aspect"),m=Oe("ease"),E=Oe("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"],w=()=>[...k(),j,V],N=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],b=()=>[j,V,c],S=()=>[hn,"full","auto",...b()],x=()=>[Mt,"none","subgrid",j,V],I=()=>["auto",{span:["full",Mt,j,V]},Mt,j,V],H=()=>[Mt,"auto",j,V],ne=()=>["auto","min","max","fr",j,V],xe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],de=()=>["start","end","center","stretch","center-safe","end-safe"],Q=()=>["auto",...b()],me=()=>[hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],P=()=>[e,j,V],U=()=>[...k(),Fa,La,{position:[j,V]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Y=()=>["auto","cover","contain",Eu,fu,{size:[j,V]}],re=()=>[To,qn,zt],$=()=>["","none","full",d,j,V],W=()=>["",te,qn,zt],we=()=>["solid","dashed","dotted","double"],pe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],se=()=>[te,To,Fa,La],Ke=()=>["","none",p,j,V],Ye=()=>["none",te,j,V],Qe=()=>["none",te,j,V],D=()=>[te,j,V],ue=()=>[hn,"full",...b()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[wt],breakpoint:[wt],color:[du],container:[wt],"drop-shadow":[wt],ease:["in","out","in-out"],font:[pu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[wt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[wt],shadow:[wt],spacing:["px",te],text:[wt],"text-shadow":[wt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",hn,V,j,v]}],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:w()}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Mt,"auto",j,V]}],basis:[{basis:[hn,"full","auto",a,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[te,hn,"auto","initial","none",V]}],grow:[{grow:["",te,j,V]}],shrink:[{shrink:["",te,j,V]}],order:[{order:[Mt,"first","last","none",j,V]}],"grid-cols":[{"grid-cols":x()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":x()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ne()}],"auto-rows":[{"auto-rows":ne()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...xe(),"normal"]}],"justify-items":[{"justify-items":[...de(),"normal"]}],"justify-self":[{"justify-self":["auto",...de()]}],"align-content":[{content:["normal",...xe()]}],"align-items":[{items:[...de(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...de(),{baseline:["","last"]}]}],"place-content":[{"place-content":xe()}],"place-items":[{"place-items":[...de(),"baseline"]}],"place-self":[{"place-self":["auto",...de()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:Q()}],mx:[{mx:Q()}],my:[{my:Q()}],ms:[{ms:Q()}],me:[{me:Q()}],mt:[{mt:Q()}],mr:[{mr:Q()}],mb:[{mb:Q()}],ml:[{ml:Q()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:me()}],w:[{w:[a,"screen",...me()]}],"min-w":[{"min-w":[a,"screen","none",...me()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...me()]}],h:[{h:["screen","lh",...me()]}],"min-h":[{"min-h":["screen","lh","none",...me()]}],"max-h":[{"max-h":["screen","lh",...me()]}],"font-size":[{text:["base",n,qn,zt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,j,Co]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",To,V]}],"font-family":[{font:[_u,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,Co]}],leading:[{leading:[i,...b()]}],"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:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...we(),"wavy"]}],"text-decoration-thickness":[{decoration:[te,"from-font","auto",j,zt]}],"text-decoration-color":[{decoration:P()}],"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:b()}],"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:U()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:Y()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Mt,j,V],radial:["",j,V],conic:[Mt,j,V]},yu,gu]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:re()}],"gradient-via-pos":[{via:re()}],"gradient-to-pos":[{to:re()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:$()}],"rounded-s":[{"rounded-s":$()}],"rounded-e":[{"rounded-e":$()}],"rounded-t":[{"rounded-t":$()}],"rounded-r":[{"rounded-r":$()}],"rounded-b":[{"rounded-b":$()}],"rounded-l":[{"rounded-l":$()}],"rounded-ss":[{"rounded-ss":$()}],"rounded-se":[{"rounded-se":$()}],"rounded-ee":[{"rounded-ee":$()}],"rounded-es":[{"rounded-es":$()}],"rounded-tl":[{"rounded-tl":$()}],"rounded-tr":[{"rounded-tr":$()}],"rounded-br":[{"rounded-br":$()}],"rounded-bl":[{"rounded-bl":$()}],"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:[...we(),"hidden","none"]}],"divide-style":[{divide:[...we(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...we(),"none","hidden"]}],"outline-offset":[{"outline-offset":[te,j,V]}],"outline-w":[{outline:["",te,qn,zt]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",h,vr,yr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,vr,yr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[te,zt]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",f,vr,yr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[te,j,V]}],"mix-blend":[{"mix-blend":[...pe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":pe()}],"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":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"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":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"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":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"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":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"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":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"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":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"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":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[j,V]}],"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":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"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":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:U()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:Y()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",j,V]}],filter:[{filter:["","none",j,V]}],blur:[{blur:Ke()}],brightness:[{brightness:[te,j,V]}],contrast:[{contrast:[te,j,V]}],"drop-shadow":[{"drop-shadow":["","none",_,vr,yr]}],"drop-shadow-color":[{"drop-shadow":P()}],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":Ke()}],"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":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"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",E,j,V]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,j,V]}],"perspective-origin":[{"perspective-origin":w()}],rotate:[{rotate:Ye()}],"rotate-x":[{"rotate-x":Ye()}],"rotate-y":[{"rotate-y":Ye()}],"rotate-z":[{"rotate-z":Ye()}],scale:[{scale:Qe()}],"scale-x":[{"scale-x":Qe()}],"scale-y":[{"scale-y":Qe()}],"scale-z":[{"scale-z":Qe()}],"scale-3d":["scale-3d"],skew:[{skew:D()}],"skew-x":[{"skew-x":D()}],"skew-y":[{"skew-y":D()}],transform:[{transform:[j,V,"","none","gpu","cpu"]}],"transform-origin":[{origin:w()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ue()}],"translate-x":[{"translate-x":ue()}],"translate-y":[{"translate-y":ue()}],"translate-z":[{"translate-z":ue()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"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":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"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",...P()]}],"stroke-w":[{stroke:[te,qn,zt,Co]}],stroke:[{stroke:["none",...P()]}],"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"]}},wu=nu(Su);function A(...e){return wu(xa(e))}function Bt(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 Nu=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},xu=e=>new Promise(t=>setTimeout(t,e)),$a=J(({className:e,children:t,...n},r)=>l(pi,{ref:r,className:A("relative overflow-hidden",e),...n,children:[l(fd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(Ha,{}),l(gd,{})]}));$a.displayName=pi.displayName;const Ha=J(({className:e,orientation:t="vertical",...n},r)=>l(mo,{ref:r,orientation:t,className:A("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(li,{className:"relative flex-1 rounded-full bg-border"})}));Ha.displayName=mo.displayName;var Tu=Symbol.for("react.lazy"),br=co[" use ".trim().toString()];function Cu(e){return typeof e=="object"&&e!==null&&"then"in e}function Ya(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Tu&&"_payload"in e&&Cu(e._payload)}function Ga(e){const t=Ru(e),n=J((r,o)=>{let{children:i,...s}=r;Ya(i)&&typeof br=="function"&&(i=br(i._payload));const a=Xe.toArray(i),c=a.find(Au);if(c){const d=c.props.children,h=a.map(u=>u===c?Xe.count(d)>1?Xe.only(null):Ze(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Ze(d)?Rt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var ku=Ga("Slot");function Ru(e){const t=J((n,r)=>{let{children:o,...i}=n;if(Ya(o)&&typeof br=="function"&&(o=br(o._payload)),Ze(o)){const s=Mu(o),a=Iu(i,o.props);return o.type!==ce&&(a.ref=r?uo(r,s):s),Rt(o,a)}return Xe.count(o)>1?Xe.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Ou=Symbol("radix.slottable");function Au(e){return Ze(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ou}function Iu(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 Mu(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 Wa=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ka=xa,Pu=(e,t)=>n=>{var r;if(t?.variants==null)return Ka(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=Wa(h)||Wa(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,..._}=h;return Object.entries(_).every(p=>{let[g,v]=p;return Array.isArray(v)?v.includes({...i,...a}[g]):{...i,...a}[g]===v})?[...d,u,f]:d},[]);return Ka(e,s,c,n?.class,n?.className)},Du=Pu("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"}}),le=J(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?ku:"button",{className:A(Du({variant:t,size:n,className:e})),ref:i,...o}));le.displayName="Button";const Lu=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Fu=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),qa=e=>{const t=Fu(e);return t.charAt(0).toUpperCase()+t.slice(1)},Xa=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Uu=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Vu={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 ju=J(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>Ge("svg",{ref:c,...Vu,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Xa("lucide",o),...!i&&!Uu(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>Ge(d,h)),...Array.isArray(i)?i:[i]])),Ie=(e,t)=>{const n=J(({className:r,...o},i)=>Ge(ju,{ref:i,iconNode:t,className:Xa(`lucide-${Lu(qa(e))}`,`lucide-${e}`,r),...o}));return n.displayName=qa(e),n},zu=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ko=Ie("chevron-down",zu),Bu=[["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"}]],$u=Ie("ellipsis-vertical",Bu),Hu=[["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"}]],Za=Ie("file-text",Hu),Yu=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Ja=Ie("info",Yu),Gu=[["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"}]],Wu=Ie("maximize-2",Gu),Ku=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],qu=Ie("menu",Ku),Xu=[["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"}]],Xn=Ie("message-square-plus",Xu),Zu=[["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"}]],Ro=Ie("mic",Zu),Ju=[["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"}]],Qu=Ie("minimize-2",Ju),eh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Qa=Ie("plus",eh),th=[["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"}]],nh=Ie("rotate-ccw",th),rh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],el=Ie("square",rh),oh=[["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"}]],Sr=Ie("thumbs-up",oh),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"}]],wr=Ie("thumbs-down",sh),ih=[["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"}]],ah=Ie("triangle-alert",ih),lh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],fn=Ie("x",lh),ch=[["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"}]],dh=Ie("zoom-in",ch),tl=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},uh=(e=>e?tl(e):tl),hh=e=>e;function mh(e,t=hh){const n=xn.useSyncExternalStore(e.subscribe,xn.useCallback(()=>t(e.getState()),[e,t]),xn.useCallback(()=>t(e.getInitialState()),[e,t]));return xn.useDebugValue(n),n}const ph=e=>{const t=uh(e),n=r=>mh(t,r);return Object.assign(n,t),n},fh=(e=>ph);function nl(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 Oo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Oo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Oo(r)(n)}}}},gh=(e,t)=>(n,r,o)=>{let i={storage:nl(()=>localStorage),partialize:g=>g,version:0,merge:(g,v)=>({...v,...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,v)=>(u(g,v),h());const f=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>f;let _;const p=()=>{var g,v;if(!d)return;s=!1,a.forEach(E=>{var y;return E((y=r())!=null?y:f)});const m=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(g=r())!=null?g:f))||void 0;return Oo(d.getItem.bind(d))(i.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==i.version){if(i.migrate){const y=i.migrate(E.state,E.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,E.state];return[!1,void 0]}).then(E=>{var y;const[k,w]=E;if(_=i.merge(w,(y=r())!=null?y:f),n(_,!0),k)return h()}).then(()=>{m?.(_,void 0),_=r(),s=!0,c.forEach(E=>E(_))}).catch(E=>{m?.(void 0,E)})};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(),_||f},_h=gh,je={USER:"user",ASSISTANT:"assistant"};var Ee=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Ee||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let Nt="";const Zn=e=>`med-assist-store-${e}`,Eh=e=>{Nt=Zn(e)},rl={sessionId:"",isStreaming:!1,recordingStatus:Ee.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:{}},ol={...rl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},G=fh()(_h((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:Ee.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(rl),await sessionStorage.removeItem(Nt||Zn(t().agentId))},clearUser:()=>{e(ol),sessionStorage.removeItem(Nt||Zn(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:nl(()=>({getItem:()=>Nt?sessionStorage.getItem(Nt):null,setItem:(e,t)=>{Nt&&sessionStorage.setItem(Nt,t)},removeItem:()=>{Nt&&sessionStorage.removeItem(Nt)}})),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})})),yh=e=>{const t=Zn(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(ol),n&&G.setState(n)},Ao=vt(null),vh=({children:e})=>{const[t,n]=L(null);return l(Ao.Provider,{value:{synapse:t,setSynapse:n},children:e})},bh=()=>{const e=St(Ao);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Sh=()=>{const e=St(Ao);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},wh=()=>{const[e,t]=L(M.VOICE_AGENT_STATE.IDLE),[n,r]=L(!1),o=bh(),{setError:i}=G();z(()=>{if(!o)return;const h=o.voice,u=_=>{t(_)},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=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}},$t=J(({className:e,...t},n)=>l("div",{ref:n,className:A("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));$t.displayName="Card";const sl=J(({className:e,...t},n)=>l("div",{ref:n,className:A("flex flex-col space-y-1.5 p-6",e),...t}));sl.displayName="CardHeader";const il=J(({className:e,...t},n)=>l("div",{ref:n,className:A("font-semibold leading-none tracking-tight",e),...t}));il.displayName="CardTitle";const Nh=J(({className:e,...t},n)=>l("div",{ref:n,className:A("text-sm text-muted-foreground",e),...t}));Nh.displayName="CardDescription";const al=J(({className:e,...t},n)=>l("div",{ref:n,className:A("p-6 pt-0",e),...t}));al.displayName="CardContent";const ll=J(({className:e,...t},n)=>l("div",{ref:n,className:A("flex items-center p-6 pt-0",e),...t}));ll.displayName="CardFooter";const Io=5,xh=10*1024*1024,Nr={width:384,height:600},xr=20,Th=150;function Ch({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=fe(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Nr.width-xr,y:window.innerHeight-Nr.height-xr},[]),[i,s]=L(()=>e??o()),[a,c]=L(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);z(()=>{t||(u.current=!1)},[t]),at(()=>{!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 v=()=>{s(E=>{const y=Math.max(0,window.innerWidth-Nr.width-xr),k=Math.max(0,window.innerHeight-Nr.height-xr),w=Math.max(0,Math.min(E.x,y)),N=Math.max(0,Math.min(E.y,k));return w===E.x&&N===E.y?E:{x:w,y:N}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(v,Th)};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 v=h.current;if(v){const m=v.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]),_=fe(g=>{if(!t||!a)return;const v=g.clientX-d.current.x,m=g.clientY-d.current.y,E=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(v,E)),w=Math.max(0,Math.min(m,y));s({x:k,y:w})},[a,t]),p=fe(()=>{!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",_),document.addEventListener("mouseup",p),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""}},[a,_,p]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Mo="#6B5CE0",kh="#F0F0F0",Tr={background:kh,backgroundImage:void 0,primary:Mo,textColor:"black"},Rh="rgba(0, 0, 0, 0.4)",Oh="24px";function Ah(e){if(e==="dark")return"white";if(e==="light")return"black"}function Ih(e){const t=e?.primary??e?.primaryColor??Tr.primary,n=e?.textColor??Ah(e?.mode);return{background:e?.background??Tr.background,backgroundImage:e?.backgroundImage??Tr.backgroundImage,primary:t,primaryColor:t,textColor:n??Tr.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Mh(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 Ph(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 Dh(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 Po(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return Mh(t);if(t.startsWith("rgb"))return Ph(t);if(t.startsWith("hsl"))return Dh(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function cl(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Do(e){return cl(e)>.5?"0 0% 9%":"0 0% 98%"}function Lh(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 Fh(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 dl(e,t){const n=t.primary??Mo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(_,p)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(_,p)};let c;try{c=Po(n)}catch{c=Po(Mo)}a("--primary",c),a("--primary-foreground",Do(c)),a("--ring",c),a("--border-primary",c);const d=Fh(c);for(const[_,p]of Object.entries(d))a(`--primary-${_}`,p);const h=Do(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const _=i?"#191919":"#F0F0F0";try{a("--background",Po(_))}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",Lh(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 _=cl(h)>.5;a("--header-tagline",_?"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 _ of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${_}`,`var(--${f}-${_})`);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",Do(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",Oh),a("--theme-background-overlay",Rh),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 Ht({className:e,style:t}){return l("div",{className:A("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 Lo(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function ul(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Lo,{}),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(Ht,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Ht,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Ht,{className:"h-9 w-9 rounded-full"}),l(Ht,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function Uh(){return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(Lo,{}),[{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:A("flex",e.role==="user"?"justify-end":"justify-start"),children:l(Ht,{className:A("rounded-lg",e.size)})},t))]})}function Vh({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(Lo,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Ht,{className:A("h-5 rounded-md",t[r%t.length])}),l(Ht,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function jh(e,t=[]){let n=[];function r(i,s){const a=vt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:_,...p}=u,g=f?.[e]?.[c]||a,v=_e(()=>p,Object.values(p));return l(g.Provider,{value:v,children:_})};d.displayName=i+"Provider";function h(u,f){const _=f?.[e]?.[c]||a,p=St(_);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=>vt(s));return function(s){const a=s?.[e]||i;return _e(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,zh(o,...t)]}function zh(...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 _e(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Bh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Fo=Bh.reduce((e,t)=>{const n=Ga(`Primitive.${t}`),r=J((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}},{}),hl={exports:{}},Uo={};const $h=_d(co);var ml;function Hh(){if(ml)return Uo;ml=1;var e=$h;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 _=f(),p=r({inst:{value:_,getSnapshot:f}}),g=p[0].inst,v=p[1];return i(function(){g.value=_,g.getSnapshot=f,c(g)&&v({inst:g})},[u,_,f]),o(function(){return c(g)&&v({inst:g}),u(function(){c(g)&&v({inst:g})})},[u]),s(_),_}function c(u){var f=u.getSnapshot;u=u.value;try{var _=f();return!n(u,_)}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 Uo.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,Uo}var pl;function Yh(){return pl||(pl=1,hl.exports=Hh()),hl.exports}var Gh=Yh();function Wh(){return Gh.useSyncExternalStore(Kh,()=>!0,()=>!1)}function Kh(){return()=>{}}var Vo="Avatar",[qh]=jh(Vo),[Xh,fl]=qh(Vo),gl=J((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=L("idle");return l(Xh,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(Fo.span,{...r,ref:t})})});gl.displayName=Vo;var _l="AvatarImage",El=J((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=fl(_l,n),a=Zh(r,i),c=At(d=>{o(d),s.onImageLoadingStatusChange(d)});return jt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(Fo.img,{...i,ref:t,src:r}):null});El.displayName=_l;var yl="AvatarFallback",vl=J((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=fl(yl,n),[s,a]=L(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(Fo.span,{...o,ref:t}):null});vl.displayName=yl;function bl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Zh(e,{referrerPolicy:t,crossOrigin:n}){const r=Wh(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=L(()=>bl(i,e));return jt(()=>{a(bl(i,e))},[i,e]),jt(()=>{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 Sl=gl,wl=El,Nl=vl;const jo=J(({className:e,...t},n)=>l(Sl,{ref:n,className:A("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));jo.displayName=Sl.displayName;const xl=J(({className:e,...t},n)=>l(wl,{ref:n,className:A("aspect-square h-full w-full",e),...t}));xl.displayName=wl.displayName;const zo=J(({className:e,...t},n)=>l(Nl,{ref:n,className:A("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));zo.displayName=Nl.displayName;const Tl=vt(!1);function Jh({enabled:e,children:t}){return l(Tl.Provider,{value:e,children:t})}function Qh(){return St(Tl)}const Cl="(max-width: 768px), (pointer: coarse)",kl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function em(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Cl)?.matches??!1,t=kl.test(navigator?.userAgent??"");return e||t}function Rl(){const[e,t]=L(em);return z(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Cl),r=kl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function tm({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=Rl(),_=Qh()&&!f,p=G(S=>S.displayMode)==="full",g=G(S=>S.initialDisplayMode)==="full",v=!p&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",m=G(S=>S.connectionStatus),E=G(S=>S.level)==="user",[y,k]=L(!1),w=X(null),N=_e(()=>a==="connected"||a==="connecting"||a==="listening"||a==="speaking"||a==="thinking",[a]),T=fe(()=>{y||(k(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,k(!1)},6e3),s())},[y,s]);z(()=>{m===ge.CONNECTED&&(k(!1),w.current&&clearTimeout(w.current))},[m]);const b=(()=>{switch(m){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(jo,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(zo,{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:A("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",b.dotColor,m===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:A("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",v),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:b.text})})]})]}),l("div",{className:A("flex items-center",!_&&"gap-1"),children:[!N&&(!E||!u)&&l(le,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:T,disabled:y,className:A("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",v),children:l(Xn,{className:"w-5 h-5"})}),h&&E&&l(le,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:A("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:l($u,{className:"w-5 h-5"})}),_&&l(le,{onClick:d,type:"button",variant:"ghost",size:"icon",title:p?"Exit fullscreen":"Enter fullscreen",className:A("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:p?l(Qu,{className:"w-8 h-8"}):l(Wu,{className:"w-8 h-8"})}),(t||!g)&&l(le,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:A("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:l(fn,{className:"w-8 h-8"})})]})]})})}const Bo=J(({className:e,...t},n)=>l("textarea",{className:A("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}));Bo.displayName="Textarea";function Ol({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=L(!1),[s,a]=L(""),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 _=1024,p=["B","KB","MB","GB"],g=Math.floor(Math.log(f)/Math.log(_));return`${(f/Math.pow(_,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(Za,{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(fn,{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(fn,{className:"h-3 w-3"})})]})}function $o({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(Ol,{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(Ol,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const Ho=({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"})}),Al=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),nm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Il=({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"})}),rm=We(()=>Al().then(e=>({default:e.ElicitationInput})));function om({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:_,allowed:p,showStartNewChatButton:g,onStartNewChat:v,isVoiceAgentActive:m,handleVoiceMode:E,isAuthComponent:y,activeElicitationState:k,isFullScreen:w}){const N=X(null),T=X(null),b=e.trim().length>0||a,S=!p||p.includes(M.SYNAPSE_CONVERSATION.AUDIO),x=!p||p.includes(M.SYNAPSE_CONVERSATION.VOICE),I=b||!S,H=b,ne=!p||p.includes(M.SYNAPSE_CONVERSATION.FILE),xe=(d||f!==Ee.IDLE)&&!s,de=A("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)]":xe?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),Q=Y=>{const re=Array.from(Y.target.files||[]);re.length>0&&r(re)},me=()=>{d||(N.current&&(N.current.value=""),N.current?.click())},P=Y=>{Y.key==="Enter"&&!Y.shiftKey&&H&&!d&&(Y.preventDefault(),n())},U=Y=>{Y.style.height="auto",Y.style.overflow="hidden";const re=Y.scrollHeight,$=w?20:28,W=120,we=Math.max($,Math.min(re,W));Y.style.height=we+"px",re>W?Y.style.overflow="auto":Y.style.overflow="hidden"},Z=Y=>{U(Y.currentTarget)};return z(()=>{T.current&&U(T.current)},[e]),z(()=>{!d&&!u&&T.current?.focus()},[d]),g&&v?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:v,className:A("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(Xn,{className:"w-5 h-5","aria-hidden":!0})]})}):l(ce,{children:y?l($e,{fallback:l(ul,{}),children:l(rm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:_,isMobile:u,onSend:n})}):w?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($o,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:N,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:Q,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(Bo,{ref:T,onInput:Z,placeholder:h,value:e,onChange:Y=>t(Y.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:P,title:"Enter your message","aria-label":"Enter your message",className:A("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:ne&&f===Ee.IDLE&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:me,disabled:d,className:A("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(Qa,{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(le,{type:"button",variant:"ghost",size:"icon",onClick:i,className:A("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(el,{className:"w-4 h-4"})}):S&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:xe,className:A("h-10 w-10 shrink-0 p-2",de),title:"Start recording","aria-label":"Start recording",children:l(Ro,{className:"w-6 h-6",strokeWidth:1.5})}),I&&!s?l(le,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!H,variant:"ghost",className:A("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",H?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:H?"Send message":"Type a message to send","aria-label":H?"Send message":"Type a message to send",children:l(Ho,{className:"w-4 h-4 text-primary-foreground"})}):S&&x&&!s&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:E,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(Il,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:N,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:Q,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($o,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(Bo,{ref:T,onInput:Z,placeholder:h,value:e,onChange:Y=>t(Y.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:P,title:"Enter your message","aria-label":"Enter your message",className:A("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:ne&&f===Ee.IDLE&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:me,disabled:d,className:A("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(Qa,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,className:A("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(el,{className:"w-4 h-4"})}):I?l(le,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!H,variant:"ghost",className:A("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",H?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:H?"Send message":"Type a message to send","aria-label":H?"Send message":"Type a message to send",children:l(Ho,{className:"w-4 h-4 text-primary-foreground"})}):S&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:xe,className:A("h-10 w-10 shrink-0",de),title:"Start recording","aria-label":"Start recording",children:l(Ro,{className:"w-5 h-5",strokeWidth:1.5})}),S&&x&&!s&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:E,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(Il,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}function sm({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(fn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function im(){const e=G(r=>r.toastMessage),t=G(r=>r.setToastMessage),n=fe(()=>{t(null)},[t]);return z(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(sm,{message:e,onDismiss:n}):null}function Yo({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 am="Before we begin",lm=e=>`A quick note on how ${e} works and handles your information.`,Ml=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.`],cm="I agree and consent",dm="By continuing, you consent to the above.",um="Continue";function Pl({botName:e,isFullScreen:t}){return l(ce,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:A("font-semibold text-foreground text-left text-pretty",t?"text-2xl":"text-lg"),children:am}),l("p",{className:A("text-muted-foreground text-left text-pretty",t?"text-sm leading-5":"text-xs leading-4"),children:lm(e)})]}),l("div",{className:A("overflow-y-auto rounded-lg border border-border-subtle flex flex-col",t?"max-h-[340px] p-4 gap-4":"max-h-[180px] p-3 gap-3"),tabIndex:0,role:"region","aria-label":"Consent details",children:Ml(e).map((n,r)=>l("p",{className:A("text-foreground/80 text-left text-pretty",t?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:n},r))})]})}function hm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,isFullScreen:o}){const i=!!r&&!!o;return l(Yo,{isOpen:e,onClose:t,children:l("div",{className:A("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",i?"p-8 gap-6 max-w-[560px]":"p-6 gap-4 max-w-[320px]"),children:[r?l(Pl,{botName:n,isFullScreen:i}):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"}),Ml(n).map((s,a)=>l("p",{className:A("text-foreground/80 text-left text-pretty",o?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:s},a))]}),l(le,{onClick:t,className:A("w-full bg-primary hover:bg-primary/90 text-primary-foreground",i&&"h-11 text-base"),children:"Got it"})]})})}function mm({isOpen:e,botName:t,onAccept:n,isFullScreen:r}){const[o,i]=L(!1);return e?l(Yo,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:A("bg-elicitationBg rounded-2xl shadow-xl mx-6 w-full flex flex-col border border-primary/50",r?"p-8 gap-6 max-w-[560px]":"p-5 gap-4 max-w-[320px]"),children:[l(Pl,{botName:t,isFullScreen:r}),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:o,onChange:()=>i(s=>!s),className:"sr-only peer"}),l("div",{"aria-hidden":"true",className:A("shrink-0 rounded-[4px] border transition-colors flex items-center justify-center peer-focus-visible:ring-2 peer-focus-visible:ring-primary/50",r?"w-5 h-5":"w-4 h-4",o?"border-primary bg-primary":"border-muted-foreground bg-transparent"),children:o&&l("svg",{width:r?"11":"9",height:r?"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:A("text-foreground cursor-pointer",r?"text-base":"text-sm"),children:cm})]}),l("p",{className:A("text-muted-foreground text-left text-pretty cursor-pointer",r?"text-xs leading-[18px] pl-7":"text-[10px] leading-[14px] pl-6"),onChange:()=>i(s=>!s),children:dm})]}),l(le,{disabled:!o,onClick:()=>o&&n(),className:A("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",r&&"h-11 text-base"),children:um})]})}):null}const pm=We(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),fm=We(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),gm=We(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),_m=We(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),Em=We(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),ym=[{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"}],vm=[{Icon:pm,label:"Bad",score:1},{Icon:fm,label:"Poor",score:2},{Icon:gm,label:"Okay",score:3},{Icon:_m,label:"Good",score:4},{Icon:Em,label:"Great!",score:5}];function bm(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Sm({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=L(null),[d,h]=L(new Set),[u,f]=L(!1),_=s&&a!==null?bm(a,t):t.form?.default?.length?t.form.default:ym,p=E=>{h(y=>{const k=new Set(y);return k.has(E)?k.delete(E):k.add(E),k})},g=E=>{c(E),h(new Set)},v=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(Yo,{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:vm.map(({Icon:E,label:y,score:k})=>{const w=a===k,N=a!==null&&!w;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 ${w?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${N?"opacity-50":""}`,style:w?{filter:"brightness(1.25)"}:void 0,children:l($e,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(E,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${w?"text-primary/50 font-medium":N?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&_.length>0&&l("div",{className:"flex flex-col gap-2",children:_.map(E=>l("div",{onClick:()=>p(E.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(E.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:E.label},E.value))}),l(le,{disabled:!v,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(E=>!E),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 Dl({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:_,chatComposer:p,environment:g,mode:v,onToggleDisplayMode:m,onOpenSessionDrawer:E,historyEnabled:y=!1,isAuthComponent:k,activeElicitation:w,voiceAgentState:N,theme:T,feedbackModal:b,consentModal:S}){const[x,I]=L(!1),[H,ne]=L(!1),[xe,de]=L(!1),Q=X(null),me=G(D=>D.level),P=v,U=P==="full",Z=X(null),[Y,re]=L("");z(()=>{Z.current!==null&&Z.current!==P&&re(P==="full"?"Switched to fullscreen mode":P==="widget"?"Switched to widget mode":"Switched to mobile layout"),Z.current=P},[P]);const $=_e(()=>Ih(T),[T]),{setIsMobile:W}=G(D=>D),we=!!k,pe=async D=>{if(!(!p?.onSend||H)){ne(!0);try{await p.onSend(D)}finally{ne(!1)}}};at(()=>{if(!Q.current)return;const D=P==="full"?{...$,headerTinted:!1}:$;dl(Q.current,D),P==="full"&&!$.backgroundImage?(Q.current.style.setProperty("--background","0 0% 100%"),Q.current.style.setProperty("--widget-bg-overlay","transparent")):(Q.current.style.removeProperty("--background"),Q.current.style.removeProperty("--widget-bg-overlay"),dl(Q.current,$))},[$,P]),z(()=>{const D=()=>{const ue=window?.innerWidth??0,ie=navigator?.userAgent?.toLowerCase()??"",ke=ue<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ie);I(ke),W(ke)};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]),at(()=>{if(!e||!x||!Q.current)return;const D=Q.current;let ue=null,ie=null,ke=null,Me=window.visualViewport?.offsetTop??0,Te=0;const ct=2,Ae=80;if(window.visualViewport){const Ne=()=>{if(D&&window.visualViewport){const Be=window.visualViewport.height,Re=window.visualViewport.offsetTop;ue=requestAnimationFrame(()=>{D.style.transition="none",D.style.top=`${Re}px`,D.style.left="0",D.style.right="0",D.style.bottom="auto",D.style.width="100vw",D.style.height=`${Be}px`,D.style.maxHeight=`${Be}px`,D.style.minHeight=`${Be}px`,ie&&clearTimeout(ie),ie=setTimeout(()=>{D.style.transition=""},100)})}},et=()=>{Ne()},ze=()=>{if(!D||!window.visualViewport)return;const Be=window.visualViewport.offsetTop,Re=Date.now();Math.abs(Be-Me)<ct||Re-Te<Ae||(Te=Re,Me=Be,ue=requestAnimationFrame(()=>{D.style.transition="none",D.style.top=`${Be}px`,ke&&clearTimeout(ke),ke=setTimeout(()=>{D.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",et),window.visualViewport.addEventListener("scroll",ze),Ne(),()=>{ue&&cancelAnimationFrame(ue),ie&&clearTimeout(ie),ke&&clearTimeout(ke),window.visualViewport?.removeEventListener("resize",et),window.visualViewport?.removeEventListener("scroll",ze),D&&(D.style.width="",D.style.height="",D.style.maxHeight="",D.style.minHeight="",D.style.transition="")}}else{const Ne=()=>{D&&(D.style.transition="none",D.style.top="0",D.style.left="0",D.style.right="0",D.style.bottom="auto",D.style.width="100vw",D.style.height="100svh",D.style.maxHeight="100svh",setTimeout(()=>{D.style.transition=""},100))};return window.addEventListener("resize",Ne),Ne(),()=>{window.removeEventListener("resize",Ne),D&&(D.style.width="",D.style.height="",D.style.maxHeight="",D.style.transition="")}}},[e,x]),z(()=>{if(e){const D=Q.current,ue=window.scrollY,ie=document.body.style.cssText,ke=document.documentElement.style.overflow,Me=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${ue}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",Me>0&&!x&&(document.body.style.paddingRight=`${Me}px`);let Te=0;const ct=Ne=>{Te=Ne.touches[0].clientY},Ae=Ne=>{if(Ne.touches.length!==1)return;const et=Te-Ne.touches[0].clientY;Te=Ne.touches[0].clientY;let ze=Ne.target;for(;ze&&ze!==D;){const{overflowY:Be}=window.getComputedStyle(ze);if((Be==="auto"||Be==="scroll")&&ze.scrollHeight>ze.clientHeight){const{scrollTop:Re,scrollHeight:Dt,clientHeight:dt}=ze,Kt=Re<=0&&et<0,ut=Re+dt>=Dt-1&&et>0;if(!Kt&&!ut)return;break}ze=ze.parentElement}Ne.preventDefault()};return D&&(D.addEventListener("touchstart",ct,{passive:!0}),D.addEventListener("touchmove",Ae,{passive:!1})),()=>{D&&(D.removeEventListener("touchstart",ct),D.removeEventListener("touchmove",Ae)),document.body.style.cssText=ie,document.documentElement.style.overflow=ke,window.scrollTo(0,ue)}}},[e,x]);const{position:se,elementRef:Ke}=Ch({enabled:e&&!x&&!U});z(()=>{Q.current&&(Ke.current=Q.current)},[Ke]);const Ye=A("synapse-chat-widget-container","fixed m-0 p-0","box-border",!x&&!U?"transition-[opacity,transform] duration-300":"",x?"w-screen h-[100svh]":U?"w-screen h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Qe=A("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",$.backgroundImage?"theme-with-background":"",x?"rounded-none border-0 flex-col":U?"rounded-none border-0 flex-row":"rounded-3xl flex-col");return l("div",{ref:Q,"data-mode":P,className:Ye,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...U&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...U&&!e&&{display:"none"},...!x&&!U&&{left:`${se.x}px`,top:`${se.y}px`,bottom:"auto",right:"auto"},...x&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:$.backgroundImage?"transparent":"hsl(var(--background))"}},children:[l("style",{children:`
1
+ var yc=Object.defineProperty;var vc=(e,t,n)=>t in e?yc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>vc(e,typeof t!="symbol"?t+"":t,n);var vn,q,os,kt,ss,is,as,Ur,rr,bn,ls,Fr,Vr,jr,cs,or={},sr=[],bc=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Sn=Array.isArray;function pt(e,t){for(var n in t)e[n]=t[n];return e}function zr(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Ge(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?vn.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 wn(e,s,r,o,null)}function wn(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??++os,__i:-1,__u:0};return o==null&&q.vnode!=null&&q.vnode(i),i}function ds(){return{current:null}}function ce(e){return e.children}function ot(e,t){this.props=e,this.context=t}function Qt(e,t){if(t==null)return e.__?Qt(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"?Qt(e):null}function Sc(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=pt({},t);i.__v=t.__v+1,q.vnode&&q.vnode(i),$r(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??Qt(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,gs(r,i,o),t.__e=t.__=null,i.__e!=n&&us(i)}}function us(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}),us(e)}function Br(e){(!e.__d&&(e.__d=!0)&&kt.push(e)&&!ir.__r++||ss!=q.debounceRendering)&&((ss=q.debounceRendering)||is)(ir)}function ir(){try{for(var e,t=1;kt.length;)kt.length>t&&kt.sort(as),e=kt.shift(),t=kt.length,Sc(e)}finally{kt.length=ir.__r=0}}function hs(e,t,n,r,o,i,s,a,c,d,h){var u,f,_,p,g,v,m,E=r&&r.__k||sr,y=t.length;for(c=wc(n,t,E,c,y),u=0;u<y;u++)(_=n.__k[u])!=null&&(f=_.__i!=-1&&E[_.__i]||or,_.__i=u,v=$r(e,_,f,o,i,s,a,c,d,h),p=_.__e,_.ref&&f.ref!=_.ref&&(f.ref&&Yr(f.ref,null,_),h.push(_.ref,_.__c||p,_)),g==null&&p!=null&&(g=p),(m=!!(4&_.__u))||f.__k===_.__k?(c=ms(_,c,e,m),m&&f.__e&&(f.__e=null)):typeof _.type=="function"&&v!==void 0?c=v:p&&(c=p.nextSibling),_.__u&=-7);return n.__e=g,c}function wc(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]=wn(null,s,null,null,null):Sn(s)?s=e.__k[i]=wn(ce,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=wn(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=Nc(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=Qt(a)),Es(a,a));return r}function ms(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=ms(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=Qt(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function yt(e,t){return t=t||[],e==null||typeof e=="boolean"||(Sn(e)?e.some(function(n){yt(n,t)}):t.push(e)),t}function Nc(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 ps(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||bc.test(t)?n:n+"px"}function ar(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||ps(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ps(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(ls,"$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[bn]=r[bn]:(n[bn]=Fr,e.addEventListener(t,i?jr:Vr,i)):e.removeEventListener(t,i?jr:Vr,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 fs(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[rr]==null)t[rr]=Fr++;else if(t[rr]<n[bn])return;return n(q.event?q.event(t):t)}}}function $r(e,t,n,r,o,i,s,a,c,d){var h,u,f,_,p,g,v,m,E,y,k,w,N,T,b,S=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(c=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=q.__b)&&h(t);e:if(typeof S=="function")try{if(m=t.props,E=S.prototype&&S.prototype.render,y=(h=S.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?v=(u=t.__c=n.__c).__=u.__E:(E?t.__c=u=new S(m,k):(t.__c=u=new ot(m,k),u.constructor=S,u.render=Tc),y&&y.sub(u),u.state||(u.state={}),u.__n=r,f=u.__d=!0,u.__h=[],u._sb=[]),E&&u.__s==null&&(u.__s=u.state),E&&S.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=pt({},u.__s)),pt(u.__s,S.getDerivedStateFromProps(m,u.__s))),_=u.props,p=u.state,u.__v=t,f)E&&S.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),E&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(E&&S.getDerivedStateFromProps==null&&m!==_&&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(x){x&&(x.__=t)}),sr.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),E&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(_,p,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,w=q.__r,N=0,E)u.state=u.__s,u.__d=!1,w&&w(t),h=u.render(u.props,u.state,u.context),sr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,w&&w(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++N<25);u.state=u.__s,u.getChildContext!=null&&(r=pt(pt({},r),u.getChildContext())),E&&!f&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(_,p)),T=h!=null&&h.type===ce&&h.key==null?_s(h.props.children):h,a=hs(e,Sn(T)?T:[T],t,n,r,o,i,s,a,c,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),v&&(u.__E=u.__=null)}catch(x){if(t.__v=null,c||i!=null)if(x.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(b=i.length;b--;)zr(i[b]);Hr(t)}else t.__e=n.__e,t.__k=n.__k,x.then||Hr(t);q.__e(x,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=xc(n.__e,t,n,r,o,i,s,c,d);return(h=q.diffed)&&h(t),128&t.__u?void 0:a}function Hr(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(Hr))}function gs(e,t,n){for(var r=0;r<n.length;r++)Yr(n[r],n[++r],n[++r]);q.__c&&q.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){q.__e(i,o.__v)}})}function _s(e){return typeof e!="object"||e==null||e.__b>0?e:Sn(e)?e.map(_s):e.constructor!==void 0?null:pt({},e)}function xc(e,t,n,r,o,i,s,a,c){var d,h,u,f,_,p,g,v=n.props||or,m=t.props,E=t.type;if(E=="svg"?o="http://www.w3.org/2000/svg":E=="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((_=i[d])&&"setAttribute"in _==!!E&&(E?_.localName==E:_.nodeType==3)){e=_,i[d]=null;break}}if(e==null){if(E==null)return document.createTextNode(m);e=document.createElementNS(o,E,m.is&&m),a&&(q.__m&&q.__m(t,i),a=!1),i=null}if(E==null)v===m||a&&e.data==m||(e.data=m);else{if(i=E=="textarea"&&m.defaultValue!=null?null:i&&vn.call(e.childNodes),!a&&i!=null)for(v={},d=0;d<e.attributes.length;d++)v[(_=e.attributes[d]).name]=_.value;for(d in v)_=v[d],d=="dangerouslySetInnerHTML"?u=_:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||ar(e,d,null,_,o);for(d in m)_=m[d],d=="children"?f=_:d=="dangerouslySetInnerHTML"?h=_:d=="value"?p=_:d=="checked"?g=_:a&&typeof _!="function"||v[d]===_||ar(e,d,_,v[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=""),hs(t.type=="template"?e.content:e,Sn(f)?f:[f],t,n,r,E=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&Qt(n,0),a,c),i!=null)for(d=i.length;d--;)zr(i[d]);a&&E!="textarea"||(d="value",E=="progress"&&p==null?e.removeAttribute("value"):p!=null&&(p!==e[d]||E=="progress"&&!p||E=="option"&&p!=v[d])&&ar(e,d,p,v[d],o),d="checked",g!=null&&g!=e[d]&&ar(e,d,g,v[d],o))}return e}function Yr(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){q.__e(o,n)}}function Es(e,t,n){var r,o;if(q.unmount&&q.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Yr(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){q.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Es(r[o],t,n||typeof e.type!="function");n||zr(e.__e),e.__c=e.__=e.__e=void 0}function Tc(e,t,n){return this.constructor(e,n)}function Nn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),q.__&&q.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],$r(t,e=(!r&&n||t).__k=Ge(ce,null,[e]),o||or,or,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?vn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),gs(i,e,s)}function ys(e,t){Nn(e,t,ys)}function Cc(e,t,n){var r,o,i,s,a=pt({},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?vn.call(arguments,2):n),wn(e.type,a,r||e.key,o||e.ref,null)}function vt(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,Br(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"+cs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}vn=sr.slice,q={__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}},os=0,ot.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=pt({},this.state),typeof e=="function"&&(e=e(pt({},n),this.props)),e&&pt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),Br(this))},ot.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Br(this))},ot.prototype.render=ce,kt=[],is=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,as=function(e,t){return e.__v.__b-t.__v.__b},ir.__r=0,Ur=Math.random().toString(8),rr="__d"+Ur,bn="__a"+Ur,ls=/(PointerCapture)$|Capture$/i,Fr=0,Vr=fs(!1),jr=fs(!0),cs=0;var kc=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:--kc,__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 q.vnode&&q.vnode(d),d}var bt,he,Gr,vs,en=0,bs=[],be=q,Ss=be.__b,ws=be.__r,Ns=be.diffed,xs=be.__c,Ts=be.unmount,Cs=be.__;function Vt(e,t){be.__h&&be.__h(he,e,en||t),en=0;var n=he.__H||(he.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function L(e){return en=1,tn(Rs,e)}function tn(e,t,n){var r=Vt(bt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Rs(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 _=f.__[0];f.__=f.__N,f.__N=void 0,_!==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=Vt(bt++,3);!be.__s&&Zr(n.__H,t)&&(n.__=e,n.u=t,he.__H.__h.push(n))}function at(e,t){var n=Vt(bt++,4);!be.__s&&Zr(n.__H,t)&&(n.__=e,n.u=t,he.__h.push(n))}function X(e){return en=5,_e(function(){return{current:e}},[])}function Wr(e,t,n){en=6,at(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 _e(e,t){var n=Vt(bt++,7);return Zr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function fe(e,t){return en=8,_e(function(){return e},t)}function St(e){var t=he.context[e.__c],n=Vt(bt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(he)),t.props.value):e.__}function Kr(e,t){be.useDebugValue&&be.useDebugValue(t?t(e):e)}function Rc(e){var t=Vt(bt++,10),n=L();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 qr(){var e=Vt(bt++,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 Oc(){for(var e;e=bs.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(lr),t.__h.some(Xr),t.__h=[]}catch(n){t.__h=[],be.__e(n,e.__v)}}}be.__b=function(e){he=null,Ss&&Ss(e)},be.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Cs&&Cs(e,t)},be.__r=function(e){ws&&ws(e),bt=0;var t=(he=e.__c).__H;t&&(Gr===he?(t.__h=[],he.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(lr),t.__h.some(Xr),t.__h=[],bt=0)),Gr=he},be.diffed=function(e){Ns&&Ns(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(bs.push(t)!==1&&vs===be.requestAnimationFrame||((vs=be.requestAnimationFrame)||Ac)(Oc)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Gr=he=null},be.__c=function(e,t){t.some(function(n){try{n.__h.some(lr),n.__h=n.__h.filter(function(r){return!r.__||Xr(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],be.__e(r,n.__v)}}),xs&&xs(e,t)},be.unmount=function(e){Ts&&Ts(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{lr(r)}catch(o){t=o}}),n.__H=void 0,t&&be.__e(t,n.__v))};var ks=typeof requestAnimationFrame=="function";function Ac(e){var t,n=function(){clearTimeout(r),ks&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ks&&(t=requestAnimationFrame(n))}function lr(e){var t=he,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),he=t}function Xr(e){var t=he;e.__c=e.__(),he=t}function Zr(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Rs(e,t){return typeof t=="function"?t(e):t}function Os(e,t){for(var n in t)e[n]=t[n];return e}function Jr(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 Qr(e,t){var n=t(),r=L({t:{__:n,u:t}}),o=r[0].t,i=r[1];return at(function(){o.__=n,o.u=t,eo(o)&&i({t:o})},[e,n,t]),z(function(){return eo(o)&&i({t:o}),e(function(){eo(o)&&i({t:o})})},[e]),n}function eo(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 to(e){e()}function no(e){return e}function ro(){return[!1,to]}var oo=at;function cr(e,t){this.props=e,this.context=t}function so(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:Jr(this.props,o)}function r(o){return this.shouldComponentUpdate=n,Ge(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(cr.prototype=new ot).isPureReactComponent=!0,cr.prototype.shouldComponentUpdate=function(e,t){return Jr(this.props,e)||Jr(this.state,t)};var As=q.__b;q.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),As&&As(e)};var Ic=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function J(e){function t(n){var r=Os({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Ic,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Is=function(e,t){return e==null?null:yt(yt(e).map(t))},Xe={map:Is,forEach:Is,count:function(e){return e?yt(e).length:0},only:function(e){var t=yt(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:yt},Mc=q.__e;q.__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)}Mc(e,t,n,r)};var Ms=q.unmount;function Ps(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=Os({},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 Ps(r,t,n)})),e}function Ds(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return Ds(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 Ls(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function We(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?Ge(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function nn(){this.i=null,this.l=null}q.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),Ms&&Ms(e)},($e.prototype=new ot).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=Ls(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]=Ds(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]=Ps(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&Ge(ce,null,e.fallback);return o&&(o.__u&=-33),[Ge(ce,null,t.__a?null:e.children),o]};var Us=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 Pc(e){return this.getChildContext=function(){return e.context},e.children}function Dc(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Nn(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)}}}Nn(Ge(Pc,{context:t.context},e.__v),t.v)}function Fs(e,t){var n=Ge(Dc,{__v:e,h:t});return n.containerInfo=t,n}(nn.prototype=new ot).__a=function(e){var t=this,n=Ls(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),Us(t,e,r)):o()};n?n(i):i()}},nn.prototype.render=function(e){this.i=null,this.l=new Map;var t=yt(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},nn.prototype.componentDidUpdate=nn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){Us(e,n,t)})};var Vs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Lc=/^(?: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]/,Uc=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Fc=/[A-Z0-9]/g,Vc=typeof document<"u",jc=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function io(e,t,n){return t.__k==null&&(t.textContent=""),Nn(e,t),typeof n=="function"&&n(),e?e.__c:null}function js(e,t,n){return ys(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 zs=q.event;q.event=function(e){return zs&&(e=zs(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var ao,zc={configurable:!0,get:function(){return this.class}},Bs=q.vnode;q.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||Vc&&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"||jc(n.type)?c==="onfocus"?s="onfocusin":c==="onblur"?s="onfocusout":Uc.test(s)&&(s=c):c=s="oninput":i&&Lc.test(s)?s=s.replace(Fc,"-$&").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=yt(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=yt(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",zc)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=Vs,Bs&&Bs(e)};var $s=q.__r;q.__r=function(e){$s&&$s(e),ao=e.__c};var Hs=q.diffed;q.diffed=function(e){Hs&&Hs(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),ao=null};var Ys={ReactCurrentDispatcher:{current:{readContext:function(e){return ao.__n[e.__c].props.value},useCallback:fe,useContext:St,useDebugValue:Kr,useDeferredValue:no,useEffect:z,useId:qr,useImperativeHandle:Wr,useInsertionEffect:oo,useLayoutEffect:at,useMemo:_e,useReducer:tn,useRef:X,useState:L,useSyncExternalStore:Qr,useTransition:ro}}},Bc="18.3.1";function Gs(e){return Ge.bind(null,e)}function Ze(e){return!!e&&e.$$typeof===Vs}function Ws(e){return Ze(e)&&e.type===ce}function Ks(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Rt(e){return Ze(e)?Cc.apply(null,arguments):e}function lo(e){return!!e.__k&&(Nn(null,e),!0)}function qs(e){return e&&(e.base||e.nodeType===1&&e)||null}var Xs=function(e,t){return e(t)},Zs=function(e,t){var n=q.debounceRendering;q.debounceRendering=function(o){return o()};var r=e(t);return q.debounceRendering=n,r},Js=Ze,xn={useState:L,useId:qr,useReducer:tn,useEffect:z,useLayoutEffect:at,useInsertionEffect:oo,useTransition:ro,useDeferredValue:no,useSyncExternalStore:Qr,startTransition:to,useRef:X,useImperativeHandle:Wr,useMemo:_e,useCallback:fe,useContext:St,useDebugValue:Kr,version:"18.3.1",Children:Xe,render:io,hydrate:js,unmountComponentAtNode:lo,createPortal:Fs,createElement:Ge,createContext:vt,createFactory:Gs,cloneElement:Rt,createRef:ds,Fragment:ce,isValidElement:Ze,isElement:Js,isFragment:Ws,isMemo:Ks,findDOMNode:qs,Component:ot,PureComponent:cr,memo:so,forwardRef:J,flushSync:Zs,unstable_batchedUpdates:Xs,StrictMode:ce,Suspense:$e,SuspenseList:nn,lazy:We,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ys};const co=Object.freeze(Object.defineProperty({__proto__:null,Children:Xe,Component:ot,Fragment:ce,PureComponent:cr,StrictMode:ce,Suspense:$e,SuspenseList:nn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ys,cloneElement:Rt,createContext:vt,createElement:Ge,createFactory:Gs,createPortal:Fs,createRef:ds,default:xn,findDOMNode:qs,flushSync:Zs,forwardRef:J,hydrate:js,isElement:Js,isFragment:Ws,isMemo:Ks,isValidElement:Ze,lazy:We,memo:so,render:io,startTransition:to,unmountComponentAtNode:lo,unstable_batchedUpdates:Xs,useCallback:fe,useContext:St,useDebugValue:Kr,useDeferredValue:no,useEffect:z,useErrorBoundary:Rc,useId:qr,useImperativeHandle:Wr,useInsertionEffect:oo,useLayoutEffect:at,useMemo:_e,useReducer:tn,useRef:X,useState:L,useSyncExternalStore:Qr,useTransition:ro,version:Bc},Symbol.toStringTag,{value:"Module"}));function $c(e){return{render:function(t){io(t,e)},unmount:function(){lo(e)}}}function Qs(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function uo(...e){return t=>{let n=!1;const r=e.map(o=>{const i=Qs(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():Qs(e[o],null)}}}}function Ot(...e){return fe(uo(...e),e)}function Hc(e){const t=Yc(e),n=J((r,o)=>{const{children:i,...s}=r,a=Xe.toArray(i),c=a.find(Wc);if(c){const d=c.props.children,h=a.map(u=>u===c?Xe.count(d)>1?Xe.only(null):Ze(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Ze(d)?Rt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Yc(e){const t=J((n,r)=>{const{children:o,...i}=n;if(Ze(o)){const s=qc(o),a=Kc(i,o.props);return o.type!==ce&&(a.ref=r?uo(r,s):s),Rt(o,a)}return Xe.count(o)>1?Xe.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Gc=Symbol("radix.slottable");function Wc(e){return Ze(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Gc}function Kc(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 Xc=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],rn=Xc.reduce((e,t)=>{const n=Hc(`Primitive.${t}`),r=J((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}},{}),jt=globalThis?.document?at:()=>{};function Zc(e,t){return tn((n,r)=>t[n][r]??n,e)}var on=e=>{const{present:t,children:n}=e,r=Jc(t),o=typeof n=="function"?n({present:r.isPresent}):Xe.only(n),i=Ot(r.ref,Qc(o));return typeof n=="function"||r.isPresent?Rt(o,{ref:i}):null};on.displayName="Presence";function Jc(e){const[t,n]=L(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,c]=Zc(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return z(()=>{const d=dr(r.current);i.current=a==="mounted"?d:"none"},[a]),jt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,f=dr(d);e?c("MOUNT"):f==="none"||d?.display==="none"?c("UNMOUNT"):c(h&&u!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,c]),jt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=_=>{const p=dr(r.current).includes(CSS.escape(_.animationName));if(_.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=_=>{_.target===t&&(i.current=dr(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 dr(e){return e?.animationName||"none"}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)}function ei(e,t=[]){let n=[];function r(i,s){const a=vt(s),c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:_,...p}=u,g=f?.[e]?.[c]||a,v=_e(()=>p,Object.values(p));return l(g.Provider,{value:v,children:_})};d.displayName=i+"Provider";function h(u,f){const _=f?.[e]?.[c]||a,p=St(_);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=>vt(s));return function(s){const a=s?.[e]||i;return _e(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,ed(o,...t)]}function ed(...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 _e(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function At(e){const t=X(e);return z(()=>{t.current=e}),_e(()=>(...n)=>t.current?.(...n),[])}var td=vt(void 0);function nd(e){const t=St(td);return e||t||"ltr"}function rd(e,[t,n]){return Math.min(n,Math.max(t,e))}function It(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function od(e,t){return tn((n,r)=>t[n][r]??n,e)}var ho="ScrollArea",[ti]=ei(ho),[sd,st]=ti(ho),ni=J((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,c]=L(null),[d,h]=L(null),[u,f]=L(null),[_,p]=L(null),[g,v]=L(null),[m,E]=L(0),[y,k]=L(0),[w,N]=L(!1),[T,b]=L(!1),S=Ot(t,I=>c(I)),x=nd(o);return l(sd,{scope:n,type:r,dir:x,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:f,scrollbarX:_,onScrollbarXChange:p,scrollbarXEnabled:w,onScrollbarXEnabledChange:N,scrollbarY:g,onScrollbarYChange:v,scrollbarYEnabled:T,onScrollbarYEnabledChange:b,onCornerWidthChange:E,onCornerHeightChange:k,children:l(rn.div,{dir:x,...s,ref:S,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});ni.displayName=ho;var ri="ScrollAreaViewport",oi=J((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=st(ri,n),a=X(null),c=Ot(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(rn.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})})]})});oi.displayName=ri;var ft="ScrollAreaScrollbar",mo=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,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(id,{...r,ref:t,forceMount:n}):o.type==="scroll"?l(ad,{...r,ref:t,forceMount:n}):o.type==="auto"?l(si,{...r,ref:t,forceMount:n}):o.type==="always"?l(po,{...r,ref:t}):null});mo.displayName=ft;var id=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,e.__scopeScrollArea),[i,s]=L(!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(on,{present:n||i,children:l(si,{"data-state":i?"visible":"hidden",...r,ref:t})})}),ad=J((e,t)=>{const{forceMount:n,...r}=e,o=st(ft,e.__scopeScrollArea),i=e.orientation==="horizontal",s=pr(()=>c("SCROLL_END"),100),[a,c]=od("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 _=d[h];u!==_&&(c("SCROLL"),s()),u=_};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,c,s]),l(on,{present:n||a!=="hidden",children:l(po,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:It(e.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:It(e.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),si=J((e,t)=>{const n=st(ft,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=L(!1),a=e.orientation==="horizontal",c=pr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return sn(n.viewport,c),sn(n.content,c),l(on,{present:r||i,children:l(po,{"data-state":i?"visible":"hidden",...o,ref:t})})}),po=J((e,t)=>{const{orientation:n="vertical",...r}=e,o=st(ft,e.__scopeScrollArea),i=X(null),s=X(0),[a,c]=L({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=di(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,_){return md(f,s.current,a,_)}return n==="horizontal"?l(ld,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,_=ui(f,a,o.dir);i.current.style.transform=`translate3d(${_}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(cd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,_=ui(f,a);i.current.style.transform=`translate3d(0, ${_}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=u(f))}}):null}),ld=J((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(ft,e.__scopeScrollArea),[s,a]=L(),c=X(null),d=Ot(t,c,i.onScrollbarXChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(ai,{"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":mr(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),mi(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:hr(s.paddingLeft),paddingEnd:hr(s.paddingRight)}})}})}),cd=J((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=st(ft,e.__scopeScrollArea),[s,a]=L(),c=X(null),d=Ot(t,c,i.onScrollbarYChange);return z(()=>{c.current&&a(getComputedStyle(c.current))},[c]),l(ai,{"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":mr(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),mi(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:hr(s.paddingTop),paddingEnd:hr(s.paddingBottom)}})}})}),[dd,ii]=ti(ft),ai=J((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,_=st(ft,n),[p,g]=L(null),v=Ot(t,S=>g(S)),m=X(null),E=X(""),y=_.viewport,k=r.content-r.viewport,w=At(h),N=At(c),T=pr(u,10);function b(S){if(m.current){const x=S.clientX-m.current.left,I=S.clientY-m.current.top;d({x,y:I})}}return z(()=>{const S=x=>{const I=x.target;p?.contains(I)&&w(x,k)};return document.addEventListener("wheel",S,{passive:!1}),()=>document.removeEventListener("wheel",S,{passive:!1})},[y,p,k,w]),z(N,[r,N]),sn(p,T),sn(_.content,T),l(dd,{scope:n,scrollbar:p,hasThumb:o,onThumbChange:At(i),onThumbPointerUp:At(s),onThumbPositionChange:N,onThumbPointerDown:At(a),children:l(rn.div,{...f,ref:v,style:{position:"absolute",...f.style},onPointerDown:It(e.onPointerDown,S=>{S.button===0&&(S.target.setPointerCapture(S.pointerId),m.current=p.getBoundingClientRect(),E.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",_.viewport&&(_.viewport.style.scrollBehavior="auto"),b(S))}),onPointerMove:It(e.onPointerMove,b),onPointerUp:It(e.onPointerUp,S=>{const x=S.target;x.hasPointerCapture(S.pointerId)&&x.releasePointerCapture(S.pointerId),document.body.style.webkitUserSelect=E.current,_.viewport&&(_.viewport.style.scrollBehavior=""),m.current=null})})})}),ur="ScrollAreaThumb",li=J((e,t)=>{const{forceMount:n,...r}=e,o=ii(ur,e.__scopeScrollArea);return l(on,{present:n||o.hasThumb,children:l(ud,{ref:t,...r})})}),ud=J((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=st(ur,n),s=ii(ur,n),{onThumbPositionChange:a}=s,c=Ot(t,u=>s.onThumbChange(u)),d=X(void 0),h=pr(()=>{d.current&&(d.current(),d.current=void 0)},100);return z(()=>{const u=i.viewport;if(u){const f=()=>{if(h(),!d.current){const _=pd(u,a);d.current=_,a()}};return a(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[i.viewport,h,a]),l(rn.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:It(e.onPointerDownCapture,u=>{const f=u.target.getBoundingClientRect(),_=u.clientX-f.left,p=u.clientY-f.top;s.onThumbPointerDown({x:_,y:p})}),onPointerUp:It(e.onPointerUp,s.onThumbPointerUp)})});li.displayName=ur;var fo="ScrollAreaCorner",ci=J((e,t)=>{const n=st(fo,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?l(hd,{...e,ref:t}):null});ci.displayName=fo;var hd=J((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=st(fo,n),[i,s]=L(0),[a,c]=L(0),d=!!(i&&a);return sn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),c(h)}),sn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?l(rn.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 hr(e){return e?parseInt(e,10):0}function di(e,t){const n=e/t;return isNaN(n)?0:n}function mr(e){const t=di(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function md(e,t,n,r="ltr"){const o=mr(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 hi([c,d],u)(e)}function ui(e,t,n="ltr"){const r=mr(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=rd(e,c);return hi([0,s],[0,a])(d)}function hi(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 mi(e,t){return e>0&&e<t}var pd=(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 pr(e,t){const n=At(e),r=X(0);return z(()=>()=>window.clearTimeout(r.current),[]),fe(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sn(e,t){const n=At(t);jt(()=>{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 pi=ni,fd=oi,gd=ci;function _d(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 an={},Tn={},fi={},Cn={},kn={},Rn={},gi;function go(){if(gi)return Rn;gi=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.EventEmitter=void 0;let e=class{constructor(){R(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 Rn.EventEmitter=e,Rn}var ln={},_i;function On(){return _i||(_i=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.DisconnectionReason=ln.ConnectionStatus=void 0,ln.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},ln.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"}),ln}var Ei;function _o(){if(Ei)return kn;Ei=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.BaseConnection=void 0;const e=go(),t=On();let n=class{constructor(){R(this,"status",t.ConnectionStatus.CONNECTING);R(this,"queue",[]);R(this,"eventEmitter",new e.EventEmitter);R(this,"disconnectionDetails",null);R(this,"onErrorCallback",null);R(this,"onDisconnectCallback",null);R(this,"onMessageCallback",null);R(this,"onOpenCallback",null);R(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 kn.BaseConnection=n,kn}var yi={},vi;function Je(){return vi||(vi=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=w,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(b,S=e.SynapseErrorCode.UNKNOWN,x={}){super(b);R(this,"code");R(this,"timestamp");R(this,"cause");R(this,"context");R(this,"hint");R(this,"displayMessage");R(this,"reason");this.name="SynapseError",this.code=S,this.timestamp=new Date,this.cause=x.cause,this.context=x.context,this.hint=x.hint,this.reason=x.reason,this.displayMessage=x.displayMessage||x?.hint||b,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(b,S,x,I){const H=n.makeMessage(S,x,b);super(H,e.SynapseErrorCode.API,{cause:x,context:{status:S,hasBody:!!x},hint:S&&S>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:b||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=S,this.error=x,this.headers=I}static makeMessage(b,S,x){const I=S instanceof Error?S.message:x;return b&&I?`HTTP ${b}: ${I}`:b?`${b} status code (no body)`:I||"(no status code or body)"}static generate(b,S,x,I){if(!b)return new r({message:x});const H=S?.error,ne=H&&typeof H=="object"&&!Array.isArray(H)?H:void 0;switch(b){case 400:return new i(x||"Bad Request",b,ne,I);case 401:return new s(x||"Unauthorized",b,ne,I);case 403:return new a(x||"Permission Denied",b,ne,I);case 404:return new c(x||"Not Found",b,ne,I);case 405:return new d(x||"Method Not Allowed",b,ne,I);case 429:return new h(x||"Rate Limit Exceeded",b,ne,I);case 500:return new u(x||"Internal Server Error",b,ne,I);default:return new n(x||"API Error",b,ne,I)}}}e.APIError=n;class r extends n{constructor({message:T}={}){super(T||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:T}={}){super(T||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class c extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="NotFoundError"}}e.NotFoundError=c;class d extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(T,b,S,x){super(T,b,S,x),this.name="InternalServerError"}}e.InternalServerError=u;class f extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.CONNECTION,b),this.name="ConnectionError"}}e.ConnectionError=f;class _ extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.RECORDING,b),this.name="RecordingError"}}e.RecordingError=_;class p extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.AUTH,b),this.name="AuthenticationError"}}e.AuthenticationError=p;class g extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.FILE,b),this.name="FileError"}}e.FileError=g;class v extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.SESSION,b),this.name="SessionError"}}e.SessionError=v;class m extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.MESSAGE,b),this.name="MessageError"}}e.MessageError=m;class E extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.STORE,b),this.name="StoreError"}}e.StoreError=E;class y extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.CONFIGURATION,b),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(T,b={}){super(T,e.SynapseErrorCode.VALIDATION,b),this.name="ValidationError"}}e.ValidationError=k;function w(N,T,b,S={}){if(N instanceof T)return N;const x={...S,context:{...N instanceof t?N.context:void 0,...S.context},hint:S.hint??(N instanceof t?N.hint:void 0),reason:S.reason??(N instanceof t?N.reason:void 0),cause:S.cause??N};if(N instanceof t)return new T(N.message,x);const I=N instanceof Error&&N.message?N.message:b;return new T(I,x)}})(yi)),yi}var bi;function Si(){if(bi)return Cn;bi=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.WebSocketConnection=void 0;const e=_o(),t=On(),n=Je();class r extends e.BaseConnection{constructor(s){super();R(this,"conversationId");R(this,"socket",null);R(this,"config");R(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 Cn.WebSocketConnection=r,Cn}var An={},wi={},Ni;function xi(){return Ni||(Ni=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})(wi)),wi}var Ti;function Ci(){if(Ti)return An;Ti=1,Object.defineProperty(An,"__esModule",{value:!0}),An.SSEConnection=void 0;const e=_o(),t=On(),n=xi(),r=Je();class o extends e.BaseConnection{constructor(a){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(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 _="";for(;;){const{done:p,value:g}=await u.read();if(p)break;_+=f.decode(g,{stream:!0}),_=this.extractJsonObjects(_)}_.trim().length>0&&this.extractJsonObjects(_)}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 _=(0,r.normalizeError)(f,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(_)}c=h+1}return""}findObjectEnd(a,c){let d=0,h=!1,u=!1;for(let f=c;f<a.length;f++){const _=a[f];if(h){u?u=!1:_==="\\"?u=!0:_==='"'&&(h=!1);continue}if(_==='"')h=!0;else if(_==="{")d++;else if(_==="}"&&(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 An.SSEConnection=o,An}var ki;function Ri(){return ki||(ki=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Si(),n=Ci(),r=Je();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})(fi)),fi}var In={},Oi;function Eo(){if(Oi)return In;Oi=1,Object.defineProperty(In,"__esModule",{value:!0}),In.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 In.getConfig=r,In}var Mn={},Pn={},Ai;function fr(){if(Ai)return Pn;Ai=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.HttpClient=void 0;const e=Je();let t=class{constructor(n){R(this,"baseUrl");R(this,"headers");R(this,"timeout");R(this,"maxRetries");R(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 Pn.HttpClient=t,Pn}var Dn={},Ln={},Ii;function Un(){if(Ii)return Ln;Ii=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.BaseResource=void 0;let e=class{constructor(t){R(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 Ln.BaseResource=e,Ln}var Mi;function Pi(){if(Mi)return Dn;Mi=1,Object.defineProperty(Dn,"__esModule",{value:!0}),Dn.Session=void 0;const e=Un();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Dn.Session=t,Dn}var Fn={},Di;function yo(){if(Di)return Fn;Di=1,Object.defineProperty(Fn,"__esModule",{value:!0}),Fn.Config=void 0;const e=Un();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Fn.Config=t,Fn}var Li={},Ui;function Fi(){return Ui||(Ui=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=fr(),n=Eo(),r=yo(),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}}}),_=new r.Config(f).retrieve(c.agentId);return _.catch(()=>{o.get(h)===_&&o.delete(h)}),o.set(h,_),_}function a(c){const d=o.get(c);return d&&o.delete(c),d}})(Li)),Li}var Vn={},Vi;function vo(){if(Vi)return Vn;Vi=1,Object.defineProperty(Vn,"__esModule",{value:!0}),Vn.Auth=void 0;const e=Un();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Vn.Auth=t,Vn}var jn={},cn={},ji;function bo(){return ji||(ji=1,Object.defineProperty(cn,"__esModule",{value:!0}),cn.ErrorType=cn.SYNAPSE_RECOVERY_REASON=void 0,cn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},cn.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"}),cn}var zn={},zi;function So(){if(zi)return zn;zi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.ErrorUtils=void 0;const e=Je();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 zn.ErrorUtils=t,zn}var Bi={},$i;function Hi(){return $i||($i=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=c;const t=fr(),n=Eo(),r=So(),o=vo(),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 _=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(_).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}})(Bi)),Bi}var Yi;function Ed(){if(Yi)return jn;Yi=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.TokenManager=void 0;const e=Je(),t=bo(),n=So(),r=Hi();let o=class{constructor(i,s,a,c){R(this,"auth");R(this,"httpClient");R(this,"agentId");R(this,"partnerAuthToken");R(this,"refreshToken");R(this,"sessToken");R(this,"_userId");R(this,"_level");R(this,"_expiresAt");R(this,"lastResponse");R(this,"initPromise",null);R(this,"refreshPromise",null);R(this,"prefetchKey");R(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 jn.TokenManager=o,jn}var Bn={},Gi;function yd(){var n;if(Gi)return Bn;Gi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.VoiceResource=void 0;const e=Un();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)}},R(n,"ICE_SERVERS_PATH","/med-assist/voice/ice-servers"),R(n,"OFFER_PATH","/med-assist/voice/offer"),n);return Bn.VoiceResource=t,Bn}var Wi;function Ki(){if(Wi)return Mn;Wi=1,Object.defineProperty(Mn,"__esModule",{value:!0}),Mn.ResourceManager=void 0;const e=fr(),t=Pi(),n=Je(),r=yo(),o=Fi(),i=vo(),s=Ed(),a=yd();class c{constructor(h){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(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:_,user_location:p,referer:g,...v}=u||{},m=this.tokenManager.userId||h,E={...m&&{user_id:m},...f&&{user_context:f},...(_||Object.keys(v).length>0)&&{session_context:{..._&&{intent:_},...p&&{user_location:p},...v}},...g&&{referer:g}},y=await this.session.create(E);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:_,feedbackReason:p,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:f,feedbacks:_,feedbackReason:p,npsBase5:g})}async callTool(h,u,f,_){return await this.session.callTool(h,u,f,_)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Mn.ResourceManager=c,Mn}var $n={},qi={},Xi;function wo(){return Xi||(Xi=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)}})(qi)),qi}var Zi={},Ji;function vd(){return Ji||(Ji=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=Je();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(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})(Zi)),Zi}var lt={},Qi;function gr(){if(Qi)return lt;Qi=1,Object.defineProperty(lt,"__esModule",{value:!0}),lt.SYNAPSE_REALTIME_RESERVED_EVENTS=lt.SYNAPSE_REALTIME_ERROR_CODES=lt.SYNAPSE_REALTIME_EVENTS=lt.SYNAPSE_MESSAGE_TYPES=void 0;const e=wo();return lt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,lt.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"},lt.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"},lt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},lt}var Hn={},ea;function bd(){if(ea)return Hn;ea=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.AudioManager=void 0;const e=Je();class t{constructor(r={}){R(this,"mediaRecorder",null);R(this,"mediaStream",null);R(this,"recordingStartTime",0);R(this,"autoPauseTimer",null);R(this,"config");R(this,"onAudioData",null);R(this,"onAudioError",null);R(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 Hn.AudioManager=t,Hn}var ta;function na(){if(ta)return $n;ta=1,Object.defineProperty($n,"__esModule",{value:!0}),$n.MessageManager=void 0;const e=wo(),t=vd(),n=gr(),r=bd(),o=Je();let i=class{constructor(s){R(this,"connection",null);R(this,"callbacks",null);R(this,"fileManager",null);R(this,"audioManager",null);R(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:_}){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},..._&&{initial_prompts:_}};return}const p=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const v=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(v),v}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},..._&&{initial_prompts:_},...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 v=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(v),v}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 $n.MessageManager=i,$n}var ra={},oa;function Sd(){return oa||(oa=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})(ra)),ra}var Yn={},Gn={},sa;function wd(){if(sa)return Gn;sa=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.VoiceAudioAnalyser=void 0;const e=256;let t=class{constructor(){R(this,"audioCtx",null);R(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 Gn.VoiceAudioAnalyser=t,Gn}var dn={},ia;function aa(){return ia||(ia=1,Object.defineProperty(dn,"__esModule",{value:!0}),dn.VOICE_AGENT_EVENTS=dn.VOICE_AGENT_STATE=void 0,dn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},dn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),dn}var la;function Nd(){if(la)return Yn;la=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.VoiceAgent=void 0;const e=go(),t=wd(),n=Je(),r=aa(),o=3e3,i=8,s=3600*1e3,a=600;function c(h,u){return new Promise(f=>{if(h.iceGatheringState==="complete"){f();return}const _=setTimeout(f,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(_),f())}})}let d=class{constructor(h,u,f){R(this,"config");R(this,"resourceManager");R(this,"getCredentials");R(this,"emitter",new e.EventEmitter);R(this,"remoteAnalyser",new t.VoiceAudioAnalyser);R(this,"localAnalyser",new t.VoiceAudioAnalyser);R(this,"pc",null);R(this,"pcId",null);R(this,"dataChannel",null);R(this,"localStream",null);R(this,"remoteAudio",null);R(this,"_state",r.VOICE_AGENT_STATE.IDLE);R(this,"_isMuted",!1);R(this,"manuallyDisconnected",!1);R(this,"_hasConnectionFailureNotified",!1);R(this,"_userSpeaking",!1);R(this,"_silenceTimer",null);R(this,"_cachedIceServers",null);R(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),_=new RTCPeerConnection({iceServers:f,iceTransportPolicy:"all"});this.pc=_,this.dataChannel=_.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(E,u)),_.ontrack=E=>this.handleRemoteTrack(E),_.onconnectionstatechange=()=>{_.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):(_.connectionState==="failed"||_.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},_.oniceconnectionstatechange=()=>{(_.iceConnectionState==="connected"||_.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(u)):_.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const p=await _.createOffer();await _.setLocalDescription(p);const g=this.config.iceGatheringTimeoutMs??o;await c(_,g);const v=E=>({sdp:_.localDescription.sdp,type:_.localDescription.type,pc_id:this.pcId,request_data:{session_id:E.sessionId,token:E.sessionToken}});let m;try{m=await this.resourceManager.sendVoiceOffer(v(h))}catch(E){if(E instanceof n.APIError&&E.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const y=await this.getCredentials();m=await this.resourceManager.sendVoiceOffer(v(y))}else throw E}if(!m)throw new Error("No answer received from voice offer");if(this.pcId=m.pc_id,_.signalingState==="closed")return;await _.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(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const p=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(p.sessionId)}else throw _}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,_=>{_?(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 Yn.VoiceAgent=d,Yn}var ca;function xd(){if(ca)return Tn;ca=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.SynapseSDK=void 0;const e=Ri(),t=On(),n=Eo(),r=Ki(),o=na(),i=gr(),s=go(),a=Je(),c=bo(),d=Sd(),h=wo(),u=Nd();class f{constructor(p){R(this,"connection",null);R(this,"messageManager");R(this,"resourceManager");R(this,"sessionConfig",null);R(this,"config");R(this,"connectionType");R(this,"isRefreshingSession",!1);R(this,"isRecovering",!1);R(this,"forceConsumed",!1);R(this,"connectionAttempts",0);R(this,"sdkEventEmitter",new s.EventEmitter);R(this,"_voice",null);R(this,"pendingNetworkReconnect",!1);R(this,"boundOnlineHandler",null);R(this,"isReconnecting",!1);R(this,"reconnectTimer",null);R(this,"boundVisibilityHandler",null);R(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:v=>this.config.callbacks?.onTokenExchange?.(v)}),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:v,tool_declined:m,tool_id:E,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:v,...m&&{tool_declined:m},...E&&{tool_id:E},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(N){this.emitError(N)}break;default:const w=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(w),w}}async sendMessageFeedback(p,g,v){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:v});break}}async sendSessionFeedback(p,g){if(!this.connection){const v=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(v),v}if(!this.sessionConfig?.session_id){const v=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(v),v}if(!p?.length&&!g){const v=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(v),v}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,v){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,v);if(m.error)throw new a.APIError(m.error.msg,500,m.error);let E={data:{...m.data},messageId:m._id,timestamp:m.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,E);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 v=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(v),v}}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,v,m){return(0,a.normalizeError)(p,a.SessionError,g,{context:v,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),v=this.connectionType===e.ConnectionType.SOCKET,m=v?g.WEBSOCKET_URL:g.BASE_API_URL,E=this.config.serverUrl?v?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:E||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,...w)=>{y(k,...w),this.sdkEventEmitter.emit(k,...w)}}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 v=(0,d.outcomeForCloseCode)(g.code);if(v){await this.handleRecovery(v,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(p){if(p instanceof a.APIError){const v=(0,d.outcomeForHttpStatus)(p.status);if(v){this.handleRecovery(v,{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,v){this.emitError(new a.SessionError(g,{reason:p,cause:v,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 v=this.statusOf(g);if(v===401||v===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 E=this.statusOf(m);if(E===401||E===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,v,m){return(0,a.normalizeError)(p,a.ConnectionError,g,{context:v,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 Tn.SynapseSDK=f,Tn}var da={},ua;function Td(){return ua||(ua=1,Object.defineProperty(da,"__esModule",{value:!0})),da}var _r={},ha;function Cd(){return ha||(ha=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.USER_FEEDBACK=void 0,_r.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),_r}var ma={},pa;function kd(){return pa||(pa=1,Object.defineProperty(ma,"__esModule",{value:!0})),ma}var Wn={},fa;function Rd(){if(fa)return Wn;fa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ToolCall=void 0;const e=Un();let t=class extends e.BaseResource{constructor(){super(...arguments);R(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 Wn.ToolCall=t,Wn}var He={},ga;function Od(){if(ga)return He;ga=1,Object.defineProperty(He,"__esModule",{value:!0}),He.SYNAPSE_EICITATION_STATUS=He.SYNAPSE_CTA_ACTIONS=He.SYNAPSE_TOOL_FORMATS=He.SYNAPSE_TOOL_CALLBACK_NAME=He.SYNAPSE_COMPONENTS=He.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||(He.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||(He.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||(He.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(He.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(He.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(He.SYNAPSE_EICITATION_STATUS=i={})),He}var _a={},Ea;function Ad(){return Ea||(Ea=1,Object.defineProperty(_a,"__esModule",{value:!0})),_a}var ya={},va;function Id(){return va||(va=1,Object.defineProperty(ya,"__esModule",{value:!0})),ya}var Kn={},ba;function Md(){if(ba)return Kn;ba=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(Kn.SYNAPSE_CONVERSATION=e={})),Kn}var un={},Sa;function Pd(){return Sa||(Sa=1,(function(e){var t=un&&un.__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=un&&un.__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(aa(),e)})(un)),un}var wa;function Dd(){return wa||(wa=1,(function(e){var t=an&&an.__createBinding||(Object.create?(function(N,T,b,S){S===void 0&&(S=b);var x=Object.getOwnPropertyDescriptor(T,b);(!x||("get"in x?!T.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return T[b]}}),Object.defineProperty(N,S,x)}):(function(N,T,b,S){S===void 0&&(S=b),N[S]=T[b]})),n=an&&an.__exportStar||function(N,T){for(var b in N)b!=="default"&&!Object.prototype.hasOwnProperty.call(T,b)&&t(T,N,b)};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=xd();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=_o();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Si();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Ci();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Ri();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(On(),e);var c=Ki();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return c.ResourceManager}}),n(Td(),e);var d=Pi();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(Cd(),e);var h=vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=Hi();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(kd(),e);var f=yo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var _=Fi();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return _.prefetchAgentConfig}});var p=Rd();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return p.ToolCall}}),n(Od(),e);var g=na();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(gr(),e),n(Ad(),e);var v=fr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return v.HttpClient}});var m=Je();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 E=bo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return E.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return E.SYNAPSE_RECOVERY_REASON}});var y=So();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(Id(),e);var k=xi();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 w=gr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return w.SYNAPSE_MESSAGE_TYPES}}),n(Md(),e),n(Pd(),e)})(an)),an}var M=Dd();function Na(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=Na(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function xa(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Na(e))&&(r&&(r+=" "),r+=t);return r}const Ld=(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},Ud=(e,t)=>({classGroupId:e,validator:t}),Ta=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Er="-",Ca=[],Fd="arbitrary..",Vd=e=>{const t=zd(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return jd(o);const i=o.split(Er),s=i[0]===""&&i.length>1?1:0;return ka(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?Ld(a,s):s:a||Ca}return n[o]||Ca}}},ka=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const c=ka(e,t+1,o);if(c)return c}const i=n.validators;if(i===null)return;const s=t===0?e.join(Er):e.slice(t).join(Er),a=i.length;for(let c=0;c<a;c++){const d=i[c];if(d.validator(s))return d.classGroupId}},jd=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?Fd+r:void 0})(),zd=e=>{const{theme:t,classGroups:n}=e;return Bd(n,t)},Bd=(e,t)=>{const n=Ta();for(const r in e){const o=e[r];No(o,n,r,t)}return n},No=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];$d(s,t,n,r)}},$d=(e,t,n,r)=>{if(typeof e=="string"){Hd(e,t,n);return}if(typeof e=="function"){Yd(e,t,n,r);return}Gd(e,t,n,r)},Hd=(e,t,n)=>{const r=e===""?t:Ra(t,e);r.classGroupId=n},Yd=(e,t,n,r)=>{if(Wd(e)){No(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(Ud(n,e))},Gd=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,c]=o[s];No(c,Ra(t,a),n,r)}},Ra=(e,t)=>{let n=e;const r=t.split(Er),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Ta(),n.nextPart.set(s,a)),n=a}return n},Wd=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Kd=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)}}},xo="!",Oa=":",qd=[],Aa=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Xd=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 v=o[g];if(s===0&&a===0){if(v===Oa){i.push(o.slice(c,g)),c=g+1;continue}if(v==="/"){d=g;continue}}v==="["?s++:v==="]"?s--:v==="("?a++:v===")"&&a--}const u=i.length===0?o:o.slice(c);let f=u,_=!1;u.endsWith(xo)?(f=u.slice(0,-1),_=!0):u.startsWith(xo)&&(f=u.slice(1),_=!0);const p=d&&d>c?d-c:void 0;return Aa(i,_,f,p)};if(t){const o=t+Oa,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Aa(qd,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Zd=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}},Jd=e=>({cache:Kd(e.cacheSize),parseClassName:Xd(e),sortModifiers:Zd(e),...Vd(e)}),Qd=/\s+/,eu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Qd);let c="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:f,hasImportantModifier:_,baseClassName:p,maybePostfixModifierPosition:g}=n(h);if(u){c=h+(c.length>0?" "+c:c);continue}let v=!!g,m=r(v?p.substring(0,g):p);if(!m){if(!v){c=h+(c.length>0?" "+c:c);continue}if(m=r(p),!m){c=h+(c.length>0?" "+c:c);continue}v=!1}const E=f.length===0?"":f.length===1?f[0]:i(f).join(":"),y=_?E+xo:E,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const w=o(m,v);for(let N=0;N<w.length;++N){const T=w[N];s.push(y+T)}c=h+(c.length>0?" "+c:c)}return c},tu=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Ia(n))&&(o&&(o+=" "),o+=r);return o},Ia=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Ia(e[r]))&&(n&&(n+=" "),n+=t);return n},nu=(e,...t)=>{let n,r,o,i;const s=c=>{const d=t.reduce((h,u)=>u(h),e());return n=Jd(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=eu(c,n);return o(c,h),h};return i=s,(...c)=>i(tu(...c))},ru=[],Oe=e=>{const t=n=>n[e]||ru;return t.isThemeGetter=!0,t},Ma=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Pa=/^\((?:(\w[\w-]*):)?(.+)\)$/i,ou=/^\d+\/\d+$/,su=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,iu=/\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$/,au=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,lu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,cu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,hn=e=>ou.test(e),te=e=>!!e&&!Number.isNaN(Number(e)),Mt=e=>!!e&&Number.isInteger(Number(e)),To=e=>e.endsWith("%")&&te(e.slice(0,-1)),wt=e=>su.test(e),du=()=>!0,uu=e=>iu.test(e)&&!au.test(e),Da=()=>!1,hu=e=>lu.test(e),mu=e=>cu.test(e),pu=e=>!V(e)&&!j(e),fu=e=>mn(e,ja,Da),V=e=>Ma.test(e),zt=e=>mn(e,za,uu),Co=e=>mn(e,vu,te),La=e=>mn(e,Fa,Da),gu=e=>mn(e,Va,mu),yr=e=>mn(e,Ba,hu),j=e=>Pa.test(e),qn=e=>pn(e,za),_u=e=>pn(e,bu),Ua=e=>pn(e,Fa),Eu=e=>pn(e,ja),yu=e=>pn(e,Va),vr=e=>pn(e,Ba,!0),mn=(e,t,n)=>{const r=Ma.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},pn=(e,t,n=!1)=>{const r=Pa.exec(e);return r?r[1]?t(r[1]):n:!1},Fa=e=>e==="position"||e==="percentage",Va=e=>e==="image"||e==="url",ja=e=>e==="length"||e==="size"||e==="bg-size",za=e=>e==="length",vu=e=>e==="number",bu=e=>e==="family-name",Ba=e=>e==="shadow",Su=()=>{const e=Oe("color"),t=Oe("font"),n=Oe("text"),r=Oe("font-weight"),o=Oe("tracking"),i=Oe("leading"),s=Oe("breakpoint"),a=Oe("container"),c=Oe("spacing"),d=Oe("radius"),h=Oe("shadow"),u=Oe("inset-shadow"),f=Oe("text-shadow"),_=Oe("drop-shadow"),p=Oe("blur"),g=Oe("perspective"),v=Oe("aspect"),m=Oe("ease"),E=Oe("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"],w=()=>[...k(),j,V],N=()=>["auto","hidden","clip","visible","scroll"],T=()=>["auto","contain","none"],b=()=>[j,V,c],S=()=>[hn,"full","auto",...b()],x=()=>[Mt,"none","subgrid",j,V],I=()=>["auto",{span:["full",Mt,j,V]},Mt,j,V],H=()=>[Mt,"auto",j,V],ne=()=>["auto","min","max","fr",j,V],xe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],de=()=>["start","end","center","stretch","center-safe","end-safe"],Q=()=>["auto",...b()],me=()=>[hn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...b()],P=()=>[e,j,V],F=()=>[...k(),Ua,La,{position:[j,V]}],Z=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Y=()=>["auto","cover","contain",Eu,fu,{size:[j,V]}],re=()=>[To,qn,zt],$=()=>["","none","full",d,j,V],W=()=>["",te,qn,zt],we=()=>["solid","dashed","dotted","double"],pe=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],se=()=>[te,To,Ua,La],Ke=()=>["","none",p,j,V],Ye=()=>["none",te,j,V],Qe=()=>["none",te,j,V],D=()=>[te,j,V],ue=()=>[hn,"full",...b()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[wt],breakpoint:[wt],color:[du],container:[wt],"drop-shadow":[wt],ease:["in","out","in-out"],font:[pu],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[wt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[wt],shadow:[wt],spacing:["px",te],text:[wt],"text-shadow":[wt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",hn,V,j,v]}],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:w()}],overflow:[{overflow:N()}],"overflow-x":[{"overflow-x":N()}],"overflow-y":[{"overflow-y":N()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:S()}],"inset-x":[{"inset-x":S()}],"inset-y":[{"inset-y":S()}],start:[{start:S()}],end:[{end:S()}],top:[{top:S()}],right:[{right:S()}],bottom:[{bottom:S()}],left:[{left:S()}],visibility:["visible","invisible","collapse"],z:[{z:[Mt,"auto",j,V]}],basis:[{basis:[hn,"full","auto",a,...b()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[te,hn,"auto","initial","none",V]}],grow:[{grow:["",te,j,V]}],shrink:[{shrink:["",te,j,V]}],order:[{order:[Mt,"first","last","none",j,V]}],"grid-cols":[{"grid-cols":x()}],"col-start-end":[{col:I()}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":x()}],"row-start-end":[{row:I()}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":ne()}],"auto-rows":[{"auto-rows":ne()}],gap:[{gap:b()}],"gap-x":[{"gap-x":b()}],"gap-y":[{"gap-y":b()}],"justify-content":[{justify:[...xe(),"normal"]}],"justify-items":[{"justify-items":[...de(),"normal"]}],"justify-self":[{"justify-self":["auto",...de()]}],"align-content":[{content:["normal",...xe()]}],"align-items":[{items:[...de(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...de(),{baseline:["","last"]}]}],"place-content":[{"place-content":xe()}],"place-items":[{"place-items":[...de(),"baseline"]}],"place-self":[{"place-self":["auto",...de()]}],p:[{p:b()}],px:[{px:b()}],py:[{py:b()}],ps:[{ps:b()}],pe:[{pe:b()}],pt:[{pt:b()}],pr:[{pr:b()}],pb:[{pb:b()}],pl:[{pl:b()}],m:[{m:Q()}],mx:[{mx:Q()}],my:[{my:Q()}],ms:[{ms:Q()}],me:[{me:Q()}],mt:[{mt:Q()}],mr:[{mr:Q()}],mb:[{mb:Q()}],ml:[{ml:Q()}],"space-x":[{"space-x":b()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":b()}],"space-y-reverse":["space-y-reverse"],size:[{size:me()}],w:[{w:[a,"screen",...me()]}],"min-w":[{"min-w":[a,"screen","none",...me()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...me()]}],h:[{h:["screen","lh",...me()]}],"min-h":[{"min-h":["screen","lh","none",...me()]}],"max-h":[{"max-h":["screen","lh",...me()]}],"font-size":[{text:["base",n,qn,zt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,j,Co]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",To,V]}],"font-family":[{font:[_u,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,Co]}],leading:[{leading:[i,...b()]}],"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:P()}],"text-color":[{text:P()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...we(),"wavy"]}],"text-decoration-thickness":[{decoration:[te,"from-font","auto",j,zt]}],"text-decoration-color":[{decoration:P()}],"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:b()}],"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:F()}],"bg-repeat":[{bg:Z()}],"bg-size":[{bg:Y()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Mt,j,V],radial:["",j,V],conic:[Mt,j,V]},yu,gu]}],"bg-color":[{bg:P()}],"gradient-from-pos":[{from:re()}],"gradient-via-pos":[{via:re()}],"gradient-to-pos":[{to:re()}],"gradient-from":[{from:P()}],"gradient-via":[{via:P()}],"gradient-to":[{to:P()}],rounded:[{rounded:$()}],"rounded-s":[{"rounded-s":$()}],"rounded-e":[{"rounded-e":$()}],"rounded-t":[{"rounded-t":$()}],"rounded-r":[{"rounded-r":$()}],"rounded-b":[{"rounded-b":$()}],"rounded-l":[{"rounded-l":$()}],"rounded-ss":[{"rounded-ss":$()}],"rounded-se":[{"rounded-se":$()}],"rounded-ee":[{"rounded-ee":$()}],"rounded-es":[{"rounded-es":$()}],"rounded-tl":[{"rounded-tl":$()}],"rounded-tr":[{"rounded-tr":$()}],"rounded-br":[{"rounded-br":$()}],"rounded-bl":[{"rounded-bl":$()}],"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:[...we(),"hidden","none"]}],"divide-style":[{divide:[...we(),"hidden","none"]}],"border-color":[{border:P()}],"border-color-x":[{"border-x":P()}],"border-color-y":[{"border-y":P()}],"border-color-s":[{"border-s":P()}],"border-color-e":[{"border-e":P()}],"border-color-t":[{"border-t":P()}],"border-color-r":[{"border-r":P()}],"border-color-b":[{"border-b":P()}],"border-color-l":[{"border-l":P()}],"divide-color":[{divide:P()}],"outline-style":[{outline:[...we(),"none","hidden"]}],"outline-offset":[{"outline-offset":[te,j,V]}],"outline-w":[{outline:["",te,qn,zt]}],"outline-color":[{outline:P()}],shadow:[{shadow:["","none",h,vr,yr]}],"shadow-color":[{shadow:P()}],"inset-shadow":[{"inset-shadow":["none",u,vr,yr]}],"inset-shadow-color":[{"inset-shadow":P()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:P()}],"ring-offset-w":[{"ring-offset":[te,zt]}],"ring-offset-color":[{"ring-offset":P()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":P()}],"text-shadow":[{"text-shadow":["none",f,vr,yr]}],"text-shadow-color":[{"text-shadow":P()}],opacity:[{opacity:[te,j,V]}],"mix-blend":[{"mix-blend":[...pe(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":pe()}],"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":P()}],"mask-image-linear-to-color":[{"mask-linear-to":P()}],"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":P()}],"mask-image-t-to-color":[{"mask-t-to":P()}],"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":P()}],"mask-image-r-to-color":[{"mask-r-to":P()}],"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":P()}],"mask-image-b-to-color":[{"mask-b-to":P()}],"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":P()}],"mask-image-l-to-color":[{"mask-l-to":P()}],"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":P()}],"mask-image-x-to-color":[{"mask-x-to":P()}],"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":P()}],"mask-image-y-to-color":[{"mask-y-to":P()}],"mask-image-radial":[{"mask-radial":[j,V]}],"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":P()}],"mask-image-radial-to-color":[{"mask-radial-to":P()}],"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":P()}],"mask-image-conic-to-color":[{"mask-conic-to":P()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:F()}],"mask-repeat":[{mask:Z()}],"mask-size":[{mask:Y()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",j,V]}],filter:[{filter:["","none",j,V]}],blur:[{blur:Ke()}],brightness:[{brightness:[te,j,V]}],contrast:[{contrast:[te,j,V]}],"drop-shadow":[{"drop-shadow":["","none",_,vr,yr]}],"drop-shadow-color":[{"drop-shadow":P()}],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":Ke()}],"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":b()}],"border-spacing-x":[{"border-spacing-x":b()}],"border-spacing-y":[{"border-spacing-y":b()}],"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",E,j,V]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,j,V]}],"perspective-origin":[{"perspective-origin":w()}],rotate:[{rotate:Ye()}],"rotate-x":[{"rotate-x":Ye()}],"rotate-y":[{"rotate-y":Ye()}],"rotate-z":[{"rotate-z":Ye()}],scale:[{scale:Qe()}],"scale-x":[{"scale-x":Qe()}],"scale-y":[{"scale-y":Qe()}],"scale-z":[{"scale-z":Qe()}],"scale-3d":["scale-3d"],skew:[{skew:D()}],"skew-x":[{"skew-x":D()}],"skew-y":[{"skew-y":D()}],transform:[{transform:[j,V,"","none","gpu","cpu"]}],"transform-origin":[{origin:w()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:ue()}],"translate-x":[{"translate-x":ue()}],"translate-y":[{"translate-y":ue()}],"translate-z":[{"translate-z":ue()}],"translate-none":["translate-none"],accent:[{accent:P()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:P()}],"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":b()}],"scroll-mx":[{"scroll-mx":b()}],"scroll-my":[{"scroll-my":b()}],"scroll-ms":[{"scroll-ms":b()}],"scroll-me":[{"scroll-me":b()}],"scroll-mt":[{"scroll-mt":b()}],"scroll-mr":[{"scroll-mr":b()}],"scroll-mb":[{"scroll-mb":b()}],"scroll-ml":[{"scroll-ml":b()}],"scroll-p":[{"scroll-p":b()}],"scroll-px":[{"scroll-px":b()}],"scroll-py":[{"scroll-py":b()}],"scroll-ps":[{"scroll-ps":b()}],"scroll-pe":[{"scroll-pe":b()}],"scroll-pt":[{"scroll-pt":b()}],"scroll-pr":[{"scroll-pr":b()}],"scroll-pb":[{"scroll-pb":b()}],"scroll-pl":[{"scroll-pl":b()}],"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",...P()]}],"stroke-w":[{stroke:[te,qn,zt,Co]}],stroke:[{stroke:["none",...P()]}],"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"]}},wu=nu(Su);function A(...e){return wu(xa(e))}function Bt(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 Nu=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},xu=e=>new Promise(t=>setTimeout(t,e)),$a=J(({className:e,children:t,...n},r)=>l(pi,{ref:r,className:A("relative overflow-hidden",e),...n,children:[l(fd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),l(Ha,{}),l(gd,{})]}));$a.displayName=pi.displayName;const Ha=J(({className:e,orientation:t="vertical",...n},r)=>l(mo,{ref:r,orientation:t,className:A("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(li,{className:"relative flex-1 rounded-full bg-border"})}));Ha.displayName=mo.displayName;var Tu=Symbol.for("react.lazy"),br=co[" use ".trim().toString()];function Cu(e){return typeof e=="object"&&e!==null&&"then"in e}function Ya(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===Tu&&"_payload"in e&&Cu(e._payload)}function Ga(e){const t=Ru(e),n=J((r,o)=>{let{children:i,...s}=r;Ya(i)&&typeof br=="function"&&(i=br(i._payload));const a=Xe.toArray(i),c=a.find(Au);if(c){const d=c.props.children,h=a.map(u=>u===c?Xe.count(d)>1?Xe.only(null):Ze(d)?d.props.children:null:u);return l(t,{...s,ref:o,children:Ze(d)?Rt(d,void 0,h):null})}return l(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var ku=Ga("Slot");function Ru(e){const t=J((n,r)=>{let{children:o,...i}=n;if(Ya(o)&&typeof br=="function"&&(o=br(o._payload)),Ze(o)){const s=Mu(o),a=Iu(i,o.props);return o.type!==ce&&(a.ref=r?uo(r,s):s),Rt(o,a)}return Xe.count(o)>1?Xe.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Ou=Symbol("radix.slottable");function Au(e){return Ze(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ou}function Iu(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 Mu(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 Wa=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ka=xa,Pu=(e,t)=>n=>{var r;if(t?.variants==null)return Ka(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=Wa(h)||Wa(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,..._}=h;return Object.entries(_).every(p=>{let[g,v]=p;return Array.isArray(v)?v.includes({...i,...a}[g]):{...i,...a}[g]===v})?[...d,u,f]:d},[]);return Ka(e,s,c,n?.class,n?.className)},Du=Pu("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"}}),le=J(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>l(r?ku:"button",{className:A(Du({variant:t,size:n,className:e})),ref:i,...o}));le.displayName="Button";const Lu=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Uu=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),qa=e=>{const t=Uu(e);return t.charAt(0).toUpperCase()+t.slice(1)},Xa=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Fu=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Vu={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 ju=J(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},c)=>Ge("svg",{ref:c,...Vu,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Xa("lucide",o),...!i&&!Fu(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>Ge(d,h)),...Array.isArray(i)?i:[i]])),Ie=(e,t)=>{const n=J(({className:r,...o},i)=>Ge(ju,{ref:i,iconNode:t,className:Xa(`lucide-${Lu(qa(e))}`,`lucide-${e}`,r),...o}));return n.displayName=qa(e),n},zu=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ko=Ie("chevron-down",zu),Bu=[["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"}]],$u=Ie("ellipsis-vertical",Bu),Hu=[["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"}]],Za=Ie("file-text",Hu),Yu=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Ja=Ie("info",Yu),Gu=[["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"}]],Wu=Ie("maximize-2",Gu),Ku=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],qu=Ie("menu",Ku),Xu=[["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"}]],Xn=Ie("message-square-plus",Xu),Zu=[["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"}]],Ro=Ie("mic",Zu),Ju=[["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"}]],Qu=Ie("minimize-2",Ju),eh=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Qa=Ie("plus",eh),th=[["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"}]],nh=Ie("rotate-ccw",th),rh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],el=Ie("square",rh),oh=[["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"}]],Sr=Ie("thumbs-up",oh),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"}]],wr=Ie("thumbs-down",sh),ih=[["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"}]],ah=Ie("triangle-alert",ih),lh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],fn=Ie("x",lh),ch=[["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"}]],dh=Ie("zoom-in",ch),tl=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},uh=(e=>e?tl(e):tl),hh=e=>e;function mh(e,t=hh){const n=xn.useSyncExternalStore(e.subscribe,xn.useCallback(()=>t(e.getState()),[e,t]),xn.useCallback(()=>t(e.getInitialState()),[e,t]));return xn.useDebugValue(n),n}const ph=e=>{const t=uh(e),n=r=>mh(t,r);return Object.assign(n,t),n},fh=(e=>ph);function nl(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 Oo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Oo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Oo(r)(n)}}}},gh=(e,t)=>(n,r,o)=>{let i={storage:nl(()=>localStorage),partialize:g=>g,version:0,merge:(g,v)=>({...v,...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,v)=>(u(g,v),h());const f=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>f;let _;const p=()=>{var g,v;if(!d)return;s=!1,a.forEach(E=>{var y;return E((y=r())!=null?y:f)});const m=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(g=r())!=null?g:f))||void 0;return Oo(d.getItem.bind(d))(i.name).then(E=>{if(E)if(typeof E.version=="number"&&E.version!==i.version){if(i.migrate){const y=i.migrate(E.state,E.version);return y instanceof Promise?y.then(k=>[!0,k]):[!0,y]}}else return[!1,E.state];return[!1,void 0]}).then(E=>{var y;const[k,w]=E;if(_=i.merge(w,(y=r())!=null?y:f),n(_,!0),k)return h()}).then(()=>{m?.(_,void 0),_=r(),s=!0,c.forEach(E=>E(_))}).catch(E=>{m?.(void 0,E)})};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(),_||f},_h=gh,je={USER:"user",ASSISTANT:"assistant"};var Ee=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Ee||{}),ge=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(ge||{});let Nt="";const Zn=e=>`med-assist-store-${e}`,Eh=e=>{Nt=Zn(e)},rl={sessionId:"",isStreaming:!1,recordingStatus:Ee.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:{}},ol={...rl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},G=fh()(_h((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:Ee.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(rl),await sessionStorage.removeItem(Nt||Zn(t().agentId))},clearUser:()=>{e(ol),sessionStorage.removeItem(Nt||Zn(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:nl(()=>({getItem:()=>Nt?sessionStorage.getItem(Nt):null,setItem:(e,t)=>{Nt&&sessionStorage.setItem(Nt,t)},removeItem:()=>{Nt&&sessionStorage.removeItem(Nt)}})),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})})),yh=e=>{const t=Zn(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(ol),n&&G.setState(n)},Ao=vt(null),vh=({children:e})=>{const[t,n]=L(null);return l(Ao.Provider,{value:{synapse:t,setSynapse:n},children:e})},bh=()=>{const e=St(Ao);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Sh=()=>{const e=St(Ao);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},wh=()=>{const[e,t]=L(M.VOICE_AGENT_STATE.IDLE),[n,r]=L(!1),o=bh(),{setError:i}=G();z(()=>{if(!o)return;const h=o.voice,u=_=>{t(_)},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=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}},$t=J(({className:e,...t},n)=>l("div",{ref:n,className:A("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));$t.displayName="Card";const sl=J(({className:e,...t},n)=>l("div",{ref:n,className:A("flex flex-col space-y-1.5 p-6",e),...t}));sl.displayName="CardHeader";const il=J(({className:e,...t},n)=>l("div",{ref:n,className:A("font-semibold leading-none tracking-tight",e),...t}));il.displayName="CardTitle";const Nh=J(({className:e,...t},n)=>l("div",{ref:n,className:A("text-sm text-muted-foreground",e),...t}));Nh.displayName="CardDescription";const al=J(({className:e,...t},n)=>l("div",{ref:n,className:A("p-6 pt-0",e),...t}));al.displayName="CardContent";const ll=J(({className:e,...t},n)=>l("div",{ref:n,className:A("flex items-center p-6 pt-0",e),...t}));ll.displayName="CardFooter";const Io=5,xh=10*1024*1024,Nr={width:384,height:600},xr=20,Th=150;function Ch({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=fe(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Nr.width-xr,y:window.innerHeight-Nr.height-xr},[]),[i,s]=L(()=>e??o()),[a,c]=L(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);z(()=>{t||(u.current=!1)},[t]),at(()=>{!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 v=()=>{s(E=>{const y=Math.max(0,window.innerWidth-Nr.width-xr),k=Math.max(0,window.innerHeight-Nr.height-xr),w=Math.max(0,Math.min(E.x,y)),N=Math.max(0,Math.min(E.y,k));return w===E.x&&N===E.y?E:{x:w,y:N}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(v,Th)};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 v=h.current;if(v){const m=v.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]),_=fe(g=>{if(!t||!a)return;const v=g.clientX-d.current.x,m=g.clientY-d.current.y,E=window.innerWidth-(h.current?.offsetWidth||0),y=window.innerHeight-(h.current?.offsetHeight||0),k=Math.max(0,Math.min(v,E)),w=Math.max(0,Math.min(m,y));s({x:k,y:w})},[a,t]),p=fe(()=>{!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",_),document.addEventListener("mouseup",p),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",p),document.body.style.cursor="",document.body.style.userSelect=""}},[a,_,p]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Mo="#6B5CE0",kh="#F0F0F0",Tr={background:kh,backgroundImage:void 0,primary:Mo,textColor:"black"},Rh="rgba(0, 0, 0, 0.4)",Oh="24px";function Ah(e){if(e==="dark")return"white";if(e==="light")return"black"}function Ih(e){const t=e?.primary??e?.primaryColor??Tr.primary,n=e?.textColor??Ah(e?.mode);return{background:e?.background??Tr.background,backgroundImage:e?.backgroundImage??Tr.backgroundImage,primary:t,primaryColor:t,textColor:n??Tr.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Mh(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 Ph(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 Dh(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 Po(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return Mh(t);if(t.startsWith("rgb"))return Ph(t);if(t.startsWith("hsl"))return Dh(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function cl(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function Do(e){return cl(e)>.5?"0 0% 9%":"0 0% 98%"}function Lh(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 Uh(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 dl(e,t){const n=t.primary??Mo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(_,p)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(_,p)};let c;try{c=Po(n)}catch{c=Po(Mo)}a("--primary",c),a("--primary-foreground",Do(c)),a("--ring",c),a("--border-primary",c);const d=Uh(c);for(const[_,p]of Object.entries(d))a(`--primary-${_}`,p);const h=Do(c);if(a("--color-on-primary",h),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const _=i?"#191919":"#F0F0F0";try{a("--background",Po(_))}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",Lh(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 _=cl(h)>.5;a("--header-tagline",_?"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 _ of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${_}`,`var(--${f}-${_})`);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",Do(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",Oh),a("--theme-background-overlay",Rh),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 Ht({className:e,style:t}){return l("div",{className:A("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 Lo(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function ul(){return l("div",{className:"px-3 pb-2 pt-1",children:[l(Lo,{}),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(Ht,{className:"h-5 w-3/5 rounded-md"})}),l("div",{className:"flex items-center justify-between px-1 py-1",children:[l(Ht,{className:"h-9 w-9 rounded-full"}),l("div",{className:"flex items-center gap-2",children:[l(Ht,{className:"h-9 w-9 rounded-full"}),l(Ht,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function Fh(){return l("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[l(Lo,{}),[{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:A("flex",e.role==="user"?"justify-end":"justify-start"),children:l(Ht,{className:A("rounded-lg",e.size)})},t))]})}function Vh({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(Lo,{}),Array.from({length:e},(n,r)=>l("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[l(Ht,{className:A("h-5 rounded-md",t[r%t.length])}),l(Ht,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function jh(e,t=[]){let n=[];function r(i,s){const a=vt(s);a.displayName=i+"Context";const c=n.length;n=[...n,s];const d=u=>{const{scope:f,children:_,...p}=u,g=f?.[e]?.[c]||a,v=_e(()=>p,Object.values(p));return l(g.Provider,{value:v,children:_})};d.displayName=i+"Provider";function h(u,f){const _=f?.[e]?.[c]||a,p=St(_);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=>vt(s));return function(s){const a=s?.[e]||i;return _e(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,zh(o,...t)]}function zh(...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 _e(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Bh=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Uo=Bh.reduce((e,t)=>{const n=Ga(`Primitive.${t}`),r=J((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}},{}),hl={exports:{}},Fo={};const $h=_d(co);var ml;function Hh(){if(ml)return Fo;ml=1;var e=$h;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 _=f(),p=r({inst:{value:_,getSnapshot:f}}),g=p[0].inst,v=p[1];return i(function(){g.value=_,g.getSnapshot=f,c(g)&&v({inst:g})},[u,_,f]),o(function(){return c(g)&&v({inst:g}),u(function(){c(g)&&v({inst:g})})},[u]),s(_),_}function c(u){var f=u.getSnapshot;u=u.value;try{var _=f();return!n(u,_)}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 Fo.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,Fo}var pl;function Yh(){return pl||(pl=1,hl.exports=Hh()),hl.exports}var Gh=Yh();function Wh(){return Gh.useSyncExternalStore(Kh,()=>!0,()=>!1)}function Kh(){return()=>{}}var Vo="Avatar",[qh]=jh(Vo),[Xh,fl]=qh(Vo),gl=J((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=L("idle");return l(Xh,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:l(Uo.span,{...r,ref:t})})});gl.displayName=Vo;var _l="AvatarImage",El=J((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=fl(_l,n),a=Zh(r,i),c=At(d=>{o(d),s.onImageLoadingStatusChange(d)});return jt(()=>{a!=="idle"&&c(a)},[a,c]),a==="loaded"?l(Uo.img,{...i,ref:t,src:r}):null});El.displayName=_l;var yl="AvatarFallback",vl=J((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=fl(yl,n),[s,a]=L(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(Uo.span,{...o,ref:t}):null});vl.displayName=yl;function bl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Zh(e,{referrerPolicy:t,crossOrigin:n}){const r=Wh(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=L(()=>bl(i,e));return jt(()=>{a(bl(i,e))},[i,e]),jt(()=>{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 Sl=gl,wl=El,Nl=vl;const jo=J(({className:e,...t},n)=>l(Sl,{ref:n,className:A("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));jo.displayName=Sl.displayName;const xl=J(({className:e,...t},n)=>l(wl,{ref:n,className:A("aspect-square h-full w-full",e),...t}));xl.displayName=wl.displayName;const zo=J(({className:e,...t},n)=>l(Nl,{ref:n,className:A("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));zo.displayName=Nl.displayName;const Tl=vt(!1);function Jh({enabled:e,children:t}){return l(Tl.Provider,{value:e,children:t})}function Qh(){return St(Tl)}const Cl="(max-width: 768px), (pointer: coarse)",kl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function em(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Cl)?.matches??!1,t=kl.test(navigator?.userAgent??"");return e||t}function Rl(){const[e,t]=L(em);return z(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Cl),r=kl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function tm({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=Rl(),_=Qh()&&!f,p=G(S=>S.displayMode)==="full",g=G(S=>S.initialDisplayMode)==="full",v=!p&&c?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",m=G(S=>S.connectionStatus),E=G(S=>S.level)==="user",[y,k]=L(!1),w=X(null),N=_e(()=>a==="connected"||a==="connecting"||a==="listening"||a==="speaking"||a==="thinking",[a]),T=fe(()=>{y||(k(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{w.current=null,k(!1)},6e3),s())},[y,s]);z(()=>{m===ge.CONNECTED&&(k(!1),w.current&&clearTimeout(w.current))},[m]);const b=(()=>{switch(m){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(jo,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:l(zo,{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:A("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",b.dotColor,m===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:A("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",v),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:b.text})})]})]}),l("div",{className:A("flex items-center",!_&&"gap-1"),children:[!N&&(!E||!u)&&l(le,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:T,disabled:y,className:A("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",v),children:l(Xn,{className:"w-5 h-5"})}),h&&E&&l(le,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:A("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:l($u,{className:"w-5 h-5"})}),_&&l(le,{onClick:d,type:"button",variant:"ghost",size:"icon",title:p?"Exit fullscreen":"Enter fullscreen",className:A("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:p?l(Qu,{className:"w-8 h-8"}):l(Wu,{className:"w-8 h-8"})}),(t||!g)&&l(le,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:A("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",v),children:l(fn,{className:"w-8 h-8"})})]})]})})}const Bo=J(({className:e,...t},n)=>l("textarea",{className:A("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}));Bo.displayName="Textarea";function Ol({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=L(!1),[s,a]=L(""),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 _=1024,p=["B","KB","MB","GB"],g=Math.floor(Math.log(f)/Math.log(_));return`${(f/Math.pow(_,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(Za,{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(fn,{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(fn,{className:"h-3 w-3"})})]})}function $o({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(Ol,{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(Ol,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const Ho=({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"})}),Al=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),nm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Il=({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"})}),rm=We(()=>Al().then(e=>({default:e.ElicitationInput})));function om({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:_,allowed:p,showStartNewChatButton:g,onStartNewChat:v,isVoiceAgentActive:m,handleVoiceMode:E,isAuthComponent:y,activeElicitationState:k,isFullScreen:w}){const N=X(null),T=X(null),b=e.trim().length>0||a,S=!p||p.includes(M.SYNAPSE_CONVERSATION.AUDIO),x=!p||p.includes(M.SYNAPSE_CONVERSATION.VOICE),I=b||!S,H=b,ne=!p||p.includes(M.SYNAPSE_CONVERSATION.FILE),xe=(d||f!==Ee.IDLE)&&!s,de=A("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)]":xe?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),Q=Y=>{const re=Array.from(Y.target.files||[]);re.length>0&&r(re)},me=()=>{d||(N.current&&(N.current.value=""),N.current?.click())},P=Y=>{Y.key==="Enter"&&!Y.shiftKey&&H&&!d&&(Y.preventDefault(),n())},F=Y=>{Y.style.height="auto",Y.style.overflow="hidden";const re=Y.scrollHeight,$=w?20:28,W=120,we=Math.max($,Math.min(re,W));Y.style.height=we+"px",re>W?Y.style.overflow="auto":Y.style.overflow="hidden"},Z=Y=>{F(Y.currentTarget)};return z(()=>{T.current&&F(T.current)},[e]),z(()=>{!d&&!u&&T.current?.focus()},[d]),g&&v?l("div",{className:"px-4 py-2 flex justify-unset",children:l("button",{type:"button",onClick:v,className:A("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(Xn,{className:"w-5 h-5","aria-hidden":!0})]})}):l(ce,{children:y?l($e,{fallback:l(ul,{}),children:l(rm,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:_,isMobile:u,onSend:n})}):w?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($o,{files:c,onRemoveFile:o,isPreview:!0})}),l("input",{ref:N,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:Q,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(Bo,{ref:T,onInput:Z,placeholder:h,value:e,onChange:Y=>t(Y.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:P,title:"Enter your message","aria-label":"Enter your message",className:A("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:ne&&f===Ee.IDLE&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:me,disabled:d,className:A("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(Qa,{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(le,{type:"button",variant:"ghost",size:"icon",onClick:i,className:A("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(el,{className:"w-4 h-4"})}):S&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:xe,className:A("h-10 w-10 shrink-0 p-2",de),title:"Start recording","aria-label":"Start recording",children:l(Ro,{className:"w-6 h-6",strokeWidth:1.5})}),I&&!s?l(le,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!H,variant:"ghost",className:A("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",H?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:H?"Send message":"Type a message to send","aria-label":H?"Send message":"Type a message to send",children:l(Ho,{className:"w-4 h-4 text-primary-foreground"})}):S&&x&&!s&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:E,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(Il,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):l("div",{className:"px-3 pt-1",children:[l("input",{ref:N,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:Q,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($o,{files:c,onRemoveFile:o,isPreview:!0})}),l("div",{className:"px-1 pt-1 pb-0",children:l(Bo,{ref:T,onInput:Z,placeholder:h,value:e,onChange:Y=>t(Y.target.value),rows:1,maxLength:1e3,autoFocus:!u,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:P,title:"Enter your message","aria-label":"Enter your message",className:A("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:ne&&f===Ee.IDLE&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:me,disabled:d,className:A("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(Qa,{className:"w-5 h-5",strokeWidth:1.5})})}),l("div",{className:"flex items-center gap-2 shrink-0",children:[s?l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,className:A("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(el,{className:"w-4 h-4"})}):I?l(le,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!H,variant:"ghost",className:A("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",H?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:H?"Send message":"Type a message to send","aria-label":H?"Send message":"Type a message to send",children:l(Ho,{className:"w-4 h-4 text-primary-foreground"})}):S&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:xe,className:A("h-10 w-10 shrink-0",de),title:"Start recording","aria-label":"Start recording",children:l(Ro,{className:"w-5 h-5",strokeWidth:1.5})}),S&&x&&!s&&l(le,{type:"button",variant:"ghost",size:"icon",onClick:E,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(Il,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}function sm({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(fn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function im(){const e=G(r=>r.toastMessage),t=G(r=>r.setToastMessage),n=fe(()=>{t(null)},[t]);return z(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?l(sm,{message:e,onDismiss:n}):null}function Yo({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 am="Before we begin",lm=e=>`A quick note on how ${e} works and handles your information.`,cm=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 dm(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 Ml=(e,t)=>{if(t){const n=dm(t,e);if(n.length)return n}return cm(e)},um="I agree and consent",hm="By continuing, you consent to the above.",mm="Continue";function Pl({botName:e,consentContent:t,isFullScreen:n}){return l(ce,{children:[l("div",{className:"flex flex-col gap-1",children:[l("h2",{className:A("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:am}),l("p",{className:A("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:lm(e)})]}),l("div",{className:A("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:Ml(e,t).map((r,o)=>l("p",{className:A("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function pm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return l(Yo,{isOpen:e,onClose:t,children:l("div",{className:A("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(Pl,{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"}),Ml(n,o).map((a,c)=>l("p",{className:A("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},c))]}),l(le,{onClick:t,className:A("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function fm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=L(!1);return e?l(Yo,{isOpen:e,children:l("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:A("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(Pl,{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:A("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:A("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:um})]}),l("p",{className:A("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:hm})]}),l(le,{disabled:!i,onClick:()=>i&&r(),className:A("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:mm})]})}):null}const gm=We(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),_m=We(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),Em=We(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),ym=We(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),vm=We(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),bm=[{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"}],Sm=[{Icon:gm,label:"Bad",score:1},{Icon:_m,label:"Poor",score:2},{Icon:Em,label:"Okay",score:3},{Icon:ym,label:"Good",score:4},{Icon:vm,label:"Great!",score:5}];function wm(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Nm({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,c]=L(null),[d,h]=L(new Set),[u,f]=L(!1),_=s&&a!==null?wm(a,t):t.form?.default?.length?t.form.default:bm,p=E=>{h(y=>{const k=new Set(y);return k.has(E)?k.delete(E):k.add(E),k})},g=E=>{c(E),h(new Set)},v=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?l(Yo,{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:Sm.map(({Icon:E,label:y,score:k})=>{const w=a===k,N=a!==null&&!w;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 ${w?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${N?"opacity-50":""}`,style:w?{filter:"brightness(1.25)"}:void 0,children:l($e,{fallback:l("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:l(E,{})})}),l("span",{className:`text-[10px] leading-none transition-colors ${w?"text-primary/50 font-medium":N?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&_.length>0&&l("div",{className:"flex flex-col gap-2",children:_.map(E=>l("div",{onClick:()=>p(E.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(E.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:E.label},E.value))}),l(le,{disabled:!v,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(E=>!E),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 Dl({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:_,chatComposer:p,environment:g,mode:v,onToggleDisplayMode:m,onOpenSessionDrawer:E,historyEnabled:y=!1,isAuthComponent:k,activeElicitation:w,voiceAgentState:N,theme:T,feedbackModal:b,consentModal:S}){const[x,I]=L(!1),[H,ne]=L(!1),[xe,de]=L(!1),Q=X(null),me=G(D=>D.level),P=v,F=P==="full",Z=X(null),[Y,re]=L("");z(()=>{Z.current!==null&&Z.current!==P&&re(P==="full"?"Switched to fullscreen mode":P==="widget"?"Switched to widget mode":"Switched to mobile layout"),Z.current=P},[P]);const $=_e(()=>Ih(T),[T]),{setIsMobile:W}=G(D=>D),we=!!k,pe=async D=>{if(!(!p?.onSend||H)){ne(!0);try{await p.onSend(D)}finally{ne(!1)}}};at(()=>{if(!Q.current)return;const D=P==="full"?{...$,headerTinted:!1}:$;dl(Q.current,D),P==="full"&&!$.backgroundImage?(Q.current.style.setProperty("--background","0 0% 100%"),Q.current.style.setProperty("--widget-bg-overlay","transparent")):(Q.current.style.removeProperty("--background"),Q.current.style.removeProperty("--widget-bg-overlay"),dl(Q.current,$))},[$,P]),z(()=>{const D=()=>{const ue=window?.innerWidth??0,ie=navigator?.userAgent?.toLowerCase()??"",ke=ue<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ie);I(ke),W(ke)};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]),at(()=>{if(!e||!x||!Q.current)return;const D=Q.current;let ue=null,ie=null,ke=null,Me=window.visualViewport?.offsetTop??0,Te=0;const ct=2,Ae=80;if(window.visualViewport){const Ne=()=>{if(D&&window.visualViewport){const Be=window.visualViewport.height,Re=window.visualViewport.offsetTop;ue=requestAnimationFrame(()=>{D.style.transition="none",D.style.top=`${Re}px`,D.style.left="0",D.style.right="0",D.style.bottom="auto",D.style.width="100vw",D.style.height=`${Be}px`,D.style.maxHeight=`${Be}px`,D.style.minHeight=`${Be}px`,ie&&clearTimeout(ie),ie=setTimeout(()=>{D.style.transition=""},100)})}},et=()=>{Ne()},ze=()=>{if(!D||!window.visualViewport)return;const Be=window.visualViewport.offsetTop,Re=Date.now();Math.abs(Be-Me)<ct||Re-Te<Ae||(Te=Re,Me=Be,ue=requestAnimationFrame(()=>{D.style.transition="none",D.style.top=`${Be}px`,ke&&clearTimeout(ke),ke=setTimeout(()=>{D.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",et),window.visualViewport.addEventListener("scroll",ze),Ne(),()=>{ue&&cancelAnimationFrame(ue),ie&&clearTimeout(ie),ke&&clearTimeout(ke),window.visualViewport?.removeEventListener("resize",et),window.visualViewport?.removeEventListener("scroll",ze),D&&(D.style.width="",D.style.height="",D.style.maxHeight="",D.style.minHeight="",D.style.transition="")}}else{const Ne=()=>{D&&(D.style.transition="none",D.style.top="0",D.style.left="0",D.style.right="0",D.style.bottom="auto",D.style.width="100vw",D.style.height="100svh",D.style.maxHeight="100svh",setTimeout(()=>{D.style.transition=""},100))};return window.addEventListener("resize",Ne),Ne(),()=>{window.removeEventListener("resize",Ne),D&&(D.style.width="",D.style.height="",D.style.maxHeight="",D.style.transition="")}}},[e,x]),z(()=>{if(e){const D=Q.current,ue=window.scrollY,ie=document.body.style.cssText,ke=document.documentElement.style.overflow,Me=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${ue}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",Me>0&&!x&&(document.body.style.paddingRight=`${Me}px`);let Te=0;const ct=Ne=>{Te=Ne.touches[0].clientY},Ae=Ne=>{if(Ne.touches.length!==1)return;const et=Te-Ne.touches[0].clientY;Te=Ne.touches[0].clientY;let ze=Ne.target;for(;ze&&ze!==D;){const{overflowY:Be}=window.getComputedStyle(ze);if((Be==="auto"||Be==="scroll")&&ze.scrollHeight>ze.clientHeight){const{scrollTop:Re,scrollHeight:Dt,clientHeight:dt}=ze,Kt=Re<=0&&et<0,ut=Re+dt>=Dt-1&&et>0;if(!Kt&&!ut)return;break}ze=ze.parentElement}Ne.preventDefault()};return D&&(D.addEventListener("touchstart",ct,{passive:!0}),D.addEventListener("touchmove",Ae,{passive:!1})),()=>{D&&(D.removeEventListener("touchstart",ct),D.removeEventListener("touchmove",Ae)),document.body.style.cssText=ie,document.documentElement.style.overflow=ke,window.scrollTo(0,ue)}}},[e,x]);const{position:se,elementRef:Ke}=Ch({enabled:e&&!x&&!F});z(()=>{Q.current&&(Ke.current=Q.current)},[Ke]);const Ye=A("synapse-chat-widget-container","fixed m-0 p-0","box-border",!x&&!F?"transition-[opacity,transform] duration-300":"",x?"w-screen h-[100svh]":F?"w-screen h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Qe=A("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",$.backgroundImage?"theme-with-background":"",x?"rounded-none border-0 flex-col":F?"rounded-none border-0 flex-row":"rounded-3xl flex-col");return l("div",{ref:Q,"data-mode":P,className:Ye,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...F&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...F&&!e&&{display:"none"},...!x&&!F&&{left:`${se.x}px`,top:`${se.y}px`,bottom:"auto",right:"auto"},...x&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:$.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 yc=Object.defineProperty;var vc=(e,t,n)=>t in e?yc(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($t,{className:Qe,"data-text-color":$.textColor,style:x?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:Y}),!$.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),$.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${$.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),$.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:$.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(hm,{isOpen:xe,onClose:()=>de(!1),botName:h,explicitDisclaimer:T?.explicitDisclaimer,isFullScreen:U}),S?.isOpen&&l(mm,{isOpen:!0,botName:h,onAccept:S.onAccept,isFullScreen:U}),b?.isOpen&&l(Sm,{isOpen:b.isOpen,config:b.config,onSubmit:b.onSubmit,onSkip:b.onSkip,onClose:b.onClose,onDontShowAgain:b.onDontShowAgain}),U&&a,me==="user"&&!U&&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:{...U?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!x&&!U&&{cursor:e?"grab":"default"}},children:l(tm,{onClose:t,showCloseButton:n,title:h,titleImg:u,tagline:f,iconUrl:r,startNewConversation:o,voiceAgentState:N,headerTinted:U?!1:$.headerTinted,onToggleDisplayMode:m,onOpenSessionDrawer:U?void 0:E,historyEnabled:y})}),(()=>{const D=U&&!!d,ue=p&&N===M.VOICE_AGENT_STATE.IDLE?l($e,{fallback:l(ul,{}),children:l(om,{value:p.value,onChange:p.onChange,onSend:we?pe:p.onSend,onFileChange:p.onFileChange,onRemoveFile:p.onRemoveFile,onRecording:p.onRecording,isRecording:p.isRecording,hasAttachment:p.hasAttachment,attachmentFiles:p.attachmentFiles,isDisabled:p.isDisabled||we&&H,isMobile:x,placeholder:p.placeholder,recordingStatus:p.recordingStatus,theme:$,onStartNewChat:o,showStartNewChatButton:i,isVoiceAgentActive:p.isVoiceAgentActive,handleVoiceMode:p.handleVoiceMode,allowed:p.allowed,isAuthComponent:k,activeElicitationState:w,isFullScreen:U&&!D})}):null,ie={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},ke=l(ce,{children:[_&&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: ",_]})}),U?l("div",{onClick:()=>de(!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:ie,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):T?.explicitDisclaimer?l("div",{onClick:()=>de(!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:[T?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>de(!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:[T?.hideWatermark!==!0&&l(ce,{children:[l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Eka Care"})]}),l(Ja,{className:"w-3 h-3"})]})]}),Me=d&&U?d({composer:D?ue:null,composerFooter:D?ke:null}):null;return l(ce,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Me??s,l(im,{})]}),p&&!D&&l("div",{className:A("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:A(U&&"max-w-2xl mx-auto w-full"),children:ue}),ke]})]})})()]})]})]})}function wm(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Nm(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 xm({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:A("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:A("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(Xn,{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(Xn,{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(Vh,{}):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=Nm(d),u=wm(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(Tm,{})]})]},a.session_id)})})]})}function Tm(){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 Cm(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(ce,{children:[l("div",{className:A("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:A("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(fn,{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(Xn,{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 ${Cm(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(Ll,{})]})]}):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(Ll,{})]})},s.session_id)})})]})]})}function Ll(){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 Rm(){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 Om=180;function Am({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<=Om&&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:Rm()}),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:A("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 Fl(){const[e,t]=L(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 Ul=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Im=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Mm=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}},Pm=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},Vl=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Dm=({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?Um(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:Vl(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,...Ul(a),slots:a.slots??d.slots}}}return s},Lm=(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,...Ul(o),availability:Dm({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},jl=e=>!!e&&Array.isArray(e.doctors),Fm=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!jl(e)||!jl(t))return e;const r=e.format||t.format;return{...t,doctors:Lm(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Um=(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},zl=(e,t)=>`${e}::${t}`,Vm=e=>e<1e12?e*1e3:e,jm=(e,t)=>`${e}::${t}::answer`,zm=e=>!!e?.tool_id&&!!e?.component;function Bm(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(zm),i=r.timestamp?Bt(Vm(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===je.USER?je.USER:je.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>zl(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[zl(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:jm(r.id,s.tool_id),content:s.answer,role:je.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Yt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},$m=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=L([]),d=X([]),[h,u]=L(!1),[f,_]=L(!1),p=X(new Map),g=X(0),[v,m]=L(!1),E=X([]),y=X(null),k=Sh(),w=X(null),{isOnline:N}=Fl(),T=X(!1),b=G(O=>O.agentId),S=G(O=>O.sessionId),x=G(O=>O.isStreaming),I=G(O=>O.isWaitingForResponse),H=G(O=>O.initialMessage),ne=G(O=>O.userId),xe=G(O=>O.fileUploadPerSession),{setSessionId:de,setRefreshToken:Q,setSessToken:me,setLevel:P,setError:U,setConnectionStatus:Z,setShowRetryButton:Y,setStartNewConnection:re,setIsStreaming:$,setIsWaitingForResponse:W,setProgressMessage:we,setRecordingStatus:pe,clearSession:se,clearUser:Ke,addMessageToSession:Ye,getMessagesForSession:Qe,setMessagesForSession:D,updateMessageInSession:ue,setUserId:ie,setFileUploadPerSession:ke,setToastMessage:Me,upsertElicitationState:Te,setElicitationState:ct,setInitialMessage:Ae,setSessionInitialMessage:Ne}=G.getState();z(()=>{if(!N)U({title:"No internet connection",description:"Please check your internet connection."}),Z(ge.NOT_CONNECTED);else if(!v)Z(ge.CONNECTING);else if(Re())Z(ge.CONNECTED),dt();else{const{showRetryButton:O,startNewConnection:C,error:F}=G.getState();(O||C||F)&&!Re()&&dt()}},[N,v]),z(()=>{S&&(c(O=>{const C=new Set(O.map(F=>F.id));return[...O,...(Qe(S)||[]).filter(F=>!C.has(F.id))]}),E.current=[])},[S]),z(()=>{if(m(!1),!b)return;const O=new M.SynapseSDK({agentId:b,...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:ne,callbacks:{onError:C=>{if(typeof navigator<"u"&&!navigator.onLine){Z(ge.NOT_CONNECTED),U({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"?(Ke(),y.current?.clearTokens(),_n()):En();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:En();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:U(null),Z(ge.NOT_CONNECTED),re(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:Z(ge.CONNECTING);return}switch(C.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const F=C;F.status===404||F?.context?.status===404?re(!0):(Z(ge.NOT_CONNECTED),U({title:"Something went wrong!",description:Yt(C)}),Y(!0));break}case M.SynapseErrorCode.RECORDING:U({title:"Recording failed",description:Yt(C)});break;case M.SynapseErrorCode.CONNECTION:Re()||(Z(ge.NOT_CONNECTED),g.current<2?(g.current=g.current+1,et(S)):(Y(!0),U({title:"Trying to connect...",description:Yt(C)})));break;default:U({title:"Something went wrong",description:Yt(C)}),Y(!0);break}},onTokenExchange:C=>{const F=G.getState().userId;(C?.user_id&&F&&C.user_id!==F||C?.userid_change_detected)&&se(),C?.refresh_token&&Q(C.refresh_token),C?.sess_token&&me(C.sess_token),C?.level&&P(C.level),C?.user_id&&ie(C.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=O,k(O),m(!0),()=>{m(!1),Dt(),y.current=null,k(null),w.current&&(clearTimeout(w.current),w.current=null)}},[b,e,o]),z(()=>{d.current=a},[a]),z(()=>{const O=d.current[d.current.length-1];!O?.role||!S||(O?.role===je.USER&&!O.isStored?Ye(S,{...O,isStored:!0}):!x&&!O.isStored&&(c(C=>{const F=[...C];return F[F.length-1]={...O,isStored:!0},F}),Ye(S,{...O,isStored:!0})))},[a,x]),z(()=>()=>{const O=d.current[d.current.length-1];O&&!O?.isStored&&S&&Ye(S,{...O,isStored:!0})},[]),z(()=>(w.current&&(clearTimeout(w.current),w.current=null),I&&!x?w.current=setTimeout(()=>{W(!1),w.current=null},3e4):x&&w.current&&(clearTimeout(w.current),w.current=null),()=>{w.current&&(clearTimeout(w.current),w.current=null)}),[I,x,W]);const et=async O=>{try{const C=await y.current?.startSession(O?{session_id:O}:void 0);if(C?.session_id&&de(C.session_id),C?.user_id&&ie(C.user_id),C?.initial_message){Ae(C.initial_message);const F=C.session_id||O;F&&Ne(F,C.initial_message)}C?.error?.msg&&Me(C.error.msg)}catch(C){if(C?.reason)return;const F=C;F.status===404||F.context?.status==404?(U(null),Z(ge.NOT_CONNECTED),re(!0)):(U({title:"Connection Lost!",description:Yt(C)}),Y(!0))}},ze=async O=>{const C=G.getState().chats[O];if(C?.length)return c(C),C;const F=p.current.get(O);if(F)return F;const K=(async()=>{try{const ae=await y.current?.getSessionMessages(O);if(!ae?.length)return[];const{messages:oe,elicitations:Se}=Bm(ae);return Object.keys(Se).length&&ct({...G.getState().elicitationState,...Se}),D(O,oe),c(oe),oe}catch{return[]}finally{p.current.delete(O)}})();p.current.set(O,K),_(!0);try{return await K}finally{_(!1)}},Be=async({forceNewSession:O=!1,sessionId:C}={})=>{try{if(!y.current){U({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),O){Z(ge.CONNECTING),c([]),await se(),await y?.current?.endSession(),dt(),await et(),Kt();return}const F=G.getState()?.sessionId,K=C||F||void 0;K!==F&&(Dt(),c([]),K&&await ze(K)),await et(K),Kt()}catch{}finally{u(!1)}},Re=()=>y.current?.isConnected()??!1,Dt=()=>{y.current?.endSession()},dt=()=>{g.current=0,Y(!1),re(!1),U(null)},Kt=()=>{y.current?.on(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,O=>{const C=O;if(C.data?.text&&C.messageId){x||(W(!1),$(!0)),Re()&&Z(ge.CONNECTED),dt();const F=C.data.text,K=C.messageId,ae=T.current;T.current=!1,c(oe=>{const Se=oe[oe.length-1];if(Se&&Se.id===K&&Se.role===je.ASSISTANT){const Ue=[...oe],tt=ae&&Se.content.length>0&&!/\s$/.test(Se.content)&&!/^\s/.test(F)?`
38
+ `}),l($t,{className:Qe,"data-text-color":$.textColor,style:x?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:Y}),!$.backgroundImage&&l("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),$.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${$.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),$.backgroundImage&&l("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:$.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),l(pm,{isOpen:xe,onClose:()=>de(!1),botName:h,explicitDisclaimer:T?.explicitDisclaimer,consentContent:T?.consentContent,isFullScreen:F}),S?.isOpen&&l(fm,{isOpen:!0,botName:h,consentContent:T?.consentContent,onAccept:S.onAccept,isFullScreen:F}),b?.isOpen&&l(Nm,{isOpen:b.isOpen,config:b.config,onSubmit:b.onSubmit,onSkip:b.onSkip,onClose:b.onClose,onDontShowAgain:b.onDontShowAgain}),F&&a,me==="user"&&!F&&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:{...F?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!x&&!F&&{cursor:e?"grab":"default"}},children:l(tm,{onClose:t,showCloseButton:n,title:h,titleImg:u,tagline:f,iconUrl:r,startNewConversation:o,voiceAgentState:N,headerTinted:F?!1:$.headerTinted,onToggleDisplayMode:m,onOpenSessionDrawer:F?void 0:E,historyEnabled:y})}),(()=>{const D=F&&!!d,ue=p&&N===M.VOICE_AGENT_STATE.IDLE?l($e,{fallback:l(ul,{}),children:l(om,{value:p.value,onChange:p.onChange,onSend:we?pe:p.onSend,onFileChange:p.onFileChange,onRemoveFile:p.onRemoveFile,onRecording:p.onRecording,isRecording:p.isRecording,hasAttachment:p.hasAttachment,attachmentFiles:p.attachmentFiles,isDisabled:p.isDisabled||we&&H,isMobile:x,placeholder:p.placeholder,recordingStatus:p.recordingStatus,theme:$,onStartNewChat:o,showStartNewChatButton:i,isVoiceAgentActive:p.isVoiceAgentActive,handleVoiceMode:p.handleVoiceMode,allowed:p.allowed,isAuthComponent:k,activeElicitationState:w,isFullScreen:F&&!D})}):null,ie={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},ke=l(ce,{children:[_&&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: ",_]})}),F?l("div",{onClick:()=>de(!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:ie,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):T?.explicitDisclaimer?l("div",{onClick:()=>de(!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:[T?.hideWatermark!==!0&&l("div",{className:"flex justify-center items-center gap-1",children:[l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Eka Care"})]}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:["AI can make mistakes. ",l("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):l("div",{onClick:()=>de(!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:[T?.hideWatermark!==!0&&l(ce,{children:[l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Powered by"}),l("span",{className:"text-[10px] leading-[14px]",style:ie,children:"Eka Care"})]}),l(Ja,{className:"w-3 h-3"})]})]}),Me=d&&F?d({composer:D?ue:null,composerFooter:D?ke:null}):null;return l(ce,{children:[l("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Me??s,l(im,{})]}),p&&!D&&l("div",{className:A("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[l("div",{className:A(F&&"max-w-2xl mx-auto w-full"),children:ue}),ke]})]})})()]})]})]})}function xm(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Tm(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 Cm({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:A("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:A("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(Xn,{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(Xn,{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(Vh,{}):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=Tm(d),u=xm(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(km,{})]})]},a.session_id)})})]})}function km(){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 Rm(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 Om({isOpen:e,onClose:t,sessions:n,activeSessionId:r,onSelectSession:o,onNewChat:i}){return l(ce,{children:[l("div",{className:A("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:A("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(fn,{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(Xn,{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 ${Rm(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(Ll,{})]})]}):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(Ll,{})]})},s.session_id)})})]})]})}function Ll(){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 Am(){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 Im=180;function Mm({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<=Im&&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:Am()}),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:A("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 Ul(){const[e,t]=L(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 Fl=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Pm=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Dm=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}},Lm=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},Vl=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Um=({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?jm(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:Vl(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,...Fl(a),slots:a.slots??d.slots}}}return s},Fm=(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,...Fl(o),availability:Um({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:c,format:n})}}}return r},jl=e=>!!e&&Array.isArray(e.doctors),Vm=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!jl(e)||!jl(t))return e;const r=e.format||t.format;return{...t,doctors:Fm(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},jm=(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},zl=(e,t)=>`${e}::${t}`,zm=e=>e<1e12?e*1e3:e,Bm=(e,t)=>`${e}::${t}::answer`,$m=e=>!!e?.tool_id&&!!e?.component;function Hm(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter($m),i=r.timestamp?Bt(zm(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===je.USER?je.USER:je.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>zl(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[zl(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:Bm(r.id,s.tool_id),content:s.answer,role:je.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Yt=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Ym=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,c]=L([]),d=X([]),[h,u]=L(!1),[f,_]=L(!1),p=X(new Map),g=X(0),[v,m]=L(!1),E=X([]),y=X(null),k=Sh(),w=X(null),{isOnline:N}=Ul(),T=X(!1),b=G(O=>O.agentId),S=G(O=>O.sessionId),x=G(O=>O.isStreaming),I=G(O=>O.isWaitingForResponse),H=G(O=>O.initialMessage),ne=G(O=>O.userId),xe=G(O=>O.fileUploadPerSession),{setSessionId:de,setRefreshToken:Q,setSessToken:me,setLevel:P,setError:F,setConnectionStatus:Z,setShowRetryButton:Y,setStartNewConnection:re,setIsStreaming:$,setIsWaitingForResponse:W,setProgressMessage:we,setRecordingStatus:pe,clearSession:se,clearUser:Ke,addMessageToSession:Ye,getMessagesForSession:Qe,setMessagesForSession:D,updateMessageInSession:ue,setUserId:ie,setFileUploadPerSession:ke,setToastMessage:Me,upsertElicitationState:Te,setElicitationState:ct,setInitialMessage:Ae,setSessionInitialMessage:Ne}=G.getState();z(()=>{if(!N)F({title:"No internet connection",description:"Please check your internet connection."}),Z(ge.NOT_CONNECTED);else if(!v)Z(ge.CONNECTING);else if(Re())Z(ge.CONNECTED),dt();else{const{showRetryButton:O,startNewConnection:C,error:U}=G.getState();(O||C||U)&&!Re()&&dt()}},[N,v]),z(()=>{S&&(c(O=>{const C=new Set(O.map(U=>U.id));return[...O,...(Qe(S)||[]).filter(U=>!C.has(U.id))]}),E.current=[])},[S]),z(()=>{if(m(!1),!b)return;const O=new M.SynapseSDK({agentId:b,...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:ne,callbacks:{onError:C=>{if(typeof navigator<"u"&&!navigator.onLine){Z(ge.NOT_CONNECTED),F({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"?(Ke(),y.current?.clearTokens(),_n()):En();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:En();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:F(null),Z(ge.NOT_CONNECTED),re(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:Z(ge.CONNECTING);return}switch(C.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const U=C;U.status===404||U?.context?.status===404?re(!0):(Z(ge.NOT_CONNECTED),F({title:"Something went wrong!",description:Yt(C)}),Y(!0));break}case M.SynapseErrorCode.RECORDING:F({title:"Recording failed",description:Yt(C)});break;case M.SynapseErrorCode.CONNECTION:Re()||(Z(ge.NOT_CONNECTED),g.current<2?(g.current=g.current+1,et(S)):(Y(!0),F({title:"Trying to connect...",description:Yt(C)})));break;default:F({title:"Something went wrong",description:Yt(C)}),Y(!0);break}},onTokenExchange:C=>{const U=G.getState().userId;(C?.user_id&&U&&C.user_id!==U||C?.userid_change_detected)&&se(),C?.refresh_token&&Q(C.refresh_token),C?.sess_token&&me(C.sess_token),C?.level&&P(C.level),C?.user_id&&ie(C.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=O,k(O),m(!0),()=>{m(!1),Dt(),y.current=null,k(null),w.current&&(clearTimeout(w.current),w.current=null)}},[b,e,o]),z(()=>{d.current=a},[a]),z(()=>{const O=d.current[d.current.length-1];!O?.role||!S||(O?.role===je.USER&&!O.isStored?Ye(S,{...O,isStored:!0}):!x&&!O.isStored&&(c(C=>{const U=[...C];return U[U.length-1]={...O,isStored:!0},U}),Ye(S,{...O,isStored:!0})))},[a,x]),z(()=>()=>{const O=d.current[d.current.length-1];O&&!O?.isStored&&S&&Ye(S,{...O,isStored:!0})},[]),z(()=>(w.current&&(clearTimeout(w.current),w.current=null),I&&!x?w.current=setTimeout(()=>{W(!1),w.current=null},3e4):x&&w.current&&(clearTimeout(w.current),w.current=null),()=>{w.current&&(clearTimeout(w.current),w.current=null)}),[I,x,W]);const et=async O=>{try{const C=await y.current?.startSession(O?{session_id:O}:void 0);if(C?.session_id&&de(C.session_id),C?.user_id&&ie(C.user_id),C?.initial_message){Ae(C.initial_message);const U=C.session_id||O;U&&Ne(U,C.initial_message)}C?.error?.msg&&Me(C.error.msg)}catch(C){if(C?.reason)return;const U=C;U.status===404||U.context?.status==404?(F(null),Z(ge.NOT_CONNECTED),re(!0)):(F({title:"Connection Lost!",description:Yt(C)}),Y(!0))}},ze=async O=>{const C=G.getState().chats[O];if(C?.length)return c(C),C;const U=p.current.get(O);if(U)return U;const K=(async()=>{try{const ae=await y.current?.getSessionMessages(O);if(!ae?.length)return[];const{messages:oe,elicitations:Se}=Hm(ae);return Object.keys(Se).length&&ct({...G.getState().elicitationState,...Se}),D(O,oe),c(oe),oe}catch{return[]}finally{p.current.delete(O)}})();p.current.set(O,K),_(!0);try{return await K}finally{_(!1)}},Be=async({forceNewSession:O=!1,sessionId:C}={})=>{try{if(!y.current){F({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),O){Z(ge.CONNECTING),c([]),await se(),await y?.current?.endSession(),dt(),await et(),Kt();return}const U=G.getState()?.sessionId,K=C||U||void 0;K!==U&&(Dt(),c([]),K&&await ze(K)),await et(K),Kt()}catch{}finally{u(!1)}},Re=()=>y.current?.isConnected()??!1,Dt=()=>{y.current?.endSession()},dt=()=>{g.current=0,Y(!1),re(!1),F(null)},Kt=()=>{y.current?.on(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,O=>{const C=O;if(C.data?.text&&C.messageId){x||(W(!1),$(!0)),Re()&&Z(ge.CONNECTED),dt();const U=C.data.text,K=C.messageId,ae=T.current;T.current=!1,c(oe=>{const Se=oe[oe.length-1];if(Se&&Se.id===K&&Se.role===je.ASSISTANT){const Fe=[...oe],tt=ae&&Se.content.length>0&&!/\s$/.test(Se.content)&&!/^\s/.test(U)?`
39
39
 
40
- `:"";return Ue[Ue.length-1]={...Se,content:Se.content+tt+F},Ue}else return[...oe,{id:K,content:F,role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}]})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{T.current=!1,$(!1),we(null),W(!1)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{dt(),Z(ge.CONNECTED)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,O=>{T.current=!0;const C=O;if(!C?.messageId||!C?.data||!C?.data?.details?.component||!C?.data?.tool_id)return;I&&W(!1);const{messageId:F,data:K}=C,ae=K.tool_id,oe=`${F}::${ae}`,Se=G.getState().elicitationState[oe],Ue=K.details?.component,tt=C?.data?.details?._meta?.tool_result,qt=K.details?.input,Lt=Fm(Se?.input,qt,Ue);let Ve=C.data.details?._meta?.disp_toast_msg;const nt=K?.details?._meta?.schema?.required||[];switch(K?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Pe=C?.data?.details?.input||{},De=nt.reduce((_t,Et)=>(Pe[Et]!==void 0&&(_t[Et]=Pe[Et]),_t),{}),ee={...Se?.server_input||{},...De},Ft=nt.filter(_t=>!ee[_t]),Ut=C.data.details?._meta?.mcp_meta_fields||[];Te(oe,{tool_id:ae,active:!0,disabled:!1,input:Lt,server_input:ee,messageId:F,required:nt,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:tt,orientation:C.data.details?._meta?.orientation,...Ut.length&&{mcp_meta_fields:Ut},...Ft?{toolSelectionNames:Ft}:{},...Se?.hide_show_more!==void 0?{hide_show_more:Se.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{Te(oe,{...Se||{},tool_id:ae,disabled:!0,active:Nu(Ue),messageId:F,component:Ue,input:Lt,tool_result:tt,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{Te(oe,{...Se||{},tool_id:ae,active:!1,messageId:F,response_value:{label:K?.details?._meta?.disp_message||"Tool call failed"},tool_result:tt,disabled:!0});break}default:Te(oe,{tool_id:ae,disabled:!1,active:!1,messageId:F,tool_result:tt,input:Lt,component:Ue})}Ve&&Me(Ve);const it=C?.data?.details?._meta?.user_hint;c(Pe=>{let De=Pe[Pe.length-1]?.id===F?Pe.length-1:Pe.findIndex?.(ee=>ee.id===F);if(De==-1){const ee={id:F,content:C.data?.details?.input?.text||"",role:je.ASSISTANT,tool_keys:[oe],isResponseFromTool:!0,isStored:!1,...it?{userHint:it}:{}};return[...Pe,ee]}else{const ee={...Pe[De],isResponseFromTool:!0,tool_keys:[...new Set([...Pe[De].tool_keys||[],oe])],...it?{userHint:it}:{}};Pe[De]=ee,ue(S,F,ee)}return[...Pe]});const rt=C?.data?.details?._meta?.disp_message,ht=G.getState().elicitationState;if((!ht[oe]?.active||ht[oe]?.send_to_llm)&&(rt||Object.keys(tt||{}).length))try{ut({message:rt||"",tool_result:tt,toolCalled:!0,tool_key:oe})}catch{}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,O=>{if(O?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const C=typeof navigator<"u"&&!navigator.onLine;if(Z(ge.NOT_CONNECTED),C){U({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),Y(!1);return}g.current<2?(g.current=g.current+1,Y(!0),U({title:"Something went wrong!",description:"Please try again."})):(U({title:"Something went wrong!",description:"Please start a new Chat."}),re(!0))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.ERROR,O=>{switch(O?.data?.code){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:re(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:U({title:"Session not found",description:"Please start a new chat from onError callback"}),re(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:_n();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++,yn();return}U({title:"Error parsing request",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:U({title:"Request timed out",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:U({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:U({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:U({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;default:U({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async O=>{const C=O;C?.data?.text&&(c(F=>[...F,{id:Date.now().toString(),content:C.data.text||"",role:je.USER,timestamp:Bt(Date.now()),isStored:!0}]),pe(Ee.IDLE)),$(!1),W(!1),we(null)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,O=>{T.current=!0;const C=O;C.data?.text&&(W(!1),we(C.data.text))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,O=>{T.current=!0;const C=O;if(C.data?.name&&C.messageId){const F=C.messageId;c(K=>{const ae=K[K.length-1];if(ae&&ae.id===F&&ae.role===je.ASSISTANT){const oe=[...K];return oe[oe.length-1]={...ae,toolCallStatus:`Calling tool: ${C.data.name}...`},S&&ue(S,F,{toolCallStatus:`Calling tool: ${C.data.name}...`}),oe}return K})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,O=>{T.current=!0;const C=O;if(C.data?.name&&C.messageId){const F=C.messageId;c(K=>{const ae=K[K.length-1];if(ae&&ae.id===F&&ae.role===je.ASSISTANT){const oe=[...K];return oe[oe.length-1]={...ae,toolCallStatus:"Tool call completed."},S&&ue(S,F,{toolCallStatus:"Tool call completed."}),oe}return K})}})},ut=async({message:O,files:C,audio:F,toolCalled:K,selectedComponent:ae,resend:oe,tool_declined:Se,tool_result:Ue,tool_key:tt})=>{const qt=G.getState().elicitationState,Lt=Object.values(qt).some(Ve=>Ve.active);if(!(!K&&(!C||C.length===0)&&!O?.trim()&&!F?.audio&&!ae&&!Lt&&!Ue&&!Object.keys(Ue||{}).length)){if(C&&C.length>3){U({title:"Maximum 3 files are allowed to be sent at a time",description:"Please try again"});return}if(C&&C.length>0&&C.reduce((Ve,nt)=>Ve+nt.size,0)>10*1024*1024){U({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+xe>Io){const Ve=Io-xe;U({title:`You can only upload up to ${Io} files per session`,description:`${Ve<=0?"Maximum file upload limit reached":`You have ${Ve} file${Ve===1?"":"s"} upload${Ve===1?"":"s"} left`}`});return}else C&&C.length&&ke(xe+C.length);U(null),Y(!1),Re()&&Z(ge.CONNECTED);try{const Ve=a.length<=2&&E.current.length==1?E.current:null;let nt=null,it=null;const rt=a.length-1,ht=rt>=0?a[rt]:null,Pe=G.getState().elicitationState,De=tt||null,ee=De?Pe[De]:void 0,Ft=ee?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===M.SYNAPSE_COMPONENTS.CARD?!!ee&&!Ue&&!!ee.active:!!ee?.active,Ut=!!(C||[]).length||!!F?.audio||!!Se||!Ft||!K,_t=ae?ae.label:void 0,Et=ee?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof _t=="string"?_t:null;if(!Ut&&Ft&&De&&ee?.messageId){const Ce=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(ve=>!ee.server_input?.[ve])??[],qe=Ce.reduce((ve,B)=>{if(ae){const ye=ae[B];ye!==void 0&&(ve[B]=ye)}else Ce.length===1&&(ve[B]=O);return ve},{}),mt=ee.mcp_meta_fields?.reduce((ve,B)=>(Ce.includes(B)?ve[B]=qe[B]:ee.server_input?.[B]&&(ve[B]=ee.server_input[B]),oe&&!ve.is_resend&&(ve.is_resend=oe),ve),{}),Xt=Object.keys(ee.server_input||{})?.reduce((ve,B)=>{const ye=!Object.keys(mt||{})?.includes(B),Le=!!ee.server_input?.[B];return(oe?ye&&Le:ye&&ee.required?.includes(B)&&Le)&&(ve[B]=ee.server_input?.[B]),ve},{}),Zt=oe?{}:(ee.required||Ce).reduce((ve,B)=>(Object.keys(mt||{}).includes(B)||(qe[B]!==void 0?ve[B]=qe[B]:ae&&ae[B]!==void 0&&(ve[B]=ae[B])),ve),{}),Ct={...Xt||{},...Zt,...Object.keys(mt||{}).length&&{mcp_meta_fields:mt}};if(!Object.keys(Ct).length)return;await Te(De,{...ee,server_input:{...ee.server_input||{},...Ct}});try{await nr(ee.tool_id,ee.messageId,Ct),nt=!0}catch(ve){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Yt(ve)}`}}),it="Tool call failed",Te(De,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Yt(ve)}`}})}}else{const Ce=ht?.id,qe=Ce?Object.entries(qt).filter(([Xt,Zt])=>{const[Ct]=Xt.split("::");return Ct===Ce&&Zt.active}):[],mt=Ue??ee?.tool_result;await y.current?.sendMessage({message:O??"",files:C,audio:F,...Ve&&{initial_prompts:Ve},...Se||qe.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...mt&&{tool_result:mt}})}(O||C&&C.length>0||F?.audio||Et||it)&&(c(Ce=>{if(nt)return Ce;const qe=Ce.length===0&&H?.text?[{id:"initial-bot-message",content:H.text,role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}]:[];return[...Ce,...qe,{id:Date.now().toString(),content:Et||it||O||"",files:C||[],audio:F,role:je.USER,timestamp:Bt(Date.now()),isStored:!1}]}),nt||W(!0),nt=null);const Lr=G.getState().elicitationState,Tt=new Set;De&&Tt.add(De),ht?.tool_keys?.forEach(Ce=>Tt.add(Ce)),Tt.forEach(Ce=>{const qe=Lr[Ce];qe&&Te(Ce,{...qe,...Ut&&{active:!1,disabled:!0},...Ce===De?{response_value:{...qe?.response_value||{},label:Et||O||""}}:{}})})}catch{}}},Pr=O=>O.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(O.type)?(U({title:`File type not supported: ${O.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):O.size>3*1024*1024?(U({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,tr=async()=>{try{await y.current?.startRecording({onChunks:async O=>{pe(Ee.PROCESSING),await ut({audio:O}),pe(Ee.TRANSCRIBING)},onError(O){pe(Ee.IDLE)}}),pe(Ee.LISTENING)}catch(O){throw pe(Ee.IDLE),O}},Dr=()=>{y.current?.endRecording()},nr=async(O,C,F)=>{try{if(!Re())throw new Error("Not connected to the server");await y.current?.callTool(O,C,F)}catch(K){throw K}},_n=async()=>{dt(),await se(),await Be({forceNewSession:!0})},En=()=>{Ke(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),Z(ge.NOT_CONNECTED),U({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},yn=async()=>{if(Re()){Z(ge.CONNECTED);const O=d.current[d.current.length-1];if(O&&O.role===je.USER)try{y.current?.sendMessage({message:O.content,files:O.files||[],messageId:O.id,audio:O.audio})}catch{}}else if(Z(ge.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:O}=G.getState();await et(O)}else g.current===2?(g.current++,Y(!0),U({title:"Trying to connect..."})):(U({title:"Something went wrong!",description:"Please start a new chat."}),re(!0))};return{sendMessage:ut,startSession:Be,incomingMessages:a,loading:h,isLoadingSessionMessages:f,endSession:Dt,isReady:v,startRecording:tr,stopRecording:Dr,getPastSessions:async()=>{try{const O=await y.current?.getPastSessions();return!O||!O?.data?.length?[]:O.data}catch{return[]}},handleRetry:yn,isValidFile:Pr,handleStartNewConnection:_n,callTool:nr,handleInitialTaskClick:async O=>{const{message:C}=O;if(!H?.suggestions?.length||!C)return;const F=H.suggestions.find(K=>K.value===C);if(E.current=[{role:"assistant",text:`${H.text} ${F?.response||""}`}],!F||!F.response){await ut(O);return}c(K=>[...K,{id:Date.now().toString(),content:C,role:je.USER,timestamp:Bt(Date.now()),isStored:!1}]),W(!0),await xu(1e3),W(!1),c(K=>[...K,{id:Date.now().toString(),content:F.response||"Please try again",role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}])},sendMessageFeedback:async(O,C,F)=>{if(Re())try{await y.current?.sendMessageFeedback(C,O,F)}catch{}},sendSessionFeedback:async(O,C)=>{if(!(!Re()||!O?.length&&!C))try{await y.current?.sendSessionFeedback(O,C)}catch{}},clearElicitationState:async(O,C)=>{const F=G.getState().elicitationState,K=O?F[O]:void 0;try{await ut({message:C||"User aborted elicitation",tool_declined:!0,tool_result:K?.tool_result,tool_key:O})}catch{}finally{O&&K&&Te(O,{...K,active:!1,disabled:!0})}}}};function Hm(e){return e==="full"?M.SYNAPSE_CHANNELS.WEB:e==="side-panel"?M.SYNAPSE_CHANNELS.SIDE_PANEL:M.SYNAPSE_CHANNELS.WIDGET}const Ym=32,Gm=100,Wm=320;function Km(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function qm({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=L(!1),c=X(null),d=X(!1),h=X("auto"),u=X(!0),f=fe(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),_=fe(v=>Km()?"auto":v,[]),p=fe(v=>{const m=f();m&&(m.scrollTo({top:m.scrollHeight,behavior:_(v)}),a(!1))},[f,_]),g=fe(v=>{d.current=!0,h.current=v,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 v=setTimeout(()=>g("auto"),Wm);return()=>clearTimeout(v)},[r,e,g]),z(()=>{let v=!1,m=null,E=null,y=0;const k=()=>{if(v)return;const w=f(),N=i.current?.parentElement;if(!w||!N){requestAnimationFrame(k);return}const T=()=>{const{scrollTop:x,scrollHeight:I,clientHeight:H}=w;return I-x-H<=Ym};u.current=!0;let b=0;const S=()=>{if(b>0){b--;return}u.current=T()};w.addEventListener("scroll",S,{passive:!0}),E=()=>w.removeEventListener("scroll",S),m=new ResizeObserver(()=>{if(!u.current)return;const x=Date.now();x-y<Gm||(y=x,b++,g("auto"))}),m.observe(N)};return k(),()=>{v=!0,m?.disconnect(),E?.()}},[f,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:p,scheduleScrollToBottom:g}}const Go="eka-medassist-agent-config",Bl="feedback_hidden",Wo="upfront_consent_accepted";function Ko(e,t){try{const n=localStorage.getItem(Go);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function $l(e,t){try{const n=localStorage.getItem(Go),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(Go,JSON.stringify(r))}catch{}}function Xm({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=wh(),d=()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()},h=r!==M.VOICE_AGENT_STATE.IDLE,[u,f]=L(""),[_,p]=L(!1),g=G(B=>B.setDisplayMode),[v,m]=L(n.displayMode==="full"?"full":"widget"),E=()=>m(B=>B==="full"?"widget":"full"),y=Rl()?"mobile":v,[k,w]=L([]),N=X(!1),[T,b]=L(!1),[S,x]=L(!1),[I,H]=L(()=>!!n.theme?.upfrontConsent&&!Ko(t,Wo)),ne=X(null),{setAgentId:xe,startNewConnection:de,showRetryButton:Q,clearError:me,error:P,connectionStatus:U,recordingStatus:Z,isWaitingForResponse:Y,isStreaming:re,setError:$,sessionId:W,setContext:we,initialMessage:pe,setInitialMessage:se,sessionInitialMessages:Ke,setInitialDisplayMode:Ye,clearSession:Qe}=G(),D=G(B=>B.elicitationState),ue=G(B=>B.level),{incomingMessages:ie,loading:ke,isLoadingSessionMessages:Me,sendMessage:Te,handleInitialTaskClick:ct,startSession:Ae,isReady:Ne,startRecording:et,stopRecording:ze,handleRetry:Be,isValidFile:Re,sendMessageFeedback:Dt,clearElicitationState:dt,sendSessionFeedback:Kt,getPastSessions:ut}=$m({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:Hm(n.displayMode)}),[Pr,tr]=L(!1),[Dr,nr]=L([]),[_n,En]=L(!0),yn=X(ut);z(()=>{yn.current=ut});const O=fe(async()=>{En(!0);try{const B=await yn.current();nr(B)}catch{}finally{En(!1)}},[]),C=fe(async()=>{tr(!0),await O()},[O]),F=fe(()=>{tr(!1)},[]),[K,ae]=L(!1),oe=fe(()=>ae(B=>!B),[]);z(()=>{y!=="full"||ue!=="user"||O()},[y,ue,W,O]),z(()=>{t&&(ne.current!==t&&(Eh(t),yh(t),xe(t),n.force&&Qe(),(n.displayMode==="full"||n.displayMode==="widget")&&(g(n.displayMode),Ye(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&we(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&se(n.initialMessage),ne.current=t),e&&Ne&&!N.current&&(N.current=!0,Ae({forceNewSession:!1})))},[e,Ne,t]),z(()=>{nm([Al])},[]),z(()=>()=>{s()},[]),z(()=>{!n.theme?.upfrontConsent||!t||Ko(t,Wo)||H(!0)},[n.theme?.upfrontConsent,t]);const Se=fe(()=>{$l(t,Wo),H(!1)},[t]),Ue=()=>{n.feedback&&!Ko(t,Bl)?x(!0):n.onClose()},tt=async(B,ye)=>{await Kt(B,ye),x(!1),n.onClose()},qt=()=>{x(!1),n.onClose()},Lt=()=>{$l(t,Bl),x(!1),n.onClose()},Ve=()=>{x(!1)},nt=ie.length>0,it=ie.length===1,rt=_e(()=>{const B=ie[ie.length-1],ye=B?.tool_keys?.[B.tool_keys.length-1];if(!ye)return null;const Le=D[ye];return Le?.active?{...Le,tool_key:ye}:null},[ie,D]),ht=_e(()=>(W?Ke[W]:void 0)??pe??n?.initialMessage??null,[W,Ke,pe,n?.initialMessage]),Pe=_e(()=>!!ht?.text||!!ht?.suggestions?.length,[ht]),De=_e(()=>Pe&&ie?.length===0&&!Me,[ie,Pe,Me]),ee=_e(()=>rt?rt.component===M.SYNAPSE_COMPONENTS.MOBILE||rt.component===M.SYNAPSE_COMPONENTS.OTP||rt.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[rt]),{scrollAreaRef:Ft,messagesEndRef:Ut,showScrollButton:_t,scrollToBottom:Et}=qm({messageCount:ie.length,isStreaming:re,isFirstMessage:it,resolvedMode:y}),Lr=U===ge.CONNECTED,Tt=Y||re,Ce=_e(()=>Z===Ee.IDLE?null:Z===Ee.LISTENING?"Listening...":Z===Ee.PROCESSING?"Processing...":Z===Ee.TRANSCRIBING?"Transcribing...":null,[Z]),qe=Ce&&Z!==Ee.IDLE?Ce:Y||re?"Please wait for the response...":"Type a reply\u2026",mt=async(B,ye)=>{if(Tt)return;const Le=ye?ct:Te,Jt=B?.message??u;k.length>0?(await Le({files:k,message:Jt.trim()}),w([]),b(!1)):Jt.trim()?await Le({...B,message:Jt.trim()}):B?.resend?await Le(B):B&&await Le(B),f(""),p(!1),b(!1)},Xt=B=>{if(B&&B.length>0){const ye=B.filter(Le=>!!Re(Le));if(ye?.length+k.length>3){$({title:"You can only upload up to 3 files at a time",description:"Please remove some files and try again."});return}if(ye?.length>0&&ye.reduce((Le,Jt)=>Le+Jt.size,0)>10*1024*1024){$({title:`Total file size limit of ${xh} MB exceeded`,description:"Please reduce the size of the files or try again with less files"});return}if(ye?.length>0)B=ye;else return}w(ye=>(b((ye?.length??0)+(B?.length??0)>0),[...ye,...B]))},Zt=B=>{w(ye=>{const Le=ye.filter((Jt,Ec)=>Ec!==B);return b(Le.length>0),Le})},Ct=async()=>{if(_)await ze(),p(!1);else{if(Tt)return;try{await et(),p(!0)}catch{}}},ve={value:u,onChange:f,onSend:mt,onFileChange:Xt,onRemoveFile:Zt,onRecording:Ct,isRecording:_,hasAttachment:T,attachmentFiles:k,isDisabled:Tt,placeholder:qe,recordingStatus:Z,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d};return{inputValue:u,setInputValue:f,isRecording:_,hasAttachment:T,attachmentFiles:k,showScrollButton:_t,displayMode:v,setDisplayMode:m,toggleDisplayMode:E,resolvedMode:y,currentDisplayMode:v,setCurrentDisplayMode:m,scrollAreaRef:Ft,messagesEndRef:Ut,startNewConnection:de,showRetryButton:Q,clearError:me,error:P,connectionStatus:U,isStreaming:re,sessionId:W,activeElicitation:rt,inConversation:nt,isFirstMessage:it,isEmptyChat:De,isAuthComponent:ee,isConnected:Lr,isComposerDisabled:Tt,loading:ke,isLoadingSessionMessages:Me,initialMessage:ht,incomingMessages:ie,sendMessage:Te,startSession:Ae,sendMessageFeedback:Dt,clearElicitationState:dt,handleRetry:Be,handleSendMessage:mt,handleFileChange:Xt,handleRemoveFile:Zt,handleRecording:Ct,scrollToBottom:Et,handleClose:Ue,showFeedbackModal:S,handleSessionFeedbackSubmit:tt,handleSessionFeedbackSkip:qt,handleDontShowAgain:Lt,handleCloseModal:Ve,showConsentModal:I,handleConsentAccept:Se,chatComposerProps:ve,isSessionDrawerOpen:Pr,pastSessions:Dr,isLoadingPastSessions:_n,openSessionDrawer:C,closeSessionDrawer:F,refreshPastSessions:O,userLevel:ue,isSidebarCollapsed:K,toggleSidebar:oe,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,connectVoiceAgent:i,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c,handleVoiceAgentClick:d}}function Gt(){return Gt=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},Gt.apply(this,arguments)}const Zm=["children","options"],Hl=["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"}),Yl={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Jm=["style","script","pre"],Qm=["src","href","data","formAction","srcDoc","action"],ep=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,tp=/\n{2,}$/,Gl=/^(\s*>[\s\S]*?)(?=\n\n|$)/,np=/^ *> ?/gm,rp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,op=/^ {2,}\n/,sp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Wl=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Kl=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,ip=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,ap=/^(?:\n *)*\n/,lp=/\r\n?/g,cp=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,dp=/^\[\^([^\]]+)]/,up=/\f/g,hp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,mp=/^\s*?\[(x|\s)\]/,ql=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Xl=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Zl=/^([^\n]+)\n *(=|-)\2{2,} *\n/,qo=/^ *(?!<[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,Jl=/^<!--[\s\S]*?(?:-->)/,fp=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,Xo=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,gp=/^\{.*\}$/,_p=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,Ep=/^<([^ >]+[:@\/][^ >]+)>/,yp=/-([a-z])?/gi,Ql=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,vp=/^[^\n]+(?: \n|\n{2,})/,bp=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,Sp=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,wp=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Np=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,xp=/\t/g,Tp=/(^ *\||\| *$)/g,Cp=/^ *:-+: *$/,kp=/^ *:-+ *$/,Rp=/^ *-+: *$/,Cr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,kr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Op=RegExp(`^([*_])\\1${Cr(1)}${kr}\\1\\1(?!\\1)`),Ap=RegExp(`^([*_])${Cr(0)}${kr}\\1(?!\\1)`),Ip=RegExp(`^(==)${Cr(0)}${kr}\\1`),Mp=RegExp(`^(~~)${Cr(0)}${kr}\\1`),Pp=/^(:[a-zA-Z0-9-_]+:)/,Dp=/^\\([^0-9A-Za-z\s])/,Lp=/\\([^0-9A-Za-z\s])/g,Fp=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Up=/^\n+/,Vp=/^([ \t]*)/,jp=/(?:^|\n)( *)$/,Zo="(?:\\d+\\.)",Jo="(?:[*+-])";function ec(e){return"( *)("+(e===1?Zo:Jo)+") +"}const tc=ec(1),nc=ec(2);function rc(e){return RegExp("^"+(e===1?tc:nc))}const zp=rc(1),Bp=rc(2);function oc(e){return RegExp("^"+(e===1?tc:nc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?Zo:Jo)+" )[^\\n]*)*(\\n|$)","gm")}const $p=oc(1),Hp=oc(2);function sc(e){const t=e===1?Zo:Jo;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const ic=sc(1),ac=sc(2);function lc(e,t){const n=t===1,r=n?ic:ac,o=n?$p:Hp,i=n?zp:Bp;return{t:s=>i.test(s),o:gn(function(s,a){const c=jp.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(tp,`
40
+ `:"";return Fe[Fe.length-1]={...Se,content:Se.content+tt+U},Fe}else return[...oe,{id:K,content:U,role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}]})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{T.current=!1,$(!1),we(null),W(!1)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{dt(),Z(ge.CONNECTED)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,O=>{T.current=!0;const C=O;if(!C?.messageId||!C?.data||!C?.data?.details?.component||!C?.data?.tool_id)return;I&&W(!1);const{messageId:U,data:K}=C,ae=K.tool_id,oe=`${U}::${ae}`,Se=G.getState().elicitationState[oe],Fe=K.details?.component,tt=C?.data?.details?._meta?.tool_result,qt=K.details?.input,Lt=Vm(Se?.input,qt,Fe);let Ve=C.data.details?._meta?.disp_toast_msg;const nt=K?.details?._meta?.schema?.required||[];switch(K?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Pe=C?.data?.details?.input||{},De=nt.reduce((_t,Et)=>(Pe[Et]!==void 0&&(_t[Et]=Pe[Et]),_t),{}),ee={...Se?.server_input||{},...De},Ut=nt.filter(_t=>!ee[_t]),Ft=C.data.details?._meta?.mcp_meta_fields||[];Te(oe,{tool_id:ae,active:!0,disabled:!1,input:Lt,server_input:ee,messageId:U,required:nt,component:Fe,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:tt,orientation:C.data.details?._meta?.orientation,...Ft.length&&{mcp_meta_fields:Ft},...Ut?{toolSelectionNames:Ut}:{},...Se?.hide_show_more!==void 0?{hide_show_more:Se.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{Te(oe,{...Se||{},tool_id:ae,disabled:!0,active:Nu(Fe),messageId:U,component:Fe,input:Lt,tool_result:tt,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{Te(oe,{...Se||{},tool_id:ae,active:!1,messageId:U,response_value:{label:K?.details?._meta?.disp_message||"Tool call failed"},tool_result:tt,disabled:!0});break}default:Te(oe,{tool_id:ae,disabled:!1,active:!1,messageId:U,tool_result:tt,input:Lt,component:Fe})}Ve&&Me(Ve);const it=C?.data?.details?._meta?.user_hint;c(Pe=>{let De=Pe[Pe.length-1]?.id===U?Pe.length-1:Pe.findIndex?.(ee=>ee.id===U);if(De==-1){const ee={id:U,content:C.data?.details?.input?.text||"",role:je.ASSISTANT,tool_keys:[oe],isResponseFromTool:!0,isStored:!1,...it?{userHint:it}:{}};return[...Pe,ee]}else{const ee={...Pe[De],isResponseFromTool:!0,tool_keys:[...new Set([...Pe[De].tool_keys||[],oe])],...it?{userHint:it}:{}};Pe[De]=ee,ue(S,U,ee)}return[...Pe]});const rt=C?.data?.details?._meta?.disp_message,ht=G.getState().elicitationState;if((!ht[oe]?.active||ht[oe]?.send_to_llm)&&(rt||Object.keys(tt||{}).length))try{ut({message:rt||"",tool_result:tt,toolCalled:!0,tool_key:oe})}catch{}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,O=>{if(O?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const C=typeof navigator<"u"&&!navigator.onLine;if(Z(ge.NOT_CONNECTED),C){F({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),Y(!1);return}g.current<2?(g.current=g.current+1,Y(!0),F({title:"Something went wrong!",description:"Please try again."})):(F({title:"Something went wrong!",description:"Please start a new Chat."}),re(!0))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.ERROR,O=>{switch(O?.data?.code){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:re(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:F({title:"Session not found",description:"Please start a new chat from onError callback"}),re(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:_n();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++,yn();return}F({title:"Error parsing request",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:F({title:"Request timed out",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:F({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:F({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:F({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return;default:F({title:"Something went wrong",description:"please try again"}),Y(!0),pe(Ee.IDLE);return}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async O=>{const C=O;C?.data?.text&&(c(U=>[...U,{id:Date.now().toString(),content:C.data.text||"",role:je.USER,timestamp:Bt(Date.now()),isStored:!0}]),pe(Ee.IDLE)),$(!1),W(!1),we(null)}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,O=>{T.current=!0;const C=O;C.data?.text&&(W(!1),we(C.data.text))}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,O=>{T.current=!0;const C=O;if(C.data?.name&&C.messageId){const U=C.messageId;c(K=>{const ae=K[K.length-1];if(ae&&ae.id===U&&ae.role===je.ASSISTANT){const oe=[...K];return oe[oe.length-1]={...ae,toolCallStatus:`Calling tool: ${C.data.name}...`},S&&ue(S,U,{toolCallStatus:`Calling tool: ${C.data.name}...`}),oe}return K})}}),y.current?.on(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,O=>{T.current=!0;const C=O;if(C.data?.name&&C.messageId){const U=C.messageId;c(K=>{const ae=K[K.length-1];if(ae&&ae.id===U&&ae.role===je.ASSISTANT){const oe=[...K];return oe[oe.length-1]={...ae,toolCallStatus:"Tool call completed."},S&&ue(S,U,{toolCallStatus:"Tool call completed."}),oe}return K})}})},ut=async({message:O,files:C,audio:U,toolCalled:K,selectedComponent:ae,resend:oe,tool_declined:Se,tool_result:Fe,tool_key:tt})=>{const qt=G.getState().elicitationState,Lt=Object.values(qt).some(Ve=>Ve.active);if(!(!K&&(!C||C.length===0)&&!O?.trim()&&!U?.audio&&!ae&&!Lt&&!Fe&&!Object.keys(Fe||{}).length)){if(C&&C.length>3){F({title:"Maximum 3 files are allowed to be sent at a time",description:"Please try again"});return}if(C&&C.length>0&&C.reduce((Ve,nt)=>Ve+nt.size,0)>10*1024*1024){F({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+xe>Io){const Ve=Io-xe;F({title:`You can only upload up to ${Io} files per session`,description:`${Ve<=0?"Maximum file upload limit reached":`You have ${Ve} file${Ve===1?"":"s"} upload${Ve===1?"":"s"} left`}`});return}else C&&C.length&&ke(xe+C.length);F(null),Y(!1),Re()&&Z(ge.CONNECTED);try{const Ve=a.length<=2&&E.current.length==1?E.current:null;let nt=null,it=null;const rt=a.length-1,ht=rt>=0?a[rt]:null,Pe=G.getState().elicitationState,De=tt||null,ee=De?Pe[De]:void 0,Ut=ee?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||ee?.component===M.SYNAPSE_COMPONENTS.CARD?!!ee&&!Fe&&!!ee.active:!!ee?.active,Ft=!!(C||[]).length||!!U?.audio||!!Se||!Ut||!K,_t=ae?ae.label:void 0,Et=ee?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof _t=="string"?_t:null;if(!Ft&&Ut&&De&&ee?.messageId){const Ce=ee.toolSelectionNames?.length?ee.toolSelectionNames:ee.required?.filter(ve=>!ee.server_input?.[ve])??[],qe=Ce.reduce((ve,B)=>{if(ae){const ye=ae[B];ye!==void 0&&(ve[B]=ye)}else Ce.length===1&&(ve[B]=O);return ve},{}),mt=ee.mcp_meta_fields?.reduce((ve,B)=>(Ce.includes(B)?ve[B]=qe[B]:ee.server_input?.[B]&&(ve[B]=ee.server_input[B]),oe&&!ve.is_resend&&(ve.is_resend=oe),ve),{}),Xt=Object.keys(ee.server_input||{})?.reduce((ve,B)=>{const ye=!Object.keys(mt||{})?.includes(B),Le=!!ee.server_input?.[B];return(oe?ye&&Le:ye&&ee.required?.includes(B)&&Le)&&(ve[B]=ee.server_input?.[B]),ve},{}),Zt=oe?{}:(ee.required||Ce).reduce((ve,B)=>(Object.keys(mt||{}).includes(B)||(qe[B]!==void 0?ve[B]=qe[B]:ae&&ae[B]!==void 0&&(ve[B]=ae[B])),ve),{}),Ct={...Xt||{},...Zt,...Object.keys(mt||{}).length&&{mcp_meta_fields:mt}};if(!Object.keys(Ct).length)return;await Te(De,{...ee,server_input:{...ee.server_input||{},...Ct}});try{await nr(ee.tool_id,ee.messageId,Ct),nt=!0}catch(ve){await y.current?.sendMessage({tool_result:{...ee.tool_result,error:`Tool call failed: ${Yt(ve)}`}}),it="Tool call failed",Te(De,{...ee,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${Yt(ve)}`}})}}else{const Ce=ht?.id,qe=Ce?Object.entries(qt).filter(([Xt,Zt])=>{const[Ct]=Xt.split("::");return Ct===Ce&&Zt.active}):[],mt=Fe??ee?.tool_result;await y.current?.sendMessage({message:O??"",files:C,audio:U,...Ve&&{initial_prompts:Ve},...Se||qe.length>0?{tool_declined:!0,tool_id:ee?.tool_id||""}:{},...mt&&{tool_result:mt}})}(O||C&&C.length>0||U?.audio||Et||it)&&(c(Ce=>{if(nt)return Ce;const qe=Ce.length===0&&H?.text?[{id:"initial-bot-message",content:H.text,role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}]:[];return[...Ce,...qe,{id:Date.now().toString(),content:Et||it||O||"",files:C||[],audio:U,role:je.USER,timestamp:Bt(Date.now()),isStored:!1}]}),nt||W(!0),nt=null);const Lr=G.getState().elicitationState,Tt=new Set;De&&Tt.add(De),ht?.tool_keys?.forEach(Ce=>Tt.add(Ce)),Tt.forEach(Ce=>{const qe=Lr[Ce];qe&&Te(Ce,{...qe,...Ft&&{active:!1,disabled:!0},...Ce===De?{response_value:{...qe?.response_value||{},label:Et||O||""}}:{}})})}catch{}}},Pr=O=>O.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(O.type)?(F({title:`File type not supported: ${O.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):O.size>3*1024*1024?(F({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,tr=async()=>{try{await y.current?.startRecording({onChunks:async O=>{pe(Ee.PROCESSING),await ut({audio:O}),pe(Ee.TRANSCRIBING)},onError(O){pe(Ee.IDLE)}}),pe(Ee.LISTENING)}catch(O){throw pe(Ee.IDLE),O}},Dr=()=>{y.current?.endRecording()},nr=async(O,C,U)=>{try{if(!Re())throw new Error("Not connected to the server");await y.current?.callTool(O,C,U)}catch(K){throw K}},_n=async()=>{dt(),await se(),await Be({forceNewSession:!0})},En=()=>{Ke(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),Z(ge.NOT_CONNECTED),F({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},yn=async()=>{if(Re()){Z(ge.CONNECTED);const O=d.current[d.current.length-1];if(O&&O.role===je.USER)try{y.current?.sendMessage({message:O.content,files:O.files||[],messageId:O.id,audio:O.audio})}catch{}}else if(Z(ge.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:O}=G.getState();await et(O)}else g.current===2?(g.current++,Y(!0),F({title:"Trying to connect..."})):(F({title:"Something went wrong!",description:"Please start a new chat."}),re(!0))};return{sendMessage:ut,startSession:Be,incomingMessages:a,loading:h,isLoadingSessionMessages:f,endSession:Dt,isReady:v,startRecording:tr,stopRecording:Dr,getPastSessions:async()=>{try{const O=await y.current?.getPastSessions();return!O||!O?.data?.length?[]:O.data}catch{return[]}},handleRetry:yn,isValidFile:Pr,handleStartNewConnection:_n,callTool:nr,handleInitialTaskClick:async O=>{const{message:C}=O;if(!H?.suggestions?.length||!C)return;const U=H.suggestions.find(K=>K.value===C);if(E.current=[{role:"assistant",text:`${H.text} ${U?.response||""}`}],!U||!U.response){await ut(O);return}c(K=>[...K,{id:Date.now().toString(),content:C,role:je.USER,timestamp:Bt(Date.now()),isStored:!1}]),W(!0),await xu(1e3),W(!1),c(K=>[...K,{id:Date.now().toString(),content:U.response||"Please try again",role:je.ASSISTANT,timestamp:Bt(Date.now()),isStored:!1}])},sendMessageFeedback:async(O,C,U)=>{if(Re())try{await y.current?.sendMessageFeedback(C,O,U)}catch{}},sendSessionFeedback:async(O,C)=>{if(!(!Re()||!O?.length&&!C))try{await y.current?.sendSessionFeedback(O,C)}catch{}},clearElicitationState:async(O,C)=>{const U=G.getState().elicitationState,K=O?U[O]:void 0;try{await ut({message:C||"User aborted elicitation",tool_declined:!0,tool_result:K?.tool_result,tool_key:O})}catch{}finally{O&&K&&Te(O,{...K,active:!1,disabled:!0})}}}};function Gm(e){return e==="full"?M.SYNAPSE_CHANNELS.WEB:e==="side-panel"?M.SYNAPSE_CHANNELS.SIDE_PANEL:M.SYNAPSE_CHANNELS.WIDGET}const Wm=32,Km=100,qm=320;function Xm(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Zm({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=L(!1),c=X(null),d=X(!1),h=X("auto"),u=X(!0),f=fe(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),_=fe(v=>Xm()?"auto":v,[]),p=fe(v=>{const m=f();m&&(m.scrollTo({top:m.scrollHeight,behavior:_(v)}),a(!1))},[f,_]),g=fe(v=>{d.current=!0,h.current=v,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 v=setTimeout(()=>g("auto"),qm);return()=>clearTimeout(v)},[r,e,g]),z(()=>{let v=!1,m=null,E=null,y=0;const k=()=>{if(v)return;const w=f(),N=i.current?.parentElement;if(!w||!N){requestAnimationFrame(k);return}const T=()=>{const{scrollTop:x,scrollHeight:I,clientHeight:H}=w;return I-x-H<=Wm};u.current=!0;let b=0;const S=()=>{if(b>0){b--;return}u.current=T()};w.addEventListener("scroll",S,{passive:!0}),E=()=>w.removeEventListener("scroll",S),m=new ResizeObserver(()=>{if(!u.current)return;const x=Date.now();x-y<Km||(y=x,b++,g("auto"))}),m.observe(N)};return k(),()=>{v=!0,m?.disconnect(),E?.()}},[f,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:p,scheduleScrollToBottom:g}}const Go="eka-medassist-agent-config",Bl="feedback_hidden",Wo="upfront_consent_accepted";function Ko(e,t){try{const n=localStorage.getItem(Go);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function $l(e,t){try{const n=localStorage.getItem(Go),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(Go,JSON.stringify(r))}catch{}}function Jm({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:c}=wh(),d=()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()},h=r!==M.VOICE_AGENT_STATE.IDLE,[u,f]=L(""),[_,p]=L(!1),g=G(B=>B.setDisplayMode),[v,m]=L(n.displayMode==="full"?"full":"widget"),E=()=>m(B=>B==="full"?"widget":"full"),y=Rl()?"mobile":v,[k,w]=L([]),N=X(!1),[T,b]=L(!1),[S,x]=L(!1),[I,H]=L(()=>!!n.theme?.upfrontConsent&&!Ko(t,Wo)),ne=X(null),{setAgentId:xe,startNewConnection:de,showRetryButton:Q,clearError:me,error:P,connectionStatus:F,recordingStatus:Z,isWaitingForResponse:Y,isStreaming:re,setError:$,sessionId:W,setContext:we,initialMessage:pe,setInitialMessage:se,sessionInitialMessages:Ke,setInitialDisplayMode:Ye,clearSession:Qe}=G(),D=G(B=>B.elicitationState),ue=G(B=>B.level),{incomingMessages:ie,loading:ke,isLoadingSessionMessages:Me,sendMessage:Te,handleInitialTaskClick:ct,startSession:Ae,isReady:Ne,startRecording:et,stopRecording:ze,handleRetry:Be,isValidFile:Re,sendMessageFeedback:Dt,clearElicitationState:dt,sendSessionFeedback:Kt,getPastSessions:ut}=Ym({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:Gm(n.displayMode)}),[Pr,tr]=L(!1),[Dr,nr]=L([]),[_n,En]=L(!0),yn=X(ut);z(()=>{yn.current=ut});const O=fe(async()=>{En(!0);try{const B=await yn.current();nr(B)}catch{}finally{En(!1)}},[]),C=fe(async()=>{tr(!0),await O()},[O]),U=fe(()=>{tr(!1)},[]),[K,ae]=L(!1),oe=fe(()=>ae(B=>!B),[]);z(()=>{y!=="full"||ue!=="user"||O()},[y,ue,W,O]),z(()=>{t&&(ne.current!==t&&(Eh(t),yh(t),xe(t),n.force&&Qe(),(n.displayMode==="full"||n.displayMode==="widget")&&(g(n.displayMode),Ye(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&we(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&se(n.initialMessage),ne.current=t),e&&Ne&&!N.current&&(N.current=!0,Ae({forceNewSession:!1})))},[e,Ne,t]),z(()=>{nm([Al])},[]),z(()=>()=>{s()},[]),z(()=>{!n.theme?.upfrontConsent||!t||Ko(t,Wo)||H(!0)},[n.theme?.upfrontConsent,t]);const Se=fe(()=>{$l(t,Wo),H(!1)},[t]),Fe=()=>{n.feedback&&!Ko(t,Bl)?x(!0):n.onClose()},tt=async(B,ye)=>{await Kt(B,ye),x(!1),n.onClose()},qt=()=>{x(!1),n.onClose()},Lt=()=>{$l(t,Bl),x(!1),n.onClose()},Ve=()=>{x(!1)},nt=ie.length>0,it=ie.length===1,rt=_e(()=>{const B=ie[ie.length-1],ye=B?.tool_keys?.[B.tool_keys.length-1];if(!ye)return null;const Le=D[ye];return Le?.active?{...Le,tool_key:ye}:null},[ie,D]),ht=_e(()=>(W?Ke[W]:void 0)??pe??n?.initialMessage??null,[W,Ke,pe,n?.initialMessage]),Pe=_e(()=>!!ht?.text||!!ht?.suggestions?.length,[ht]),De=_e(()=>Pe&&ie?.length===0&&!Me,[ie,Pe,Me]),ee=_e(()=>rt?rt.component===M.SYNAPSE_COMPONENTS.MOBILE||rt.component===M.SYNAPSE_COMPONENTS.OTP||rt.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[rt]),{scrollAreaRef:Ut,messagesEndRef:Ft,showScrollButton:_t,scrollToBottom:Et}=Zm({messageCount:ie.length,isStreaming:re,isFirstMessage:it,resolvedMode:y}),Lr=F===ge.CONNECTED,Tt=Y||re,Ce=_e(()=>Z===Ee.IDLE?null:Z===Ee.LISTENING?"Listening...":Z===Ee.PROCESSING?"Processing...":Z===Ee.TRANSCRIBING?"Transcribing...":null,[Z]),qe=Ce&&Z!==Ee.IDLE?Ce:Y||re?"Please wait for the response...":"Type a reply\u2026",mt=async(B,ye)=>{if(Tt)return;const Le=ye?ct:Te,Jt=B?.message??u;k.length>0?(await Le({files:k,message:Jt.trim()}),w([]),b(!1)):Jt.trim()?await Le({...B,message:Jt.trim()}):B?.resend?await Le(B):B&&await Le(B),f(""),p(!1),b(!1)},Xt=B=>{if(B&&B.length>0){const ye=B.filter(Le=>!!Re(Le));if(ye?.length+k.length>3){$({title:"You can only upload up to 3 files at a time",description:"Please remove some files and try again."});return}if(ye?.length>0&&ye.reduce((Le,Jt)=>Le+Jt.size,0)>10*1024*1024){$({title:`Total file size limit of ${xh} MB exceeded`,description:"Please reduce the size of the files or try again with less files"});return}if(ye?.length>0)B=ye;else return}w(ye=>(b((ye?.length??0)+(B?.length??0)>0),[...ye,...B]))},Zt=B=>{w(ye=>{const Le=ye.filter((Jt,Ec)=>Ec!==B);return b(Le.length>0),Le})},Ct=async()=>{if(_)await ze(),p(!1);else{if(Tt)return;try{await et(),p(!0)}catch{}}},ve={value:u,onChange:f,onSend:mt,onFileChange:Xt,onRemoveFile:Zt,onRecording:Ct,isRecording:_,hasAttachment:T,attachmentFiles:k,isDisabled:Tt,placeholder:qe,recordingStatus:Z,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d};return{inputValue:u,setInputValue:f,isRecording:_,hasAttachment:T,attachmentFiles:k,showScrollButton:_t,displayMode:v,setDisplayMode:m,toggleDisplayMode:E,resolvedMode:y,currentDisplayMode:v,setCurrentDisplayMode:m,scrollAreaRef:Ut,messagesEndRef:Ft,startNewConnection:de,showRetryButton:Q,clearError:me,error:P,connectionStatus:F,isStreaming:re,sessionId:W,activeElicitation:rt,inConversation:nt,isFirstMessage:it,isEmptyChat:De,isAuthComponent:ee,isConnected:Lr,isComposerDisabled:Tt,loading:ke,isLoadingSessionMessages:Me,initialMessage:ht,incomingMessages:ie,sendMessage:Te,startSession:Ae,sendMessageFeedback:Dt,clearElicitationState:dt,handleRetry:Be,handleSendMessage:mt,handleFileChange:Xt,handleRemoveFile:Zt,handleRecording:Ct,scrollToBottom:Et,handleClose:Fe,showFeedbackModal:S,handleSessionFeedbackSubmit:tt,handleSessionFeedbackSkip:qt,handleDontShowAgain:Lt,handleCloseModal:Ve,showConsentModal:I,handleConsentAccept:Se,chatComposerProps:ve,isSessionDrawerOpen:Pr,pastSessions:Dr,isLoadingPastSessions:_n,openSessionDrawer:C,closeSessionDrawer:U,refreshPastSessions:O,userLevel:ue,isSidebarCollapsed:K,toggleSidebar:oe,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,connectVoiceAgent:i,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:c,handleVoiceAgentClick:d}}function Gt(){return Gt=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},Gt.apply(this,arguments)}const Qm=["children","options"],Hl=["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"}),Yl={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},ep=["style","script","pre"],tp=["src","href","data","formAction","srcDoc","action"],np=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,rp=/\n{2,}$/,Gl=/^(\s*>[\s\S]*?)(?=\n\n|$)/,op=/^ *> ?/gm,sp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,ip=/^ {2,}\n/,ap=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Wl=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Kl=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,lp=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,cp=/^(?:\n *)*\n/,dp=/\r\n?/g,up=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,hp=/^\[\^([^\]]+)]/,mp=/\f/g,pp=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,fp=/^\s*?\[(x|\s)\]/,ql=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Xl=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Zl=/^([^\n]+)\n *(=|-)\2{2,} *\n/,qo=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,gp=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Jl=/^<!--[\s\S]*?(?:-->)/,_p=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,Xo=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Ep=/^\{.*\}$/,yp=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,vp=/^<([^ >]+[:@\/][^ >]+)>/,bp=/-([a-z])?/gi,Ql=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,Sp=/^[^\n]+(?: \n|\n{2,})/,wp=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,Np=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,xp=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Tp=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Cp=/\t/g,kp=/(^ *\||\| *$)/g,Rp=/^ *:-+: *$/,Op=/^ *:-+ *$/,Ap=/^ *-+: *$/,Cr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,kr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Ip=RegExp(`^([*_])\\1${Cr(1)}${kr}\\1\\1(?!\\1)`),Mp=RegExp(`^([*_])${Cr(0)}${kr}\\1(?!\\1)`),Pp=RegExp(`^(==)${Cr(0)}${kr}\\1`),Dp=RegExp(`^(~~)${Cr(0)}${kr}\\1`),Lp=/^(:[a-zA-Z0-9-_]+:)/,Up=/^\\([^0-9A-Za-z\s])/,Fp=/\\([^0-9A-Za-z\s])/g,Vp=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,jp=/^\n+/,zp=/^([ \t]*)/,Bp=/(?:^|\n)( *)$/,Zo="(?:\\d+\\.)",Jo="(?:[*+-])";function ec(e){return"( *)("+(e===1?Zo:Jo)+") +"}const tc=ec(1),nc=ec(2);function rc(e){return RegExp("^"+(e===1?tc:nc))}const $p=rc(1),Hp=rc(2);function oc(e){return RegExp("^"+(e===1?tc:nc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?Zo:Jo)+" )[^\\n]*)*(\\n|$)","gm")}const Yp=oc(1),Gp=oc(2);function sc(e){const t=e===1?Zo:Jo;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const ic=sc(1),ac=sc(2);function lc(e,t){const n=t===1,r=n?ic:ac,o=n?Yp:Gp,i=n?$p:Hp;return{t:s=>i.test(s),o:gn(function(s,a){const c=Bp.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(rp,`
41
41
  `).match(o);let u=!1;return{items:h.map(function(f,_){const p=i.exec(f)[0].length,g=RegExp("^ {1,"+p+"}","gm"),v=f.replace(g,"").replace(i,""),m=_===h.length-1,E=v.indexOf(`
42
42
 
43
43
  `)!==-1||m&&u;u=E;const y=c.inline,k=c.list;let w;c.list=!0,E?(c.inline=!1,w=Jn(v)+`
44
44
 
45
- `):(c.inline=!0,w=Jn(v));const N=a(w,c);return c.inline=y,c.list=k,N}),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 Yp=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Gp=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function cc(e){return typeof e=="string"}function Jn(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Rr(e,t){return e.startsWith(t)}function Wp(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Rr(e,n[r]))return!0;return!1}return n(e,t)}function Qn(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 Kp(e){return Rp.test(e)?"right":Cp.test(e)?"center":kp.test(e)?"left":null}function dc(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 qp(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(Tp,"").split("|").map(Kp):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
- `).map(function(d){return dc(d,a,c,!0)})})(e[3],t,n):[],i=dc(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 uc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function gn(e){return e.inline=1,e}function Wt(e){return gn(function(t,n){return n.inline?e.exec(t):null})}function Pt(e){return gn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function xt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Or(e){return gn(function(t){return e.exec(t)})}const Xp=/(javascript|vbscript|data(?!:image)):/i;function Zp(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Xp.test(t))return null}catch{return null}return e}function gt(e){return e&&e.replace(Lp,"$1")}function Ar(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 Jp(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 Qp(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Qo=(e,t,n)=>({children:Ar(t,e[2],n)});function es(){return{}}function ts(){return null}function ef(...e){return e.filter(Boolean).join(" ")}function ns(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 tf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?Gt({},Yl,t.namedCodesToUnicode):Yl;const n=t.slugify||Qn,r=t.sanitizer||Zp,o=t.createElement||Ge,i=[Gl,Wl,Kl,t.enforceAtxHeadings?Xl:ql,Zl,Ql,ic,ac],s=[...i,vp,qo,Jl,Xo];function a(m,E){for(let y=0;y<m.length;y++)if(m[y].test(E))return!0;return!1}function c(m,E,...y){const k=ns(t.overrides,m+".props",{});return o((function(w,N){const T=ns(N,w);return T?typeof T=="function"||typeof T=="object"&&"render"in T?T:ns(N,w+".component",w):w})(m,t.overrides),Gt({},E,k,{className:ef(E?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(hp,"");let E=!1;t.forceInline?E=!0:t.forceBlock||(E=Np.test(m)===!1);const y=g(p(E?m:Jn(m).replace(Up,"")+`
45
+ `):(c.inline=!0,w=Jn(v));const N=a(w,c);return c.inline=y,c.list=k,N}),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 Wp=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),Kp=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function cc(e){return typeof e=="string"}function Jn(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Rr(e,t){return e.startsWith(t)}function qp(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Rr(e,n[r]))return!0;return!1}return n(e,t)}function Qn(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 Xp(e){return Ap.test(e)?"right":Rp.test(e)?"center":Op.test(e)?"left":null}function dc(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 Zp(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(kp,"").split("|").map(Xp):[],o=e[3]?(function(s,a,c){return s.trim().split(`
46
+ `).map(function(d){return dc(d,a,c,!0)})})(e[3],t,n):[],i=dc(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 uc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function gn(e){return e.inline=1,e}function Wt(e){return gn(function(t,n){return n.inline?e.exec(t):null})}function Pt(e){return gn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function xt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function Or(e){return gn(function(t){return e.exec(t)})}const Jp=/(javascript|vbscript|data(?!:image)):/i;function Qp(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Jp.test(t))return null}catch{return null}return e}function gt(e){return e&&e.replace(Fp,"$1")}function Ar(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 ef(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 tf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Qo=(e,t,n)=>({children:Ar(t,e[2],n)});function es(){return{}}function ts(){return null}function nf(...e){return e.filter(Boolean).join(" ")}function ns(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 rf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?Gt({},Yl,t.namedCodesToUnicode):Yl;const n=t.slugify||Qn,r=t.sanitizer||Qp,o=t.createElement||Ge,i=[Gl,Wl,Kl,t.enforceAtxHeadings?Xl:ql,Zl,Ql,ic,ac],s=[...i,Sp,qo,Jl,Xo];function a(m,E){for(let y=0;y<m.length;y++)if(m[y].test(E))return!0;return!1}function c(m,E,...y){const k=ns(t.overrides,m+".props",{});return o((function(w,N){const T=ns(N,w);return T?typeof T=="function"||typeof T=="object"&&"render"in T?T:ns(N,w+".component",w):w})(m,t.overrides),Gt({},E,k,{className:nf(E?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(pp,"");let E=!1;t.forceInline?E=!0:t.forceBlock||(E=Tp.test(m)===!1);const y=g(p(E?m:Jn(m).replace(jp,"")+`
47
47
 
48
- `,{inline:E}));for(;cc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(E?"span":"div");let w;if(y.length>1||t.forceWrapper)w=y;else{if(y.length===1)return w=y[0],typeof w=="string"?c("span",{key:"outer"},w):w;w=null}return o(k,{key:"outer"},w)}function h(m,E){if(!E||!E.trim())return null;const y=E.match(ep);return y?y.reduce(function(k,w){const N=w.indexOf("=");if(N!==-1){const T=(function(I){return I.indexOf("-")!==-1&&I.match(fp)===null&&(I=I.replace(yp,function(H,ne){return ne.toUpperCase()})),I})(w.slice(0,N)).trim(),b=(function(I){const H=I[0];return(H==='"'||H==="'")&&I.length>=2&&I[I.length-1]===H?I.slice(1,-1):I})(w.slice(N+1).trim()),S=Hl[T]||T;if(S==="ref")return k;const x=k[S]=(function(I,H,ne,xe){return H==="style"?(function(de){const Q=[];let me="",P=!1,U=!1,Z="";if(!de)return Q;for(let re=0;re<de.length;re++){const $=de[re];if($!=='"'&&$!=="'"||P||(U?$===Z&&(U=!1,Z=""):(U=!0,Z=$)),$==="("&&me.endsWith("url")?P=!0:$===")"&&P&&(P=!1),$!==";"||U||P)me+=$;else{const W=me.trim();if(W){const we=W.indexOf(":");if(we>0){const pe=W.slice(0,we).trim(),se=W.slice(we+1).trim();Q.push([pe,se])}}me=""}}const Y=me.trim();if(Y){const re=Y.indexOf(":");if(re>0){const $=Y.slice(0,re).trim(),W=Y.slice(re+1).trim();Q.push([$,W])}}return Q})(ne).reduce(function(de,[Q,me]){return de[Q.replace(/(-[a-z])/g,P=>P[1].toUpperCase())]=xe(me,I,Q),de},{}):Qm.indexOf(H)!==-1?xe(gt(ne),I,H):(ne.match(gp)&&(ne=gt(ne.slice(1,ne.length-1))),ne==="true"||ne!=="false"&&ne)})(m,T,b,r);typeof x=="string"&&(qo.test(x)||Xo.test(x))&&(k[S]=d(x.trim()))}else w!=="style"&&(k[Hl[w]||w]=!0);return k},{}):null}const u=[],f={},_={0:{t:[">"],o:xt(Gl),i:1,u(m,E,y){const[,k,w]=m[0].replace(np,"").match(rp);return{alert:k,children:E(w,y)}},l(m,E,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),Qn),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,E(m.children,y))}},1:{t:[" "],o:Or(op),i:1,u:es,l:(m,E,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:xt(sp),i:1,u:es,l:(m,E,y)=>c("hr",{key:y.key})},3:{t:[" "],o:xt(Kl),i:0,u:m=>({lang:void 0,text:gt(Jn(m[0].replace(/^ {4}/gm,"")))}),l:(m,E,y)=>c("pre",{key:y.key},c("code",Gt({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:xt(Wl),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Pt(ip),i:3,u:m=>({text:gt(m[2])}),l:(m,E,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:xt(cp),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:ts},7:{t:["[^"],o:Wt(dp),i:1,u:m=>({target:"#"+n(m[1],Qn),text:m[1]}),l:(m,E,y)=>c("a",{key:y.key,href:r(m.target,"a","href")},c("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:Wt(mp),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,E,y)=>c("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:xt(t.enforceAtxHeadings?Xl:ql),i:1,u:(m,E,y)=>({children:Ar(E,m[2],y),id:n(m[2],Qn),level:m[1].length}),l:(m,E,y)=>c("h"+m.level,{id:m.id,key:y.key},E(m.children,y))},10:{t:m=>{const E=m.indexOf(`
49
- `);return E>0&&E<m.length-1&&(m[E+1]==="="||m[E+1]==="-")},o:xt(Zl),i:1,u:(m,E,y)=>({children:Ar(E,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Or(qo),i:1,u(m,E,y){const[,k]=m[3].match(Vp),w=RegExp("^"+k,"gm"),N=m[3].replace(w,""),T=a(s,N)?Qp:Ar,b=m[1].toLowerCase(),S=Jm.indexOf(b)!==-1,x=(S?b:m[1]).trim(),I={attrs:h(x,m[2]),noInnerParse:S,tag:x};if(y.inAnchor=y.inAnchor||b==="a",S)I.text=m[3];else{const H=y.inHTML;y.inHTML=!0,I.children=T(E,N,y),y.inHTML=H}return y.inAnchor=!1,I},l:(m,E,y)=>c(m.tag,Gt({key:y.key},m.attrs),m.text||(m.children?E(m.children,y):""))},13:{t:["<"],o:Or(Xo),i:1,u(m){const E=m[1].trim();return{attrs:h(E,m[2]||""),tag:E}},l:(m,E,y)=>c(m.tag,Gt({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Or(Jl),i:1,u:()=>({}),l:ts},14:{t:["!["],o:Pt(Gp),i:1,u:m=>({alt:gt(m[1]),target:gt(m[2]),title:gt(m[3])}),l:(m,E,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:Wt(Yp),i:3,u:(m,E,y)=>({children:Jp(E,m[1],y),target:gt(m[2]),title:gt(m[3])}),l:(m,E,y)=>c("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},E(m.children,y))},16:{t:["<"],o:Wt(Ep),i:0,u(m){let E=m[1],y=!1;return E.indexOf("@")!==-1&&E.indexOf("//")===-1&&(y=!0,E=E.replace("mailto:","")),{children:[{text:E,type:"27"}],target:y?"mailto:"+E:E,type:"15"}}},17:{t:(m,E)=>!E.inAnchor&&!t.disableAutoLink&&(Rr(m,"http://")||Rr(m,"https://")),o:Wt(_p),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:lc(c,1),33:lc(c,2),19:{t:[`
50
- `],o:xt(ap),i:3,u:es,l:()=>`
48
+ `,{inline:E}));for(;cc(y[y.length-1])&&!y[y.length-1].trim();)y.pop();if(t.wrapper===null)return y;const k=t.wrapper||(E?"span":"div");let w;if(y.length>1||t.forceWrapper)w=y;else{if(y.length===1)return w=y[0],typeof w=="string"?c("span",{key:"outer"},w):w;w=null}return o(k,{key:"outer"},w)}function h(m,E){if(!E||!E.trim())return null;const y=E.match(np);return y?y.reduce(function(k,w){const N=w.indexOf("=");if(N!==-1){const T=(function(I){return I.indexOf("-")!==-1&&I.match(_p)===null&&(I=I.replace(bp,function(H,ne){return ne.toUpperCase()})),I})(w.slice(0,N)).trim(),b=(function(I){const H=I[0];return(H==='"'||H==="'")&&I.length>=2&&I[I.length-1]===H?I.slice(1,-1):I})(w.slice(N+1).trim()),S=Hl[T]||T;if(S==="ref")return k;const x=k[S]=(function(I,H,ne,xe){return H==="style"?(function(de){const Q=[];let me="",P=!1,F=!1,Z="";if(!de)return Q;for(let re=0;re<de.length;re++){const $=de[re];if($!=='"'&&$!=="'"||P||(F?$===Z&&(F=!1,Z=""):(F=!0,Z=$)),$==="("&&me.endsWith("url")?P=!0:$===")"&&P&&(P=!1),$!==";"||F||P)me+=$;else{const W=me.trim();if(W){const we=W.indexOf(":");if(we>0){const pe=W.slice(0,we).trim(),se=W.slice(we+1).trim();Q.push([pe,se])}}me=""}}const Y=me.trim();if(Y){const re=Y.indexOf(":");if(re>0){const $=Y.slice(0,re).trim(),W=Y.slice(re+1).trim();Q.push([$,W])}}return Q})(ne).reduce(function(de,[Q,me]){return de[Q.replace(/(-[a-z])/g,P=>P[1].toUpperCase())]=xe(me,I,Q),de},{}):tp.indexOf(H)!==-1?xe(gt(ne),I,H):(ne.match(Ep)&&(ne=gt(ne.slice(1,ne.length-1))),ne==="true"||ne!=="false"&&ne)})(m,T,b,r);typeof x=="string"&&(qo.test(x)||Xo.test(x))&&(k[S]=d(x.trim()))}else w!=="style"&&(k[Hl[w]||w]=!0);return k},{}):null}const u=[],f={},_={0:{t:[">"],o:xt(Gl),i:1,u(m,E,y){const[,k,w]=m[0].replace(op,"").match(sp);return{alert:k,children:E(w,y)}},l(m,E,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),Qn),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),c("blockquote",k,E(m.children,y))}},1:{t:[" "],o:Or(ip),i:1,u:es,l:(m,E,y)=>c("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:xt(ap),i:1,u:es,l:(m,E,y)=>c("hr",{key:y.key})},3:{t:[" "],o:xt(Kl),i:0,u:m=>({lang:void 0,text:gt(Jn(m[0].replace(/^ {4}/gm,"")))}),l:(m,E,y)=>c("pre",{key:y.key},c("code",Gt({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:xt(Wl),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Pt(lp),i:3,u:m=>({text:gt(m[2])}),l:(m,E,y)=>c("code",{key:y.key},m.text)},6:{t:["[^"],o:xt(up),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:ts},7:{t:["[^"],o:Wt(hp),i:1,u:m=>({target:"#"+n(m[1],Qn),text:m[1]}),l:(m,E,y)=>c("a",{key:y.key,href:r(m.target,"a","href")},c("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:Wt(fp),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,E,y)=>c("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:xt(t.enforceAtxHeadings?Xl:ql),i:1,u:(m,E,y)=>({children:Ar(E,m[2],y),id:n(m[2],Qn),level:m[1].length}),l:(m,E,y)=>c("h"+m.level,{id:m.id,key:y.key},E(m.children,y))},10:{t:m=>{const E=m.indexOf(`
49
+ `);return E>0&&E<m.length-1&&(m[E+1]==="="||m[E+1]==="-")},o:xt(Zl),i:1,u:(m,E,y)=>({children:Ar(E,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:Or(qo),i:1,u(m,E,y){const[,k]=m[3].match(zp),w=RegExp("^"+k,"gm"),N=m[3].replace(w,""),T=a(s,N)?tf:Ar,b=m[1].toLowerCase(),S=ep.indexOf(b)!==-1,x=(S?b:m[1]).trim(),I={attrs:h(x,m[2]),noInnerParse:S,tag:x};if(y.inAnchor=y.inAnchor||b==="a",S)I.text=m[3];else{const H=y.inHTML;y.inHTML=!0,I.children=T(E,N,y),y.inHTML=H}return y.inAnchor=!1,I},l:(m,E,y)=>c(m.tag,Gt({key:y.key},m.attrs),m.text||(m.children?E(m.children,y):""))},13:{t:["<"],o:Or(Xo),i:1,u(m){const E=m[1].trim();return{attrs:h(E,m[2]||""),tag:E}},l:(m,E,y)=>c(m.tag,Gt({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:Or(Jl),i:1,u:()=>({}),l:ts},14:{t:["!["],o:Pt(Kp),i:1,u:m=>({alt:gt(m[1]),target:gt(m[2]),title:gt(m[3])}),l:(m,E,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:Wt(Wp),i:3,u:(m,E,y)=>({children:ef(E,m[1],y),target:gt(m[2]),title:gt(m[3])}),l:(m,E,y)=>c("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},E(m.children,y))},16:{t:["<"],o:Wt(vp),i:0,u(m){let E=m[1],y=!1;return E.indexOf("@")!==-1&&E.indexOf("//")===-1&&(y=!0,E=E.replace("mailto:","")),{children:[{text:E,type:"27"}],target:y?"mailto:"+E:E,type:"15"}}},17:{t:(m,E)=>!E.inAnchor&&!t.disableAutoLink&&(Rr(m,"http://")||Rr(m,"https://")),o:Wt(yp),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:lc(c,1),33:lc(c,2),19:{t:[`
50
+ `],o:xt(cp),i:3,u:es,l:()=>`
51
51
  `},21:{o:gn(function(m,E){if(E.inline||E.simple||E.inHTML&&m.indexOf(`
52
52
 
53
53
  `)===-1&&E.prevCapture.indexOf(`
54
54
 
55
55
  `)===-1)return null;let y="",k=0;for(;;){const N=m.indexOf(`
56
- `,k),T=m.slice(k,N===-1?void 0:N+1);if(a(i,T)||(y+=T,N===-1||!T.trim()))break;k=N+1}const w=Jn(y);return w===""?null:[y,,w]}),i:3,u:Qo,l:(m,E,y)=>c("p",{key:y.key},E(m.children,y))},22:{t:["["],o:Wt(bp),i:0,u:m=>(f[m[1]]={target:m[2],title:m[4]},{}),l:ts},23:{t:["!["],o:Pt(Sp),i:0,u:m=>({alt:m[1]?gt(m[1]):void 0,ref:m[2]}),l:(m,E,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:Wt(wp),i:0,u:(m,E,y)=>({children:E(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,E,y)=>f[m.ref]?c("a",{key:y.key,href:r(f[m.ref].target,"a","href"),title:f[m.ref].title},E(m.children,y)):c("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:xt(Ql),i:1,u:qp,l(m,E,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(w,N){return c("th",{key:N,style:uc(k,N)},E(w,y))}))),c("tbody",null,k.cells.map(function(w,N){return c("tr",{key:N},w.map(function(T,b){return c("td",{key:b,style:uc(k,b)},E(T,y))}))})))}},27:{o:gn(function(m,E){let y;return Rr(m,":")&&(y=Pp.exec(m)),y||Fp.exec(m)}),i:4,u(m){const E=m[0];return{text:E.indexOf("&")===-1?E:E.replace(pp,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Pt(Op),i:2,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>c("strong",{key:y.key},E(m.children,y))},29:{t:m=>{const E=m[0];return(E==="*"||E==="_")&&m[1]!==E},o:Pt(Ap),i:3,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>c("em",{key:y.key},E(m.children,y))},30:{t:["\\"],o:Pt(Dp),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Pt(Ip),i:3,u:Qo,l:(m,E,y)=>c("mark",{key:y.key},E(m.children,y))},32:{t:["~~"],o:Pt(Mp),i:3,u:Qo,l:(m,E,y)=>c("del",{key:y.key},E(m.children,y))}};t.disableParsingRawHTML===!0&&(delete _[11],delete _[13]);const p=(function(m){var E=Object.keys(m);function y(k,w){var N=[];if(w.prevCapture=w.prevCapture||"",k.trim())for(;k;)for(var T=0;T<E.length;){var b=E[T],S=m[b];if(!S.t||Wp(k,w,S.t)){var x=S.o(k,w);if(x&&x[0]){k=k.substring(x[0].length);var I=S.u(x,y,w);w.prevCapture+=x[0],I.type||(I.type=b),N.push(I);break}T++}else T++}return w.prevCapture="",N}return E.sort(function(k,w){return m[k].i-m[w].i||(k<w?-1:1)}),function(k,w){return y((function(N){return N.replace(lp,`
57
- `).replace(up,"").replace(xp," ")})(k),w)}})(_),g=(function(m,E){return function y(k,w={}){if(Array.isArray(k)){const N=w.key,T=[];let b=!1;for(let S=0;S<k.length;S++){w.key=S;const x=y(k[S],w),I=cc(x);I&&b?T[T.length-1]+=x:x!==null&&T.push(x),b=I}return w.key=N,T}return(function(N,T,b){const S=m[N.type].l;return E?E(()=>S(N,T,b),N,T,b):S(N,T,b)})(k,y,w)}})(_,t.renderRule),v=d(e);return u.length?c("div",null,v,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,Qn),key:m.identifier},m.identifier,g(p(m.footnote,{inline:!0})))}))):v}const nf=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,Zm);return Rt(tf(t??"",n),r)},rf={disableParsingRawHTML:!0,forceBlock:!0};function Ir({children:e}){return l(nf,{options:rf,children:e})}function hc({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:A("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 of=We(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),sf=We(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),af=We(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),lf=We(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),cf=We(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function Fe({className:e}){return l("div",{className:A("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 er({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(Mr,{}),l(Fe,{className:"h-8 w-20 rounded-full"}),l(Fe,{className:"h-8 w-24 rounded-full"}),l(Fe,{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(Mr,{}),l(Fe,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(Fe,{className:"h-3 w-3/4 rounded"}),l(Fe,{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(Mr,{}),l(Fe,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(Fe,{className:"h-9 w-full rounded-lg"}),l(Fe,{className:"h-9 w-full rounded-lg"}),l(Fe,{className:"h-9 w-full rounded-lg"})]}),l(Fe,{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(Mr,{}),l("div",{className:"flex items-center gap-3",children:[l(Fe,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(Fe,{className:"h-3 w-3/4 rounded"}),l(Fe,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(Fe,{className:"h-3 w-full rounded"}),l(Fe,{className:"h-3 w-5/6 rounded"})]}),l(Fe,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Mr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function df({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=L([]),[a,c]=L({}),[d,h]=L(!1),[u,f]=L(5),_=n.component,p=n.disabled,g=_e(()=>n.input,[n.input]);z(()=>{_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&c(g.doctor_details)},[_,g?.doctor_details]),z(()=>{n.disabled||(h(!1),f(5),s([]))},[g,n.disabled]);const v=async S=>{h(!0),await r({message:S.value,messageId:e,toolCalled:!0,selectedComponent:S,tool_key:t})},m=async(S,x,I,H=!0)=>{await r({toolCalled:H,selectedComponent:S,selected_id:S.doctor_id,message:x,tool_key:t,messageId:e,...I&&{tool_result:I}})},E=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 S=_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options;return S?Array.isArray(S)?S.map((x,I)=>({id:`option-${I}`,label:x.label,value:x.value})):Object.keys(S).map((x,I)=>({id:`option-${I}`,label:x,value:x})):[]},w=_e(()=>{if(_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(S=>!!S&&!!S.doctor_id)},[_,g?.doctors]);if(!_)return null;const N=_===M.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,T=_===M.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,b=_===M.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return l("div",{className:"flex justify-end",children:[N&&l("div",{className:`flex ${N.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[N.slice(0,u).map((S,x)=>l(hc,{disabled:p||o||d,text:S?.label||"",onClick:()=>v(S),className:"cursor-pointer"},x)),N.length>u&&l("button",{type:"button",disabled:p||o||d,onClick:()=>f(S=>S+5),className:A("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(ko,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,N.length-u)," more"]})]}),_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options&&l($e,{fallback:l(er,{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(of,{options:k(),selectedValues:i,onSelectionChange:s,disabled:p||o}),l(le,{onClick:y,disabled:i.length===0||p||o,className:A("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"})]})}),w&&w.length>0?l($e,{fallback:l(er,{variant:"card"}),children:l(sf,{count:w.length>1?w.length+1:w.length,renderItem:(S,x)=>{if(w.length>1&&S===w.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:E,disabled:o||p,className:A("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:A("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(dh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const I=w[S];return l($e,{fallback:l(er,{variant:"card"}),children:l(af,{doctor:I,doctorDetails:a?.[I.doctor_id],disabled:o,onSelect:m,isActive:x})},I.doctor_id)}})}):null,T&&l($e,{fallback:l(er,{variant:"card"}),children:l(lf,{cards:T,onSelect:async S=>{await r({...S,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:p||o})}),b&&l($e,{fallback:l(er,{variant:"media"}),children:l("div",{className:"mt-3",children:l(cf,{card:b})})})]})}function uf({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:_,isAuthComponent:p,isFullScreen:g}){const v=t==="user",[m,E]=L(M.USER_FEEDBACK.NONE),y=G(N=>N.isStreaming),k=N=>{E(N),u(N)},w=!!(n?.trim()||r&&r.length>0||d||i||a);return l(ce,{children:[w&&l("div",{className:A("flex",v?"justify-end":"justify-start"),children:l("div",{className:A("flex gap-3",v?"flex-row-reverse":"flex-row",v?"max-w-[60%]":g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l($t,{className:A("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",v?"bg-primary text-primary-foreground shadow-sm":A("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!v&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!v&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!v&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:A("markdown-content",g&&!v?"text-base leading-6":"text-sm"),children:l(Ir,{children:`${n} ${!v&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l($o,{files:r,isPreview:!1,className:""})}),i&&!v&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!v&&!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(le,{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(Sr,{className:"h-3 w-3"})}),l(le,{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(wr,{className:"h-3 w-3"})})]})}),!a&&!v&&!y&&o&&m===M.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Sr,{className:"h-3 w-3"})})}),!a&&!v&&!y&&o&&m===M.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(wr,{className:"h-3 w-3"})})}),p&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{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 N=s[s.length-1];N&&c[N]?.active&&_(N,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(N=>{const T=c[N];return T?l(df,{messageId:e,tool_key:N,entry:T,onSendMessage:h,disabled:f||T.disabled},N):null}),a&&!v&&l("div",{className:"flex justify-start",children:l("div",{className:A("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l($t,{className:A("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:A("markdown-content",g?"text-base leading-6":"text-sm"),children:l(Ir,{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(le,{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(Sr,{className:"h-3 w-3"})}),l(le,{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(wr,{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(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Sr,{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(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(wr,{className:"h-3 w-3"})})})]})})})]})}function hf({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:A("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l($t,{className:A("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:A("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Ir,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:A("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(hc,{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=G(u=>u.isWaitingForResponse),d=G(u=>u.elicitationState),h=G(u=>u.progressMessage);return e.length===0&&!h?l(hf,{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(uf,{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:_=>n(_,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($t,{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 mc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=Fl(),[c,d]=L(!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:A("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:A("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:A("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 ff=We(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function gf({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:_,isAuthComponent:p,isConnected:g,inConversation:v,isFirstMessage:m,isEmptyChat:E,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:w,startSession:N,sendMessageFeedback:T,clearElicitationState:b,handleRetry:S,scrollToBottom:x,chatComposerProps:I,isComposerDisabled:H,voiceAgentState:ne,isMuted:xe,isVoiceAgentActive:de,disconnectVoiceAgent:Q,resetVoiceAgent:me,toggleMute:P,handleClose:U,isSessionDrawerOpen:Z,pastSessions:Y,isLoadingPastSessions:re,openSessionDrawer:$,closeSessionDrawer:W,userLevel:we,isSidebarCollapsed:pe,toggleSidebar:se,showFeedbackModal:Ke,handleSessionFeedbackSubmit:Ye,handleSessionFeedbackSkip:Qe,handleDontShowAgain:D,handleCloseModal:ue,showConsentModal:ie,handleConsentAccept:ke,handleSendMessage:Me}=Xm({isOpen:e,agentId:t,config:n});z(()=>{w.length||x("auto")},[w.length,x]);const Te=_e(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),ct=o==="full"&&we==="user"?l(xm,{sessions:Y,activeSessionId:f,onSelectSession:Ae=>N({sessionId:Ae}),onNewChat:()=>N({forceNewSession:!0}),isCollapsed:pe,onToggle:se,isLoading:re}):void 0;return l(Jh,{enabled:!!n.resize,children:l(Dl,{isOpen:e,onClose:U,feedbackModal:n.feedback?{isOpen:Ke,config:n.feedback,onSubmit:Ye,onSkip:Qe,onClose:ue,onDontShowAgain:D}:void 0,consentModal:n.theme?.upfrontConsent?{isOpen:ie,onAccept:ke}:void 0,showCloseButton:n.showCloseButton,title:n.title,showStartNewChatButton:c,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:()=>N({forceNewSession:!0}),sessionId:f,environment:n.environment,mode:o,onToggleDisplayMode:n.resize?r:void 0,theme:n.theme,isAuthComponent:p,activeElicitation:_,voiceAgentState:ne,chatComposer:I,onOpenSessionDrawer:$,sessionDrawer:l(km,{isOpen:Z,onClose:W,sessions:Y,activeSessionId:f,onSelectSession:Ae=>{N({sessionId:Ae})},onNewChat:()=>N({forceNewSession:!0})}),sidebar:ct,fullScreenEmptyState:E?Ae=>l(Am,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:Ne=>Me(Ne,!0),disabled:H,composer:Ae.composer,composerFooter:Ae.composerFooter,connectionBanner:l(mc,{onRetry:S,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})}):void 0,children:de?l($e,{fallback:l(pc,{}),children:l(ff,{state:ne,isMuted:xe,onEndCall:Q,onClose:me,onToggleMute:P,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l($e,{fallback:l(pc,{}),children:l("div",{className:A("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($a,{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:A("min-w-0 overflow-x-hidden",v?"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(Uh,{}):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:Te}),l(mf,{messages:w,onSendMessage:Ae=>Me(Ae,E),iconUrl:n.iconUrl,onToggleFeedback:T,onClearElicitationState:b,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(le,{onClick:()=>x("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(ko,{className:"w-5 h-5 text-text-primary"})})}),l(mc,{className:"mt-2",onRetry:S,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})]})})})})}function pc(){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 rs(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 _f extends ot{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:rs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(vf,{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 Ef({error:e}){throw e}function yf(e){const[t,n]=L(null);return z(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||(i?.error?n(rs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(rs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(_f,{...e,children:t?l(Ef,{error:t}):e.children})}function vf({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=_e(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]);return l(Dl,{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(ah,{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(le,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(nh,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})}function bf({agentId:e,config:t}){const[n,r]=L(t.displayMode==="full");z(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(yf,{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(vh,{children:l(gf,{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 fc=(e,t,n)=>{const r=n||{},o=$c(e);return o.render(l(ce,{children:l(bf,{agentId:t,config:r})})),o},Sf=e=>{try{const t=sessionStorage.getItem(Zn(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{}}},gc=e=>{const{refreshToken:t,sessToken:n}=Sf(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},_c=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=fc,window.fetchAgentConfig=_c,window.prefetchAuth=gc);export{X as A,le as B,ko as C,J as D,Za as F,Ja as I,Ro as M,so as N,rn as P,co as R,Ho as S,_e as T,fn as X,at as _,M as a,A as b,Ie as c,L as d,ce as e,jt as f,_c as fetchAgentConfig,ei as g,on as h,Ot as i,It as j,Mm as k,sl as l,jo as m,xl as n,zo as o,Im as p,gc as prefetchAuth,fe as q,al as r,fc as renderMedAssist,Ir as s,Vl as t,l as u,$t as v,Pm as w,il as x,z as y,ll as z};
56
+ `,k),T=m.slice(k,N===-1?void 0:N+1);if(a(i,T)||(y+=T,N===-1||!T.trim()))break;k=N+1}const w=Jn(y);return w===""?null:[y,,w]}),i:3,u:Qo,l:(m,E,y)=>c("p",{key:y.key},E(m.children,y))},22:{t:["["],o:Wt(wp),i:0,u:m=>(f[m[1]]={target:m[2],title:m[4]},{}),l:ts},23:{t:["!["],o:Pt(Np),i:0,u:m=>({alt:m[1]?gt(m[1]):void 0,ref:m[2]}),l:(m,E,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:Wt(xp),i:0,u:(m,E,y)=>({children:E(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,E,y)=>f[m.ref]?c("a",{key:y.key,href:r(f[m.ref].target,"a","href"),title:f[m.ref].title},E(m.children,y)):c("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:xt(Ql),i:1,u:Zp,l(m,E,y){const k=m;return c("table",{key:y.key},c("thead",null,c("tr",null,k.header.map(function(w,N){return c("th",{key:N,style:uc(k,N)},E(w,y))}))),c("tbody",null,k.cells.map(function(w,N){return c("tr",{key:N},w.map(function(T,b){return c("td",{key:b,style:uc(k,b)},E(T,y))}))})))}},27:{o:gn(function(m,E){let y;return Rr(m,":")&&(y=Lp.exec(m)),y||Vp.exec(m)}),i:4,u(m){const E=m[0];return{text:E.indexOf("&")===-1?E:E.replace(gp,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Pt(Ip),i:2,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>c("strong",{key:y.key},E(m.children,y))},29:{t:m=>{const E=m[0];return(E==="*"||E==="_")&&m[1]!==E},o:Pt(Mp),i:3,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>c("em",{key:y.key},E(m.children,y))},30:{t:["\\"],o:Pt(Up),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Pt(Pp),i:3,u:Qo,l:(m,E,y)=>c("mark",{key:y.key},E(m.children,y))},32:{t:["~~"],o:Pt(Dp),i:3,u:Qo,l:(m,E,y)=>c("del",{key:y.key},E(m.children,y))}};t.disableParsingRawHTML===!0&&(delete _[11],delete _[13]);const p=(function(m){var E=Object.keys(m);function y(k,w){var N=[];if(w.prevCapture=w.prevCapture||"",k.trim())for(;k;)for(var T=0;T<E.length;){var b=E[T],S=m[b];if(!S.t||qp(k,w,S.t)){var x=S.o(k,w);if(x&&x[0]){k=k.substring(x[0].length);var I=S.u(x,y,w);w.prevCapture+=x[0],I.type||(I.type=b),N.push(I);break}T++}else T++}return w.prevCapture="",N}return E.sort(function(k,w){return m[k].i-m[w].i||(k<w?-1:1)}),function(k,w){return y((function(N){return N.replace(dp,`
57
+ `).replace(mp,"").replace(Cp," ")})(k),w)}})(_),g=(function(m,E){return function y(k,w={}){if(Array.isArray(k)){const N=w.key,T=[];let b=!1;for(let S=0;S<k.length;S++){w.key=S;const x=y(k[S],w),I=cc(x);I&&b?T[T.length-1]+=x:x!==null&&T.push(x),b=I}return w.key=N,T}return(function(N,T,b){const S=m[N.type].l;return E?E(()=>S(N,T,b),N,T,b):S(N,T,b)})(k,y,w)}})(_,t.renderRule),v=d(e);return u.length?c("div",null,v,c("footer",{key:"footer"},u.map(function(m){return c("div",{id:n(m.identifier,Qn),key:m.identifier},m.identifier,g(p(m.footnote,{inline:!0})))}))):v}const of=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,Qm);return Rt(rf(t??"",n),r)},sf={disableParsingRawHTML:!0,forceBlock:!0};function Ir({children:e}){return l(of,{options:sf,children:e})}function hc({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:A("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 af=We(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),lf=We(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),cf=We(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),df=We(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),uf=We(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function Ue({className:e}){return l("div",{className:A("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 er({variant:e}){return e==="pill"?l("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[l(Mr,{}),l(Ue,{className:"h-8 w-20 rounded-full"}),l(Ue,{className:"h-8 w-24 rounded-full"}),l(Ue,{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(Mr,{}),l(Ue,{className:"h-24 w-full rounded-lg"}),l("div",{className:"mt-3 space-y-2",children:[l(Ue,{className:"h-3 w-3/4 rounded"}),l(Ue,{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(Mr,{}),l(Ue,{className:"h-3 w-32 rounded mb-3"}),l("div",{className:"space-y-2",children:[l(Ue,{className:"h-9 w-full rounded-lg"}),l(Ue,{className:"h-9 w-full rounded-lg"}),l(Ue,{className:"h-9 w-full rounded-lg"})]}),l(Ue,{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(Mr,{}),l("div",{className:"flex items-center gap-3",children:[l(Ue,{className:"h-10 w-10 rounded-full"}),l("div",{className:"flex-1 space-y-2",children:[l(Ue,{className:"h-3 w-3/4 rounded"}),l(Ue,{className:"h-3 w-1/2 rounded"})]})]}),l("div",{className:"mt-4 space-y-2",children:[l(Ue,{className:"h-3 w-full rounded"}),l(Ue,{className:"h-3 w-5/6 rounded"})]}),l(Ue,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Mr(){return l("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function hf({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=L([]),[a,c]=L({}),[d,h]=L(!1),[u,f]=L(5),_=n.component,p=n.disabled,g=_e(()=>n.input,[n.input]);z(()=>{_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&c(g.doctor_details)},[_,g?.doctor_details]),z(()=>{n.disabled||(h(!1),f(5),s([]))},[g,n.disabled]);const v=async S=>{h(!0),await r({message:S.value,messageId:e,toolCalled:!0,selectedComponent:S,tool_key:t})},m=async(S,x,I,H=!0)=>{await r({toolCalled:H,selectedComponent:S,selected_id:S.doctor_id,message:x,tool_key:t,messageId:e,...I&&{tool_result:I}})},E=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 S=_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options;return S?Array.isArray(S)?S.map((x,I)=>({id:`option-${I}`,label:x.label,value:x.value})):Object.keys(S).map((x,I)=>({id:`option-${I}`,label:x,value:x})):[]},w=_e(()=>{if(_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(S=>!!S&&!!S.doctor_id)},[_,g?.doctors]);if(!_)return null;const N=_===M.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,T=_===M.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,b=_===M.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return l("div",{className:"flex justify-end",children:[N&&l("div",{className:`flex ${N.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[N.slice(0,u).map((S,x)=>l(hc,{disabled:p||o||d,text:S?.label||"",onClick:()=>v(S),className:"cursor-pointer"},x)),N.length>u&&l("button",{type:"button",disabled:p||o||d,onClick:()=>f(S=>S+5),className:A("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(ko,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,N.length-u)," more"]})]}),_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options&&l($e,{fallback:l(er,{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(af,{options:k(),selectedValues:i,onSelectionChange:s,disabled:p||o}),l(le,{onClick:y,disabled:i.length===0||p||o,className:A("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"})]})}),w&&w.length>0?l($e,{fallback:l(er,{variant:"card"}),children:l(lf,{count:w.length>1?w.length+1:w.length,renderItem:(S,x)=>{if(w.length>1&&S===w.length&&n?.hide_show_more!==!0)return l("button",{type:"button",onClick:E,disabled:o||p,className:A("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:A("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:l(dh,{className:"w-4 h-4 text-primary"})}),l("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const I=w[S];return l($e,{fallback:l(er,{variant:"card"}),children:l(cf,{doctor:I,doctorDetails:a?.[I.doctor_id],disabled:o,onSelect:m,isActive:x})},I.doctor_id)}})}):null,T&&l($e,{fallback:l(er,{variant:"card"}),children:l(df,{cards:T,onSelect:async S=>{await r({...S,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:p||o})}),b&&l($e,{fallback:l(er,{variant:"media"}),children:l("div",{className:"mt-3",children:l(uf,{card:b})})})]})}function mf({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:_,isAuthComponent:p,isFullScreen:g}){const v=t==="user",[m,E]=L(M.USER_FEEDBACK.NONE),y=G(N=>N.isStreaming),k=N=>{E(N),u(N)},w=!!(n?.trim()||r&&r.length>0||d||i||a);return l(ce,{children:[w&&l("div",{className:A("flex",v?"justify-end":"justify-start"),children:l("div",{className:A("flex gap-3",v?"flex-row-reverse":"flex-row",v?"max-w-[60%]":g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l($t,{className:A("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",v?"bg-primary text-primary-foreground shadow-sm":A("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!v&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!v&&l("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!v&&o&&l("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),n&&l("div",{className:A("markdown-content",g&&!v?"text-base leading-6":"text-sm"),children:l(Ir,{children:`${n} ${!v&&y&&o?"...":""}`})}),r&&r.length>0&&l("div",{className:"mt-2",children:l($o,{files:r,isPreview:!1,className:""})}),i&&!v&&o&&l("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!v&&!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(le,{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(Sr,{className:"h-3 w-3"})}),l(le,{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(wr,{className:"h-3 w-3"})})]})}),!a&&!v&&!y&&o&&m===M.USER_FEEDBACK.LIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Sr,{className:"h-3 w-3"})})}),!a&&!v&&!y&&o&&m===M.USER_FEEDBACK.DISLIKE&&l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(wr,{className:"h-3 w-3"})})}),p&&o&&s?.length?l("div",{className:"flex items-center gap-2 self-start mt-1",children:l(le,{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 N=s[s.length-1];N&&c[N]?.active&&_(N,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(N=>{const T=c[N];return T?l(hf,{messageId:e,tool_key:N,entry:T,onSendMessage:h,disabled:f||T.disabled},N):null}),a&&!v&&l("div",{className:"flex justify-start",children:l("div",{className:A("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:l("div",{className:"flex flex-col",children:[l($t,{className:A("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:A("markdown-content",g?"text-base leading-6":"text-sm"),children:l(Ir,{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(le,{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(Sr,{className:"h-3 w-3"})}),l(le,{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(wr,{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(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(Sr,{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(le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:l(wr,{className:"h-3 w-3"})})})]})})})]})}function pf({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:A("flex gap-3 flex-row",o?"w-full":"max-w-xs"),children:l($t,{className:A("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:A("markdown-content",o?"text-base leading-6":"text-sm"),children:l(Ir,{children:e})})})})}),t&&t.length>0&&l("div",{className:"flex justify-end",children:l("div",{className:A("flex gap-2 mt-3",t.length>3?"flex-col":"flex-wrap"),children:t.map((s,a)=>l(hc,{text:s.label||"",onClick:()=>i(s),disabled:r,className:"cursor-pointer"},a))})})]})}function ff({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(pf,{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(mf,{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:_=>n(_,u.id),onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),c&&l(gf,{})]})}function gf(){return l("div",{children:l("div",{className:"flex justify-start",children:l("div",{className:"flex gap-3",children:l($t,{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 mc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=Ul(),[c,d]=L(!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:A("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:A("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:A("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 _f=We(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function Ef({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:_,isAuthComponent:p,isConnected:g,inConversation:v,isFirstMessage:m,isEmptyChat:E,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:w,startSession:N,sendMessageFeedback:T,clearElicitationState:b,handleRetry:S,scrollToBottom:x,chatComposerProps:I,isComposerDisabled:H,voiceAgentState:ne,isMuted:xe,isVoiceAgentActive:de,disconnectVoiceAgent:Q,resetVoiceAgent:me,toggleMute:P,handleClose:F,isSessionDrawerOpen:Z,pastSessions:Y,isLoadingPastSessions:re,openSessionDrawer:$,closeSessionDrawer:W,userLevel:we,isSidebarCollapsed:pe,toggleSidebar:se,showFeedbackModal:Ke,handleSessionFeedbackSubmit:Ye,handleSessionFeedbackSkip:Qe,handleDontShowAgain:D,handleCloseModal:ue,showConsentModal:ie,handleConsentAccept:ke,handleSendMessage:Me}=Jm({isOpen:e,agentId:t,config:n});z(()=>{w.length||x("auto")},[w.length,x]);const Te=_e(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),ct=o==="full"&&we==="user"?l(Cm,{sessions:Y,activeSessionId:f,onSelectSession:Ae=>N({sessionId:Ae}),onNewChat:()=>N({forceNewSession:!0}),isCollapsed:pe,onToggle:se,isLoading:re}):void 0;return l(Jh,{enabled:!!n.resize,children:l(Dl,{isOpen:e,onClose:F,feedbackModal:n.feedback?{isOpen:Ke,config:n.feedback,onSubmit:Ye,onSkip:Qe,onClose:ue,onDontShowAgain:D}:void 0,consentModal:n.theme?.upfrontConsent?{isOpen:ie,onAccept:ke}:void 0,showCloseButton:n.showCloseButton,title:n.title,showStartNewChatButton:c,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:()=>N({forceNewSession:!0}),sessionId:f,environment:n.environment,mode:o,onToggleDisplayMode:n.resize?r:void 0,theme:n.theme,isAuthComponent:p,activeElicitation:_,voiceAgentState:ne,chatComposer:I,onOpenSessionDrawer:$,sessionDrawer:l(Om,{isOpen:Z,onClose:W,sessions:Y,activeSessionId:f,onSelectSession:Ae=>{N({sessionId:Ae})},onNewChat:()=>N({forceNewSession:!0})}),sidebar:ct,fullScreenEmptyState:E?Ae=>l(Mm,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:Ne=>Me(Ne,!0),disabled:H,composer:Ae.composer,composerFooter:Ae.composerFooter,connectionBanner:l(mc,{onRetry:S,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})}):void 0,children:de?l($e,{fallback:l(pc,{}),children:l(_f,{state:ne,isMuted:xe,onEndCall:Q,onClose:me,onToggleMute:P,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):l($e,{fallback:l(pc,{}),children:l("div",{className:A("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($a,{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:A("min-w-0 overflow-x-hidden",v?"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(Fh,{}):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:Te}),l(ff,{messages:w,onSendMessage:Ae=>Me(Ae,E),iconUrl:n.iconUrl,onToggleFeedback:T,onClearElicitationState:b,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(le,{onClick:()=>x("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(ko,{className:"w-5 h-5 text-text-primary"})})}),l(mc,{className:"mt-2",onRetry:S,showRetryButton:d,startNewConnection:c,clearError:h,error:u,isConnected:g})]})})})})}function pc(){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 rs(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 yf extends ot{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:rs(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?l(Sf,{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 vf({error:e}){throw e}function bf(e){const[t,n]=L(null);return z(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||(i?.error?n(rs(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(rs(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),l(yf,{...e,children:t?l(vf,{error:t}):e.children})}function Sf({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=_e(()=>c?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[c?.textColor]);return l(Dl,{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(ah,{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(le,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:c?.primary??void 0},children:[l(nh,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})}function wf({agentId:e,config:t}){const[n,r]=L(t.displayMode==="full");z(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return l(bf,{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(vh,{children:l(Ef,{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 fc=(e,t,n)=>{const r=n||{},o=$c(e);return o.render(l(ce,{children:l(wf,{agentId:t,config:r})})),o},Nf=e=>{try{const t=sessionStorage.getItem(Zn(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{}}},gc=e=>{const{refreshToken:t,sessToken:n}=Nf(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},_c=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=fc,window.fetchAgentConfig=_c,window.prefetchAuth=gc);export{X as A,le as B,ko as C,J as D,Za as F,Ja as I,Ro as M,so as N,rn as P,co as R,Ho as S,_e as T,fn as X,at as _,M as a,A as b,Ie as c,L as d,ce as e,jt as f,_c as fetchAgentConfig,ei as g,on as h,Ot as i,It as j,Dm as k,sl as l,jo as m,xl as n,zo as o,Pm as p,gc as prefetchAuth,fe as q,al as r,fc as renderMedAssist,Ir as s,Vl as t,l as u,$t as v,Lm as w,il as x,z as y,ll as z};