@eka-care/medassist-widget 0.1.138-0 → 0.1.138-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/medassist-widget.css +1 -1
- package/dist/medassist-widget.js +16 -16
- package/package.json +2 -2
package/dist/medassist-widget.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var vd=Object.defineProperty;var wd=(e,t,n)=>t in e?vd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>wd(e,typeof t!="symbol"?t+"":t,n);var zn,J,Us,jt,Fs,Vs,js,go,Lr,$n,zs,_o,Eo,So,$s,Dr={},Ur=[],Td=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Hn=Array.isArray;function bt(e,t){for(var n in t)e[n]=t[n];return e}function yo(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function Ze(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?zn.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 Yn(e,s,r,o,null)}function Yn(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??++Us,__i:-1,__u:0};return o==null&&J.vnode!=null&&J.vnode(i),i}function Hs(){return{current:null}}function _e(e){return e.children}function dt(e,t){this.props=e,this.context=t}function mn(e,t){if(t==null)return e.__?mn(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"?mn(e):null}function Nd(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=bt({},t);i.__v=t.__v+1,J.vnode&&J.vnode(i),vo(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??mn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,qs(r,i,o),t.__e=t.__=null,i.__e!=n&&Ys(i)}}function Ys(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}),Ys(e)}function bo(e){(!e.__d&&(e.__d=!0)&&jt.push(e)&&!Fr.__r++||Fs!=J.debounceRendering)&&((Fs=J.debounceRendering)||Vs)(Fr)}function Fr(){try{for(var e,t=1;jt.length;)jt.length>t&&jt.sort(js),e=jt.shift(),t=jt.length,Nd(e)}finally{jt.length=Fr.__r=0}}function Bs(e,t,n,r,o,i,s,a,l,d,p){var h,f,m,E,S,w,u,g=r&&r.__k||Ur,_=t.length;for(l=Cd(n,t,g,l,_),h=0;h<_;h++)(m=n.__k[h])!=null&&(f=m.__i!=-1&&g[m.__i]||Dr,m.__i=h,w=vo(e,m,f,o,i,s,a,l,d,p),E=m.__e,m.ref&&f.ref!=m.ref&&(f.ref&&To(f.ref,null,m),p.push(m.ref,m.__c||E,m)),S==null&&E!=null&&(S=E),(u=!!(4&m.__u))||f.__k===m.__k?(l=Gs(m,l,e,u),u&&f.__e&&(f.__e=null)):typeof m.type=="function"&&w!==void 0?l=w:E&&(l=E.nextSibling),m.__u&=-7);return n.__e=S,l}function Cd(e,t,n,r,o){var i,s,a,l,d,p=n.length,h=p,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]=Yn(null,s,null,null,null):Hn(s)?s=e.__k[i]=Yn(_e,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Yn(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,l=i+f,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=xd(s,n,l,h))!=-1&&(h--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>p?f--:o<p&&f++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?f--:d==l+1?f++:(d>l?f--:f++,s.__u|=4))):e.__k[i]=null;if(h)for(i=0;i<p;i++)(a=n[i])!=null&&(2&a.__u)==0&&(a.__e==r&&(r=mn(a)),Js(a,a));return r}function Gs(e,t,n,r){var o,i;if(typeof e.type=="function"){for(o=e.__k,i=0;o&&i<o.length;i++)o[i]&&(o[i].__=e,t=Gs(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=mn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function It(e,t){return t=t||[],e==null||typeof e=="boolean"||(Hn(e)?e.some(function(n){It(n,t)}):t.push(e)),t}function xd(e,t,n,r){var o,i,s,a=e.key,l=e.type,d=t[n],p=d!=null&&(2&d.__u)==0;if(d===null&&a==null||p&&a==d.key&&l==d.type)return n;if(r>(p?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&&l==d.type)return s}return-1}function Ws(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||Td.test(t)?n:n+"px"}function Vr(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||Ws(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ws(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(zs,"$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[$n]=r[$n]:(n[$n]=_o,e.addEventListener(t,i?So:Eo,i)):e.removeEventListener(t,i?So:Eo,i);else{if(o=="http://www.w3.org/2000/svg")t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(t!="width"&&t!="height"&&t!="href"&&t!="list"&&t!="form"&&t!="tabIndex"&&t!="download"&&t!="rowSpan"&&t!="colSpan"&&t!="role"&&t!="popover"&&t in e)try{e[t]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&t[4]!="-"?e.removeAttribute(t):e.setAttribute(t,t=="popover"&&n==1?"":n))}}function Ks(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Lr]==null)t[Lr]=_o++;else if(t[Lr]<n[$n])return;return n(J.event?J.event(t):t)}}}function vo(e,t,n,r,o,i,s,a,l,d){var p,h,f,m,E,S,w,u,g,_,b,N,T,O,y,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[a=t.__e=n.__e]),(p=J.__b)&&p(t);e:if(typeof v=="function")try{if(u=t.props,g=v.prototype&&v.prototype.render,_=(p=v.contextType)&&r[p.__c],b=p?_?_.props.value:p.__:r,n.__c?w=(h=t.__c=n.__c).__=h.__E:(g?t.__c=h=new v(u,b):(t.__c=h=new dt(u,b),h.constructor=v,h.render=Rd),_&&_.sub(h),h.state||(h.state={}),h.__n=r,f=h.__d=!0,h.__h=[],h._sb=[]),g&&h.__s==null&&(h.__s=h.state),g&&v.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=bt({},h.__s)),bt(h.__s,v.getDerivedStateFromProps(u,h.__s))),m=h.props,E=h.state,h.__v=t,f)g&&v.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),g&&h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(g&&v.getDerivedStateFromProps==null&&u!==m&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(u,b),t.__v==n.__v||!h.__e&&h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(u,h.__s,b)===!1){t.__v!=n.__v&&(h.props=u,h.state=h.__s,h.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(x){x&&(x.__=t)}),Ur.push.apply(h.__h,h._sb),h._sb=[],h.__h.length&&s.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(u,h.__s,b),g&&h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(m,E,S)})}if(h.context=b,h.props=u,h.__P=e,h.__e=!1,N=J.__r,T=0,g)h.state=h.__s,h.__d=!1,N&&N(t),p=h.render(h.props,h.state,h.context),Ur.push.apply(h.__h,h._sb),h._sb=[];else do h.__d=!1,N&&N(t),p=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++T<25);h.state=h.__s,h.getChildContext!=null&&(r=bt(bt({},r),h.getChildContext())),g&&!f&&h.getSnapshotBeforeUpdate!=null&&(S=h.getSnapshotBeforeUpdate(m,E)),O=p!=null&&p.type===_e&&p.key==null?Xs(p.props.children):p,a=Bs(e,Hn(O)?O:[O],t,n,r,o,i,s,a,l,d),h.base=t.__e,t.__u&=-161,h.__h.length&&s.push(h),w&&(h.__E=h.__=null)}catch(x){if(t.__v=null,l||i!=null)if(x.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(y=i.length;y--;)yo(i[y]);wo(t)}else t.__e=n.__e,t.__k=n.__k,x.then||wo(t);J.__e(x,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=Od(n.__e,t,n,r,o,i,s,l,d);return(p=J.diffed)&&p(t),128&t.__u?void 0:a}function wo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(wo))}function qs(e,t,n){for(var r=0;r<n.length;r++)To(n[r],n[++r],n[++r]);J.__c&&J.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){J.__e(i,o.__v)}})}function Xs(e){return typeof e!="object"||e==null||e.__b>0?e:Hn(e)?e.map(Xs):e.constructor!==void 0?null:bt({},e)}function Od(e,t,n,r,o,i,s,a,l){var d,p,h,f,m,E,S,w=n.props||Dr,u=t.props,g=t.type;if(g=="svg"?o="http://www.w3.org/2000/svg":g=="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((m=i[d])&&"setAttribute"in m==!!g&&(g?m.localName==g:m.nodeType==3)){e=m,i[d]=null;break}}if(e==null){if(g==null)return document.createTextNode(u);e=document.createElementNS(o,g,u.is&&u),a&&(J.__m&&J.__m(t,i),a=!1),i=null}if(g==null)w===u||a&&e.data==u||(e.data=u);else{if(i=g=="textarea"&&u.defaultValue!=null?null:i&&zn.call(e.childNodes),!a&&i!=null)for(w={},d=0;d<e.attributes.length;d++)w[(m=e.attributes[d]).name]=m.value;for(d in w)m=w[d],d=="dangerouslySetInnerHTML"?h=m:d=="children"||d in u||d=="value"&&"defaultValue"in u||d=="checked"&&"defaultChecked"in u||Vr(e,d,null,m,o);for(d in u)m=u[d],d=="children"?f=m:d=="dangerouslySetInnerHTML"?p=m:d=="value"?E=m:d=="checked"?S=m:a&&typeof m!="function"||w[d]===m||Vr(e,d,m,w[d],o);if(p)a||h&&(p.__html==h.__html||p.__html==e.innerHTML)||(e.innerHTML=p.__html),t.__k=[];else if(h&&(e.innerHTML=""),Bs(t.type=="template"?e.content:e,Hn(f)?f:[f],t,n,r,g=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&mn(n,0),a,l),i!=null)for(d=i.length;d--;)yo(i[d]);a&&g!="textarea"||(d="value",g=="progress"&&E==null?e.removeAttribute("value"):E!=null&&(E!==e[d]||g=="progress"&&!E||g=="option"&&E!=w[d])&&Vr(e,d,E,w[d],o),d="checked",S!=null&&S!=e[d]&&Vr(e,d,S,w[d],o))}return e}function To(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){J.__e(o,n)}}function Js(e,t,n){var r,o;if(J.unmount&&J.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||To(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){J.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Js(r[o],t,n||typeof e.type!="function");n||yo(e.__e),e.__c=e.__=e.__e=void 0}function Rd(e,t,n){return this.constructor(e,n)}function Bn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),J.__&&J.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],vo(t,e=(!r&&n||t).__k=Ze(_e,null,[e]),o||Dr,Dr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?zn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),qs(i,e,s)}function Zs(e,t){Bn(e,t,Zs)}function kd(e,t,n){var r,o,i,s,a=bt({},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?zn.call(arguments,2):n),Yn(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,bo(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"+$s++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}zn=Ur.slice,J={__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}},Us=0,dt.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=bt({},this.state),typeof e=="function"&&(e=e(bt({},n),this.props)),e&&bt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),bo(this))},dt.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),bo(this))},dt.prototype.render=_e,jt=[],Vs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,js=function(e,t){return e.__v.__b-t.__v.__b},Fr.__r=0,go=Math.random().toString(8),Lr="__d"+go,$n="__a"+go,zs=/(PointerCapture)$|Capture$/i,_o=0,Eo=Ks(!1),So=Ks(!0),$s=0;var Ad=0;function c(e,t,n,r,o,i){t||(t={});var s,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?s=t[a]:l[a]=t[a];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Ad,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)l[a]===void 0&&(l[a]=s[a]);return J.vnode&&J.vnode(d),d}var Mt,Ee,No,Qs,fn=0,ei=[],xe=J,ti=xe.__b,ni=xe.__r,ri=xe.diffed,oi=xe.__c,si=xe.unmount,ii=xe.__;function Xt(e,t){xe.__h&&xe.__h(Ee,e,fn||t),fn=0;var n=Ee.__H||(Ee.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function U(e){return fn=1,gn(li,e)}function gn(e,t,n){var r=Xt(Mt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):li(void 0,t),function(a){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,a);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=Ee,!Ee.__f)){var o=function(a,l,d){if(!r.__c.__H)return!0;var p=r.__c.__H.__.filter(function(f){return f.__c});if(p.every(function(f){return!f.__N}))return!i||i.call(this,a,l,d);var h=r.__c.props!==a;return p.some(function(f){if(f.__N){var m=f.__[0];f.__=f.__N,f.__N=void 0,m!==f.__[0]&&(h=!0)}}),i&&i.call(this,a,l,d)||h};Ee.__f=!0;var i=Ee.shouldComponentUpdate,s=Ee.componentWillUpdate;Ee.componentWillUpdate=function(a,l,d){if(this.__e){var p=i;i=void 0,o(a,l,d),i=p}s&&s.call(this,a,l,d)},Ee.shouldComponentUpdate=o}return r.__N||r.__}function j(e,t){var n=Xt(Mt++,3);!xe.__s&&ko(n.__H,t)&&(n.__=e,n.u=t,Ee.__H.__h.push(n))}function gt(e,t){var n=Xt(Mt++,4);!xe.__s&&ko(n.__H,t)&&(n.__=e,n.u=t,Ee.__h.push(n))}function X(e){return fn=5,ce(function(){return{current:e}},[])}function Co(e,t,n){fn=6,gt(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 ce(e,t){var n=Xt(Mt++,7);return ko(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function pe(e,t){return fn=8,ce(function(){return e},t)}function wt(e){var t=Ee.context[e.__c],n=Xt(Mt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(Ee)),t.props.value):e.__}function xo(e,t){xe.useDebugValue&&xe.useDebugValue(t?t(e):e)}function Id(e){var t=Xt(Mt++,10),n=U();return t.__=e,Ee.componentDidCatch||(Ee.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function Oo(){var e=Xt(Mt++,11);if(!e.__){for(var t=Ee.__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 Md(){for(var e;e=ei.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(jr),t.__h.some(Ro),t.__h=[]}catch(n){t.__h=[],xe.__e(n,e.__v)}}}xe.__b=function(e){Ee=null,ti&&ti(e)},xe.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ii&&ii(e,t)},xe.__r=function(e){ni&&ni(e),Mt=0;var t=(Ee=e.__c).__H;t&&(No===Ee?(t.__h=[],Ee.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(jr),t.__h.some(Ro),t.__h=[],Mt=0)),No=Ee},xe.diffed=function(e){ri&&ri(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(ei.push(t)!==1&&Qs===xe.requestAnimationFrame||((Qs=xe.requestAnimationFrame)||Pd)(Md)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),No=Ee=null},xe.__c=function(e,t){t.some(function(n){try{n.__h.some(jr),n.__h=n.__h.filter(function(r){return!r.__||Ro(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],xe.__e(r,n.__v)}}),oi&&oi(e,t)},xe.unmount=function(e){si&&si(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{jr(r)}catch(o){t=o}}),n.__H=void 0,t&&xe.__e(t,n.__v))};var ai=typeof requestAnimationFrame=="function";function Pd(e){var t,n=function(){clearTimeout(r),ai&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ai&&(t=requestAnimationFrame(n))}function jr(e){var t=Ee,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),Ee=t}function Ro(e){var t=Ee;e.__c=e.__(),Ee=t}function ko(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function li(e,t){return typeof t=="function"?t(e):t}function ci(e,t){for(var n in t)e[n]=t[n];return e}function Ao(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 Io(e,t){var n=t(),r=U({t:{__:n,u:t}}),o=r[0].t,i=r[1];return gt(function(){o.__=n,o.u=t,Mo(o)&&i({t:o})},[e,n,t]),j(function(){return Mo(o)&&i({t:o}),e(function(){Mo(o)&&i({t:o})})},[e]),n}function Mo(e){try{return!((t=e.__)===(n=e.u())&&(t!==0||1/t==1/n)||t!=t&&n!=n)}catch{return!0}var t,n}function Po(e){e()}function Lo(e){return e}function Do(){return[!1,Po]}var Uo=gt;function zr(e,t){this.props=e,this.context=t}function Jt(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:Ao(this.props,o)}function r(o){return this.shouldComponentUpdate=n,Ze(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(zr.prototype=new dt).isPureReactComponent=!0,zr.prototype.shouldComponentUpdate=function(e,t){return Ao(this.props,e)||Ao(this.state,t)};var di=J.__b;J.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),di&&di(e)};var Ld=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=ci({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=Ld,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var ui=function(e,t){return e==null?null:It(It(e).map(t))},st={map:ui,forEach:ui,count:function(e){return e?It(e).length:0},only:function(e){var t=It(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:It},Dd=J.__e;J.__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)}Dd(e,t,n,r)};var hi=J.unmount;function pi(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=ci({},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 pi(r,t,n)})),e}function mi(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return mi(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 Ke(){this.__u=0,this.o=null,this.__b=null}function fi(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function Qe(e){var t,n,r,o=null;function i(s){if(t||(t=e()).then(function(a){a&&(o=a.default||a),r=!0},function(a){n=a,r=!0}),n)throw n;if(!r)throw t;return o?Ze(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function _n(){this.i=null,this.l=null}J.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),hi&&hi(e)},(Ke.prototype=new dt).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=fi(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(l):l())};n.__R=s;var a=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=mi(d,d.__c.__P,d.__c.__O)}var p;for(r.setState({__a:r.__b=null});p=r.o.pop();)p.__P=a,p.forceUpdate()}};r.__u++||32&t.__u||r.setState({__a:r.__b=r.__v.__k[0]}),e.then(s,s)},Ke.prototype.componentWillUnmount=function(){this.o=[]},Ke.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]=pi(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&Ze(_e,null,e.fallback);return o&&(o.__u&=-33),[Ze(_e,null,t.__a?null:e.children),o]};var gi=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 Ud(e){return this.getChildContext=function(){return e.context},e.children}function Fd(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Bn(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)}}}Bn(Ze(Ud,{context:t.context},e.__v),t.v)}function _i(e,t){var n=Ze(Fd,{__v:e,h:t});return n.containerInfo=t,n}(_n.prototype=new dt).__a=function(e){var t=this,n=fi(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),gi(t,e,r)):o()};n?n(i):i()}},_n.prototype.render=function(e){this.i=null,this.l=new Map;var t=It(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},_n.prototype.componentDidUpdate=_n.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){gi(e,n,t)})};var Ei=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,Vd=/^(?: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]/,jd=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,zd=/[A-Z0-9]/g,$d=typeof document<"u",Hd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function Fo(e,t,n){return t.__k==null&&(t.textContent=""),Bn(e,t),typeof n=="function"&&n(),e?e.__c:null}function Si(e,t,n){return Zs(e,t),typeof n=="function"&&n(),e?e.__c:null}dt.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(dt.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var yi=J.event;J.event=function(e){return yi&&(e=yi(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Vo,Yd={configurable:!0,get:function(){return this.class}},bi=J.vnode;J.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||$d&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||Hd(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":jd.test(s)&&(s=l):l=s="oninput":i&&Vd.test(s)?s=s.replace(zd,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&o[s=l]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=It(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=It(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",Yd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=Ei,bi&&bi(e)};var vi=J.__r;J.__r=function(e){vi&&vi(e),Vo=e.__c};var wi=J.diffed;J.diffed=function(e){wi&&wi(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),Vo=null};var Ti={ReactCurrentDispatcher:{current:{readContext:function(e){return Vo.__n[e.__c].props.value},useCallback:pe,useContext:wt,useDebugValue:xo,useDeferredValue:Lo,useEffect:j,useId:Oo,useImperativeHandle:Co,useInsertionEffect:Uo,useLayoutEffect:gt,useMemo:ce,useReducer:gn,useRef:X,useState:U,useSyncExternalStore:Io,useTransition:Do}}},Bd="18.3.1";function Ni(e){return Ze.bind(null,e)}function it(e){return!!e&&e.$$typeof===Ei}function Ci(e){return it(e)&&e.type===_e}function xi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function zt(e){return it(e)?kd.apply(null,arguments):e}function jo(e){return!!e.__k&&(Bn(null,e),!0)}function Oi(e){return e&&(e.base||e.nodeType===1&&e)||null}var Ri=function(e,t){return e(t)},ki=function(e,t){var n=J.debounceRendering;J.debounceRendering=function(o){return o()};var r=e(t);return J.debounceRendering=n,r},Ai=it,Gn={useState:U,useId:Oo,useReducer:gn,useEffect:j,useLayoutEffect:gt,useInsertionEffect:Uo,useTransition:Do,useDeferredValue:Lo,useSyncExternalStore:Io,startTransition:Po,useRef:X,useImperativeHandle:Co,useMemo:ce,useCallback:pe,useContext:wt,useDebugValue:xo,version:"18.3.1",Children:st,render:Fo,hydrate:Si,unmountComponentAtNode:jo,createPortal:_i,createElement:Ze,createContext:vt,createFactory:Ni,cloneElement:zt,createRef:Hs,Fragment:_e,isValidElement:it,isElement:Ai,isFragment:Ci,isMemo:xi,findDOMNode:Oi,Component:dt,PureComponent:zr,memo:Jt,forwardRef:ee,flushSync:ki,unstable_batchedUpdates:Ri,StrictMode:_e,Suspense:Ke,SuspenseList:_n,lazy:Qe,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ti};const zo=Object.freeze(Object.defineProperty({__proto__:null,Children:st,Component:dt,Fragment:_e,PureComponent:zr,StrictMode:_e,Suspense:Ke,SuspenseList:_n,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Ti,cloneElement:zt,createContext:vt,createElement:Ze,createFactory:Ni,createPortal:_i,createRef:Hs,default:Gn,findDOMNode:Oi,flushSync:ki,forwardRef:ee,hydrate:Si,isElement:Ai,isFragment:Ci,isMemo:xi,isValidElement:it,lazy:Qe,memo:Jt,render:Fo,startTransition:Po,unmountComponentAtNode:jo,unstable_batchedUpdates:Ri,useCallback:pe,useContext:wt,useDebugValue:xo,useDeferredValue:Lo,useEffect:j,useErrorBoundary:Id,useId:Oo,useImperativeHandle:Co,useInsertionEffect:Uo,useLayoutEffect:gt,useMemo:ce,useReducer:gn,useRef:X,useState:U,useSyncExternalStore:Io,useTransition:Do,version:Bd},Symbol.toStringTag,{value:"Module"}));function Gd(e){return{render:function(t){Fo(t,e)},unmount:function(){jo(e)}}}function Ii(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function $o(...e){return t=>{let n=!1;const r=e.map(o=>{const i=Ii(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():Ii(e[o],null)}}}}function $t(...e){return pe($o(...e),e)}function Wd(e){const t=Kd(e),n=ee((r,o)=>{const{children:i,...s}=r,a=st.toArray(i),l=a.find(Xd);if(l){const d=l.props.children,p=a.map(h=>h===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:h);return c(t,{...s,ref:o,children:it(d)?zt(d,void 0,p):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Kd(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(it(o)){const s=Zd(o),a=Jd(i,o.props);return o.type!==_e&&(a.ref=r?$o(r,s):s),zt(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var qd=Symbol("radix.slottable");function Xd(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===qd}function Jd(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 Zd(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 Qd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],En=Qd.reduce((e,t)=>{const n=Wd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Zt=globalThis?.document?gt:()=>{};function eu(e,t){return gn((n,r)=>t[n][r]??n,e)}var Sn=e=>{const{present:t,children:n}=e,r=tu(t),o=typeof n=="function"?n({present:r.isPresent}):st.only(n),i=$t(r.ref,nu(o));return typeof n=="function"||r.isPresent?zt(o,{ref:i}):null};Sn.displayName="Presence";function tu(e){const[t,n]=U(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,l]=eu(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return j(()=>{const d=$r(r.current);i.current=a==="mounted"?d:"none"},[a]),Zt(()=>{const d=r.current,p=o.current;if(p!==e){const h=i.current,f=$r(d);e?l("MOUNT"):f==="none"||d?.display==="none"?l("UNMOUNT"):l(p&&h!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Zt(()=>{if(t){let d;const p=t.ownerDocument.defaultView??window,h=m=>{const E=$r(r.current).includes(CSS.escape(m.animationName));if(m.target===t&&E&&(l("ANIMATION_END"),!o.current)){const S=t.style.animationFillMode;t.style.animationFillMode="forwards",d=p.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=S)})}},f=m=>{m.target===t&&(i.current=$r(r.current))};return t.addEventListener("animationstart",f),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{p.clearTimeout(d),t.removeEventListener("animationstart",f),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:pe(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function $r(e){return e?.animationName||"none"}function nu(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}function Mi(e,t=[]){let n=[];function r(i,s){const a=vt(s),l=n.length;n=[...n,s];const d=h=>{const{scope:f,children:m,...E}=h,S=f?.[e]?.[l]||a,w=ce(()=>E,Object.values(E));return c(S.Provider,{value:w,children:m})};d.displayName=i+"Provider";function p(h,f){const m=f?.[e]?.[l]||a,E=wt(m);if(E)return E;if(s!==void 0)return s;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,p]}const o=()=>{const i=n.map(s=>vt(s));return function(s){const a=s?.[e]||i;return ce(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,ru(o,...t)]}function ru(...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:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ce(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function Ht(e){const t=X(e);return j(()=>{t.current=e}),ce(()=>(...n)=>t.current?.(...n),[])}var ou=vt(void 0);function su(e){const t=wt(ou);return e||t||"ltr"}function iu(e,[t,n]){return Math.min(n,Math.max(t,e))}function Yt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function au(e,t){return gn((n,r)=>t[n][r]??n,e)}var Ho="ScrollArea",[Pi]=Mi(Ho),[lu,ut]=Pi(Ho),Li=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,l]=U(null),[d,p]=U(null),[h,f]=U(null),[m,E]=U(null),[S,w]=U(null),[u,g]=U(0),[_,b]=U(0),[N,T]=U(!1),[O,y]=U(!1),v=$t(t,P=>l(P)),x=su(o);return c(lu,{scope:n,type:r,dir:x,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:p,content:h,onContentChange:f,scrollbarX:m,onScrollbarXChange:E,scrollbarXEnabled:N,onScrollbarXEnabledChange:T,scrollbarY:S,onScrollbarYChange:w,scrollbarYEnabled:O,onScrollbarYEnabledChange:y,onCornerWidthChange:g,onCornerHeightChange:b,children:c(En.div,{dir:x,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":u+"px","--radix-scroll-area-corner-height":_+"px",...e.style}})})});Li.displayName=Ho;var Di="ScrollAreaViewport",Ui=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=ut(Di,n),a=X(null),l=$t(t,a,s.onViewportChange);return c(_e,{children:[c("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}),c(En.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ui.displayName=Di;var Tt="ScrollAreaScrollbar",Yo=ee((e,t)=>{const{forceMount:n,...r}=e,o=ut(Tt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return j(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?c(cu,{...r,ref:t,forceMount:n}):o.type==="scroll"?c(du,{...r,ref:t,forceMount:n}):o.type==="auto"?c(Fi,{...r,ref:t,forceMount:n}):o.type==="always"?c(Bo,{...r,ref:t}):null});Yo.displayName=Tt;var cu=ee((e,t)=>{const{forceMount:n,...r}=e,o=ut(Tt,e.__scopeScrollArea),[i,s]=U(!1);return j(()=>{const a=o.scrollArea;let l=0;if(a){const d=()=>{window.clearTimeout(l),s(!0)},p=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",p),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",p)}}},[o.scrollArea,o.scrollHideDelay]),c(Sn,{present:n||i,children:c(Fi,{"data-state":i?"visible":"hidden",...r,ref:t})})}),du=ee((e,t)=>{const{forceMount:n,...r}=e,o=ut(Tt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Gr(()=>l("SCROLL_END"),100),[a,l]=au("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 j(()=>{if(a==="idle"){const d=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,l]),j(()=>{const d=o.viewport,p=i?"scrollLeft":"scrollTop";if(d){let h=d[p];const f=()=>{const m=d[p];h!==m&&(l("SCROLL"),s()),h=m};return d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[o.viewport,i,l,s]),c(Sn,{present:n||a!=="hidden",children:c(Bo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:Yt(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:Yt(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Fi=ee((e,t)=>{const n=ut(Tt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=U(!1),a=e.orientation==="horizontal",l=Gr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,p=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:p)}},10);return yn(n.viewport,l),yn(n.content,l),c(Sn,{present:r||i,children:c(Bo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Bo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=ut(Tt,e.__scopeScrollArea),i=X(null),s=X(0),[a,l]=U({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Hi(a.viewport,a.content),p={...r,sizes:a,onSizesChange:l,hasThumb:d>0&&d<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function h(f,m){return gu(f,s.current,a,m)}return n==="horizontal"?c(uu,{...p,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollLeft,m=Yi(f,a,o.dir);i.current.style.transform=`translate3d(${m}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=h(f,o.dir))}}):n==="vertical"?c(hu,{...p,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const f=o.viewport.scrollTop,m=Yi(f,a);i.current.style.transform=`translate3d(0, ${m}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=h(f))}}):null}),uu=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ut(Tt,e.__scopeScrollArea),[s,a]=U(),l=X(null),d=$t(t,l,i.onScrollbarXChange);return j(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ji,{"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":Br(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,h)=>{if(i.viewport){const f=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(f),Gi(f,h)&&p.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Yr(s.paddingLeft),paddingEnd:Yr(s.paddingRight)}})}})}),hu=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=ut(Tt,e.__scopeScrollArea),[s,a]=U(),l=X(null),d=$t(t,l,i.onScrollbarYChange);return j(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ji,{"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":Br(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,h)=>{if(i.viewport){const f=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(f),Gi(f,h)&&p.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Yr(s.paddingTop),paddingEnd:Yr(s.paddingBottom)}})}})}),[pu,Vi]=Pi(Tt),ji=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:d,onWheelScroll:p,onResize:h,...f}=e,m=ut(Tt,n),[E,S]=U(null),w=$t(t,v=>S(v)),u=X(null),g=X(""),_=m.viewport,b=r.content-r.viewport,N=Ht(p),T=Ht(l),O=Gr(h,10);function y(v){if(u.current){const x=v.clientX-u.current.left,P=v.clientY-u.current.top;d({x,y:P})}}return j(()=>{const v=x=>{const P=x.target;E?.contains(P)&&N(x,b)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[_,E,b,N]),j(T,[r,T]),yn(E,O),yn(m.content,O),c(pu,{scope:n,scrollbar:E,hasThumb:o,onThumbChange:Ht(i),onThumbPointerUp:Ht(s),onThumbPositionChange:T,onThumbPointerDown:Ht(a),children:c(En.div,{...f,ref:w,style:{position:"absolute",...f.style},onPointerDown:Yt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),u.current=E.getBoundingClientRect(),g.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",m.viewport&&(m.viewport.style.scrollBehavior="auto"),y(v))}),onPointerMove:Yt(e.onPointerMove,y),onPointerUp:Yt(e.onPointerUp,v=>{const x=v.target;x.hasPointerCapture(v.pointerId)&&x.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=g.current,m.viewport&&(m.viewport.style.scrollBehavior=""),u.current=null})})})}),Hr="ScrollAreaThumb",zi=ee((e,t)=>{const{forceMount:n,...r}=e,o=Vi(Hr,e.__scopeScrollArea);return c(Sn,{present:n||o.hasThumb,children:c(mu,{ref:t,...r})})}),mu=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=ut(Hr,n),s=Vi(Hr,n),{onThumbPositionChange:a}=s,l=$t(t,h=>s.onThumbChange(h)),d=X(void 0),p=Gr(()=>{d.current&&(d.current(),d.current=void 0)},100);return j(()=>{const h=i.viewport;if(h){const f=()=>{if(p(),!d.current){const m=_u(h,a);d.current=m,a()}};return a(),h.addEventListener("scroll",f),()=>h.removeEventListener("scroll",f)}},[i.viewport,p,a]),c(En.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:Yt(e.onPointerDownCapture,h=>{const f=h.target.getBoundingClientRect(),m=h.clientX-f.left,E=h.clientY-f.top;s.onThumbPointerDown({x:m,y:E})}),onPointerUp:Yt(e.onPointerUp,s.onThumbPointerUp)})});zi.displayName=Hr;var Go="ScrollAreaCorner",$i=ee((e,t)=>{const n=ut(Go,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c(fu,{...e,ref:t}):null});$i.displayName=Go;var fu=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=ut(Go,n),[i,s]=U(0),[a,l]=U(0),d=!!(i&&a);return yn(o.scrollbarX,()=>{const p=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(p),l(p)}),yn(o.scrollbarY,()=>{const p=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(p),s(p)}),d?c(En.div,{...r,ref:t,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}}):null});function Yr(e){return e?parseInt(e,10):0}function Hi(e,t){const n=e/t;return isNaN(n)?0:n}function Br(e){const t=Hi(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function gu(e,t,n,r="ltr"){const o=Br(n),i=o/2,s=t||i,a=o-s,l=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-a,p=n.content-n.viewport,h=r==="ltr"?[0,p]:[p*-1,0];return Bi([l,d],h)(e)}function Yi(e,t,n="ltr"){const r=Br(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],d=iu(e,l);return Bi([0,s],[0,a])(d)}function Bi(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Gi(e,t){return e>0&&e<t}var _u=(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 Gr(e,t){const n=Ht(e),r=X(0);return j(()=>()=>window.clearTimeout(r.current),[]),pe(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function yn(e,t){const n=Ht(t);Zt(()=>{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 Wi=Li,Eu=Ui,Su=$i;function yu(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 bn={},Wn={},Ki={},Kn={},qn={},Xn={},qi;function Wo(){if(qi)return Xn;qi=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.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 Xn.EventEmitter=e,Xn}var vn={},Xi;function Jn(){return Xi||(Xi=1,Object.defineProperty(vn,"__esModule",{value:!0}),vn.DisconnectionReason=vn.ConnectionStatus=void 0,vn.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},vn.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"}),vn}var Ji;function Ko(){if(Ji)return qn;Ji=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.BaseConnection=void 0;const e=Wo(),t=Jn();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 qn.BaseConnection=n,qn}var Zi={},Qi;function at(){return Qi||(Qi=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=N,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(y,v=e.SynapseErrorCode.UNKNOWN,x={}){super(y);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=v,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||y,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(y,v,x,P){const G=n.makeMessage(v,x,y);super(G,e.SynapseErrorCode.API,{cause:x,context:{status:v,hasBody:!!x},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:y||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=x,this.headers=P}static makeMessage(y,v,x){const P=v instanceof Error?v.message:x;return y&&P?`HTTP ${y}: ${P}`:y?`${y} status code (no body)`:P||"(no status code or body)"}static generate(y,v,x,P){if(!y)return new r({message:x});const G=v?.error,W=G&&typeof G=="object"&&!Array.isArray(G)?G:void 0;switch(y){case 400:return new i(x||"Bad Request",y,W,P);case 401:return new s(x||"Unauthorized",y,W,P);case 403:return new a(x||"Permission Denied",y,W,P);case 404:return new l(x||"Not Found",y,W,P);case 405:return new d(x||"Method Not Allowed",y,W,P);case 429:return new p(x||"Rate Limit Exceeded",y,W,P);case 500:return new h(x||"Internal Server Error",y,W,P);default:return new n(x||"API Error",y,W,P)}}}e.APIError=n;class r extends n{constructor({message:O}={}){super(O||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:O}={}){super(O||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class l extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="NotFoundError"}}e.NotFoundError=l;class d extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class p extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="RateLimitError"}}e.RateLimitError=p;class h extends n{constructor(O,y,v,x){super(O,y,v,x),this.name="InternalServerError"}}e.InternalServerError=h;class f extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.CONNECTION,y),this.name="ConnectionError"}}e.ConnectionError=f;class m extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.RECORDING,y),this.name="RecordingError"}}e.RecordingError=m;class E extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.AUTH,y),this.name="AuthenticationError"}}e.AuthenticationError=E;class S extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.FILE,y),this.name="FileError"}}e.FileError=S;class w extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.SESSION,y),this.name="SessionError"}}e.SessionError=w;class u extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.MESSAGE,y),this.name="MessageError"}}e.MessageError=u;class g extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.STORE,y),this.name="StoreError"}}e.StoreError=g;class _ extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.CONFIGURATION,y),this.name="ConfigurationError"}}e.ConfigurationError=_;class b extends t{constructor(O,y={}){super(O,e.SynapseErrorCode.VALIDATION,y),this.name="ValidationError"}}e.ValidationError=b;function N(T,O,y,v={}){if(T instanceof O)return T;const x={...v,context:{...T instanceof t?T.context:void 0,...v.context},hint:v.hint??(T instanceof t?T.hint:void 0),reason:v.reason??(T instanceof t?T.reason:void 0),cause:v.cause??T};if(T instanceof t)return new O(T.message,x);const P=T instanceof Error&&T.message?T.message:y;return new O(P,x)}})(Zi)),Zi}var ea;function ta(){if(ea)return Kn;ea=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.WebSocketConnection=void 0;const e=Ko(),t=Jn(),n=at();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 l=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(l)}}handleError(s){}handleClose(s){const a=s.wasClean,l=s.code,d=s.reason;let p,h;this.authenticated=!1,!this.isConnected()&&(l===1e3?(p=t.DisconnectionReason.CLIENT_CLOSED,h="Connection closed normally"):l===1001||l===1006?(p=t.DisconnectionReason.NETWORK_ERROR,h=s.reason||"Network connection lost"):l===4001||l===1008?s.reason==="timeout"||s.reason==="Authentication timeout"?(p=t.DisconnectionReason.TIMEOUT,h="Connection timed out"):(p=t.DisconnectionReason.AUTHENTICATION_ERROR,h=s.reason||"Authentication failed"):l===4401||l===4403?(p=t.DisconnectionReason.AUTHENTICATION_ERROR,h=s.reason||(l===4401?"Session token expired":"Session credentials rejected")):l===4404?(p=t.DisconnectionReason.SERVER_CLOSED,h=s.reason||"Session no longer exists"):l===1013?(p=t.DisconnectionReason.SERVER_CLOSED,h=s.reason||"Server busy, try again later"):a?(p=t.DisconnectionReason.SERVER_CLOSED,h=d||"Server closed connection"):(p=t.DisconnectionReason.CONNECTION_ERROR,h=d||"Connection closed unexpectedly"),this.disconnect({reason:p,message:h,code:l,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 l=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(l),l}}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 Kn.WebSocketConnection=r,Kn}var Zn={},na={},ra;function Wr(){return ra||(ra=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",MCP:"mcp"},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)}})(na)),na}var oa={},sa;function ia(){return sa||(sa=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})(oa)),oa}var aa;function la(){if(aa)return Zn;aa=1,Object.defineProperty(Zn,"__esModule",{value:!0}),Zn.SSEConnection=void 0;const e=Ko(),t=Jn(),n=Wr(),r=ia(),o=at();class i extends e.BaseConnection{constructor(l){super();R(this,"conversationId");R(this,"config");R(this,"connected",!1);R(this,"activeStreamController",null);this.config=l,this.conversationId=l.auth.sessionId,this.connect()}connect(){this.updateStatus(t.ConnectionStatus.CONNECTING),this.connected=!0,setTimeout(()=>{this.onOpenCallback?.()},0)}onOpen(l){this.onOpenCallback=l,this.connected&&setTimeout(()=>l(),0)}buildChatUrl(){const l=new URL(this.config.serverUrl);return l.pathname=`${l.pathname.replace(/\/$/,"")}/med-assist/session/${this.config.auth.sessionId}/chat`,l.toString()}sendMessage(l){if(!this.connected){const p=new o.ConnectionError("SSE connection is not open",{context:{stage:"sendMessage"}});this.onErrorCallback?.(p);return}if(l.ev===n.SOCKET_EVENTS.CHAT&&"ct"in l&&l.ct===n.SOCKET_CONTENT_TYPES.MCP){this.postSideChannel(l);return}this.activeStreamController?.abort();const d=new AbortController;this.activeStreamController=d,this.streamChat(l,d)}async postSideChannel(l){const d=this.buildChatUrl(),p=new AbortController;try{let h=await this.postChat(d,l,p);if(h.status===401&&this.config.auth.onUnauthorized&&await this.config.auth.onUnauthorized()&&(h=await this.postChat(d,l,p)),!h.ok)throw new o.APIError("Failed to send client-tool reply",h.status,{});await h.body?.cancel()}catch(h){this.onErrorCallback?.(h instanceof o.APIError?h:(0,o.normalizeError)(h,o.ConnectionError,"Client-tool reply failed",{context:{stage:"postSideChannel"}}))}}postChat(l,d,p){return fetch(l,{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??r.DEFAULT_CHANNEL},body:JSON.stringify(d),signal:p.signal})}async streamChat(l,d){const p=this.buildChatUrl();try{let h=await this.postChat(p,l,d);if(h.status===401&&this.config.auth.onUnauthorized){const S=await this.config.auth.onUnauthorized();if(d.signal.aborted)return;S&&(h=await this.postChat(p,l,d))}if(!h.ok||!h.body)throw new o.APIError("Failed to send message to http stream",h.status,h.body||{});const f=h.body.getReader(),m=new TextDecoder;let E="";for(;;){const{done:S,value:w}=await f.read();if(S)break;E+=m.decode(w,{stream:!0}),E=this.extractJsonObjects(E)}E.trim().length>0&&this.extractJsonObjects(E)}catch(h){if(d.signal.aborted)return;const f=h instanceof o.APIError?h:(0,o.normalizeError)(h,o.ConnectionError,"SSE chat stream failed",{context:{stage:"streamChat"}});this.onErrorCallback?.(f)}finally{this.activeStreamController===d&&(this.activeStreamController=null)}}extractJsonObjects(l){let d=0;for(;d<l.length;){const p=l.indexOf("{",d);if(p===-1)return"";const h=this.findObjectEnd(l,p);if(h===-1)return l.slice(p);const f=l.slice(p,h+1);try{const m=JSON.parse(f);this.handleMessage(m)}catch(m){const E=(0,o.normalizeError)(m,o.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:f}});this.onErrorCallback?.(E)}d=h+1}return""}findObjectEnd(l,d){let p=0,h=!1,f=!1;for(let m=d;m<l.length;m++){const E=l[m];if(h){f?f=!1:E==="\\"?f=!0:E==='"'&&(h=!1);continue}if(E==='"')h=!0;else if(E==="{")p++;else if(E==="}"&&(p--,p===0))return m}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 Zn.SSEConnection=i,Zn}var ca;function da(){return ca||(ca=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=ta(),n=la(),r=at();e.ConnectionType={SOCKET:"socket",HTTP_STREAM:"http_stream"};class o{static async createConnection(s,a){switch(s){case e.ConnectionType.SOCKET:return new t.WebSocketConnection(a);case e.ConnectionType.HTTP_STREAM:return new n.SSEConnection(a);default:throw new r.ConnectionError(`Unsupported connection type: ${s}`,{context:{type:s}})}}}e.ConnectionFactory=o})(Ki)),Ki}var Qn={},ua;function qo(){if(ua)return Qn;ua=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix-ws.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix-ws.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 Qn.getConfig=r,Qn}var er={},tr={},ha;function Kr(){if(ha)return tr;ha=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.HttpClient=void 0;const e=at();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 l=this.buildUrl(r,o?.params),d=await fetch(l,{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(l){if(s=l,a===i||!(l instanceof TypeError&&l.message==="Failed to fetch"||l instanceof DOMException&&l.name==="AbortError"||l instanceof SyntaxError))break;const d=Math.pow(2,a)*100;await new Promise(p=>setTimeout(p,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 tr.HttpClient=t,tr}var nr={},rr={},pa;function or(){if(pa)return rr;pa=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.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 rr.BaseResource=e,rr}var ma;function fa(){if(ma)return nr;ma=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.Session=void 0;const e=or();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:l}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...l&&{nps_base5:l}})}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 nr.Session=t,nr}var sr={},ga;function Xo(){if(ga)return sr;ga=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.Config=void 0;const e=or();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 sr.Config=t,sr}var _a={},Ea;function Sa(){return Ea||(Ea=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Kr(),n=qo(),r=Xo(),o=new Map,i=(l,d)=>`${l.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(l){const d=l.serverUrl||(0,n.getConfig)(l.environment).BASE_API_URL,p=(0,e.buildAgentConfigKey)(d,l.agentId),h=o.get(p);if(h)return h;const f=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":l.agentId,...l.channel&&{"x-channel":l.channel}}}),m=new r.Config(f).retrieve(l.agentId);return m.catch(()=>{o.get(p)===m&&o.delete(p)}),o.set(p,m),m}function a(l){const d=o.get(l);return d&&o.delete(l),d}})(_a)),_a}var ir={},ya;function Jo(){if(ya)return ir;ya=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.Auth=void 0;const e=or();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 ir.Auth=t,ir}var ar={},wn={},ba;function Zo(){return ba||(ba=1,Object.defineProperty(wn,"__esModule",{value:!0}),wn.ErrorType=wn.SYNAPSE_RECOVERY_REASON=void 0,wn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},wn.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"}),wn}var lr={},va;function Qo(){if(va)return lr;va=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.ErrorUtils=void 0;const e=at();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 lr.ErrorUtils=t,lr}var wa={},Ta;function Na(){return Ta||(Ta=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=l;const t=Kr(),n=qo(),r=Qo(),o=Jo(),i=new Map,s=(d,p,h)=>`${d.replace(/\/$/,"")}|${p}|${h??""}`;e.buildPrefetchKey=s;function a(d){const p=d.serverUrl||(0,n.getConfig)(d.environment).BASE_API_URL,h=(0,e.buildPrefetchKey)(p,d.agentId,d.authToken),f=i.get(h);if(f)return f;const m=new t.HttpClient({baseUrl:p,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),E=new o.Auth(m).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return E.catch(S=>{r.ErrorUtils.isAuthError(S)||i.get(h)===E&&i.delete(h)}),i.set(h,E),E}function l(d){const p=i.get(d);return p&&i.delete(d),p}})(wa)),wa}var Ca;function bu(){if(Ca)return ar;Ca=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.TokenManager=void 0;const e=at(),t=Zo(),n=Qo(),r=Na();let o=class{constructor(i,s,a,l){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=l.partnerAuthToken,this.refreshToken=l.refreshToken,this.onTokenExchange=l.onTokenExchange,this._level=l.level,this._userId=l.userId,l.sessToken&&(this.sessToken=l.sessToken,this.httpClient.setAuthorization(l.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(l.serverUrl,a,l.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,l){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,l,{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 ar.TokenManager=o,ar}var cr={},xa;function vu(){var n;if(xa)return cr;xa=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.VoiceResource=void 0;const e=or();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 cr.VoiceResource=t,cr}var Oa;function Ra(){if(Oa)return er;Oa=1,Object.defineProperty(er,"__esModule",{value:!0}),er.ResourceManager=void 0;const e=Kr(),t=fa(),n=at(),r=Xo(),o=Sa(),i=Jo(),s=bu(),a=vu();class l{constructor(p){R(this,"resourceConfig");R(this,"httpClient");R(this,"session");R(this,"config");R(this,"auth");R(this,"tokenManager");R(this,"voiceResource");this.resourceConfig=p,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(p){this.httpClient.setUnauthorizedHandler(p)}clearTokens(){this.tokenManager.clearTokens()}clearAll(){this.tokenManager.clearAll()}async createSession(p,h){try{const{profile:f,intent:m,user_location:E,referer:S,...w}=h||{},u=this.tokenManager.userId||p,g={...u&&{user_id:u},...f&&{user_context:f},...(m||Object.keys(w).length>0)&&{session_context:{...m&&{intent:m},...E&&{user_location:E},...w}},...S&&{referer:S}},_=await this.session.create(g);if(!_?.session_id)throw new n.APIError("Failed to start session.",500,void 0,void 0);return _}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 p=(0,o.consumePrefetchedAgentConfig)((0,o.buildAgentConfigKey)(this.resourceConfig.serverUrl,this.resourceConfig.agentId));if(p)try{return await p}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(p){return await this.session.retrieve(p)}async getPastSessions(){return await this.session.history()}async getSessionMessages(p){return(await this.session.retrieve(p,{includeMessages:!0}))?.messages??[]}async refreshTokens(){return await this.tokenManager.refresh()}async sendFeedback({sessionId:p,messageId:h,feedback:f,feedbacks:m,feedbackReason:E,npsBase5:S}){return await this.session.feedback({sessionId:p,messageId:h,feedback:f,feedbacks:m,feedbackReason:E,npsBase5:S})}async callTool(p,h,f,m){return await this.session.callTool(p,h,f,m)}async getVoiceIceServers(p){return await this.voiceResource.getIceServers(p,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(p){return await this.voiceResource.sendOffer(p)}}return er.ResourceManager=l,er}var dr={},ka={},Aa;function wu(){return Aa||(Aa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=at();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[]);R(this,"pendingSizes",[])}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),this.pendingSizes=s.map(a=>a.size)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[],sizes:this.pendingSizes||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.map((a,l)=>({entry:a,file:this.pendingFiles[l]})).filter(({entry:a,file:l})=>l&&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{entry:l,file:d}=s[a],p=await fetch(l.url,this.buildUploadRequest(l,d));if(!p.ok)throw new t.FileError(`Failed to upload ${d.name} to URL ${a+1}: ${p.status} ${p.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(l.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"}})}}buildUploadRequest(o,i){if(o.fields){const s=new FormData;for(const[a,l]of Object.entries(o.fields))s.append(a,l);return s.append("file",i),{method:"POST",body:s}}return{method:"PUT",body:i,headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"}}}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=[],this.pendingSizes=[]}}e.Filemanager=n})(ka)),ka}var _t={},Ia;function qr(){if(Ia)return _t;Ia=1,Object.defineProperty(_t,"__esModule",{value:!0}),_t.SYNAPSE_REALTIME_RESERVED_EVENTS=_t.SYNAPSE_REALTIME_ERROR_CODES=_t.SYNAPSE_REALTIME_EVENTS=_t.SYNAPSE_MESSAGE_TYPES=void 0;const e=Wr();return _t.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,_t.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",CLIENT_TOOL_CALL:"client_tool_call",CLIENT_TOOL_PROGRESS:"client_tool_progress",CLIENT_TOOL_RESULT:"client_tool_result"},_t.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"},_t.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},_t}var ur={},Ma;function Tu(){if(Ma)return ur;Ma=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.AudioManager=void 0;const e=at();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 ur.AudioManager=t,ur}var Pa;function La(){if(Pa)return dr;Pa=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.MessageManager=void 0;const e=Wr(),t=wu(),n=qr(),r=Tu(),o=at();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);R(this,"clientToolRuntime",null);this.callbacks=s||null}setConnection(s){this.connection=s}setClientToolRuntime(s){this.clientToolRuntime=s}sendMcpMessage(s){const a=this.assertConnection("sendMcpMessage");if(!a.isConnected()){const d=new o.ConnectionError("Connection is not open",{context:{stage:"sendMcpMessage"}});throw this.emitError(d),d}const l={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.MCP,_id:Date.now().toString(),ts:Date.now(),data:s};a.sendMessage(l)}handleFileUploadProcess({files:s,message:a,urls:l,tool_declined:d,tool_result:p,client_tools:h}){this.fileManager||(this.fileManager=new t.Filemanager);let f;if(s&&s.length>0)this.fileManager.setFilesForUpload(s,a),f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{extensions:this.fileManager.getPendingFileState().formats,file_sizes:this.fileManager.getPendingFileState().sizes,...d&&{tool_declined:d},...p&&{tool_result:p},...h&&{client_tools:h}}};else if(l&&l.length>0){const m=this.fileManager.getPendingFileState().message;f={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.FILE,_id:Date.now().toString(),ts:Date.now(),data:{urls:l,...m&&{text:m},...d&&{tool_declined:d},...p&&{tool_result:p}}},this.fileManager?.clearPendingFilesState()}return f}sendSocketMessage({message:s,files:a,audio:l,urls:d,tool_declined:p,tool_id:h,tool_result:f,initial_prompts:m,client_tools:E}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...l&&{audio:l},...d&&{urls:d},...p&&{tool_declined:p},...h&&{tool_id:h},...f&&{tool_result:f},...m&&{initial_prompts:m},...E&&{client_tools:E}};return}const S=this.connection;let w;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const u=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(u),u}w=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:p,tool_result:f,client_tools:E})}else s?w={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:s,...p&&{tool_declined:p},...h&&{tool_id:h},...m&&{initial_prompts:m},...f&&{tool_result:f},...E&&{client_tools:E}}}:l&&l?.audio&&l?.format?w={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:l?.audio,format:l?.format,...p&&{tool_declined:p},...f&&{tool_result:f},...E&&{client_tools:E}}}:f&&(w={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",...h&&{tool_id:h},tool_result:f,...E&&{client_tools:E}}});if(!w){const u=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(u),u}S.sendMessage(w)}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(l=>{this.sendSocketMessage({urls:l})}).catch(l=>{const d=this.toFileError(l,"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 l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,l)}break;case e.SOCKET_CONTENT_TYPES.MCP:this.clientToolRuntime?.handleMessage(s.data,{messageId:s._id});break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const l={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,l)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,l)}break}}handleIncomingSocketStreamMessage(s){const a=this.assertConnection("handleIncomingSocketStreamMessage");switch(s.ct){case e.SOCKET_CONTENT_TYPES.TEXT:if(s?.data?.progress_msg){const h={data:{text:s.data.progress_msg},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,h);return}if(s?.data?.text){const h={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,h)}break;case e.SOCKET_CONTENT_TYPES.TIPS:if(s?.data?.tips){const h={data:{tips:s.data.tips},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TIPS_MESSAGE,h);return}break;case e.SOCKET_CONTENT_TYPES.MCP:this.clientToolRuntime?.handleMessage(s.data,{messageId:s._id});break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const h={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,h);return}break;case e.SOCKET_CONTENT_TYPES.TOOL_START:const l={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,l);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 p=new o.MessageError(`Unsupported content type ${s?.ct}`,{context:{stage:"handleIncomingSocketStreamMessage",contentType:s.ct}});throw this.emitError(p),p}}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 l=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"),l={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(l)}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 l=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(l),l}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,l=>{const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(l){const d=this.toRecordingError(l,"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,l,d){return(0,o.normalizeError)(s,o.FileError,a,{context:l,hint:d})}toRecordingError(s,a,l,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:l,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 dr.MessageManager=i,dr}var Da={},Ua;function Nu(){return Ua||(Ua=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})(Da)),Da}var hr={},pr={},Fa;function Cu(){if(Fa)return pr;Fa=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.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),l=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((p,h)=>p+h,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(l)};l()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return pr.VoiceAudioAnalyser=t,pr}var Tn={},Va;function ja(){return Va||(Va=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.VOICE_AGENT_EVENTS=Tn.VOICE_AGENT_STATE=void 0,Tn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Tn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Tn}var za;function xu(){if(za)return hr;za=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.VoiceAgent=void 0;const e=Wo(),t=Cu(),n=at(),r=ja(),o=3e3,i=8,s=3600*1e3,a=600;function l(p,h){return new Promise(f=>{if(p.iceGatheringState==="complete"){f();return}const m=setTimeout(f,h);p.onicegatheringstatechange=()=>{p.iceGatheringState==="complete"&&(clearTimeout(m),f())}})}let d=class{constructor(p,h,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=p,this.resourceManager=h,this.getCredentials=f}get state(){return this._state}get isMuted(){return this._isMuted}on(p,h){this.emitter.on(p,h)}off(p,h){this.emitter.off(p,h)}async connect(){const p=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 h=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:16e3},video:!1});this.localStream=h;const f=await this.fetchIceServers(p),m=new RTCPeerConnection({iceServers:f,iceTransportPolicy:"all"});this.pc=m,this.dataChannel=m.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"),h.getAudioTracks().forEach(g=>m.addTrack(g,h)),m.ontrack=g=>this.handleRemoteTrack(g),m.onconnectionstatechange=()=>{m.connectionState==="connected"?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(h)):(m.connectionState==="failed"||m.connectionState==="closed")&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))},m.oniceconnectionstatechange=()=>{(m.iceConnectionState==="connected"||m.iceConnectionState==="completed")&&this._state===r.VOICE_AGENT_STATE.CONNECTING?(this.setState(r.VOICE_AGENT_STATE.LISTENING),this.startLocalAudioAnalysis(h)):m.iceConnectionState==="failed"&&(this.releaseResources(),this.setState(r.VOICE_AGENT_STATE.IDLE))};const E=await m.createOffer();await m.setLocalDescription(E);const S=this.config.iceGatheringTimeoutMs??o;await l(m,S);const w=g=>({sdp:m.localDescription.sdp,type:m.localDescription.type,pc_id:this.pcId,request_data:{session_id:g.sessionId,token:g.sessionToken}});let u;try{u=await this.resourceManager.sendVoiceOffer(w(p))}catch(g){if(g instanceof n.APIError&&g.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const _=await this.getCredentials();u=await this.resourceManager.sendVoiceOffer(w(_))}else throw g}if(!u)throw new Error("No answer received from voice offer");if(this.pcId=u.pc_id,m.signalingState==="closed")return;await m.setRemoteDescription(new RTCSessionDescription({sdp:u.sdp,type:u.type}))}catch(h){this.handleConnectionFailure(h)}}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 p=this.localStream.getAudioTracks()[0];if(!p)return;const h=p.enabled;this.localStream.getAudioTracks().forEach(f=>{f.enabled=!h}),this._isMuted=h,this.clearSilenceTimer(),this._userSpeaking=!1,this.setState(h?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(p){if(this.config.iceServers)return this.config.iceServers;const h=Date.now();if(this._cachedIceServers&&h-this._iceServersCachedAt<s)return this._cachedIceServers;let f;try{f=await this.resourceManager.getVoiceIceServers(p.sessionId)}catch(m){if(m instanceof n.APIError&&m.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const E=await this.getCredentials();f=await this.resourceManager.getVoiceIceServers(E.sessionId)}else throw m}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(p){this._state=p,this.emitter.emit(r.VOICE_AGENT_EVENTS.STATE_CHANGED,p)}clearSilenceTimer(){this._silenceTimer!==null&&(clearTimeout(this._silenceTimer),this._silenceTimer=null)}handleConnectionFailure(p,h="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:h,cause:p};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(p=>p.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(p){const h=this.config.speakingThreshold??i;this.localAnalyser.start(p,h,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(p){this.remoteAudio||(this.remoteAudio=new Audio,this.remoteAudio.autoplay=!0);const h=p.streams[0];this.remoteAudio.srcObject=h;const f=this.config.speakingThreshold??i;this.remoteAnalyser.start(h,f,m=>{m?(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 hr.VoiceAgent=d,hr}var mr={},Nn={},$a;function Ha(){if($a)return Nn;$a=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.canonicalJson=e,Nn.fnv1a64Hex=n,Nn.hashDeclarations=r;function e(o){return JSON.stringify(t(o))}function t(o){if(Array.isArray(o))return o.map(t);if(o&&typeof o=="object"){const i=o,s={};for(const a of Object.keys(i).sort())i[a]!==void 0&&(s[a]=t(i[a]));return s}return o}function n(o){const i=0x100000001b3n,s=0xffffffffffffffffn;let a=0xcbf29ce484222325n;for(const l of new TextEncoder().encode(o))a^=BigInt(l),a=a*i&s;return a.toString(16).padStart(16,"0")}function r(o){const i=[...o].sort((s,a)=>s.name.localeCompare(a.name));return n(e(i))}return Nn}var je={},Ya;function fr(){return Ya||(Ya=1,Object.defineProperty(je,"__esModule",{value:!0}),je.JSON_RPC_ERRORS=je.MCP_METHODS=je.CLIENT_TOOL_ERROR_CODES=je.CLIENT_TOOL_NAME_PATTERN=je.CLIENT_TOOL_PROGRESS_THROTTLE_MS=je.CLIENT_TOOL_DEFAULT_TIMEOUT_MS=je.CLIENT_TOOLS_MAX_RESULT_BYTES=je.CLIENT_TOOLS_PROTOCOL_VERSION=void 0,je.CLIENT_TOOLS_PROTOCOL_VERSION="1",je.CLIENT_TOOLS_MAX_RESULT_BYTES=262144,je.CLIENT_TOOL_DEFAULT_TIMEOUT_MS=3e4,je.CLIENT_TOOL_PROGRESS_THROTTLE_MS=250,je.CLIENT_TOOL_NAME_PATTERN=/^[a-zA-Z0-9_-]{1,64}$/,je.CLIENT_TOOL_ERROR_CODES={EXECUTION_FAILED:"execution_failed",TIMEOUT:"timeout",RESULT_TOO_LARGE:"result_too_large"},je.MCP_METHODS={TOOLS_CALL:"tools/call",CANCELLED:"notifications/cancelled",PROGRESS:"notifications/progress"},je.JSON_RPC_ERRORS={METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,CANCELLED:-32800}),je}var Ba;function Ga(){if(Ba)return mr;Ba=1,Object.defineProperty(mr,"__esModule",{value:!0}),mr.ClientToolRegistry=void 0;const e=Ha(),t=fr();class n{constructor(){R(this,"tools",new Map);R(this,"cachedHash",null)}register(i){const s=new Map;for(const a of i){if(r(a),s.has(a.name))throw new Error(`Client tool "${a.name}" is registered twice`);s.set(a.name,a)}this.tools=s,this.cachedHash=null}get(i){return this.tools.get(i)}size(){return this.tools.size}declarations(){return[...this.tools.values()].sort((i,s)=>i.name.localeCompare(s.name)).map(i=>({name:i.name,description:i.description,inputSchema:i.inputSchema,...i.outputSchema&&{outputSchema:i.outputSchema},...i.annotations&&{annotations:i.annotations}}))}hash(){return this.cachedHash===null&&(this.cachedHash=(0,e.hashDeclarations)(this.declarations())),this.cachedHash}}mr.ClientToolRegistry=n;function r(o){if(!o||typeof o!="object")throw new Error("Client tool definition must be an object");if(typeof o.name!="string"||!t.CLIENT_TOOL_NAME_PATTERN.test(o.name))throw new Error(`Client tool name "${String(o.name)}" must match ${t.CLIENT_TOOL_NAME_PATTERN}`);if(typeof o.description!="string"||!o.description.trim())throw new Error(`Client tool "${o.name}" needs a description`);if(!o.inputSchema||typeof o.inputSchema!="object")throw new Error(`Client tool "${o.name}" needs an inputSchema object`);if(typeof o.run!="function")throw new Error(`Client tool "${o.name}" needs a run function`)}return mr}var Qt={},Bt={},Wa;function Ka(){if(Wa)return Bt;Wa=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.isToolsCallRequest=r,Bt.isCancelledNotification=o,Bt.rpcResult=i,Bt.rpcError=s,Bt.rpcProgress=a;const e=fr(),t=l=>typeof l=="object"&&l!==null&&!Array.isArray(l),n=l=>typeof l=="string"||typeof l=="number";function r(l){if(!t(l)||l.method!==e.MCP_METHODS.TOOLS_CALL||!n(l.id))return!1;const d=l.params;return!t(d)||typeof d.name!="string"?!1:d.arguments===void 0||t(d.arguments)}function o(l){return!t(l)||l.method!==e.MCP_METHODS.CANCELLED?!1:t(l.params)&&n(l.params.requestId)}function i(l,d){return{jsonrpc:"2.0",id:l,result:d}}function s(l,d,p,h){return{jsonrpc:"2.0",id:l,error:{code:d,message:p,...h!==void 0&&{data:h}}}}function a(l,d,p,h){return{jsonrpc:"2.0",method:e.MCP_METHODS.PROGRESS,params:{progressToken:l,progress:d,...p!==void 0&&{total:p},...h!==void 0&&{message:h}}}}return Bt}var qa;function Xa(){if(qa)return Qt;qa=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.ClientToolRuntime=void 0,Qt.toCallToolResult=i,Qt.toErrorResult=s;const e=Ka(),t=fr(),n=200;class r extends Error{}class o{constructor(m){R(this,"registry");R(this,"transport");R(this,"maxResultBytes");R(this,"defaultTimeoutMs");R(this,"progressThrottleMs");R(this,"onEvent");R(this,"onError");R(this,"inflight",new Map);R(this,"seen",new Set);R(this,"lastSentHash",null);R(this,"everDeclared",!1);this.registry=m.registry,this.transport=m.transport,this.maxResultBytes=m.maxResultBytes??t.CLIENT_TOOLS_MAX_RESULT_BYTES,this.defaultTimeoutMs=m.defaultTimeoutMs??t.CLIENT_TOOL_DEFAULT_TIMEOUT_MS,this.progressThrottleMs=m.progressThrottleMs??t.CLIENT_TOOL_PROGRESS_THROTTLE_MS,this.onEvent=m.onEvent,this.onError=m.onError}handleMessage(m,E={}){if((0,e.isCancelledNotification)(m)){const S=this.inflight.get(String(m.params.requestId));return S&&this.abort(S,"backend_cancelled"),!0}if((0,e.isToolsCallRequest)(m)){const S=String(m.id);return this.seen.has(S)||(this.remember(S),this.execute(m,E)),!0}return!1}abortAll(){for(const m of this.inflight.values())m.finished||m.abortKind||(this.abort(m,"session_ended"),m.replied=!0,this.safeSend((0,e.rpcError)(m.id,t.JSON_RPC_ERRORS.CANCELLED,"Request cancelled")))}declarationsForSend(){if(this.registry.size()===0&&!this.everDeclared)return null;const m=this.registry.hash();return m!==this.lastSentHash?(this.markDeclarationsSent(m),{hash:m,tools:this.registry.declarations()}):{hash:m}}markDeclarationsSent(m){this.lastSentHash=m,this.everDeclared=!0}markDeclarationsUnsent(){this.lastSentHash=null}async execute(m,E){const{id:S,params:w}=m,u=w.name,g=Date.now(),_=this.registry.get(u),b=_?.annotations?.title,N=E.messageId??w._meta?.message_id,T=w.arguments??{};if(this.emit({type:"call",requestId:S,name:u,title:b,arguments:T,messageId:N}),!_){this.finish({id:S,name:u,title:b,messageId:N,startedAt:g},(0,e.rpcError)(S,t.JSON_RPC_ERRORS.METHOD_NOT_FOUND,`Unknown tool: ${u}`));return}let O;try{O=_.parse?_.parse(T):T}catch(ne){this.finish({id:S,name:u,title:b,messageId:N,startedAt:g},(0,e.rpcError)(S,t.JSON_RPC_ERRORS.INVALID_PARAMS,"Invalid params",{message:d(ne)}));return}const y={id:S,name:u,controller:new AbortController,abortKind:null,finished:!1,replied:!1,progressToken:w._meta?.progressToken,progressStep:0,lastProgressSentAt:0,pendingProgress:null,progressTimer:null};this.inflight.set(String(S),y);const v={requestId:S,messageId:N,signal:y.controller.signal,progress:ne=>this.reportProgress(y,b,N,ne)},x=_.timeoutMs??this.defaultTimeoutMs;let P=null;const G=new Promise((ne,de)=>{y.controller.signal.addEventListener("abort",()=>de(new r)),P=setTimeout(()=>this.abort(y,"timeout"),x)});let W;try{const ne=await Promise.race([Promise.resolve().then(()=>_.run(O,v)),G]);W=y.abortKind?this.abortedReply(y,x):(0,e.rpcResult)(S,this.enforceSize(i(ne)))}catch(ne){W=y.abortKind?this.abortedReply(y,x):(0,e.rpcResult)(S,s(ne,t.CLIENT_TOOL_ERROR_CODES.EXECUTION_FAILED))}finally{P&&clearTimeout(P),y.finished=!0,this.flushProgress(y),this.inflight.delete(String(S))}this.finish({id:S,name:u,title:b,messageId:N,startedAt:g},W,y.replied)}abortedReply(m,E){switch(m.abortKind){case"backend_cancelled":return null;case"timeout":return(0,e.rpcResult)(m.id,a(t.CLIENT_TOOL_ERROR_CODES.TIMEOUT,`Tool "${m.name}" timed out after ${E} ms`));default:return(0,e.rpcError)(m.id,t.JSON_RPC_ERRORS.CANCELLED,"Request cancelled")}}finish(m,E,S=!1){E&&!S&&this.safeSend(E);const w=E&&"result"in E?E.result:E&&"error"in E?{error:E.error}:{error:{code:t.JSON_RPC_ERRORS.CANCELLED,message:"Cancelled by server"}};this.emit({type:"result",requestId:m.id,name:m.name,title:m.title,result:w,durationMs:Date.now()-m.startedAt,messageId:m.messageId})}abort(m,E){m.finished||m.abortKind||(m.abortKind=E,m.controller.abort())}reportProgress(m,E,S,w){if(m.finished)return;m.progressStep+=1;const u=w.progress??m.progressStep;if(this.emit({type:"progress",requestId:m.id,name:m.name,title:E,message:w.message,progress:u,total:w.total,messageId:S}),m.progressToken===void 0)return;const g=(0,e.rpcProgress)(m.progressToken,u,w.total,w.message),_=Date.now()-m.lastProgressSentAt;if(_>=this.progressThrottleMs&&!m.progressTimer){this.sendProgress(m,g);return}m.pendingProgress=g,m.progressTimer||(m.progressTimer=setTimeout(()=>{m.progressTimer=null,this.flushProgress(m)},Math.max(0,this.progressThrottleMs-_)))}flushProgress(m){if(m.progressTimer&&(clearTimeout(m.progressTimer),m.progressTimer=null),m.pendingProgress){const E=m.pendingProgress;m.pendingProgress=null,this.sendProgress(m,E)}}sendProgress(m,E){m.lastProgressSentAt=Date.now(),this.safeSend(E)}enforceSize(m){return h(JSON.stringify(m))<=this.maxResultBytes?m:a(t.CLIENT_TOOL_ERROR_CODES.RESULT_TOO_LARGE,`Result exceeds ${this.maxResultBytes} bytes; ask for less data`)}remember(m){if(this.seen.add(m),this.seen.size>n){const E=this.seen.values().next().value;E!==void 0&&this.seen.delete(E)}}safeSend(m){try{this.transport.send(m)}catch(E){this.onError?.(E)}}emit(m){try{this.onEvent?.(m)}catch(E){this.onError?.(E)}}}Qt.ClientToolRuntime=o;function i(f){if(l(f))return f;if(f&&typeof f=="object"&&!Array.isArray(f)){const m=f;return{content:[{type:"text",text:p(m)}],structuredContent:m}}return{content:[{type:"text",text:f===void 0?"":String(f)}]}}function s(f,m){const E=f??{},S=typeof E.code=="string"?E.code:m,w=E.data&&typeof E.data=="object"&&!Array.isArray(E.data)?E.data:void 0;return a(S,d(f),w)}function a(f,m,E){return{isError:!0,content:[{type:"text",text:m}],structuredContent:{code:f,message:m,...E??{}}}}function l(f){return!!f&&typeof f=="object"&&Array.isArray(f.content)}function d(f){return f instanceof Error?f.message:typeof f=="string"?f:p(f)}function p(f){try{return JSON.stringify(f)??String(f)}catch{return String(f)}}function h(f){return typeof TextEncoder<"u"?new TextEncoder().encode(f).length:f.length}return Qt}var Ja;function Ou(){if(Ja)return Wn;Ja=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.SynapseSDK=void 0;const e=da(),t=Jn(),n=qo(),r=Ra(),o=La(),i=qr(),s=Wo(),a=at(),l=Zo(),d=Nu(),p=Wr(),h=xu(),f=Ga(),m=Xa(),E=fr();class S{constructor(u){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);R(this,"clientToolRegistry",new f.ClientToolRegistry);R(this,"clientToolRuntime");this.config={...u,environment:u.environment||"production"},this.connectionType=u.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:_=>this.config.callbacks?.onTokenExchange?.(_)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks),this.config.clientTools?.length&&this.clientToolRegistry.register(this.config.clientTools),this.clientToolRuntime=new m.ClientToolRuntime({registry:this.clientToolRegistry,transport:{send:_=>this.messageManager.sendMcpMessage(_)},onEvent:_=>this.emitClientToolEvent(_),onError:_=>this.emitError(_)}),this.messageManager.setClientToolRuntime(this.clientToolRuntime)}registerClientTools(u){this.clientToolRegistry.register(u)}emitClientToolEvent(u){const g=u.type==="call"?i.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_CALL:u.type==="progress"?i.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_PROGRESS:i.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_RESULT;this.sdkEventEmitter.emit(g,{messageId:u.messageId,timestamp:Date.now(),data:u})}clientCapabilities(){return{client_tools:{version:E.CLIENT_TOOLS_PROTOCOL_VERSION,max_result_bytes:E.CLIENT_TOOLS_MAX_RESULT_BYTES,cancel:!0}}}async onRestUnauthorized(){const u=await this.resourceManager.refreshBearer();if(!u)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 u}async startSession(u){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,u=void 0),await this.resourceManager.ensureCredentials(),this.clientToolRuntime.markDeclarationsUnsent();const g=u?.session_id?u:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:u,files:g,audio:_,tool_declined:b,tool_id:N,initial_prompts:T,tool_result:O}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{const v=this.clientToolRuntime.declarationsForSend();this.messageManager.sendSocketMessage({message:u,files:g,audio:_,...b&&{tool_declined:b},...N&&{tool_id:N},...T?.length&&{initial_prompts:T},...O&&Object.keys(O)?.length&&{tool_result:O},...v&&{client_tools:v}})}catch(v){this.emitError(v)}break;default:const y=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(y),y}}async sendMessageFeedback(u,g,_){if(!this.connection){const b=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(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:u,feedback:g,feedbackReason:_});break}}async sendSessionFeedback(u,g){if(!this.connection){const _=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(_),_}if(!this.sessionConfig?.session_id){const _=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(_),_}if(!u?.length&&!g){const _=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(_),_}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:u,npsBase5:g});break}}on(u,g){this.sdkEventEmitter.on(u,g)}off(u,g){this.sdkEventEmitter.off(u,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(u){return await this.resourceManager.getSessionMessages(u)}async callTool(u,g,_){if(!this.connection){const b=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(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const b=await this.resourceManager.callTool(this.sessionConfig.session_id,u,g,_);if(b.error)throw new a.APIError(b.error.msg,500,b.error);let N={data:{...b.data},messageId:b._id,timestamp:b.ts};this.connection.emit(i.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,N);break;default:const T=new a.ConnectionError("Unsupported connection type",{context:{stage:"callTool",connectionType:this.connectionType}});throw this.emitError(T),T}}async startRecording({onChunks:u,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:u,onError:g})}catch(b){throw b}break;default:const _=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(_),_}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const u=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(u),u}}async getAgentConfig(){return this.resourceManager.getAgentConfig()}isConnected(){return this.connection?.isConnected()??!1}clearTokens(){this.resourceManager.clearTokens()}get voice(){return this._voice||(this._voice=new h.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.clientToolRuntime.abortAll(),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(u){if(u instanceof a.APIError){const g=u.reason??(u.status===401||u.status===403?l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:u.error?.msg||u.message,error:u.error,code:u.code,...g&&{reason:g},status:u.status,context:u.context}}return u instanceof a.SynapseError?{message:u.displayMessage||u.message,code:u.code,...u.reason&&{reason:u.reason},context:u.context}:u instanceof Error?{message:u.message}:{message:"An unexpected error occurred"}}emitError(u){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(u))}toSessionError(u,g,_,b){return(0,a.normalizeError)(u,a.SessionError,g,{context:_,hint:b})}async initializeConnection(u){if(this.closeConnection(),!u.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=u;const g=(0,n.getConfig)(this.config?.environment),_=this.connectionType===e.ConnectionType.SOCKET,b=_?g.WEBSOCKET_URL:g.BASE_API_URL,N=this.config.serverUrl?_?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:N||b,auth:{sessionId:u.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 T=this.connection.emit.bind(this.connection);this.connection.emit=(O,...y)=>{T(O,...y),this.sdkEventEmitter.emit(O,...y)}}async createNewSession(){const u=this.clientToolRegistry.size()>0,g=this.clientToolRegistry.hash(),_=await this.resourceManager.createSession(this.config.userId,{...this.config.context||{},client_capabilities:this.clientCapabilities(),...u&&{client_tools:{hash:g,tools:this.clientToolRegistry.declarations()}}});return u&&this.clientToolRuntime.markDeclarationsSent(g),_}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 u=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==u||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const _=(0,d.outcomeForCloseCode)(g.code);if(_){await this.handleRecovery(_,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(u){if(u instanceof a.APIError){const _=(0,d.outcomeForHttpStatus)(u.status);if(_){this.handleRecovery(_,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:u.message,code:u.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,u);const g=u instanceof a.APIError?u:this.toConnectionError(u,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const u=this.resourceManager.getSessToken();if(!u){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(u)}onIncomingSocketMessage(u){switch(u.ev){case p.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(u);break;case p.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case p.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(u);break;case p.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(u);break;case p.SOCKET_EVENTS.PING:this.messageManager.sendSocketPongMessage();break;case p.SOCKET_EVENTS.PONG:this.messageManager.sendSocketPingMessage();break;case p.SOCKET_EVENTS.SYNC:break;case p.SOCKET_EVENTS.ERROR:this.messageManager.handleIncomingSocketErrorMessage(u);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:u.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const u=this.resourceManager.getLevel();return u?u==="user":!!this.config.authToken}statusOf(u){if(u instanceof a.APIError)return u.status;if(u instanceof a.SynapseError&&typeof u.context?.status=="number")return u.context.status}emitRecoveryError(u,g,_){this.emitError(new a.SessionError(g,{reason:u,cause:_,context:{stage:"connectionRecovery",reason:u}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(u,g){if(u===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(u){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(l.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(u){const g=this.statusOf(u);if(g!==403&&g!==401){this.emitError(this.toSessionError(u,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",u)}}async recoverMissingSession(){const u=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!u){this.closeConnection(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(u);await this.connectTo(g);return}catch(g){const _=this.statusOf(g);if(_===401||_===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",g);return}try{await this.connectTo(await this.createNewSession())}catch(b){const N=this.statusOf(b);if(N===401||N===403){this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Session credentials were rejected",b);return}this.emitError(this.toSessionError(b,"Failed to start a new session",{stage:"connectionRecovery"}))}}}async reconnectCurrentSession(){this.sessionConfig?.session_id&&await this.connectTo(this.sessionConfig)}async connectTo(u){await this.initializeConnection(u),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(u,g,_,b){return(0,a.normalizeError)(u,a.ConnectionError,g,{context:_,hint:b})}scheduleReconnect(u){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(u);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(u)}}},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 Wn.SynapseSDK=S,Wn}var Za={},Qa;function Ru(){return Qa||(Qa=1,Object.defineProperty(Za,"__esModule",{value:!0})),Za}var Xr={},el;function ku(){return el||(el=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.USER_FEEDBACK=void 0,Xr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Xr}var tl={},nl;function Au(){return nl||(nl=1,Object.defineProperty(tl,"__esModule",{value:!0})),tl}var gr={},rl;function Iu(){if(rl)return gr;rl=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.ToolCall=void 0;const e=or();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 gr.ToolCall=t,gr}var qe={},ol;function Mu(){if(ol)return qe;ol=1,Object.defineProperty(qe,"__esModule",{value:!0}),qe.SYNAPSE_EICITATION_STATUS=qe.SYNAPSE_CTA_ACTIONS=qe.SYNAPSE_TOOL_FORMATS=qe.SYNAPSE_TOOL_CALLBACK_NAME=qe.SYNAPSE_COMPONENTS=qe.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||(qe.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||(qe.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||(qe.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(qe.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(qe.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(qe.SYNAPSE_EICITATION_STATUS=i={})),qe}var sl={},il;function Pu(){return il||(il=1,Object.defineProperty(sl,"__esModule",{value:!0})),sl}var Cn={},al;function Lu(){return al||(al=1,(function(e){var t=Cn&&Cn.__createBinding||(Object.create?(function(a,l,d,p){p===void 0&&(p=d);var h=Object.getOwnPropertyDescriptor(l,d);(!h||("get"in h?!l.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return l[d]}}),Object.defineProperty(a,p,h)}):(function(a,l,d,p){p===void 0&&(p=d),a[p]=l[d]})),n=Cn&&Cn.__exportStar||function(a,l){for(var d in a)d!=="default"&&!Object.prototype.hasOwnProperty.call(l,d)&&t(l,a,d)};Object.defineProperty(e,"__esModule",{value:!0}),e.toErrorResult=e.toCallToolResult=e.ClientToolRuntime=e.ClientToolRegistry=e.rpcResult=e.rpcProgress=e.rpcError=e.isToolsCallRequest=e.isCancelledNotification=e.hashDeclarations=e.fnv1a64Hex=e.canonicalJson=void 0,n(fr(),e);var r=Ha();Object.defineProperty(e,"canonicalJson",{enumerable:!0,get:function(){return r.canonicalJson}}),Object.defineProperty(e,"fnv1a64Hex",{enumerable:!0,get:function(){return r.fnv1a64Hex}}),Object.defineProperty(e,"hashDeclarations",{enumerable:!0,get:function(){return r.hashDeclarations}});var o=Ka();Object.defineProperty(e,"isCancelledNotification",{enumerable:!0,get:function(){return o.isCancelledNotification}}),Object.defineProperty(e,"isToolsCallRequest",{enumerable:!0,get:function(){return o.isToolsCallRequest}}),Object.defineProperty(e,"rpcError",{enumerable:!0,get:function(){return o.rpcError}}),Object.defineProperty(e,"rpcProgress",{enumerable:!0,get:function(){return o.rpcProgress}}),Object.defineProperty(e,"rpcResult",{enumerable:!0,get:function(){return o.rpcResult}});var i=Ga();Object.defineProperty(e,"ClientToolRegistry",{enumerable:!0,get:function(){return i.ClientToolRegistry}});var s=Xa();Object.defineProperty(e,"ClientToolRuntime",{enumerable:!0,get:function(){return s.ClientToolRuntime}}),Object.defineProperty(e,"toCallToolResult",{enumerable:!0,get:function(){return s.toCallToolResult}}),Object.defineProperty(e,"toErrorResult",{enumerable:!0,get:function(){return s.toErrorResult}})})(Cn)),Cn}var ll={},cl;function Du(){return cl||(cl=1,Object.defineProperty(ll,"__esModule",{value:!0})),ll}var _r={},dl;function Uu(){if(dl)return _r;dl=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(_r.SYNAPSE_CONVERSATION=e={})),_r}var xn={},ul;function Fu(){return ul||(ul=1,(function(e){var t=xn&&xn.__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=xn&&xn.__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(ja(),e)})(xn)),xn}var hl;function Vu(){return hl||(hl=1,(function(e){var t=bn&&bn.__createBinding||(Object.create?(function(T,O,y,v){v===void 0&&(v=y);var x=Object.getOwnPropertyDescriptor(O,y);(!x||("get"in x?!O.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return O[y]}}),Object.defineProperty(T,v,x)}):(function(T,O,y,v){v===void 0&&(v=y),T[v]=O[y]})),n=bn&&bn.__exportStar||function(T,O){for(var y in T)y!=="default"&&!Object.prototype.hasOwnProperty.call(O,y)&&t(O,T,y)};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=Ou();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Ko();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=ta();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=la();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=da();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n(Jn(),e);var l=Ra();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return l.ResourceManager}}),n(Ru(),e);var d=fa();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(ku(),e);var p=Jo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return p.Auth}});var h=Na();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return h.prefetchTokenExchange}}),n(Au(),e);var f=Xo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return f.Config}});var m=Sa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return m.prefetchAgentConfig}});var E=Iu();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return E.ToolCall}}),n(Mu(),e);var S=La();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return S.MessageManager}}),n(qr(),e),n(Pu(),e),n(Lu(),e);var w=Kr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return w.HttpClient}});var u=at();Object.defineProperty(e,"SynapseError",{enumerable:!0,get:function(){return u.SynapseError}}),Object.defineProperty(e,"APIError",{enumerable:!0,get:function(){return u.APIError}}),Object.defineProperty(e,"APIUserAbortError",{enumerable:!0,get:function(){return u.APIUserAbortError}}),Object.defineProperty(e,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return u.APIConnectionTimeoutError}}),Object.defineProperty(e,"BadRequestError",{enumerable:!0,get:function(){return u.BadRequestError}}),Object.defineProperty(e,"UnauthorizedError",{enumerable:!0,get:function(){return u.UnauthorizedError}}),Object.defineProperty(e,"PermissionDeniedError",{enumerable:!0,get:function(){return u.PermissionDeniedError}}),Object.defineProperty(e,"NotFoundError",{enumerable:!0,get:function(){return u.NotFoundError}}),Object.defineProperty(e,"MethodNotAllowedError",{enumerable:!0,get:function(){return u.MethodNotAllowedError}}),Object.defineProperty(e,"RateLimitError",{enumerable:!0,get:function(){return u.RateLimitError}}),Object.defineProperty(e,"InternalServerError",{enumerable:!0,get:function(){return u.InternalServerError}}),Object.defineProperty(e,"SynapseErrorCode",{enumerable:!0,get:function(){return u.SynapseErrorCode}});var g=Zo();Object.defineProperty(e,"ErrorType",{enumerable:!0,get:function(){return g.ErrorType}}),Object.defineProperty(e,"SYNAPSE_RECOVERY_REASON",{enumerable:!0,get:function(){return g.SYNAPSE_RECOVERY_REASON}});var _=Qo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return _.ErrorUtils}}),n(Du(),e);var b=ia();Object.defineProperty(e,"SYNAPSE_CHANNELS",{enumerable:!0,get:function(){return b.SYNAPSE_CHANNELS}}),Object.defineProperty(e,"DEFAULT_CHANNEL",{enumerable:!0,get:function(){return b.DEFAULT_CHANNEL}});var N=qr();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return N.SYNAPSE_MESSAGE_TYPES}}),n(Uu(),e),n(Fu(),e)})(bn)),bn}var M=Vu();function pl(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=pl(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function ml(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=pl(e))&&(r&&(r+=" "),r+=t);return r}const ju=(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},zu=(e,t)=>({classGroupId:e,validator:t}),fl=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Jr="-",gl=[],$u="arbitrary..",Hu=e=>{const t=Bu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Yu(o);const i=o.split(Jr),s=i[0]===""&&i.length>1?1:0;return _l(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?ju(a,s):s:a||gl}return n[o]||gl}}},_l=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const l=_l(e,t+1,o);if(l)return l}const i=n.validators;if(i===null)return;const s=t===0?e.join(Jr):e.slice(t).join(Jr),a=i.length;for(let l=0;l<a;l++){const d=i[l];if(d.validator(s))return d.classGroupId}},Yu=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?$u+r:void 0})(),Bu=e=>{const{theme:t,classGroups:n}=e;return Gu(n,t)},Gu=(e,t)=>{const n=fl();for(const r in e){const o=e[r];es(o,n,r,t)}return n},es=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];Wu(s,t,n,r)}},Wu=(e,t,n,r)=>{if(typeof e=="string"){Ku(e,t,n);return}if(typeof e=="function"){qu(e,t,n,r);return}Xu(e,t,n,r)},Ku=(e,t,n)=>{const r=e===""?t:El(t,e);r.classGroupId=n},qu=(e,t,n,r)=>{if(Ju(e)){es(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(zu(n,e))},Xu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,l]=o[s];es(l,El(t,a),n,r)}},El=(e,t)=>{let n=e;const r=t.split(Jr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=fl(),n.nextPart.set(s,a)),n=a}return n},Ju=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,Zu=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)}}},ts="!",Sl=":",Qu=[],yl=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),eh=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,d;const p=o.length;for(let S=0;S<p;S++){const w=o[S];if(s===0&&a===0){if(w===Sl){i.push(o.slice(l,S)),l=S+1;continue}if(w==="/"){d=S;continue}}w==="["?s++:w==="]"?s--:w==="("?a++:w===")"&&a--}const h=i.length===0?o:o.slice(l);let f=h,m=!1;h.endsWith(ts)?(f=h.slice(0,-1),m=!0):h.startsWith(ts)&&(f=h.slice(1),m=!0);const E=d&&d>l?d-l:void 0;return yl(i,m,f,E)};if(t){const o=t+Sl,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):yl(Qu,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},th=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]==="[",l=t.has(s);a||l?(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}},nh=e=>({cache:Zu(e.cacheSize),parseClassName:eh(e),sortModifiers:th(e),...Hu(e)}),rh=/\s+/,oh=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(rh);let l="";for(let d=a.length-1;d>=0;d-=1){const p=a[d],{isExternal:h,modifiers:f,hasImportantModifier:m,baseClassName:E,maybePostfixModifierPosition:S}=n(p);if(h){l=p+(l.length>0?" "+l:l);continue}let w=!!S,u=r(w?E.substring(0,S):E);if(!u){if(!w){l=p+(l.length>0?" "+l:l);continue}if(u=r(E),!u){l=p+(l.length>0?" "+l:l);continue}w=!1}const g=f.length===0?"":f.length===1?f[0]:i(f).join(":"),_=m?g+ts:g,b=_+u;if(s.indexOf(b)>-1)continue;s.push(b);const N=o(u,w);for(let T=0;T<N.length;++T){const O=N[T];s.push(_+O)}l=p+(l.length>0?" "+l:l)}return l},sh=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=bl(n))&&(o&&(o+=" "),o+=r);return o},bl=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=bl(e[r]))&&(n&&(n+=" "),n+=t);return n},ih=(e,...t)=>{let n,r,o,i;const s=l=>{const d=t.reduce((p,h)=>h(p),e());return n=nh(d),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const d=r(l);if(d)return d;const p=oh(l,n);return o(l,p),p};return i=s,(...l)=>i(sh(...l))},ah=[],Ue=e=>{const t=n=>n[e]||ah;return t.isThemeGetter=!0,t},vl=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,wl=/^\((?:(\w[\w-]*):)?(.+)\)$/i,lh=/^\d+\/\d+$/,ch=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,dh=/\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$/,uh=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,hh=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ph=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,On=e=>lh.test(e),se=e=>!!e&&!Number.isNaN(Number(e)),Gt=e=>!!e&&Number.isInteger(Number(e)),ns=e=>e.endsWith("%")&&se(e.slice(0,-1)),Pt=e=>ch.test(e),mh=()=>!0,fh=e=>dh.test(e)&&!uh.test(e),Tl=()=>!1,gh=e=>hh.test(e),_h=e=>ph.test(e),Eh=e=>!Y(e)&&!B(e),Sh=e=>Rn(e,Rl,Tl),Y=e=>vl.test(e),en=e=>Rn(e,kl,fh),rs=e=>Rn(e,Th,se),Nl=e=>Rn(e,xl,Tl),yh=e=>Rn(e,Ol,_h),Zr=e=>Rn(e,Al,gh),B=e=>wl.test(e),Er=e=>kn(e,kl),bh=e=>kn(e,Nh),Cl=e=>kn(e,xl),vh=e=>kn(e,Rl),wh=e=>kn(e,Ol),Qr=e=>kn(e,Al,!0),Rn=(e,t,n)=>{const r=vl.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},kn=(e,t,n=!1)=>{const r=wl.exec(e);return r?r[1]?t(r[1]):n:!1},xl=e=>e==="position"||e==="percentage",Ol=e=>e==="image"||e==="url",Rl=e=>e==="length"||e==="size"||e==="bg-size",kl=e=>e==="length",Th=e=>e==="number",Nh=e=>e==="family-name",Al=e=>e==="shadow",Ch=()=>{const e=Ue("color"),t=Ue("font"),n=Ue("text"),r=Ue("font-weight"),o=Ue("tracking"),i=Ue("leading"),s=Ue("breakpoint"),a=Ue("container"),l=Ue("spacing"),d=Ue("radius"),p=Ue("shadow"),h=Ue("inset-shadow"),f=Ue("text-shadow"),m=Ue("drop-shadow"),E=Ue("blur"),S=Ue("perspective"),w=Ue("aspect"),u=Ue("ease"),g=Ue("animate"),_=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],N=()=>[...b(),B,Y],T=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto","contain","none"],y=()=>[B,Y,l],v=()=>[On,"full","auto",...y()],x=()=>[Gt,"none","subgrid",B,Y],P=()=>["auto",{span:["full",Gt,B,Y]},Gt,B,Y],G=()=>[Gt,"auto",B,Y],W=()=>["auto","min","max","fr",B,Y],ne=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],de=()=>["start","end","center","stretch","center-safe","end-safe"],ue=()=>["auto",...y()],me=()=>[On,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...y()],F=()=>[e,B,Y],le=()=>[...b(),Cl,Nl,{position:[B,Y]}],Ie=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",vh,Sh,{size:[B,Y]}],Z=()=>[ns,Er,en],$=()=>["","none","full",d,B,Y],H=()=>["",se,Er,en],re=()=>["solid","dashed","dotted","double"],he=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],q=()=>[se,ns,Cl,Nl],et=()=>["","none",E,B,Y],Ne=()=>["none",se,B,Y],Oe=()=>["none",se,B,Y],fe=()=>[se,B,Y],Me=()=>[On,"full",...y()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pt],breakpoint:[Pt],color:[mh],container:[Pt],"drop-shadow":[Pt],ease:["in","out","in-out"],font:[Eh],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pt],shadow:[Pt],spacing:["px",se],text:[Pt],"text-shadow":[Pt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",On,Y,B,w]}],container:["container"],columns:[{columns:[se,Y,B,a]}],"break-after":[{"break-after":_()}],"break-before":[{"break-before":_()}],"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:N()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:O()}],"overscroll-x":[{"overscroll-x":O()}],"overscroll-y":[{"overscroll-y":O()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Gt,"auto",B,Y]}],basis:[{basis:[On,"full","auto",a,...y()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[se,On,"auto","initial","none",Y]}],grow:[{grow:["",se,B,Y]}],shrink:[{shrink:["",se,B,Y]}],order:[{order:[Gt,"first","last","none",B,Y]}],"grid-cols":[{"grid-cols":x()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":x()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":G()}],"row-end":[{"row-end":G()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":W()}],"auto-rows":[{"auto-rows":W()}],gap:[{gap:y()}],"gap-x":[{"gap-x":y()}],"gap-y":[{"gap-y":y()}],"justify-content":[{justify:[...ne(),"normal"]}],"justify-items":[{"justify-items":[...de(),"normal"]}],"justify-self":[{"justify-self":["auto",...de()]}],"align-content":[{content:["normal",...ne()]}],"align-items":[{items:[...de(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...de(),{baseline:["","last"]}]}],"place-content":[{"place-content":ne()}],"place-items":[{"place-items":[...de(),"baseline"]}],"place-self":[{"place-self":["auto",...de()]}],p:[{p:y()}],px:[{px:y()}],py:[{py:y()}],ps:[{ps:y()}],pe:[{pe:y()}],pt:[{pt:y()}],pr:[{pr:y()}],pb:[{pb:y()}],pl:[{pl:y()}],m:[{m:ue()}],mx:[{mx:ue()}],my:[{my:ue()}],ms:[{ms:ue()}],me:[{me:ue()}],mt:[{mt:ue()}],mr:[{mr:ue()}],mb:[{mb:ue()}],ml:[{ml:ue()}],"space-x":[{"space-x":y()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":y()}],"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,Er,en]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,B,rs]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",ns,Y]}],"font-family":[{font:[bh,Y,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,B,Y]}],"line-clamp":[{"line-clamp":[se,"none",B,rs]}],leading:[{leading:[i,...y()]}],"list-image":[{"list-image":["none",B,Y]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",B,Y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[se,"from-font","auto",B,en]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[se,"auto",B,Y]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:y()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",B,Y]}],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",B,Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Ie()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Gt,B,Y],radial:["",B,Y],conic:[Gt,B,Y]},wh,yh]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:Z()}],"gradient-via-pos":[{via:Z()}],"gradient-to-pos":[{to:Z()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],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:H()}],"border-w-x":[{"border-x":H()}],"border-w-y":[{"border-y":H()}],"border-w-s":[{"border-s":H()}],"border-w-e":[{"border-e":H()}],"border-w-t":[{"border-t":H()}],"border-w-r":[{"border-r":H()}],"border-w-b":[{"border-b":H()}],"border-w-l":[{"border-l":H()}],"divide-x":[{"divide-x":H()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":H()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[se,B,Y]}],"outline-w":[{outline:["",se,Er,en]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","none",p,Qr,Zr]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",h,Qr,Zr]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[se,en]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":H()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",f,Qr,Zr]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[se,B,Y]}],"mix-blend":[{"mix-blend":[...he(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":he()}],"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":[se]}],"mask-image-linear-from-pos":[{"mask-linear-from":q()}],"mask-image-linear-to-pos":[{"mask-linear-to":q()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":q()}],"mask-image-t-to-pos":[{"mask-t-to":q()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":q()}],"mask-image-r-to-pos":[{"mask-r-to":q()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":q()}],"mask-image-b-to-pos":[{"mask-b-to":q()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":q()}],"mask-image-l-to-pos":[{"mask-l-to":q()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":q()}],"mask-image-x-to-pos":[{"mask-x-to":q()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":q()}],"mask-image-y-to-pos":[{"mask-y-to":q()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[B,Y]}],"mask-image-radial-from-pos":[{"mask-radial-from":q()}],"mask-image-radial-to-pos":[{"mask-radial-to":q()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[se]}],"mask-image-conic-from-pos":[{"mask-conic-from":q()}],"mask-image-conic-to-pos":[{"mask-conic-to":q()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Ie()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",B,Y]}],filter:[{filter:["","none",B,Y]}],blur:[{blur:et()}],brightness:[{brightness:[se,B,Y]}],contrast:[{contrast:[se,B,Y]}],"drop-shadow":[{"drop-shadow":["","none",m,Qr,Zr]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",se,B,Y]}],"hue-rotate":[{"hue-rotate":[se,B,Y]}],invert:[{invert:["",se,B,Y]}],saturate:[{saturate:[se,B,Y]}],sepia:[{sepia:["",se,B,Y]}],"backdrop-filter":[{"backdrop-filter":["","none",B,Y]}],"backdrop-blur":[{"backdrop-blur":et()}],"backdrop-brightness":[{"backdrop-brightness":[se,B,Y]}],"backdrop-contrast":[{"backdrop-contrast":[se,B,Y]}],"backdrop-grayscale":[{"backdrop-grayscale":["",se,B,Y]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[se,B,Y]}],"backdrop-invert":[{"backdrop-invert":["",se,B,Y]}],"backdrop-opacity":[{"backdrop-opacity":[se,B,Y]}],"backdrop-saturate":[{"backdrop-saturate":[se,B,Y]}],"backdrop-sepia":[{"backdrop-sepia":["",se,B,Y]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":y()}],"border-spacing-x":[{"border-spacing-x":y()}],"border-spacing-y":[{"border-spacing-y":y()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",B,Y]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[se,"initial",B,Y]}],ease:[{ease:["linear","initial",u,B,Y]}],delay:[{delay:[se,B,Y]}],animate:[{animate:["none",g,B,Y]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,B,Y]}],"perspective-origin":[{"perspective-origin":N()}],rotate:[{rotate:Ne()}],"rotate-x":[{"rotate-x":Ne()}],"rotate-y":[{"rotate-y":Ne()}],"rotate-z":[{"rotate-z":Ne()}],scale:[{scale:Oe()}],"scale-x":[{"scale-x":Oe()}],"scale-y":[{"scale-y":Oe()}],"scale-z":[{"scale-z":Oe()}],"scale-3d":["scale-3d"],skew:[{skew:fe()}],"skew-x":[{"skew-x":fe()}],"skew-y":[{"skew-y":fe()}],transform:[{transform:[B,Y,"","none","gpu","cpu"]}],"transform-origin":[{origin:N()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Me()}],"translate-x":[{"translate-x":Me()}],"translate-y":[{"translate-y":Me()}],"translate-z":[{"translate-z":Me()}],"translate-none":["translate-none"],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",B,Y]}],"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":y()}],"scroll-mx":[{"scroll-mx":y()}],"scroll-my":[{"scroll-my":y()}],"scroll-ms":[{"scroll-ms":y()}],"scroll-me":[{"scroll-me":y()}],"scroll-mt":[{"scroll-mt":y()}],"scroll-mr":[{"scroll-mr":y()}],"scroll-mb":[{"scroll-mb":y()}],"scroll-ml":[{"scroll-ml":y()}],"scroll-p":[{"scroll-p":y()}],"scroll-px":[{"scroll-px":y()}],"scroll-py":[{"scroll-py":y()}],"scroll-ps":[{"scroll-ps":y()}],"scroll-pe":[{"scroll-pe":y()}],"scroll-pt":[{"scroll-pt":y()}],"scroll-pr":[{"scroll-pr":y()}],"scroll-pb":[{"scroll-pb":y()}],"scroll-pl":[{"scroll-pl":y()}],"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",B,Y]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[se,Er,en,rs]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},xh=ih(Ch);function D(...e){return xh(ml(e))}function tn(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 Oh=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},Rh=e=>new Promise(t=>setTimeout(t,e)),Il=ee(({className:e,children:t,...n},r)=>c(Wi,{ref:r,className:D("relative overflow-hidden",e),...n,children:[c(Eu,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),c(Ml,{}),c(Su,{})]}));Il.displayName=Wi.displayName;const Ml=ee(({className:e,orientation:t="vertical",...n},r)=>c(Yo,{ref:r,orientation:t,className:D("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:c(zi,{className:"relative flex-1 rounded-full bg-border"})}));Ml.displayName=Yo.displayName;var kh=Symbol.for("react.lazy"),eo=zo[" use ".trim().toString()];function Ah(e){return typeof e=="object"&&e!==null&&"then"in e}function Pl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===kh&&"_payload"in e&&Ah(e._payload)}function Ll(e){const t=Mh(e),n=ee((r,o)=>{let{children:i,...s}=r;Pl(i)&&typeof eo=="function"&&(i=eo(i._payload));const a=st.toArray(i),l=a.find(Lh);if(l){const d=l.props.children,p=a.map(h=>h===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:h);return c(t,{...s,ref:o,children:it(d)?zt(d,void 0,p):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var Ih=Ll("Slot");function Mh(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(Pl(o)&&typeof eo=="function"&&(o=eo(o._payload)),it(o)){const s=Uh(o),a=Dh(i,o.props);return o.type!==_e&&(a.ref=r?$o(r,s):s),zt(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var Ph=Symbol("radix.slottable");function Lh(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===Ph}function Dh(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 Uh(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 Dl=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Ul=ml,Fh=(e,t)=>n=>{var r;if(t?.variants==null)return Ul(e,n?.class,n?.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const p=n?.[d],h=i?.[d];if(p===null)return null;const f=Dl(p)||Dl(h);return o[d][f]}),a=n&&Object.entries(n).reduce((d,p)=>{let[h,f]=p;return f===void 0||(d[h]=f),d},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,p)=>{let{class:h,className:f,...m}=p;return Object.entries(m).every(E=>{let[S,w]=E;return Array.isArray(w)?w.includes({...i,...a}[S]):{...i,...a}[S]===w})?[...d,h,f]:d},[]);return Ul(e,s,l,n?.class,n?.className)},Vh=Fh("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"}}),ve=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>c(r?Ih:"button",{className:D(Vh({variant:t,size:n,className:e})),ref:i,...o}));ve.displayName="Button";const jh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),zh=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),Fl=e=>{const t=zh(e);return t.charAt(0).toUpperCase()+t.slice(1)},Vl=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),$h=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Hh={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 Yh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>Ze("svg",{ref:l,...Hh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Vl("lucide",o),...!i&&!$h(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,p])=>Ze(d,p)),...Array.isArray(i)?i:[i]])),ze=(e,t)=>{const n=ee(({className:r,...o},i)=>Ze(Yh,{ref:i,iconNode:t,className:Vl(`lucide-${jh(Fl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=Fl(e),n},Bh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],os=ze("chevron-down",Bh),Gh=[["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"}]],Wh=ze("ellipsis-vertical",Gh),Kh=[["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"}]],jl=ze("file-text",Kh),qh=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],zl=ze("info",qh),Xh=[["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"}]],Jh=ze("maximize-2",Xh),Zh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Qh=ze("menu",Zh),ep=[["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"}]],Sr=ze("message-square-plus",ep),tp=[["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"}]],ss=ze("mic",tp),np=[["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"}]],rp=ze("minimize-2",np),op=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],$l=ze("plus",op),sp=[["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"}]],ip=ze("rotate-ccw",sp),ap=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Hl=ze("square",ap),lp=[["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"}]],Yl=ze("thumbs-up",lp),cp=[["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"}]],Bl=ze("thumbs-down",cp),dp=[["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"}]],up=ze("triangle-alert",dp),hp=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],An=ze("x",hp),pp=[["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"}]],mp=ze("zoom-in",pp),Gl=e=>{let t;const n=new Set,r=(a,l)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const p=t;t=l??(typeof d!="object"||d===null)?d:Object.assign({},t,d),n.forEach(h=>h(t,p))}},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},fp=(e=>e?Gl(e):Gl),gp=e=>e;function _p(e,t=gp){const n=Gn.useSyncExternalStore(e.subscribe,Gn.useCallback(()=>t(e.getState()),[e,t]),Gn.useCallback(()=>t(e.getInitialState()),[e,t]));return Gn.useDebugValue(n),n}const Ep=e=>{const t=fp(e),n=r=>_p(t,r);return Object.assign(n,t),n},Sp=(e=>Ep);function yp(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 is=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return is(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return is(r)(n)}}}},bp=(e,t)=>(n,r,o)=>{let i={storage:yp(()=>localStorage),partialize:S=>S,version:0,merge:(S,w)=>({...w,...S}),...t},s=!1;const a=new Set,l=new Set;let d=i.storage;if(!d)return e((...S)=>{n(...S)},r,o);const p=()=>{const S=i.partialize({...r()});return d.setItem(i.name,{state:S,version:i.version})},h=o.setState;o.setState=(S,w)=>(h(S,w),p());const f=e((...S)=>(n(...S),p()),r,o);o.getInitialState=()=>f;let m;const E=()=>{var S,w;if(!d)return;s=!1,a.forEach(g=>{var _;return g((_=r())!=null?_:f)});const u=((w=i.onRehydrateStorage)==null?void 0:w.call(i,(S=r())!=null?S:f))||void 0;return is(d.getItem.bind(d))(i.name).then(g=>{if(g)if(typeof g.version=="number"&&g.version!==i.version){if(i.migrate){const _=i.migrate(g.state,g.version);return _ instanceof Promise?_.then(b=>[!0,b]):[!0,_]}}else return[!1,g.state];return[!1,void 0]}).then(g=>{var _;const[b,N]=g;if(m=i.merge(N,(_=r())!=null?_:f),n(m,!0),b)return p()}).then(()=>{u?.(m,void 0),m=r(),s=!0,l.forEach(g=>g(m))}).catch(g=>{u?.(void 0,g)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(d=S.storage)},clearStorage:()=>{d?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>E(),hasHydrated:()=>s,onHydrate:S=>(a.add(S),()=>{a.delete(S)}),onFinishHydration:S=>(l.add(S),()=>{l.delete(S)})},i.skipHydration||E(),m||f},vp=bp,we={USER:"user",ASSISTANT:"assistant"};var Te=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(Te||{}),Se=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(Se||{});let ht="";const yr=e=>`med-assist-store-${e}`,wp=e=>{In(),ht=yr(e)},Tp=200;let Et=null,br=null;function In(){if(br&&(clearTimeout(br),br=null),!!Et){try{sessionStorage.setItem(Et.key,JSON.stringify(Et.value))}catch{}Et=null}}typeof window<"u"&&(window.addEventListener("pagehide",In),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&In()}));const Np={getItem:()=>{if(!ht)return null;if(Et?.key===ht)return Et.value;try{const e=sessionStorage.getItem(ht);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{ht&&(Et&&Et.key!==ht&&In(),Et={key:ht,value:t},br||(br=setTimeout(In,Tp)))},removeItem:()=>{Et?.key===ht&&(Et=null),ht&&sessionStorage.removeItem(ht)}},Wl={sessionId:"",isStreaming:!1,recordingStatus:Te.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:Se.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},Kl={...Wl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},V=Sp()(vp((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:Se.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:Te.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}),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}})),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),clearSession:async()=>{e(Wl),await sessionStorage.removeItem(ht||yr(t().agentId))},clearUser:()=>{e(Kl),sessionStorage.removeItem(ht||yr(t().agentId))}}),{name:"med-assist-store",storage:Np,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})})),Cp=e=>{const t=yr(e);In();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}V.setState(Kl),n&&V.setState(n)},as=vt(null),xp=({children:e})=>{const[t,n]=U(null);return c(as.Provider,{value:{synapse:t,setSynapse:n},children:e})},Op=()=>{const e=wt(as);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},Rp=()=>{const e=wt(as);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},kp=()=>{const[e,t]=U(M.VOICE_AGENT_STATE.IDLE),[n,r]=U(!1),o=Op(),i=V(p=>p.setError);j(()=>{if(!o)return;const p=o.voice,h=m=>{t(m)},f=()=>{i({title:"Voice connection failed. Please try again."})};return p.on(M.VOICE_AGENT_EVENTS.STATE_CHANGED,h),p.on(M.VOICE_AGENT_EVENTS.ERROR,f),()=>{p.off(M.VOICE_AGENT_EVENTS.STATE_CHANGED,h),p.off(M.VOICE_AGENT_EVENTS.ERROR,f)}},[o,i]);const s=pe(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=pe(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),l=pe(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=pe(()=>{r(p=>!p),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:l,toggleMute:d}},nn=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));nn.displayName="Card";const ql=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("flex flex-col space-y-1.5 p-6",e),...t}));ql.displayName="CardHeader";const Xl=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("font-semibold leading-none tracking-tight",e),...t}));Xl.displayName="CardTitle";const Ap=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("text-sm text-muted-foreground",e),...t}));Ap.displayName="CardDescription";const Jl=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("p-6 pt-0",e),...t}));Jl.displayName="CardContent";const Zl=ee(({className:e,...t},n)=>c("div",{ref:n,className:D("flex items-center p-6 pt-0",e),...t}));Zl.displayName="CardFooter";const ls=5,Ql=3,ec=10*1024*1024,to={width:384,height:600},no=20,Ip=400,Mp=320,Pp=560,Lp=150;function Dp({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=pe(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-to.width-no,y:window.innerHeight-to.height-no},[]),[i,s]=U(()=>e??o()),[a,l]=U(!1),d=X({x:0,y:0}),p=X(null),h=X(!1);j(()=>{t||(h.current=!1)},[t]),gt(()=>{!t||h.current||typeof window>"u"||(s(e||o()),h.current=!0)},[t,e,o]),j(()=>{if(!t||typeof window>"u")return;let S=null;const w=()=>{s(g=>{const _=Math.max(0,window.innerWidth-to.width-no),b=Math.max(0,window.innerHeight-to.height-no),N=Math.max(0,Math.min(g.x,_)),T=Math.max(0,Math.min(g.y,b));return N===g.x&&T===g.y?g:{x:N,y:T}})},u=()=>{S!==null&&clearTimeout(S),S=setTimeout(w,Lp)};return window.addEventListener("resize",u),()=>{window.removeEventListener("resize",u),S!==null&&clearTimeout(S)}},[t]);const f=pe(S=>{if(!t)return;if(!S.target.closest(".synapse-chat-widget-header")){l(!1);return}S.preventDefault(),l(!0);const w=p.current;if(w){const u=w.getBoundingClientRect();d.current={x:S.clientX-u.left,y:S.clientY-u.top}}else d.current={x:S.clientX-i.x,y:S.clientY-i.y};n?.()},[t,i.x,i.y,n]),m=pe(S=>{if(!t||!a)return;const w=S.clientX-d.current.x,u=S.clientY-d.current.y,g=window.innerWidth-(p.current?.offsetWidth||0),_=window.innerHeight-(p.current?.offsetHeight||0),b=Math.max(0,Math.min(w,g)),N=Math.max(0,Math.min(u,_));s({x:b,y:N})},[a,t]),E=pe(()=>{!t||!a||(l(!1),r?.())},[a,r]);return j(()=>{if(!t)return;const S=p.current;if(S)return S.addEventListener("mousedown",f),()=>{S.removeEventListener("mousedown",f)}},[t,f]),j(()=>{if(a)return document.addEventListener("mousemove",m),document.addEventListener("mouseup",E),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",m),document.removeEventListener("mouseup",E),document.body.style.cursor="",document.body.style.userSelect=""}},[a,m,E]),{position:i,isDragging:a,elementRef:p,setPosition:s}}const cs="#6B5CE0",Up="#F0F0F0",ro={background:Up,backgroundImage:void 0,primary:cs,textColor:"black"},Fp="rgba(0, 0, 0, 0.4)",Vp="24px";function jp(e){if(e==="dark")return"white";if(e==="light")return"black"}function zp(e){const t=e?.primary??e?.primaryColor??ro.primary,n=e?.textColor??jp(e?.mode);return{background:e?.background??ro.background,backgroundImage:e?.backgroundImage??ro.backgroundImage,primary:t,primaryColor:t,textColor:n??ro.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function $p(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 l=(o+i)/2;if(o!==i){const p=o-i;switch(a=l>.5?p/(2-o-i):p/(o+i),o){case t:s=((n-r)/p+(n<r?6:0))/6;break;case n:s=((r-t)/p+2)/6;break;case r:s=((t-n)/p+4)/6;break}}s=Math.round(s*360),a=Math.round(a*100);const d=Math.round(l*100);return`${s} ${a}% ${d}%`}function Hp(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,l=0;const d=(i+s)/2;if(i!==s){const h=i-s;switch(l=d>.5?h/(2-i-s):h/(i+s),i){case n:a=((r-o)/h+(r<o?6:0))/6;break;case r:a=((o-n)/h+2)/6;break;case o:a=((n-r)/h+4)/6;break}}a=Math.round(a*360),l=Math.round(l*100);const p=Math.round(d*100);return`${a} ${l}% ${p}%`}function Yp(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 ds(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return $p(t);if(t.startsWith("rgb"))return Hp(t);if(t.startsWith("hsl"))return Yp(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function tc(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function us(e){return tc(e)>.5?"0 0% 9%":"0 0% 98%"}function Bp(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 Gp(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 nc(e,t){const n=t.primary??cs,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(m,E)=>{const S=e instanceof ShadowRoot?e.host:e;S instanceof HTMLElement&&S.style.setProperty(m,E)};let l;try{l=ds(n)}catch{l=ds(cs)}a("--primary",l),a("--primary-foreground",us(l)),a("--ring",l),a("--border-primary",l);const d=Gp(l);for(const[m,E]of Object.entries(d))a(`--primary-${m}`,E);const p=us(l);if(a("--color-on-primary",p),o)a("--background","0 0% 0% / 0"),a("--widget-bg-overlay","transparent");else{const m=i?"#191919":"#F0F0F0";try{a("--background",ds(m))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${l} / ${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",Bp(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(${l})`),a("--header-stroke",`hsl(${l} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${l} / 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(${l} / 0.3)`)),s&&!o){const m=tc(p)>.5;a("--header-tagline",m?"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 h=e instanceof ShadowRoot?e.host:e;h instanceof HTMLElement&&(h.setAttribute("data-text-color",r),h.setAttribute("data-header-tinted",String(s))),o?a("--popover",i?"0 0% 0% / 0.5":"0 0% 100% / 0.5"):s?a("--popover",l):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const f=i?"white":"black";for(const m of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${m}`,`var(--${f}-${m})`);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",l),a("--accent-foreground",us(l)),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",Vp),a("--theme-background-overlay",Fp),h instanceof HTMLElement&&h.classList.add("theme-with-background")):(a("--theme-background-image","none"),a("--theme-background-blur","0px"),a("--theme-background-overlay","rgba(0, 0, 0, 0)"),h instanceof HTMLElement&&h.classList.remove("theme-with-background"))}function rn({className:e,style:t}){return c("div",{className:D("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 hs(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function rc(){return c("div",{className:"px-3 pb-2 pt-1",children:[c(hs,{}),c("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[c("div",{className:"px-2 pt-2 pb-1",children:c(rn,{className:"h-5 w-3/5 rounded-md"})}),c("div",{className:"flex items-center justify-between px-1 py-1",children:[c(rn,{className:"h-9 w-9 rounded-full"}),c("div",{className:"flex items-center gap-2",children:[c(rn,{className:"h-9 w-9 rounded-full"}),c(rn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function Wp(){const e=[{role:we.ASSISTANT,size:"h-16 w-[70%]"},{role:we.USER,size:"h-9 w-[45%]"},{role:we.ASSISTANT,size:"h-24 w-[75%]"},{role:we.USER,size:"h-9 w-[35%]"},{role:we.ASSISTANT,size:"h-16 w-[65%]"}];return c("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[c(hs,{}),e.map((t,n)=>c("div",{className:D("flex",t.role===we.USER?"justify-end":"justify-start"),children:c(rn,{className:D("rounded-lg",t.size)})},n))]})}function Kp({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return c("div",{"aria-hidden":"true",children:[c(hs,{}),Array.from({length:e},(n,r)=>c("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[c(rn,{className:D("h-5 rounded-md",t[r%t.length])}),c(rn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function qp(e,t=[]){let n=[];function r(i,s){const a=vt(s);a.displayName=i+"Context";const l=n.length;n=[...n,s];const d=h=>{const{scope:f,children:m,...E}=h,S=f?.[e]?.[l]||a,w=ce(()=>E,Object.values(E));return c(S.Provider,{value:w,children:m})};d.displayName=i+"Provider";function p(h,f){const m=f?.[e]?.[l]||a,E=wt(m);if(E)return E;if(s!==void 0)return s;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,p]}const o=()=>{const i=n.map(s=>vt(s));return function(s){const a=s?.[e]||i;return ce(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Xp(o,...t)]}function Xp(...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:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ce(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Jp=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ps=Jp.reduce((e,t)=>{const n=Ll(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),oc={exports:{}},ms={};const Zp=yu(zo);var sc;function Qp(){if(sc)return ms;sc=1;var e=Zp;function t(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&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(h,f){var m=f(),E=r({inst:{value:m,getSnapshot:f}}),S=E[0].inst,w=E[1];return i(function(){S.value=m,S.getSnapshot=f,l(S)&&w({inst:S})},[h,m,f]),o(function(){return l(S)&&w({inst:S}),h(function(){l(S)&&w({inst:S})})},[h]),s(m),m}function l(h){var f=h.getSnapshot;h=h.value;try{var m=f();return!n(h,m)}catch{return!0}}function d(h,f){return f()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return ms.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:p,ms}var ic;function em(){return ic||(ic=1,oc.exports=Qp()),oc.exports}var tm=em();function nm(){return tm.useSyncExternalStore(rm,()=>!0,()=>!1)}function rm(){return()=>{}}var fs="Avatar",[om]=qp(fs),[sm,ac]=om(fs),lc=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=U("idle");return c(sm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:c(ps.span,{...r,ref:t})})});lc.displayName=fs;var cc="AvatarImage",dc=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=ac(cc,n),a=im(r,i),l=Ht(d=>{o(d),s.onImageLoadingStatusChange(d)});return Zt(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?c(ps.img,{...i,ref:t,src:r}):null});dc.displayName=cc;var uc="AvatarFallback",hc=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=ac(uc,n),[s,a]=U(r===void 0);return j(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),s&&i.imageLoadingStatus!=="loaded"?c(ps.span,{...o,ref:t}):null});hc.displayName=uc;function pc(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function im(e,{referrerPolicy:t,crossOrigin:n}){const r=nm(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=U(()=>pc(i,e));return Zt(()=>{a(pc(i,e))},[i,e]),Zt(()=>{const l=h=>()=>{a(h)};if(!i)return;const d=l("loaded"),p=l("error");return i.addEventListener("load",d),i.addEventListener("error",p),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",p)}},[i,n,t]),s}var mc=lc,fc=dc,gc=hc;const gs=ee(({className:e,...t},n)=>c(mc,{ref:n,className:D("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));gs.displayName=mc.displayName;const _c=ee(({className:e,...t},n)=>c(fc,{ref:n,className:D("aspect-square h-full w-full",e),...t}));_c.displayName=fc.displayName;const _s=ee(({className:e,...t},n)=>c(gc,{ref:n,className:D("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));_s.displayName=gc.displayName;const Ec=vt(!1);function am({enabled:e,children:t}){return c(Ec.Provider,{value:e,children:t})}function lm(){return wt(Ec)}const Sc="(max-width: 768px), (pointer: coarse)",yc=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function cm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Sc)?.matches??!1,t=yc.test(navigator?.userAgent??"");return e||t}function bc(){const[e,t]=U(cm);return j(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Sc),r=yc.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function dm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:l=!1,onToggleDisplayMode:d,onOpenSessionDrawer:p}){const h=bc(),f=lm(),m=V(x=>x.displayMode)==="side_panel",E=f&&!h&&!m,S=V(x=>x.displayMode)==="full",w=V(x=>x.initialDisplayMode)==="full",u=!S&&l?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",g=V(x=>x.connectionStatus),_=V(x=>x.level)==="user",[b,N]=U(!1),T=X(null),O=ce(()=>a===M.VOICE_AGENT_STATE.CONNECTED||a===M.VOICE_AGENT_STATE.CONNECTING||a===M.VOICE_AGENT_STATE.LISTENING||a===M.VOICE_AGENT_STATE.SPEAKING||a===M.VOICE_AGENT_STATE.THINKING,[a]),y=pe(()=>{b||(N(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,N(!1)},6e3),s())},[b,s]);j(()=>{g===Se.CONNECTED&&(N(!1),T.current&&clearTimeout(T.current))},[g]);const v=(()=>{switch(g){case Se.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case Se.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case Se.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 c("div",{className:"px-6 py-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative flex-shrink-0",children:[c(gs,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:c(_s,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?c("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):c("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),c("div",{className:D("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,g===Se.CONNECTING&&"animate-pulse")})]}),c("div",{className:"flex flex-col",children:[r?c("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):c("p",{className:D("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",u),children:n||"Health Assist"}),c("div",{className:"flex items-center gap-1.5",children:c("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),c("div",{className:D("flex items-center",!E&&"gap-1"),children:[!O&&!_&&c(ve,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:y,disabled:b,className:D("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",u),children:c(Sr,{className:"w-5 h-5"})}),p&&_&&c(ve,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:p,className:D("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",u),children:c(Wh,{className:"w-5 h-5"})}),E&&c(ve,{onClick:d,type:"button",variant:"ghost",size:"icon",title:S?"Exit fullscreen":"Enter fullscreen",className:D("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",u),children:S?c(rp,{className:"w-8 h-8"}):c(Jh,{className:"w-8 h-8"})}),(t||!w)&&c(ve,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:D("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",u),children:c(An,{className:"w-8 h-8"})})]})]})})}const Es=ee(({className:e,...t},n)=>c("textarea",{className:D("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),ref:n,...t}));Es.displayName="Textarea";function vc({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=U(!1),[s,a]=U(""),l=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";j(()=>{if(l){const f=URL.createObjectURL(e);return a(f),()=>URL.revokeObjectURL(f)}},[e,l]),j(()=>{i(!1)},[e]);const p=()=>l?"text-green-600":"text-text-secondary",h=f=>{if(f===0)return"0 B";const m=1024,E=["B","KB","MB","GB"],S=Math.floor(Math.log(f)/Math.log(m));return`${(f/Math.pow(m,S)).toFixed(1)} ${E[S]}`.toLowerCase()};return!l||o?c("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:[c("div",{className:`flex-shrink-0 ${p()}`,children:c(jl,{className:"h-5 w-5"})}),c("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&c("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&c("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:h(e.size)})]}),n&&t&&c("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:c(An,{className:"h-3 w-3"})})]}):c("div",{className:`relative group flex-shrink-0 ${r}`,children:[c("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&&c("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&c("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:c(An,{className:"h-3 w-3"})})]})}function Ss({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 c("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return c(vc,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&c("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 c(vc,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const ys=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("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"})}),wc=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),um=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},Tc=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("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"})}),hm=Qe(()=>wc().then(e=>({default:e.ElicitationInput})));function pm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:l,isDisabled:d,placeholder:p,isMobile:h,recordingStatus:f,theme:m,allowed:E,showStartNewChatButton:S,onStartNewChat:w,isVoiceAgentActive:u,handleVoiceMode:g,isAuthComponent:_,activeElicitationState:b,isFullScreen:N,showAttention:T}){const O=X(null),y=X(null),v=T?c("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,x=e.trim().length>0||a,P=!E||E.includes(M.SYNAPSE_CONVERSATION.AUDIO),G=!E||E.includes(M.SYNAPSE_CONVERSATION.VOICE),W=x||!P,ne=x,de=!E||E.includes(M.SYNAPSE_CONVERSATION.FILE),ue=(d||f!==Te.IDLE)&&!s,me=D("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)]":ue?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),F=$=>{const H=Array.from($.target.files||[]);H.length>0&&r(H)},le=()=>{d||(O.current&&(O.current.value=""),O.current?.click())},Ie=$=>{$.key==="Enter"&&!$.shiftKey&&ne&&!d&&($.preventDefault(),n())},te=$=>{$.style.height="auto",$.style.overflow="hidden";const H=$.scrollHeight,re=N?20:28,he=120,q=Math.max(re,Math.min(H,he));$.style.height=q+"px",H>he?$.style.overflow="auto":$.style.overflow="hidden"},Z=$=>{te($.currentTarget)};return j(()=>{y.current&&te(y.current)},[e]),j(()=>{d||y.current?.focus()},[d]),S&&w?c("div",{className:"px-4 py-2 flex justify-unset",children:c("button",{type:"button",onClick:w,className:D("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",!h&&"hover:bg-primary/90"),children:[c("span",{children:"Start new chat"}),c(Sr,{className:"w-5 h-5","aria-hidden":!0})]})}):c(_e,{children:_?c(Ke,{fallback:c(rc,{}),children:c(hm,{elicitationEntry:b,value:e,onChange:t,isDisabled:d,theme:m,isMobile:h,onSend:n})}):N?c("div",{className:"mx-3 mb-3","data-name":"reply-box",children:c("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(Ss,{files:l,onRemoveFile:o,isPreview:!0})}),c("input",{ref:O,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:c(Es,{ref:y,onInput:Z,placeholder:p,value:e,onChange:$=>t($.target.value),rows:1,maxLength:1e3,autoFocus:!0,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:Ie,title:"Enter your message","aria-label":"Enter your message",className:D("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")})}),c("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[c("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:de&&f===Te.IDLE&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:D("rounded-full transition-all shrink-0 p-2 h-10 w-10",a?"bg-primary text-primary-foreground":"text-foreground",!h&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c($l,{className:"w-6 h-6",strokeWidth:1.5})})}),c("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?c(ve,{type:"button",variant:"ghost",size:"icon",onClick:i,className:D("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",!h&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(Hl,{className:"w-4 h-4"})}):P&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:ue,className:D("h-10 w-10 shrink-0 p-2",me),title:"Start recording","aria-label":"Start recording",children:c(ss,{className:"w-6 h-6",strokeWidth:1.5})}),W&&!s?c(ve,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!ne,variant:"ghost",className:D("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",ne?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:ne?"Send message":"Type a message to send","aria-label":ne?"Send message":"Type a message to send",children:c(ys,{className:"w-4 h-4 text-primary-foreground"})}):P&&G&&!s&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:g,disabled:d||u,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:c(Tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):c("div",{className:"px-3 pt-1",children:[c("input",{ref:O,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:F,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(Ss,{files:l,onRemoveFile:o,isPreview:!0})}),c("div",{className:"px-1 pt-1 pb-0",children:c(Es,{ref:y,onInput:Z,placeholder:p,value:e,onChange:$=>t($.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Ie,title:"Enter your message","aria-label":"Enter your message",className:D("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")})}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center shrink-0",children:de&&f===Te.IDLE&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:D("h-10 w-10 rounded-full transition-all shrink-0",a?"bg-primary text-primary-foreground":"text-foreground",!h&&(a?"hover:bg-primary/15":"hover:bg-primary hover:text-primary-foreground")),title:"Attach file","aria-label":"Attach file",children:c($l,{className:"w-5 h-5",strokeWidth:1.5})})}),c("div",{className:"flex items-center gap-2 shrink-0",children:[s?c(ve,{type:"button",variant:"ghost",size:"icon",onClick:i,className:D("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",!h&&"hover:from-red-500 hover:to-rose-600 hover:scale-105"),title:"Stop recording","aria-label":"Stop recording",children:c(Hl,{className:"w-4 h-4"})}):W?c(ve,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!ne,variant:"ghost",className:D("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",ne?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:ne?"Send message":"Type a message to send","aria-label":ne?"Send message":"Type a message to send",children:c(ys,{className:"w-4 h-4 text-primary-foreground"})}):P&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:ue,className:D("h-10 w-10 shrink-0",me),title:"Start recording","aria-label":"Start recording",children:c(ss,{className:"w-5 h-5",strokeWidth:1.5})}),P&&G&&!s&&c(ve,{type:"button",variant:"ghost",size:"icon",onClick:g,disabled:d||u,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:c(Tc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const mm=Jt(pm),Nc=vt(null),Cc=Nc.Provider;function fm(){const e=wt(Nc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function gm({message:e,onDismiss:t}){return c(_e,{children:[c("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),c("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:c("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:[c("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),c("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:c(An,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function _m(){const e=V(r=>r.toastMessage),t=V(r=>r.setToastMessage),n=pe(()=>{t(null)},[t]);return j(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?c(gm,{message:e,onDismiss:n}):null}function bs({isOpen:e,children:t,align:n="center",onClose:r}){return e?c("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:c("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Em="Before we begin",Sm=e=>`A quick note on how ${e} works and handles your information.`,ym=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 bm(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 xc=(e,t)=>{if(t){const n=bm(t,e);if(n.length)return n}return ym(e)},vm="I agree and consent",wm="By continuing, you consent to the above.",Tm="Continue";function Oc({botName:e,consentContent:t,isFullScreen:n}){return c(_e,{children:[c("div",{className:"flex flex-col gap-1",children:[c("h2",{className:D("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Em}),c("p",{className:D("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:Sm(e)})]}),c("div",{className:D("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:xc(e,t).map((r,o)=>c("p",{className:D("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function Nm({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return c(bs,{isOpen:e,onClose:t,children:c("div",{className:D("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?c(Oc,{botName:n,consentContent:o,isFullScreen:s}):c("div",{className:"flex flex-col gap-2",children:[c("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),xc(n,o).map((a,l)=>c("p",{className:D("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},l))]}),c(ve,{onClick:t,className:D("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function Cm({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=U(!1);return e?c(bs,{isOpen:e,children:c("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:D("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:[c(Oc,{botName:t,consentContent:n,isFullScreen:o}),c("div",{className:"flex flex-col gap-1.5",children:[c("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[c("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),c("div",{"aria-hidden":"true",className:D("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&&c("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:D("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:vm})]}),c("p",{className:D("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:wm})]}),c(ve,{disabled:!i,onClick:()=>i&&r(),className:D("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:Tm})]})}):null}const xm=Qe(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),Om=Qe(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),Rm=Qe(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),km=Qe(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),Am=Qe(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),Im=[{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"}],Mm=[{Icon:xm,label:"Bad",score:1},{Icon:Om,label:"Poor",score:2},{Icon:Rm,label:"Okay",score:3},{Icon:km,label:"Good",score:4},{Icon:Am,label:"Great!",score:5}];function Pm(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function Lm({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,l]=U(null),[d,p]=U(new Set),[h,f]=U(!1),m=s&&a!==null?Pm(a,t):t.form?.default?.length?t.form.default:Im,E=g=>{p(_=>{const b=new Set(_);return b.has(g)?b.delete(g):b.add(g),b})},S=g=>{l(g),p(new Set)},w=d?.size>0||a!==null||h,u=()=>{s&&a!==null&&n([...d],a),h&&i?.(),s||n([...d]),r()};return e?c(bs,{isOpen:e,onClose:o,children:c("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[c("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"}),c("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[c("div",{className:"flex flex-col gap-1",children:[t.title&&c("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&c("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&c("div",{className:"flex items-center justify-between gap-1",children:Mm.map(({Icon:g,label:_,score:b})=>{const N=a===b,T=a!==null&&!N;return c("button",{onClick:()=>S(b),title:_,className:"flex flex-col items-center gap-1.5 flex-1 cursor-pointer bg-transparent border-none p-0",children:[c("div",{className:`rounded-xl p-1 transition-all ${N?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${T?"opacity-50":""}`,style:N?{filter:"brightness(1.25)"}:void 0,children:c(Ke,{fallback:c("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:c(g,{})})}),c("span",{className:`text-[10px] leading-none transition-colors ${N?"text-primary/50 font-medium":T?"text-primary/50":"text-primary"}`,children:_})]},b)})}),(!s||a!==null)&&m.length>0&&c("div",{className:"flex flex-col gap-2",children:m.map(g=>c("div",{onClick:()=>E(g.value),className:`rounded-lg border px-3 py-2.5 text-sm text-center cursor-pointer transition-colors ${d.has(g.value)?"border-primary text-primary bg-elicitationBg":"border-primary/25 text-primary/60 bg-elicitationBg"}`,children:g.label},g.value))}),c(ve,{disabled:!w,onClick:u,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),c("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>f(g=>!g),children:[c("div",{className:"relative w-3 h-3 shrink-0",children:c("div",{className:`w-3 h-3 rounded-[3px] border transition-colors flex items-center justify-center ${h?"border-primary bg-primary":"border-muted-foreground bg-transparent"}`,children:h&&c("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),c("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function Rc({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:l,sidePanelMode:d,sidePanelWidth:p,side:h,onSidePanelPushChange:f,isAuthComponent:m,activeElicitation:E,voiceAgentState:S,theme:w,feedbackModal:u,consentModal:g}){const{onClose:_,showCloseButton:b=!0,title:N,titleImg:T,tagline:O,iconUrl:y,onStartNewSession:v,showStartNewChatButton:x,onToggleDisplayMode:P,onOpenSessionDrawer:G}=fm(),[W,ne]=U(!1),[de,ue]=U(!1),[me,F]=U(!1),le=X(null),Ie=V(z=>z.level),te=l,Z=te==="full",$=te==="side_panel",H=X(null),[re,he]=U("");j(()=>{H.current!==null&&H.current!==te&&he(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),H.current=te},[te]);const q=ce(()=>zp(w),[w]),et=V(z=>z.setIsMobile),Ne=!!m,Oe=pe(async z=>{if(!(!s?.onSend||de)){ue(!0);try{await s.onSend(z)}finally{ue(!1)}}},[s?.onSend,de]);gt(()=>{if(!le.current)return;const z=te==="full"?{...q,headerTinted:!1}:q;nc(le.current,z),te==="full"&&!q.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),nc(le.current,q))},[q,te]),j(()=>{const z=()=>{const Fe=window?.innerWidth??0,ye=navigator?.userAgent?.toLowerCase()??"",Pe=Fe<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(ye);ne(Pe),et(Pe)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),gt(()=>{if(!e||!W||!le.current)return;const z=le.current;let Fe=null,ye=null,Pe=null,Xe=window.visualViewport?.offsetTop??0,tt=0;const $e=2,pt=80;if(window.visualViewport){const Ve=()=>{if(z&&window.visualViewport){const Je=window.visualViewport.height,nt=window.visualViewport.offsetTop;Fe=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${nt}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Je}px`,z.style.maxHeight=`${Je}px`,z.style.minHeight=`${Je}px`,ye&&clearTimeout(ye),ye=setTimeout(()=>{z.style.transition=""},100)})}},xt=()=>{Ve()},Le=()=>{if(!z||!window.visualViewport)return;const Je=window.visualViewport.offsetTop,nt=Date.now();Math.abs(Je-Xe)<$e||nt-tt<pt||(tt=nt,Xe=Je,Fe=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Je}px`,Pe&&clearTimeout(Pe),Pe=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",xt),window.visualViewport.addEventListener("scroll",Le),Ve(),()=>{Fe&&cancelAnimationFrame(Fe),ye&&clearTimeout(ye),Pe&&clearTimeout(Pe),window.visualViewport?.removeEventListener("resize",xt),window.visualViewport?.removeEventListener("scroll",Le),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const Ve=()=>{z&&(z.style.transition="none",z.style.top="0",z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height="100svh",z.style.maxHeight="100svh",setTimeout(()=>{z.style.transition=""},100))};return window.addEventListener("resize",Ve),Ve(),()=>{window.removeEventListener("resize",Ve),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,W]),j(()=>{if(e&&!($&&d==="push")){const z=le.current,Fe=window.scrollY,ye=document.body.style.cssText,Pe=document.documentElement.style.overflow,Xe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Fe}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",Xe>0&&!W&&(document.body.style.paddingRight=`${Xe}px`);let tt=0;const $e=Ve=>{tt=Ve.touches[0].clientY},pt=Ve=>{if(Ve.touches.length!==1)return;const xt=tt-Ve.touches[0].clientY;tt=Ve.touches[0].clientY;let Le=Ve.target;for(;Le&&Le!==z;){const{overflowY:Je}=window.getComputedStyle(Le);if((Je==="auto"||Je==="scroll")&&Le.scrollHeight>Le.clientHeight){const{scrollTop:nt,scrollHeight:Ge,clientHeight:Kt}=Le,St=nt<=0&&xt<0,cn=nt+Kt>=Ge-1&&xt>0;if(!St&&!cn)return;break}Le=Le.parentElement}Ve.preventDefault()};return z&&(z.addEventListener("touchstart",$e,{passive:!0}),z.addEventListener("touchmove",pt,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",$e),z.removeEventListener("touchmove",pt)),document.body.style.cssText=ye,document.documentElement.style.overflow=Pe,window.scrollTo(0,Fe)}}},[e,W,$,d]),j(()=>{if(!(!$||d!=="push"||!e))return f?.(!0,p??0,h??"right"),()=>{f?.(!1,p??0,h??"right")}},[e,$,d,p,h,f]);const{position:fe,elementRef:Me}=Dp({enabled:e&&!W&&!Z&&!$});j(()=>{le.current&&(Me.current=le.current)},[Me]);const Dt=D("synapse-chat-widget-container","fixed m-0 p-0","box-border",!W&&!Z&&!$?"transition-all duration-300":"",W?"w-screen h-[100svh]":Z?"w-screen h-screen":$?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),Ct=D("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",q.backgroundImage?"theme-with-background":"",W?"rounded-none border-0 flex-col":Z?"rounded-none border-0 flex-row":$?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return c("div",{ref:le,"data-mode":te,className:Dt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...Z&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...Z&&!e&&{display:"none"},...$&&e&&{top:0,bottom:0,[h==="left"?"left":"right"]:0,[h==="left"?"right":"left"]:"auto",width:`${p}px`,height:"100vh"},...$&&!e&&{display:"none"},...!W&&!Z&&!$&&{left:`${fe.x}px`,top:`${fe.y}px`,bottom:"auto",right:"auto"},...W&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:q.backgroundImage?"transparent":"hsl(var(--background))"}},children:[c("style",{children:`
|
|
1
|
+
var Qc=Object.defineProperty;var ed=(e,t,n)=>t in e?Qc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var R=(e,t,n)=>ed(e,typeof t!="symbol"?t+"":t,n);var Pn,J,Ts,Ut,xs,Cs,ks,ro,Nr,Dn,Os,oo,so,io,Rs,Tr={},xr=[],td=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ln=Array.isArray;function bt(e,t){for(var n in t)e[n]=t[n];return e}function ao(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function tt(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?Pn.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 Un(e,s,r,o,null)}function Un(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??++Ts,__i:-1,__u:0};return o==null&&J.vnode!=null&&J.vnode(i),i}function As(){return{current:null}}function me(e){return e.children}function ct(e,t){this.props=e,this.context=t}function dn(e,t){if(t==null)return e.__?dn(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"?dn(e):null}function nd(e){if(e.__P&&e.__d){var t=e.__v,n=t.__e,r=[],o=[],i=bt({},t);i.__v=t.__v+1,J.vnode&&J.vnode(i),co(e.__P,i,t,e.__n,e.__P.namespaceURI,32&t.__u?[n]:null,r,n??dn(t),!!(32&t.__u),o),i.__v=t.__v,i.__.__k[i.__i]=i,Us(r,i,o),t.__e=t.__=null,i.__e!=n&&Is(i)}}function Is(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}),Is(e)}function lo(e){(!e.__d&&(e.__d=!0)&&Ut.push(e)&&!Cr.__r++||xs!=J.debounceRendering)&&((xs=J.debounceRendering)||Cs)(Cr)}function Cr(){try{for(var e,t=1;Ut.length;)Ut.length>t&&Ut.sort(ks),e=Ut.shift(),t=Ut.length,nd(e)}finally{Ut.length=Cr.__r=0}}function Ms(e,t,n,r,o,i,s,a,l,d,h){var u,p,_,f,g,b,m,E=r&&r.__k||xr,y=t.length;for(l=rd(n,t,E,l,y),u=0;u<y;u++)(_=n.__k[u])!=null&&(p=_.__i!=-1&&E[_.__i]||Tr,_.__i=u,b=co(e,_,p,o,i,s,a,l,d,h),f=_.__e,_.ref&&p.ref!=_.ref&&(p.ref&&ho(p.ref,null,_),h.push(_.ref,_.__c||f,_)),g==null&&f!=null&&(g=f),(m=!!(4&_.__u))||p.__k===_.__k?(l=Ps(_,l,e,m),m&&p.__e&&(p.__e=null)):typeof _.type=="function"&&b!==void 0?l=b:f&&(l=f.nextSibling),_.__u&=-7);return n.__e=g,l}function rd(e,t,n,r,o){var i,s,a,l,d,h=n.length,u=h,p=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]=Un(null,s,null,null,null):Ln(s)?s=e.__k[i]=Un(me,{children:s},null,null,null):s.constructor===void 0&&s.__b>0?s=e.__k[i]=Un(s.type,s.props,s.key,s.ref?s.ref:null,s.__v):e.__k[i]=s,l=i+p,s.__=e,s.__b=e.__b+1,a=null,(d=s.__i=od(s,n,l,u))!=-1&&(u--,(a=n[d])&&(a.__u|=2)),a==null||a.__v==null?(d==-1&&(o>h?p--:o<h&&p++),typeof s.type!="function"&&(s.__u|=4)):d!=l&&(d==l-1?p--:d==l+1?p++:(d>l?p--:p++,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=dn(a)),Vs(a,a));return r}function Ps(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=Ps(o[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dn(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do t=t&&t.nextSibling;while(t!=null&&t.nodeType==8);return t}function It(e,t){return t=t||[],e==null||typeof e=="boolean"||(Ln(e)?e.some(function(n){It(n,t)}):t.push(e)),t}function od(e,t,n,r){var o,i,s,a=e.key,l=e.type,d=t[n],h=d!=null&&(2&d.__u)==0;if(d===null&&a==null||h&&a==d.key&&l==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&&l==d.type)return s}return-1}function Ds(e,t,n){t[0]=="-"?e.setProperty(t,n??""):e[t]=n==null?"":typeof n!="number"||td.test(t)?n:n+"px"}function kr(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||Ds(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||Ds(e.style,t,n[t])}else if(t[0]=="o"&&t[1]=="n")i=t!=(t=t.replace(Os,"$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[Dn]=r[Dn]:(n[Dn]=oo,e.addEventListener(t,i?io:so,i)):e.removeEventListener(t,i?io:so,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 Ls(e){return function(t){if(this.l){var n=this.l[t.type+e];if(t[Nr]==null)t[Nr]=oo++;else if(t[Nr]<n[Dn])return;return n(J.event?J.event(t):t)}}}function co(e,t,n,r,o,i,s,a,l,d){var h,u,p,_,f,g,b,m,E,y,k,x,T,C,S,v=t.type;if(t.constructor!==void 0)return null;128&n.__u&&(l=!!(32&n.__u),i=[a=t.__e=n.__e]),(h=J.__b)&&h(t);e:if(typeof v=="function")try{if(m=t.props,E=v.prototype&&v.prototype.render,y=(h=v.contextType)&&r[h.__c],k=h?y?y.props.value:h.__:r,n.__c?b=(u=t.__c=n.__c).__=u.__E:(E?t.__c=u=new v(m,k):(t.__c=u=new ct(m,k),u.constructor=v,u.render=id),y&&y.sub(u),u.state||(u.state={}),u.__n=r,p=u.__d=!0,u.__h=[],u._sb=[]),E&&u.__s==null&&(u.__s=u.state),E&&v.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=bt({},u.__s)),bt(u.__s,v.getDerivedStateFromProps(m,u.__s))),_=u.props,f=u.state,u.__v=t,p)E&&v.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),E&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(E&&v.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(N){N&&(N.__=t)}),xr.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(_,f,g)})}if(u.context=k,u.props=m,u.__P=e,u.__e=!1,x=J.__r,T=0,E)u.state=u.__s,u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),xr.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(t),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++T<25);u.state=u.__s,u.getChildContext!=null&&(r=bt(bt({},r),u.getChildContext())),E&&!p&&u.getSnapshotBeforeUpdate!=null&&(g=u.getSnapshotBeforeUpdate(_,f)),C=h!=null&&h.type===me&&h.key==null?Fs(h.props.children):h,a=Ms(e,Ln(C)?C:[C],t,n,r,o,i,s,a,l,d),u.base=t.__e,t.__u&=-161,u.__h.length&&s.push(u),b&&(u.__E=u.__=null)}catch(N){if(t.__v=null,l||i!=null)if(N.then){for(t.__u|=l?160:128;a&&a.nodeType==8&&a.nextSibling;)a=a.nextSibling;i[i.indexOf(a)]=null,t.__e=a}else{for(S=i.length;S--;)ao(i[S]);uo(t)}else t.__e=n.__e,t.__k=n.__k,N.then||uo(t);J.__e(N,t,n)}else i==null&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):a=t.__e=sd(n.__e,t,n,r,o,i,s,l,d);return(h=J.diffed)&&h(t),128&t.__u?void 0:a}function uo(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(uo))}function Us(e,t,n){for(var r=0;r<n.length;r++)ho(n[r],n[++r],n[++r]);J.__c&&J.__c(t,e),e.some(function(o){try{e=o.__h,o.__h=[],e.some(function(i){i.call(o)})}catch(i){J.__e(i,o.__v)}})}function Fs(e){return typeof e!="object"||e==null||e.__b>0?e:Ln(e)?e.map(Fs):e.constructor!==void 0?null:bt({},e)}function sd(e,t,n,r,o,i,s,a,l){var d,h,u,p,_,f,g,b=n.props||Tr,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&&(J.__m&&J.__m(t,i),a=!1),i=null}if(E==null)b===m||a&&e.data==m||(e.data=m);else{if(i=E=="textarea"&&m.defaultValue!=null?null:i&&Pn.call(e.childNodes),!a&&i!=null)for(b={},d=0;d<e.attributes.length;d++)b[(_=e.attributes[d]).name]=_.value;for(d in b)_=b[d],d=="dangerouslySetInnerHTML"?u=_:d=="children"||d in m||d=="value"&&"defaultValue"in m||d=="checked"&&"defaultChecked"in m||kr(e,d,null,_,o);for(d in m)_=m[d],d=="children"?p=_:d=="dangerouslySetInnerHTML"?h=_:d=="value"?f=_:d=="checked"?g=_:a&&typeof _!="function"||b[d]===_||kr(e,d,_,b[d],o);if(h)a||u&&(h.__html==u.__html||h.__html==e.innerHTML)||(e.innerHTML=h.__html),t.__k=[];else if(u&&(e.innerHTML=""),Ms(t.type=="template"?e.content:e,Ln(p)?p:[p],t,n,r,E=="foreignObject"?"http://www.w3.org/1999/xhtml":o,i,s,i?i[0]:n.__k&&dn(n,0),a,l),i!=null)for(d=i.length;d--;)ao(i[d]);a&&E!="textarea"||(d="value",E=="progress"&&f==null?e.removeAttribute("value"):f!=null&&(f!==e[d]||E=="progress"&&!f||E=="option"&&f!=b[d])&&kr(e,d,f,b[d],o),d="checked",g!=null&&g!=e[d]&&kr(e,d,g,b[d],o))}return e}function ho(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){J.__e(o,n)}}function Vs(e,t,n){var r,o;if(J.unmount&&J.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||ho(r,null,t)),(r=e.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(i){J.__e(i,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Vs(r[o],t,n||typeof e.type!="function");n||ao(e.__e),e.__c=e.__=e.__e=void 0}function id(e,t,n){return this.constructor(e,n)}function Fn(e,t,n){var r,o,i,s;t==document&&(t=document.documentElement),J.__&&J.__(e,t),o=(r=typeof n=="function")?null:n&&n.__k||t.__k,i=[],s=[],co(t,e=(!r&&n||t).__k=tt(me,null,[e]),o||Tr,Tr,t.namespaceURI,!r&&n?[n]:o?null:t.firstChild?Pn.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r,s),Us(i,e,s)}function js(e,t){Fn(e,t,js)}function ad(e,t,n){var r,o,i,s,a=bt({},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?Pn.call(arguments,2):n),Un(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,lo(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"+Rs++,t.__=e,t.Provider=t.__l=(t.Consumer=function(n,r){return n.children(r)}).contextType=t,t}Pn=xr.slice,J={__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}},Ts=0,ct.prototype.setState=function(e,t){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=bt({},this.state),typeof e=="function"&&(e=e(bt({},n),this.props)),e&&bt(n,e),e!=null&&this.__v&&(t&&this._sb.push(t),lo(this))},ct.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),lo(this))},ct.prototype.render=me,Ut=[],Cs=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ks=function(e,t){return e.__v.__b-t.__v.__b},Cr.__r=0,ro=Math.random().toString(8),Nr="__d"+ro,Dn="__a"+ro,Os=/(PointerCapture)$|Capture$/i,oo=0,so=Ls(!1),io=Ls(!0),Rs=0;var ld=0;function c(e,t,n,r,o,i){t||(t={});var s,a,l=t;if("ref"in l)for(a in l={},t)a=="ref"?s=t[a]:l[a]=t[a];var d={type:e,props:l,key:n,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ld,__i:-1,__u:0,__source:o,__self:i};if(typeof e=="function"&&(s=e.defaultProps))for(a in s)l[a]===void 0&&(l[a]=s[a]);return J.vnode&&J.vnode(d),d}var Mt,ge,mo,zs,un=0,Ys=[],Ce=J,Hs=Ce.__b,$s=Ce.__r,Bs=Ce.diffed,Gs=Ce.__c,Ws=Ce.unmount,Ks=Ce.__;function qt(e,t){Ce.__h&&Ce.__h(ge,e,un||t),un=0;var n=ge.__H||(ge.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function F(e){return un=1,hn(Xs,e)}function hn(e,t,n){var r=qt(Mt++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xs(void 0,t),function(a){var l=r.__N?r.__N[0]:r.__[0],d=r.t(l,a);l!==d&&(r.__N=[d,r.__[1]],r.__c.setState({}))}],r.__c=ge,!ge.__f)){var o=function(a,l,d){if(!r.__c.__H)return!0;var h=r.__c.__H.__.filter(function(p){return p.__c});if(h.every(function(p){return!p.__N}))return!i||i.call(this,a,l,d);var u=r.__c.props!==a;return h.some(function(p){if(p.__N){var _=p.__[0];p.__=p.__N,p.__N=void 0,_!==p.__[0]&&(u=!0)}}),i&&i.call(this,a,l,d)||u};ge.__f=!0;var i=ge.shouldComponentUpdate,s=ge.componentWillUpdate;ge.componentWillUpdate=function(a,l,d){if(this.__e){var h=i;i=void 0,o(a,l,d),i=h}s&&s.call(this,a,l,d)},ge.shouldComponentUpdate=o}return r.__N||r.__}function Y(e,t){var n=qt(Mt++,3);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__H.__h.push(n))}function ft(e,t){var n=qt(Mt++,4);!Ce.__s&&Eo(n.__H,t)&&(n.__=e,n.u=t,ge.__h.push(n))}function X(e){return un=5,ie(function(){return{current:e}},[])}function po(e,t,n){un=6,ft(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 ie(e,t){var n=qt(Mt++,7);return Eo(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function de(e,t){return un=8,ie(function(){return e},t)}function wt(e){var t=ge.context[e.__c],n=qt(Mt++,9);return n.c=e,t?(n.__==null&&(n.__=!0,t.sub(ge)),t.props.value):e.__}function fo(e,t){Ce.useDebugValue&&Ce.useDebugValue(t?t(e):e)}function cd(e){var t=qt(Mt++,10),n=F();return t.__=e,ge.componentDidCatch||(ge.componentDidCatch=function(r,o){t.__&&t.__(r,o),n[1](r)}),[n[0],function(){n[1](void 0)}]}function go(){var e=qt(Mt++,11);if(!e.__){for(var t=ge.__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 dd(){for(var e;e=Ys.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Or),t.__h.some(_o),t.__h=[]}catch(n){t.__h=[],Ce.__e(n,e.__v)}}}Ce.__b=function(e){ge=null,Hs&&Hs(e)},Ce.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Ks&&Ks(e,t)},Ce.__r=function(e){$s&&$s(e),Mt=0;var t=(ge=e.__c).__H;t&&(mo===ge?(t.__h=[],ge.__h=[],t.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(t.__h.some(Or),t.__h.some(_o),t.__h=[],Mt=0)),mo=ge},Ce.diffed=function(e){Bs&&Bs(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ys.push(t)!==1&&zs===Ce.requestAnimationFrame||((zs=Ce.requestAnimationFrame)||ud)(dd)),t.__H.__.some(function(n){n.u&&(n.__H=n.u),n.u=void 0})),mo=ge=null},Ce.__c=function(e,t){t.some(function(n){try{n.__h.some(Or),n.__h=n.__h.filter(function(r){return!r.__||_o(r)})}catch(r){t.some(function(o){o.__h&&(o.__h=[])}),t=[],Ce.__e(r,n.__v)}}),Gs&&Gs(e,t)},Ce.unmount=function(e){Ws&&Ws(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(r){try{Or(r)}catch(o){t=o}}),n.__H=void 0,t&&Ce.__e(t,n.__v))};var qs=typeof requestAnimationFrame=="function";function ud(e){var t,n=function(){clearTimeout(r),qs&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);qs&&(t=requestAnimationFrame(n))}function Or(e){var t=ge,n=e.__c;typeof n=="function"&&(e.__c=void 0,n()),ge=t}function _o(e){var t=ge;e.__c=e.__(),ge=t}function Eo(e,t){return!e||e.length!==t.length||t.some(function(n,r){return n!==e[r]})}function Xs(e,t){return typeof t=="function"?t(e):t}function Zs(e,t){for(var n in t)e[n]=t[n];return e}function yo(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 So(e,t){var n=t(),r=F({t:{__:n,u:t}}),o=r[0].t,i=r[1];return ft(function(){o.__=n,o.u=t,bo(o)&&i({t:o})},[e,n,t]),Y(function(){return bo(o)&&i({t:o}),e(function(){bo(o)&&i({t:o})})},[e]),n}function bo(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 vo(e){e()}function wo(e){return e}function No(){return[!1,vo]}var To=ft;function Rr(e,t){this.props=e,this.context=t}function Xt(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:yo(this.props,o)}function r(o){return this.shouldComponentUpdate=n,tt(e,o)}return r.displayName="Memo("+(e.displayName||e.name)+")",r.__f=r.prototype.isReactComponent=!0,r.type=e,r}(Rr.prototype=new ct).isPureReactComponent=!0,Rr.prototype.shouldComponentUpdate=function(e,t){return yo(this.props,e)||yo(this.state,t)};var Js=J.__b;J.__b=function(e){e.type&&e.type.__f&&e.ref&&(e.props.ref=e.ref,e.ref=null),Js&&Js(e)};var hd=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function ee(e){function t(n){var r=Zs({},n);return delete r.ref,e(r,n.ref||null)}return t.$$typeof=hd,t.render=e,t.prototype.isReactComponent=t.__f=!0,t.displayName="ForwardRef("+(e.displayName||e.name)+")",t}var Qs=function(e,t){return e==null?null:It(It(e).map(t))},st={map:Qs,forEach:Qs,count:function(e){return e?It(e).length:0},only:function(e){var t=It(e);if(t.length!==1)throw"Children.only";return t[0]},toArray:It},md=J.__e;J.__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)}md(e,t,n,r)};var ei=J.unmount;function ti(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=Zs({},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 ti(r,t,n)})),e}function ni(e,t,n){return e&&n&&(e.__v=null,e.__k=e.__k&&e.__k.map(function(r){return ni(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 Xe(){this.__u=0,this.o=null,this.__b=null}function ri(e){var t=e.__&&e.__.__c;return t&&t.__a&&t.__a(e)}function nt(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?tt(o,s):null}return i.displayName="Lazy",i.__f=!0,i}function mn(){this.i=null,this.l=null}J.unmount=function(e){var t=e.__c;t&&(t.__z=!0),t&&t.__R&&t.__R(),t&&32&e.__u&&(e.type=null),ei&&ei(e)},(Xe.prototype=new ct).__c=function(e,t){var n=t.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var o=ri(r.__v),i=!1,s=function(){i||r.__z||(i=!0,n.__R=null,o?o(l):l())};n.__R=s;var a=n.__P;n.__P=null;var l=function(){if(!--r.__u){if(r.state.__a){var d=r.state.__a;r.__v.__k[0]=ni(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)},Xe.prototype.componentWillUnmount=function(){this.o=[]},Xe.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]=ti(this.__b,n,r.__O=r.__P)}this.__b=null}var o=t.__a&&tt(me,null,e.fallback);return o&&(o.__u&=-33),[tt(me,null,t.__a?null:e.children),o]};var oi=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 pd(e){return this.getChildContext=function(){return e.context},e.children}function fd(e){var t=this,n=e.h;if(t.componentWillUnmount=function(){Fn(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)}}}Fn(tt(pd,{context:t.context},e.__v),t.v)}function si(e,t){var n=tt(fd,{__v:e,h:t});return n.containerInfo=t,n}(mn.prototype=new ct).__a=function(e){var t=this,n=ri(t.__v),r=t.l.get(e);return r[0]++,function(o){var i=function(){t.props.revealOrder?(r.push(o),oi(t,e,r)):o()};n?n(i):i()}},mn.prototype.render=function(e){this.i=null,this.l=new Map;var t=It(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},mn.prototype.componentDidUpdate=mn.prototype.componentDidMount=function(){var e=this;this.l.forEach(function(t,n){oi(e,n,t)})};var ii=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,gd=/^(?: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]/,_d=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,Ed=/[A-Z0-9]/g,yd=typeof document<"u",Sd=function(e){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(e)};function xo(e,t,n){return t.__k==null&&(t.textContent=""),Fn(e,t),typeof n=="function"&&n(),e?e.__c:null}function ai(e,t,n){return js(e,t),typeof n=="function"&&n(),e?e.__c:null}ct.prototype.isReactComponent=!0,["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(e){Object.defineProperty(ct.prototype,e,{configurable:!0,get:function(){return this["UNSAFE_"+e]},set:function(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:t})}})});var li=J.event;J.event=function(e){return li&&(e=li(e)),e.persist=function(){},e.isPropagationStopped=function(){return this.cancelBubble},e.isDefaultPrevented=function(){return this.defaultPrevented},e.nativeEvent=e};var Co,bd={configurable:!0,get:function(){return this.class}},ci=J.vnode;J.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||yd&&s==="children"&&r==="noscript"||s==="class"||s==="className")){var l=s.toLowerCase();s==="defaultValue"&&"value"in n&&n.value==null?s="value":s==="download"&&a===!0?a="":l==="translate"&&a==="no"?a=!1:l[0]==="o"&&l[1]==="n"?l==="ondoubleclick"?s="ondblclick":l!=="onchange"||r!=="input"&&r!=="textarea"||Sd(n.type)?l==="onfocus"?s="onfocusin":l==="onblur"?s="onfocusout":_d.test(s)&&(s=l):l=s="oninput":i&&gd.test(s)?s=s.replace(Ed,"-$&").toLowerCase():a===null&&(a=void 0),l==="oninput"&&o[s=l]&&(s="oninputCapture"),o[s]=a}}r=="select"&&(o.multiple&&Array.isArray(o.value)&&(o.value=It(n.children).forEach(function(d){d.props.selected=o.value.indexOf(d.props.value)!=-1})),o.defaultValue!=null&&(o.value=It(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",bd)):n.className&&(o.class=o.className=n.className),t.props=o})(e),e.$$typeof=ii,ci&&ci(e)};var di=J.__r;J.__r=function(e){di&&di(e),Co=e.__c};var ui=J.diffed;J.diffed=function(e){ui&&ui(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),Co=null};var hi={ReactCurrentDispatcher:{current:{readContext:function(e){return Co.__n[e.__c].props.value},useCallback:de,useContext:wt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:ft,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No}}},vd="18.3.1";function mi(e){return tt.bind(null,e)}function it(e){return!!e&&e.$$typeof===ii}function pi(e){return it(e)&&e.type===me}function fi(e){return!!e&&typeof e.displayName=="string"&&e.displayName.indexOf("Memo(")==0}function Ft(e){return it(e)?ad.apply(null,arguments):e}function ko(e){return!!e.__k&&(Fn(null,e),!0)}function gi(e){return e&&(e.base||e.nodeType===1&&e)||null}var _i=function(e,t){return e(t)},Ei=function(e,t){var n=J.debounceRendering;J.debounceRendering=function(o){return o()};var r=e(t);return J.debounceRendering=n,r},yi=it,Vn={useState:F,useId:go,useReducer:hn,useEffect:Y,useLayoutEffect:ft,useInsertionEffect:To,useTransition:No,useDeferredValue:wo,useSyncExternalStore:So,startTransition:vo,useRef:X,useImperativeHandle:po,useMemo:ie,useCallback:de,useContext:wt,useDebugValue:fo,version:"18.3.1",Children:st,render:xo,hydrate:ai,unmountComponentAtNode:ko,createPortal:si,createElement:tt,createContext:vt,createFactory:mi,cloneElement:Ft,createRef:As,Fragment:me,isValidElement:it,isElement:yi,isFragment:pi,isMemo:fi,findDOMNode:gi,Component:ct,PureComponent:Rr,memo:Xt,forwardRef:ee,flushSync:Ei,unstable_batchedUpdates:_i,StrictMode:me,Suspense:Xe,SuspenseList:mn,lazy:nt,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi};const Oo=Object.freeze(Object.defineProperty({__proto__:null,Children:st,Component:ct,Fragment:me,PureComponent:Rr,StrictMode:me,Suspense:Xe,SuspenseList:mn,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:hi,cloneElement:Ft,createContext:vt,createElement:tt,createFactory:mi,createPortal:si,createRef:As,default:Vn,findDOMNode:gi,flushSync:Ei,forwardRef:ee,hydrate:ai,isElement:yi,isFragment:pi,isMemo:fi,isValidElement:it,lazy:nt,memo:Xt,render:xo,startTransition:vo,unmountComponentAtNode:ko,unstable_batchedUpdates:_i,useCallback:de,useContext:wt,useDebugValue:fo,useDeferredValue:wo,useEffect:Y,useErrorBoundary:cd,useId:go,useImperativeHandle:po,useInsertionEffect:To,useLayoutEffect:ft,useMemo:ie,useReducer:hn,useRef:X,useState:F,useSyncExternalStore:So,useTransition:No,version:vd},Symbol.toStringTag,{value:"Module"}));function wd(e){return{render:function(t){xo(t,e)},unmount:function(){ko(e)}}}function Si(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Ro(...e){return t=>{let n=!1;const r=e.map(o=>{const i=Si(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():Si(e[o],null)}}}}function Vt(...e){return de(Ro(...e),e)}function Nd(e){const t=Td(e),n=ee((r,o)=>{const{children:i,...s}=r,a=st.toArray(i),l=a.find(Cd);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}function Td(e){const t=ee((n,r)=>{const{children:o,...i}=n;if(it(o)){const s=Od(o),a=kd(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var xd=Symbol("radix.slottable");function Cd(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===xd}function kd(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 Od(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 Rd=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],pn=Rd.reduce((e,t)=>{const n=Nd(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Zt=globalThis?.document?ft:()=>{};function Ad(e,t){return hn((n,r)=>t[n][r]??n,e)}var fn=e=>{const{present:t,children:n}=e,r=Id(t),o=typeof n=="function"?n({present:r.isPresent}):st.only(n),i=Vt(r.ref,Md(o));return typeof n=="function"||r.isPresent?Ft(o,{ref:i}):null};fn.displayName="Presence";function Id(e){const[t,n]=F(),r=X(null),o=X(e),i=X("none"),s=e?"mounted":"unmounted",[a,l]=Ad(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Y(()=>{const d=Ar(r.current);i.current=a==="mounted"?d:"none"},[a]),Zt(()=>{const d=r.current,h=o.current;if(h!==e){const u=i.current,p=Ar(d);e?l("MOUNT"):p==="none"||d?.display==="none"?l("UNMOUNT"):l(h&&u!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),Zt(()=>{if(t){let d;const h=t.ownerDocument.defaultView??window,u=_=>{const f=Ar(r.current).includes(CSS.escape(_.animationName));if(_.target===t&&f&&(l("ANIMATION_END"),!o.current)){const g=t.style.animationFillMode;t.style.animationFillMode="forwards",d=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=g)})}},p=_=>{_.target===t&&(i.current=Ar(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",u),t.addEventListener("animationend",u),()=>{h.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",u),t.removeEventListener("animationend",u)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:de(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function Ar(e){return e?.animationName||"none"}function Md(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 bi(e,t=[]){let n=[];function r(i,s){const a=vt(s),l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=wt(_);if(f)return f;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 ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,Pd(o,...t)]}function Pd(...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:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}function jt(e){const t=X(e);return Y(()=>{t.current=e}),ie(()=>(...n)=>t.current?.(...n),[])}var Dd=vt(void 0);function Ld(e){const t=wt(Dd);return e||t||"ltr"}function Ud(e,[t,n]){return Math.min(n,Math.max(t,e))}function zt(e,t,{checkForDefaultPrevented:n=!0}={}){return function(r){if(e?.(r),n===!1||!r.defaultPrevented)return t?.(r)}}function Fd(e,t){return hn((n,r)=>t[n][r]??n,e)}var Ao="ScrollArea",[vi]=bi(Ao),[Vd,dt]=vi(Ao),wi=ee((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[a,l]=F(null),[d,h]=F(null),[u,p]=F(null),[_,f]=F(null),[g,b]=F(null),[m,E]=F(0),[y,k]=F(0),[x,T]=F(!1),[C,S]=F(!1),v=Vt(t,P=>l(P)),N=Ld(o);return c(Vd,{scope:n,type:r,dir:N,scrollHideDelay:i,scrollArea:a,viewport:d,onViewportChange:h,content:u,onContentChange:p,scrollbarX:_,onScrollbarXChange:f,scrollbarXEnabled:x,onScrollbarXEnabledChange:T,scrollbarY:g,onScrollbarYChange:b,scrollbarYEnabled:C,onScrollbarYEnabledChange:S,onCornerWidthChange:E,onCornerHeightChange:k,children:c(pn.div,{dir:N,...s,ref:v,style:{position:"relative","--radix-scroll-area-corner-width":m+"px","--radix-scroll-area-corner-height":y+"px",...e.style}})})});wi.displayName=Ao;var Ni="ScrollAreaViewport",Ti=ee((e,t)=>{const{__scopeScrollArea:n,children:r,nonce:o,...i}=e,s=dt(Ni,n),a=X(null),l=Vt(t,a,s.onViewportChange);return c(me,{children:[c("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}),c(pn.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...e.style},children:c("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Ti.displayName=Ni;var Nt="ScrollAreaScrollbar",Io=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=e.orientation==="horizontal";return Y(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?c(jd,{...r,ref:t,forceMount:n}):o.type==="scroll"?c(zd,{...r,ref:t,forceMount:n}):o.type==="auto"?c(xi,{...r,ref:t,forceMount:n}):o.type==="always"?c(Mo,{...r,ref:t}):null});Io.displayName=Nt;var jd=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),[i,s]=F(!1);return Y(()=>{const a=o.scrollArea;let l=0;if(a){const d=()=>{window.clearTimeout(l),s(!0)},h=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",d),a.addEventListener("pointerleave",h),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",d),a.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),c(fn,{present:n||i,children:c(xi,{"data-state":i?"visible":"hidden",...r,ref:t})})}),zd=ee((e,t)=>{const{forceMount:n,...r}=e,o=dt(Nt,e.__scopeScrollArea),i=e.orientation==="horizontal",s=Dr(()=>l("SCROLL_END"),100),[a,l]=Fd("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return Y(()=>{if(a==="idle"){const d=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[a,o.scrollHideDelay,l]),Y(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let u=d[h];const p=()=>{const _=d[h];u!==_&&(l("SCROLL"),s()),u=_};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[o.viewport,i,l,s]),c(fn,{present:n||a!=="hidden",children:c(Mo,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:zt(e.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:zt(e.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),xi=ee((e,t)=>{const n=dt(Nt,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=F(!1),a=e.orientation==="horizontal",l=Dr(()=>{if(n.viewport){const d=n.viewport.offsetWidth<n.viewport.scrollWidth,h=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?d:h)}},10);return gn(n.viewport,l),gn(n.content,l),c(fn,{present:r||i,children:c(Mo,{"data-state":i?"visible":"hidden",...o,ref:t})})}),Mo=ee((e,t)=>{const{orientation:n="vertical",...r}=e,o=dt(Nt,e.__scopeScrollArea),i=X(null),s=X(0),[a,l]=F({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=Ai(a.viewport,a.content),h={...r,sizes:a,onSizesChange:l,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:p=>s.current=p};function u(p,_){return Wd(p,s.current,a,_)}return n==="horizontal"?c(Yd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollLeft,_=Ii(p,a,o.dir);i.current.style.transform=`translate3d(${_}px, 0, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollLeft=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollLeft=u(p,o.dir))}}):n==="vertical"?c(Hd,{...h,ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const p=o.viewport.scrollTop,_=Ii(p,a);i.current.style.transform=`translate3d(0, ${_}px, 0)`}},onWheelScroll:p=>{o.viewport&&(o.viewport.scrollTop=p)},onDragScroll:p=>{o.viewport&&(o.viewport.scrollTop=u(p))}}):null}),Yd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=dt(Nt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarXChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"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":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:Mr(s.paddingLeft),paddingEnd:Mr(s.paddingRight)}})}})}),Hd=ee((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=dt(Nt,e.__scopeScrollArea),[s,a]=F(),l=X(null),d=Vt(t,l,i.onScrollbarYChange);return Y(()=>{l.current&&a(getComputedStyle(l.current))},[l]),c(ki,{"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":Pr(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,u)=>{if(i.viewport){const p=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(p),Pi(p,u)&&h.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:Mr(s.paddingTop),paddingEnd:Mr(s.paddingBottom)}})}})}),[$d,Ci]=vi(Nt),ki=ee((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:d,onWheelScroll:h,onResize:u,...p}=e,_=dt(Nt,n),[f,g]=F(null),b=Vt(t,v=>g(v)),m=X(null),E=X(""),y=_.viewport,k=r.content-r.viewport,x=jt(h),T=jt(l),C=Dr(u,10);function S(v){if(m.current){const N=v.clientX-m.current.left,P=v.clientY-m.current.top;d({x:N,y:P})}}return Y(()=>{const v=N=>{const P=N.target;f?.contains(P)&&x(N,k)};return document.addEventListener("wheel",v,{passive:!1}),()=>document.removeEventListener("wheel",v,{passive:!1})},[y,f,k,x]),Y(T,[r,T]),gn(f,C),gn(_.content,C),c($d,{scope:n,scrollbar:f,hasThumb:o,onThumbChange:jt(i),onThumbPointerUp:jt(s),onThumbPositionChange:T,onThumbPointerDown:jt(a),children:c(pn.div,{...p,ref:b,style:{position:"absolute",...p.style},onPointerDown:zt(e.onPointerDown,v=>{v.button===0&&(v.target.setPointerCapture(v.pointerId),m.current=f.getBoundingClientRect(),E.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",_.viewport&&(_.viewport.style.scrollBehavior="auto"),S(v))}),onPointerMove:zt(e.onPointerMove,S),onPointerUp:zt(e.onPointerUp,v=>{const N=v.target;N.hasPointerCapture(v.pointerId)&&N.releasePointerCapture(v.pointerId),document.body.style.webkitUserSelect=E.current,_.viewport&&(_.viewport.style.scrollBehavior=""),m.current=null})})})}),Ir="ScrollAreaThumb",Oi=ee((e,t)=>{const{forceMount:n,...r}=e,o=Ci(Ir,e.__scopeScrollArea);return c(fn,{present:n||o.hasThumb,children:c(Bd,{ref:t,...r})})}),Bd=ee((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=dt(Ir,n),s=Ci(Ir,n),{onThumbPositionChange:a}=s,l=Vt(t,u=>s.onThumbChange(u)),d=X(void 0),h=Dr(()=>{d.current&&(d.current(),d.current=void 0)},100);return Y(()=>{const u=i.viewport;if(u){const p=()=>{if(h(),!d.current){const _=Kd(u,a);d.current=_,a()}};return a(),u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,h,a]),c(pn.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:zt(e.onPointerDownCapture,u=>{const p=u.target.getBoundingClientRect(),_=u.clientX-p.left,f=u.clientY-p.top;s.onThumbPointerDown({x:_,y:f})}),onPointerUp:zt(e.onPointerUp,s.onThumbPointerUp)})});Oi.displayName=Ir;var Po="ScrollAreaCorner",Ri=ee((e,t)=>{const n=dt(Po,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?c(Gd,{...e,ref:t}):null});Ri.displayName=Po;var Gd=ee((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=dt(Po,n),[i,s]=F(0),[a,l]=F(0),d=!!(i&&a);return gn(o.scrollbarX,()=>{const h=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(h),l(h)}),gn(o.scrollbarY,()=>{const h=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(h),s(h)}),d?c(pn.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 Mr(e){return e?parseInt(e,10):0}function Ai(e,t){const n=e/t;return isNaN(n)?0:n}function Pr(e){const t=Ai(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function Wd(e,t,n,r="ltr"){const o=Pr(n),i=o/2,s=t||i,a=o-s,l=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 Mi([l,d],u)(e)}function Ii(e,t,n="ltr"){const r=Pr(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],d=Ud(e,l);return Mi([0,s],[0,a])(d)}function Mi(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 Pi(e,t){return e>0&&e<t}var Kd=(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 Dr(e,t){const n=jt(e),r=X(0);return Y(()=>()=>window.clearTimeout(r.current),[]),de(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function gn(e,t){const n=jt(t);Zt(()=>{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 Di=wi,qd=Ti,Xd=Ri;function Zd(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 _n={},jn={},Li={},zn={},Yn={},Hn={},Ui;function Do(){if(Ui)return Hn;Ui=1,Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.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 Hn.EventEmitter=e,Hn}var En={},Fi;function $n(){return Fi||(Fi=1,Object.defineProperty(En,"__esModule",{value:!0}),En.DisconnectionReason=En.ConnectionStatus=void 0,En.ConnectionStatus={CONNECTING:"connecting",CONNECTED:"connected",NOT_CONNECTED:"not_connected"},En.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"}),En}var Vi;function Lo(){if(Vi)return Yn;Vi=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.BaseConnection=void 0;const e=Do(),t=$n();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 Yn.BaseConnection=n,Yn}var ji={},zi;function at(){return zi||(zi=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=x,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(S,v=e.SynapseErrorCode.UNKNOWN,N={}){super(S);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=v,this.timestamp=new Date,this.cause=N.cause,this.context=N.context,this.hint=N.hint,this.reason=N.reason,this.displayMessage=N.displayMessage||N?.hint||S,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}e.SynapseError=t;class n extends t{constructor(S,v,N,P){const B=n.makeMessage(v,N,S);super(B,e.SynapseErrorCode.API,{cause:N,context:{status:v,hasBody:!!N},hint:v&&v>=500?"Retry the request or contact support if the issue persists.":void 0,displayMessage:S||"Something went wrong"});R(this,"status");R(this,"error");R(this,"headers");this.name="APIError",this.status=v,this.error=N,this.headers=P}static makeMessage(S,v,N){const P=v instanceof Error?v.message:N;return S&&P?`HTTP ${S}: ${P}`:S?`${S} status code (no body)`:P||"(no status code or body)"}static generate(S,v,N,P){if(!S)return new r({message:N});const B=v?.error,G=B&&typeof B=="object"&&!Array.isArray(B)?B:void 0;switch(S){case 400:return new i(N||"Bad Request",S,G,P);case 401:return new s(N||"Unauthorized",S,G,P);case 403:return new a(N||"Permission Denied",S,G,P);case 404:return new l(N||"Not Found",S,G,P);case 405:return new d(N||"Method Not Allowed",S,G,P);case 429:return new h(N||"Rate Limit Exceeded",S,G,P);case 500:return new u(N||"Internal Server Error",S,G,P);default:return new n(N||"API Error",S,G,P)}}}e.APIError=n;class r extends n{constructor({message:C}={}){super(C||"Request was aborted.",void 0,void 0,void 0),this.name="APIUserAbortError"}}e.APIUserAbortError=r;class o extends n{constructor({message:C}={}){super(C||"Request timed out.",void 0,void 0,void 0),this.name="APIConnectionTimeoutError"}}e.APIConnectionTimeoutError=o;class i extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="BadRequestError"}}e.BadRequestError=i;class s extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="UnauthorizedError"}}e.UnauthorizedError=s;class a extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="PermissionDeniedError"}}e.PermissionDeniedError=a;class l extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="NotFoundError"}}e.NotFoundError=l;class d extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="MethodNotAllowedError"}}e.MethodNotAllowedError=d;class h extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="RateLimitError"}}e.RateLimitError=h;class u extends n{constructor(C,S,v,N){super(C,S,v,N),this.name="InternalServerError"}}e.InternalServerError=u;class p extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONNECTION,S),this.name="ConnectionError"}}e.ConnectionError=p;class _ extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.RECORDING,S),this.name="RecordingError"}}e.RecordingError=_;class f extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.AUTH,S),this.name="AuthenticationError"}}e.AuthenticationError=f;class g extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.FILE,S),this.name="FileError"}}e.FileError=g;class b extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.SESSION,S),this.name="SessionError"}}e.SessionError=b;class m extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.MESSAGE,S),this.name="MessageError"}}e.MessageError=m;class E extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.STORE,S),this.name="StoreError"}}e.StoreError=E;class y extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.CONFIGURATION,S),this.name="ConfigurationError"}}e.ConfigurationError=y;class k extends t{constructor(C,S={}){super(C,e.SynapseErrorCode.VALIDATION,S),this.name="ValidationError"}}e.ValidationError=k;function x(T,C,S,v={}){if(T instanceof C)return T;const N={...v,context:{...T instanceof t?T.context:void 0,...v.context},hint:v.hint??(T instanceof t?T.hint:void 0),reason:v.reason??(T instanceof t?T.reason:void 0),cause:v.cause??T};if(T instanceof t)return new C(T.message,N);const P=T instanceof Error&&T.message?T.message:S;return new C(P,N)}})(ji)),ji}var Yi;function Hi(){if(Yi)return zn;Yi=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.WebSocketConnection=void 0;const e=Lo(),t=$n(),n=at();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 l=(0,n.normalizeError)(a,n.MessageError,"Failed to parse incoming WebSocket message",{context:{stage:"handleSocketMessage"}});this.onErrorCallback?.(l)}}handleError(s){}handleClose(s){const a=s.wasClean,l=s.code,d=s.reason;let h,u;this.authenticated=!1,!this.isConnected()&&(l===1e3?(h=t.DisconnectionReason.CLIENT_CLOSED,u="Connection closed normally"):l===1001||l===1006?(h=t.DisconnectionReason.NETWORK_ERROR,u=s.reason||"Network connection lost"):l===4001||l===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"):l===4401||l===4403?(h=t.DisconnectionReason.AUTHENTICATION_ERROR,u=s.reason||(l===4401?"Session token expired":"Session credentials rejected")):l===4404?(h=t.DisconnectionReason.SERVER_CLOSED,u=s.reason||"Session no longer exists"):l===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:l,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 l=(0,n.normalizeError)(a,n.ConnectionError,"Failed to send WebSocket message",{context:{stage:"sendMessage"}});throw this.onErrorCallback?.(l),l}}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 zn.WebSocketConnection=r,zn}var Bn={},$i={},Bi;function Gi(){return Bi||(Bi=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})($i)),$i}var Wi;function Ki(){if(Wi)return Bn;Wi=1,Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.SSEConnection=void 0;const e=Lo(),t=$n(),n=Gi(),r=at();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 l=new AbortController;this.activeStreamController=l,this.streamChat(a,l)}postChat(a,l,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(l),signal:d.signal})}async streamChat(a,l){const d=this.buildChatUrl();try{let h=await this.postChat(d,a,l);if(h.status===401&&this.config.auth.onUnauthorized){const f=await this.config.auth.onUnauthorized();if(l.signal.aborted)return;f&&(h=await this.postChat(d,a,l))}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(),p=new TextDecoder;let _="";for(;;){const{done:f,value:g}=await u.read();if(f)break;_+=p.decode(g,{stream:!0}),_=this.extractJsonObjects(_)}_.trim().length>0&&this.extractJsonObjects(_)}catch(h){if(l.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===l&&(this.activeStreamController=null)}}extractJsonObjects(a){let l=0;for(;l<a.length;){const d=a.indexOf("{",l);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 p=JSON.parse(u);this.handleMessage(p)}catch(p){const _=(0,r.normalizeError)(p,r.MessageError,"Failed to parse incoming SSE object",{context:{stage:"extractJsonObjects",objStr:u}});this.onErrorCallback?.(_)}l=h+1}return""}findObjectEnd(a,l){let d=0,h=!1,u=!1;for(let p=l;p<a.length;p++){const _=a[p];if(h){u?u=!1:_==="\\"?u=!0:_==='"'&&(h=!1);continue}if(_==='"')h=!0;else if(_==="{")d++;else if(_==="}"&&(d--,d===0))return p}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 Bn.SSEConnection=o,Bn}var qi;function Xi(){return qi||(qi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ConnectionFactory=e.ConnectionType=void 0;const t=Hi(),n=Ki(),r=at();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})(Li)),Li}var Gn={},Zi;function Uo(){if(Zi)return Gn;Zi=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.getConfig=void 0;const e={WEBSOCKET_URL:"wss://matrix-ws.eka.care/reloaded",BASE_API_URL:"https://matrix.eka.care/reloaded"},t={WEBSOCKET_URL:"wss://matrix-ws.dev.eka.care/reloaded",BASE_API_URL:"https://matrix.dev.eka.care/reloaded"},n={WEBSOCKET_URL:"wss://matrix-ws.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 Gn.getConfig=r,Gn}var Wn={},Kn={},Ji;function Lr(){if(Ji)return Kn;Ji=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.HttpClient=void 0;const e=at();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 l=this.buildUrl(r,o?.params),d=await fetch(l,{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(l){if(s=l,a===i||!(l instanceof TypeError&&l.message==="Failed to fetch"||l instanceof DOMException&&l.name==="AbortError"||l 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 Kn.HttpClient=t,Kn}var qn={},Xn={},Qi;function Zn(){if(Qi)return Xn;Qi=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.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 Xn.BaseResource=e,Xn}var ea;function ta(){if(ea)return qn;ea=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.Session=void 0;const e=Zn();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:l}){return this.put(`${this.basePath}/${r}${o?`/messages/${o}`:""}/feedback`,{feedback:i,feedbacks:s,...a&&{feedback_reason:a},...l&&{nps_base5:l}})}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 qn.Session=t,qn}var Jn={},na;function Fo(){if(na)return Jn;na=1,Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.Config=void 0;const e=Zn();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 Jn.Config=t,Jn}var ra={},oa;function sa(){return oa||(oa=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildAgentConfigKey=void 0,e.prefetchAgentConfig=s,e.consumePrefetchedAgentConfig=a;const t=Lr(),n=Uo(),r=Fo(),o=new Map,i=(l,d)=>`${l.replace(/\/$/,"")}|${d}`;e.buildAgentConfigKey=i;function s(l){const d=l.serverUrl||(0,n.getConfig)(l.environment).BASE_API_URL,h=(0,e.buildAgentConfigKey)(d,l.agentId),u=o.get(h);if(u)return u;const p=new t.HttpClient({baseUrl:d,headers:{"ngrok-skip-browser-warning":"69420","X-agent-id":l.agentId,...l.channel&&{"x-channel":l.channel}}}),_=new r.Config(p).retrieve(l.agentId);return _.catch(()=>{o.get(h)===_&&o.delete(h)}),o.set(h,_),_}function a(l){const d=o.get(l);return d&&o.delete(l),d}})(ra)),ra}var Qn={},ia;function Vo(){if(ia)return Qn;ia=1,Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.Auth=void 0;const e=Zn();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 Qn.Auth=t,Qn}var er={},yn={},aa;function jo(){return aa||(aa=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.ErrorType=yn.SYNAPSE_RECOVERY_REASON=void 0,yn.SYNAPSE_RECOVERY_REASON={AUTH_EXPIRED:"AUTH_EXPIRED",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_FORBIDDEN:"SESSION_FORBIDDEN",RETRY_LATER:"RETRY_LATER"},yn.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"}),yn}var tr={},la;function zo(){if(la)return tr;la=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.ErrorUtils=void 0;const e=at();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 tr.ErrorUtils=t,tr}var ca={},da;function ua(){return da||(da=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.buildPrefetchKey=void 0,e.prefetchTokenExchange=a,e.consumePrefetchedExchange=l;const t=Lr(),n=Uo(),r=zo(),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),p=i.get(u);if(p)return p;const _=new t.HttpClient({baseUrl:h,headers:{"ngrok-skip-browser-warning":"69420",...d.channel&&{"x-channel":d.channel},...d.sessToken&&{Authorization:`Bearer ${d.sessToken}`}}}),f=new o.Auth(_).exchange({agent_id:d.agentId,...d.authToken&&{auth_token:d.authToken},...d.refreshToken&&{refresh_token:d.refreshToken}});return f.catch(g=>{r.ErrorUtils.isAuthError(g)||i.get(u)===f&&i.delete(u)}),i.set(u,f),f}function l(d){const h=i.get(d);return h&&i.delete(d),h}})(ca)),ca}var ha;function Jd(){if(ha)return er;ha=1,Object.defineProperty(er,"__esModule",{value:!0}),er.TokenManager=void 0;const e=at(),t=jo(),n=zo(),r=ua();let o=class{constructor(i,s,a,l){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=l.partnerAuthToken,this.refreshToken=l.refreshToken,this.onTokenExchange=l.onTokenExchange,this._level=l.level,this._userId=l.userId,l.sessToken&&(this.sessToken=l.sessToken,this.httpClient.setAuthorization(l.sessToken)),this.prefetchKey=(0,r.buildPrefetchKey)(l.serverUrl,a,l.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,l){return n.ErrorUtils.isAuthError(i)?(0,e.normalizeError)(i,e.SessionError,l,{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 er.TokenManager=o,er}var nr={},ma;function Qd(){var n;if(ma)return nr;ma=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.VoiceResource=void 0;const e=Zn();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 nr.VoiceResource=t,nr}var pa;function fa(){if(pa)return Wn;pa=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.ResourceManager=void 0;const e=Lr(),t=ta(),n=at(),r=Fo(),o=sa(),i=Vo(),s=Jd(),a=Qd();class l{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:p,intent:_,user_location:f,referer:g,...b}=u||{},m=this.tokenManager.userId||h,E={...m&&{user_id:m},...p&&{user_context:p},...(_||Object.keys(b).length>0)&&{session_context:{..._&&{intent:_},...f&&{user_location:f},...b}},...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(p){throw p instanceof n.APIError?p: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:p,feedbacks:_,feedbackReason:f,npsBase5:g}){return await this.session.feedback({sessionId:h,messageId:u,feedback:p,feedbacks:_,feedbackReason:f,npsBase5:g})}async callTool(h,u,p,_){return await this.session.callTool(h,u,p,_)}async getVoiceIceServers(h){return await this.voiceResource.getIceServers(h,this.tokenManager.getSessToken()||"")}async sendVoiceOffer(h){return await this.voiceResource.sendOffer(h)}}return Wn.ResourceManager=l,Wn}var rr={},ga={},_a;function Yo(){return _a||(_a=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)}})(ga)),ga}var Ea={},ya;function eu(){return ya||(ya=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Filemanager=e.MAX_FILE_SIZE=void 0;const t=at();e.MAX_FILE_SIZE=3*1024*1024;class n{constructor(){R(this,"pendingFiles",[]);R(this,"pendingMessage","");R(this,"pendingFormats",[]);R(this,"pendingSizes",[])}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),this.pendingSizes=s.map(a=>a.size)}getPendingFileState(){return{files:this.pendingFiles,message:this.pendingMessage||"",formats:this.pendingFormats||[],sizes:this.pendingSizes||[]}}async uploadFilesToPresignedUrl(o){let i=[];const s=o.map((a,l)=>({entry:a,file:this.pendingFiles[l]})).filter(({entry:a,file:l})=>l&&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{entry:l,file:d}=s[a],h=await fetch(l.url,this.buildUploadRequest(l,d));if(!h.ok)throw new t.FileError(`Failed to upload ${d.name} to URL ${a+1}: ${h.status} ${h.statusText}`,{context:{stage:"uploadFilesToPresignedUrl"}});i.push(l.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"}})}}buildUploadRequest(o,i){if(o.fields){const s=new FormData;for(const[a,l]of Object.entries(o.fields))s.append(a,l);return s.append("file",i),{method:"POST",body:s}}return{method:"PUT",body:i,headers:{"Content-Type":i.type,"x-ms-blob-type":"BlockBlob"}}}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=[],this.pendingSizes=[]}}e.Filemanager=n})(Ea)),Ea}var gt={},Sa;function Ur(){if(Sa)return gt;Sa=1,Object.defineProperty(gt,"__esModule",{value:!0}),gt.SYNAPSE_REALTIME_RESERVED_EVENTS=gt.SYNAPSE_REALTIME_ERROR_CODES=gt.SYNAPSE_REALTIME_EVENTS=gt.SYNAPSE_MESSAGE_TYPES=void 0;const e=Yo();return gt.SYNAPSE_MESSAGE_TYPES=e.SOCKET_CONTENT_TYPES,gt.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"},gt.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"},gt.SYNAPSE_REALTIME_RESERVED_EVENTS={SESSION_TOKEN_EXPIRED:"session_expired",SESSION_INACTIVE:"session_inactive_message",SESSION_NOT_OWNED:"session_not_owned_message"},gt}var or={},ba;function tu(){if(ba)return or;ba=1,Object.defineProperty(or,"__esModule",{value:!0}),or.AudioManager=void 0;const e=at();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 or.AudioManager=t,or}var va;function wa(){if(va)return rr;va=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.MessageManager=void 0;const e=Yo(),t=eu(),n=Ur(),r=tu(),o=at();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:l,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,file_sizes:this.fileManager.getPendingFileState().sizes,...d&&{tool_declined:d},...h&&{tool_result:h}}};else if(l&&l.length>0){const p=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:l,...p&&{text:p},...d&&{tool_declined:d},...h&&{tool_result:h}}},this.fileManager?.clearPendingFilesState()}return u}sendSocketMessage({message:s,files:a,audio:l,urls:d,tool_declined:h,tool_id:u,tool_result:p,initial_prompts:_}){if(!this.connection?.isConnected()){this.outgoingBuffer={...s!==void 0&&{message:s},...a&&{files:a},...l&&{audio:l},...d&&{urls:d},...h&&{tool_declined:h},...u&&{tool_id:u},...p&&{tool_result:p},..._&&{initial_prompts:_}};return}const f=this.connection;let g;if(a&&a.length>0||d&&d.length>0){if(a&&a.length>3){const b=new o.MessageError("Maximum 3 files are allowed to be sent at a time",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}g=this.handleFileUploadProcess({files:a,message:s,urls:d,tool_declined:h,tool_result:p})}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:_},...p&&{tool_result:p}}}:l&&l?.audio&&l?.format?g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.AUDIO,_id:Date.now().toString(),ts:Date.now(),data:{audio:l?.audio,format:l?.format,...h&&{tool_declined:h},...p&&{tool_result:p}}}:p&&(g={ev:e.SOCKET_EVENTS.CHAT,ct:e.SOCKET_CONTENT_TYPES.TEXT,_id:Date.now().toString(),ts:Date.now(),data:{text:"",tool_result:p}});if(!g){const b=new o.MessageError("No message to send",{context:{stage:"sendSocketChatMessage"}});throw this.emitError(b),b}f.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(l=>{this.sendSocketMessage({urls:l})}).catch(l=>{const d=this.toFileError(l,"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 l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,l)}break;case e.SOCKET_CONTENT_TYPES.TOOL_CALL:if(s?.data?.tool_id&&s._id){const l={data:{...s.data},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,l)}break;case e.SOCKET_CONTENT_TYPES.AUDIO_TRANSCRIPT:if(s?.data?.text){const l={data:{text:s.data.text},messageId:s._id,timestamp:s.ts};a.emit(n.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,l)}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 l={data:s?.data,messageId:s._id||Date.now().toString()};a.emit(n.SYNAPSE_REALTIME_EVENTS.TOOL_START,l);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 l=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"),l={ev:e.SOCKET_EVENTS.AUTH,_id:Date.now().toString(),ts:Date.now(),data:{token:s}};a.sendMessage(l)}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 l=new o.RecordingError("onChunks is required",{context:{stage:"startRecording"},hint:"onChunks is required"});throw this.emitError(l),l}this.audioManager||(this.audioManager=new r.AudioManager);try{await this.audioManager.start(s,l=>{const d=this.toRecordingError(l,"Failed to start audio recording",{stage:"startRecording"});a?.(d),this.emitError(d)})}catch(l){const d=this.toRecordingError(l,"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,l,d){return(0,o.normalizeError)(s,o.FileError,a,{context:l,hint:d})}toRecordingError(s,a,l,d){return(0,o.normalizeError)(s,o.RecordingError,a,{context:l,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 rr.MessageManager=i,rr}var Na={},Ta;function nu(){return Ta||(Ta=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})(Na)),Na}var sr={},ir={},xa;function ru(){if(xa)return ir;xa=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.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),l=()=>{if(!this.audioCtx)return;s.getByteFrequencyData(a);const d=a.reduce((h,u)=>h+u,0)/a.length;o(d>r),this.animFrame=requestAnimationFrame(l)};l()}stop(){this.animFrame!==null&&(cancelAnimationFrame(this.animFrame),this.animFrame=null),this.audioCtx&&(this.audioCtx.close().catch(()=>{}),this.audioCtx=null)}};return ir.VoiceAudioAnalyser=t,ir}var Sn={},Ca;function ka(){return Ca||(Ca=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.VOICE_AGENT_EVENTS=Sn.VOICE_AGENT_STATE=void 0,Sn.VOICE_AGENT_STATE={IDLE:"idle",CONNECTING:"connecting",CONNECTED:"connected",LISTENING:"listening",THINKING:"thinking",SPEAKING:"speaking",MUTED:"muted",DISCONNECTING:"disconnecting",ERROR:"error"},Sn.VOICE_AGENT_EVENTS={STATE_CHANGED:"voice:state_changed",ERROR:"voice:error"}),Sn}var Oa;function ou(){if(Oa)return sr;Oa=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.VoiceAgent=void 0;const e=Do(),t=ru(),n=at(),r=ka(),o=3e3,i=8,s=3600*1e3,a=600;function l(h,u){return new Promise(p=>{if(h.iceGatheringState==="complete"){p();return}const _=setTimeout(p,u);h.onicegatheringstatechange=()=>{h.iceGatheringState==="complete"&&(clearTimeout(_),p())}})}let d=class{constructor(h,u,p){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=p}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 p=await this.fetchIceServers(h),_=new RTCPeerConnection({iceServers:p,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 f=await _.createOffer();await _.setLocalDescription(f);const g=this.config.iceGatheringTimeoutMs??o;await l(_,g);const b=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(b(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(b(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(p=>{p.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 p;try{p=await this.resourceManager.getVoiceIceServers(h.sessionId)}catch(_){if(_ instanceof n.APIError&&_.status===401&&this.config.handleRefresh){await this.config.handleRefresh();const f=await this.getCredentials();p=await this.resourceManager.getVoiceIceServers(f.sessionId)}else throw _}if(!Array.isArray(p?.ice_servers)||p.ice_servers.length===0)throw new Error("ICE servers response is empty");return this._cachedIceServers=p.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 p={message:u,cause:h};this.emitter.emit(r.VOICE_AGENT_EVENTS.ERROR,p)}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,p=>{this._state!==r.VOICE_AGENT_STATE.LISTENING&&this._state!==r.VOICE_AGENT_STATE.THINKING||(p?(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 p=this.config.speakingThreshold??i;this.remoteAnalyser.start(u,p,_=>{_?(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 sr.VoiceAgent=d,sr}var Ra;function su(){if(Ra)return jn;Ra=1,Object.defineProperty(jn,"__esModule",{value:!0}),jn.SynapseSDK=void 0;const e=Xi(),t=$n(),n=Uo(),r=fa(),o=wa(),i=Ur(),s=Do(),a=at(),l=jo(),d=nu(),h=Yo(),u=ou();class p{constructor(f){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={...f,environment:f.environment||"production"},this.connectionType=f.connectionType||e.ConnectionType.HTTP_STREAM;const g=(0,n.getConfig)(this.config?.environment).BASE_API_URL;this.resourceManager=new r.ResourceManager({agentId:this.config.agentId,serverUrl:this.config.serverUrl||g,...this.config.channel&&{channel:this.config.channel},...this.config.authToken&&{authToken:this.config.authToken},...this.config.refreshToken&&{refreshToken:this.config.refreshToken},...this.config.sessToken&&{sessToken:this.config.sessToken},...this.config.level&&{level:this.config.level},...this.config.userId&&{userId:this.config.userId},onTokenExchange:b=>this.config.callbacks?.onTokenExchange?.(b)}),this.resourceManager.setUnauthorizedHandler(()=>this.onRestUnauthorized()),this.messageManager=new o.MessageManager(this.config?.callbacks)}async onRestUnauthorized(){const f=await this.resourceManager.refreshBearer();if(!f)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 f}async startSession(f){try{this.config.force&&!this.forceConsumed&&(this.forceConsumed=!0,this.sessionConfig=null,f=void 0),await this.resourceManager.ensureCredentials();const g=f?.session_id?f:await this.createNewSession();return await this.initializeConnection(g),this.setupEventHandlers(),g}catch(g){throw this.emitError(g),g}}async sendMessage({message:f,files:g,audio:b,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:f,files:g,audio:b,...m&&{tool_declined:m},...E&&{tool_id:E},...y?.length&&{initial_prompts:y},...k&&Object.keys(k)?.length&&{tool_result:k}})}catch(T){this.emitError(T)}break;default:const x=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendChatMessage",connectionType:this.connectionType}});throw this.emitError(x),x}}async sendMessageFeedback(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"sendFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,messageId:f,feedback:g,feedbackReason:b});break}}async sendSessionFeedback(f,g){if(!this.connection){const b=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!this.sessionConfig?.session_id){const b=new a.SessionError("Session ID not found",{context:{stage:"sendSessionFeedback"},hint:"Call startSession() before attempting to send feedback."});throw this.emitError(b),b}if(!f?.length&&!g){const b=new a.SessionError("No feedback provided",{context:{stage:"sendSessionFeedback"},hint:"Provide either feedbacks or npsBase5."});throw this.emitError(b),b}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:await this.resourceManager.sendFeedback({sessionId:this.sessionConfig.session_id,feedbacks:f,npsBase5:g});break}}on(f,g){this.sdkEventEmitter.on(f,g)}off(f,g){this.sdkEventEmitter.off(f,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(f){return await this.resourceManager.getSessionMessages(f)}async callTool(f,g,b){if(!this.connection){const m=new a.ConnectionError("Connection not established. Session may not be initialized.",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}if(!this.sessionConfig?.session_id){const m=new a.SessionError("Session ID not found",{context:{stage:"callTool"},hint:"Call startSession() before attempting to call tool."});throw this.emitError(m),m}switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:const m=await this.resourceManager.callTool(this.sessionConfig.session_id,f,g,b);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:f,onError:g}){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:try{await this.messageManager.startRecording({onChunks:f,onError:g})}catch(m){throw m}break;default:const b=new a.ConnectionError("Unsupported connection type",{context:{stage:"sendAudio",connectionType:this.connectionType}});throw this.emitError(b),b}}endRecording(){switch(this.connectionType){case e.ConnectionType.SOCKET:case e.ConnectionType.HTTP_STREAM:this.messageManager.endRecordingWithSocket();break;default:const f=new a.ConnectionError("Unsupported connection type",{context:{stage:"endRecording",connectionType:this.connectionType}});throw this.emitError(f),f}}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(f){if(f instanceof a.APIError){const g=f.reason??(f.status===401||f.status===403?l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:void 0);return{message:f.error?.msg||f.message,error:f.error,code:f.code,...g&&{reason:g},status:f.status,context:f.context}}return f instanceof a.SynapseError?{message:f.displayMessage||f.message,code:f.code,...f.reason&&{reason:f.reason},context:f.context}:f instanceof Error?{message:f.message}:{message:"An unexpected error occurred"}}emitError(f){typeof navigator<"u"&&!navigator.onLine&&this.sessionConfig?.session_id&&this.registerNetworkReconnect(),this.config.callbacks?.onError?.(this.toClientError(f))}toSessionError(f,g,b,m){return(0,a.normalizeError)(f,a.SessionError,g,{context:b,hint:m})}async initializeConnection(f){if(this.closeConnection(),!f.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=f;const g=(0,n.getConfig)(this.config?.environment),b=this.connectionType===e.ConnectionType.SOCKET,m=b?g.WEBSOCKET_URL:g.BASE_API_URL,E=this.config.serverUrl?b?`wss://${this.config.serverUrl.split("://")[1]}`:this.config.serverUrl:null;this.connection=await e.ConnectionFactory.createConnection(this.connectionType,{serverUrl:E||m,auth:{sessionId:f.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,...x)=>{y(k,...x),this.sdkEventEmitter.emit(k,...x)}}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 f=this.connection;this.connection.onDisconnect(async g=>{if(this.connection!==f||g.reason===t.DisconnectionReason.CLIENT_CLOSED)return;const b=(0,d.outcomeForCloseCode)(g.code);if(b){await this.handleRecovery(b,g);return}this.registerNetworkReconnect(),!this.isReconnecting&&this.scheduleReconnect(g)}),this.registerVisibilityReconnect()}onRealtimeConnectionError(f){if(f instanceof a.APIError){const b=(0,d.outcomeForHttpStatus)(f.status);if(b){this.handleRecovery(b,{reason:t.DisconnectionReason.CONNECTION_ERROR,message:f.message,code:f.status,timestamp:new Date});return}}this.connection?.emit(i.SYNAPSE_REALTIME_EVENTS.ERROR,f);const g=f instanceof a.APIError?f:this.toConnectionError(f,"WebSocket connection error",{stage:"onSocketConnectionError"},"Verify network connectivity or attempt to reconnect.");this.emitError(g)}onSocketConnectionOpen(){const f=this.resourceManager.getSessToken();if(!f){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(f)}onIncomingSocketMessage(f){switch(f.ev){case h.SOCKET_EVENTS.CHAT:this.messageManager.handleIncomingSocketChatMessage(f);break;case h.SOCKET_EVENTS.CONNECTION_ESTABLISHED:this.messageManager.handleConnectionEstablished();break;case h.SOCKET_EVENTS.STREAM:this.messageManager.handleIncomingSocketStreamMessage(f);break;case h.SOCKET_EVENTS.END_OF_STREAM:this.messageManager.handleIncomingSocketEndOfStreamMessage(f);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(f);break;default:const g=new a.MessageError("Unsupported message type",{context:{stage:"onIncomingSocketMessage",event:f.ev??"unknown"},hint:"Ensure the server is sending supported socket events."});this.emitError(g);return}}get isAuthenticatedUser(){const f=this.resourceManager.getLevel();return f?f==="user":!!this.config.authToken}statusOf(f){if(f instanceof a.APIError)return f.status;if(f instanceof a.SynapseError&&typeof f.context?.status=="number")return f.context.status}emitRecoveryError(f,g,b){this.emitError(new a.SessionError(g,{reason:f,cause:b,context:{stage:"connectionRecovery",reason:f}}))}clearUser(){this.closeConnection(),this.resourceManager.clearAll(),this.sessionConfig=null}async handleRecovery(f,g){if(f===d.RECOVERY_OUTCOME.RETRY_LATER){this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.RETRY_LATER,"Server is busy, retrying shortly"),g&&this.scheduleReconnect(g);return}if(!this.isRecovering){this.isRecovering=!0;try{switch(f){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(l.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(f){const g=this.statusOf(f);if(g!==403&&g!==401){this.emitError(this.toSessionError(f,"Failed to refresh authentication",{stage:"tokenRefresh"}));return}this.clearUser(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN,"Guest credentials were rejected",f)}}async recoverMissingSession(){const f=this.sessionConfig?.session_id;if(!this.isAuthenticatedUser||!f){this.closeConnection(),this.emitRecoveryError(l.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND,"This chat is no longer available");return}this.closeConnection();try{const g=await this.resourceManager.reinitialiseSession(f);await this.connectTo(g);return}catch(g){const b=this.statusOf(g);if(b===401||b===403){this.clearUser(),this.emitRecoveryError(l.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(l.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(f){await this.initializeConnection(f),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(f,g,b,m){return(0,a.normalizeError)(f,a.ConnectionError,g,{context:b,hint:m})}scheduleReconnect(f){if(this.connectionAttempts>=5||!this.sessionConfig?.session_id){this.messageManager.handleDisconnect(f);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(f)}}},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 jn.SynapseSDK=p,jn}var Aa={},Ia;function iu(){return Ia||(Ia=1,Object.defineProperty(Aa,"__esModule",{value:!0})),Aa}var Fr={},Ma;function au(){return Ma||(Ma=1,Object.defineProperty(Fr,"__esModule",{value:!0}),Fr.USER_FEEDBACK=void 0,Fr.USER_FEEDBACK={LIKE:"LIKE",DISLIKE:"DISLIKE",NONE:"NONE"}),Fr}var Pa={},Da;function lu(){return Da||(Da=1,Object.defineProperty(Pa,"__esModule",{value:!0})),Pa}var ar={},La;function cu(){if(La)return ar;La=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.ToolCall=void 0;const e=Zn();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 ar.ToolCall=t,ar}var Ze={},Ua;function du(){if(Ua)return Ze;Ua=1,Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.SYNAPSE_EICITATION_STATUS=Ze.SYNAPSE_CTA_ACTIONS=Ze.SYNAPSE_TOOL_FORMATS=Ze.SYNAPSE_TOOL_CALLBACK_NAME=Ze.SYNAPSE_COMPONENTS=Ze.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||(Ze.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||(Ze.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||(Ze.SYNAPSE_TOOL_CALLBACK_NAME=n={}));var r;(function(s){s.DEFAULT="default",s.CUSTOM="custom"})(r||(Ze.SYNAPSE_TOOL_FORMATS=r={}));var o;(function(s){s.TOOL_CALL="tool_call",s.PROMPT="prompt"})(o||(Ze.SYNAPSE_CTA_ACTIONS=o={}));var i;return(function(s){s.PROGRESS="progress",s.SUCCESS="success",s.FAILURE="failure"})(i||(Ze.SYNAPSE_EICITATION_STATUS=i={})),Ze}var Fa={},Va;function uu(){return Va||(Va=1,Object.defineProperty(Fa,"__esModule",{value:!0})),Fa}var ja={},za;function hu(){return za||(za=1,Object.defineProperty(ja,"__esModule",{value:!0})),ja}var lr={},Ya;function mu(){if(Ya)return lr;Ya=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.SYNAPSE_CONVERSATION=void 0;var e;return(function(t){t.TEXT="text",t.FILE="file",t.AUDIO="audio",t.VOICE="voice"})(e||(lr.SYNAPSE_CONVERSATION=e={})),lr}var bn={},Ha;function pu(){return Ha||(Ha=1,(function(e){var t=bn&&bn.__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=bn&&bn.__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(ka(),e)})(bn)),bn}var $a;function fu(){return $a||($a=1,(function(e){var t=_n&&_n.__createBinding||(Object.create?(function(T,C,S,v){v===void 0&&(v=S);var N=Object.getOwnPropertyDescriptor(C,S);(!N||("get"in N?!C.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return C[S]}}),Object.defineProperty(T,v,N)}):(function(T,C,S,v){v===void 0&&(v=S),T[v]=C[S]})),n=_n&&_n.__exportStar||function(T,C){for(var S in T)S!=="default"&&!Object.prototype.hasOwnProperty.call(C,S)&&t(C,T,S)};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=su();Object.defineProperty(e,"SynapseSDK",{enumerable:!0,get:function(){return r.SynapseSDK}});var o=Lo();Object.defineProperty(e,"BaseConnection",{enumerable:!0,get:function(){return o.BaseConnection}});var i=Hi();Object.defineProperty(e,"WebSocketConnection",{enumerable:!0,get:function(){return i.WebSocketConnection}});var s=Ki();Object.defineProperty(e,"SSEConnection",{enumerable:!0,get:function(){return s.SSEConnection}});var a=Xi();Object.defineProperty(e,"ConnectionFactory",{enumerable:!0,get:function(){return a.ConnectionFactory}}),Object.defineProperty(e,"ConnectionType",{enumerable:!0,get:function(){return a.ConnectionType}}),n($n(),e);var l=fa();Object.defineProperty(e,"ResourceManager",{enumerable:!0,get:function(){return l.ResourceManager}}),n(iu(),e);var d=ta();Object.defineProperty(e,"Session",{enumerable:!0,get:function(){return d.Session}}),n(au(),e);var h=Vo();Object.defineProperty(e,"Auth",{enumerable:!0,get:function(){return h.Auth}});var u=ua();Object.defineProperty(e,"prefetchTokenExchange",{enumerable:!0,get:function(){return u.prefetchTokenExchange}}),n(lu(),e);var p=Fo();Object.defineProperty(e,"Config",{enumerable:!0,get:function(){return p.Config}});var _=sa();Object.defineProperty(e,"prefetchAgentConfig",{enumerable:!0,get:function(){return _.prefetchAgentConfig}});var f=cu();Object.defineProperty(e,"ToolCall",{enumerable:!0,get:function(){return f.ToolCall}}),n(du(),e);var g=wa();Object.defineProperty(e,"MessageManager",{enumerable:!0,get:function(){return g.MessageManager}}),n(Ur(),e),n(uu(),e);var b=Lr();Object.defineProperty(e,"HttpClient",{enumerable:!0,get:function(){return b.HttpClient}});var m=at();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=jo();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=zo();Object.defineProperty(e,"ErrorUtils",{enumerable:!0,get:function(){return y.ErrorUtils}}),n(hu(),e);var k=Gi();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 x=Ur();Object.defineProperty(e,"SYNAPSE_MESSAGE_TYPES",{enumerable:!0,get:function(){return x.SYNAPSE_MESSAGE_TYPES}}),n(mu(),e),n(pu(),e)})(_n)),_n}var M=fu();function Ba(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=Ba(e[t]))&&(r&&(r+=" "),r+=n)}else for(n in e)e[n]&&(r&&(r+=" "),r+=n);return r}function Ga(){for(var e,t,n=0,r="",o=arguments.length;n<o;n++)(e=arguments[n])&&(t=Ba(e))&&(r&&(r+=" "),r+=t);return r}const gu=(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},_u=(e,t)=>({classGroupId:e,validator:t}),Wa=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),Vr="-",Ka=[],Eu="arbitrary..",yu=e=>{const t=bu(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{if(o.startsWith("[")&&o.endsWith("]"))return Su(o);const i=o.split(Vr),s=i[0]===""&&i.length>1?1:0;return qa(i,s,t)},getConflictingClassGroupIds:(o,i)=>{if(i){const s=r[o],a=n[o];return s?a?gu(a,s):s:a||Ka}return n[o]||Ka}}},qa=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],o=n.nextPart.get(r);if(o){const l=qa(e,t+1,o);if(l)return l}const i=n.validators;if(i===null)return;const s=t===0?e.join(Vr):e.slice(t).join(Vr),a=i.length;for(let l=0;l<a;l++){const d=i[l];if(d.validator(s))return d.classGroupId}},Su=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?Eu+r:void 0})(),bu=e=>{const{theme:t,classGroups:n}=e;return vu(n,t)},vu=(e,t)=>{const n=Wa();for(const r in e){const o=e[r];Ho(o,n,r,t)}return n},Ho=(e,t,n,r)=>{const o=e.length;for(let i=0;i<o;i++){const s=e[i];wu(s,t,n,r)}},wu=(e,t,n,r)=>{if(typeof e=="string"){Nu(e,t,n);return}if(typeof e=="function"){Tu(e,t,n,r);return}xu(e,t,n,r)},Nu=(e,t,n)=>{const r=e===""?t:Xa(t,e);r.classGroupId=n},Tu=(e,t,n,r)=>{if(Cu(e)){Ho(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push(_u(n,e))},xu=(e,t,n,r)=>{const o=Object.entries(e),i=o.length;for(let s=0;s<i;s++){const[a,l]=o[s];Ho(l,Xa(t,a),n,r)}},Xa=(e,t)=>{let n=e;const r=t.split(Vr),o=r.length;for(let i=0;i<o;i++){const s=r[i];let a=n.nextPart.get(s);a||(a=Wa(),n.nextPart.set(s,a)),n=a}return n},Cu=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,ku=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)}}},$o="!",Za=":",Ou=[],Ja=(e,t,n,r,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:o}),Ru=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=o=>{const i=[];let s=0,a=0,l=0,d;const h=o.length;for(let g=0;g<h;g++){const b=o[g];if(s===0&&a===0){if(b===Za){i.push(o.slice(l,g)),l=g+1;continue}if(b==="/"){d=g;continue}}b==="["?s++:b==="]"?s--:b==="("?a++:b===")"&&a--}const u=i.length===0?o:o.slice(l);let p=u,_=!1;u.endsWith($o)?(p=u.slice(0,-1),_=!0):u.startsWith($o)&&(p=u.slice(1),_=!0);const f=d&&d>l?d-l:void 0;return Ja(i,_,p,f)};if(t){const o=t+Za,i=r;r=s=>s.startsWith(o)?i(s.slice(o.length)):Ja(Ou,!1,s,void 0,!0)}if(n){const o=r;r=i=>n({className:i,parseClassName:o})}return r},Au=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]==="[",l=t.has(s);a||l?(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}},Iu=e=>({cache:ku(e.cacheSize),parseClassName:Ru(e),sortModifiers:Au(e),...yu(e)}),Mu=/\s+/,Pu=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o,sortModifiers:i}=t,s=[],a=e.trim().split(Mu);let l="";for(let d=a.length-1;d>=0;d-=1){const h=a[d],{isExternal:u,modifiers:p,hasImportantModifier:_,baseClassName:f,maybePostfixModifierPosition:g}=n(h);if(u){l=h+(l.length>0?" "+l:l);continue}let b=!!g,m=r(b?f.substring(0,g):f);if(!m){if(!b){l=h+(l.length>0?" "+l:l);continue}if(m=r(f),!m){l=h+(l.length>0?" "+l:l);continue}b=!1}const E=p.length===0?"":p.length===1?p[0]:i(p).join(":"),y=_?E+$o:E,k=y+m;if(s.indexOf(k)>-1)continue;s.push(k);const x=o(m,b);for(let T=0;T<x.length;++T){const C=x[T];s.push(y+C)}l=h+(l.length>0?" "+l:l)}return l},Du=(...e)=>{let t=0,n,r,o="";for(;t<e.length;)(n=e[t++])&&(r=Qa(n))&&(o&&(o+=" "),o+=r);return o},Qa=e=>{if(typeof e=="string")return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=Qa(e[r]))&&(n&&(n+=" "),n+=t);return n},Lu=(e,...t)=>{let n,r,o,i;const s=l=>{const d=t.reduce((h,u)=>u(h),e());return n=Iu(d),r=n.cache.get,o=n.cache.set,i=a,a(l)},a=l=>{const d=r(l);if(d)return d;const h=Pu(l,n);return o(l,h),h};return i=s,(...l)=>i(Du(...l))},Uu=[],je=e=>{const t=n=>n[e]||Uu;return t.isThemeGetter=!0,t},el=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,tl=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Fu=/^\d+\/\d+$/,Vu=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ju=/\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$/,zu=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Yu=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Hu=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,vn=e=>Fu.test(e),ne=e=>!!e&&!Number.isNaN(Number(e)),Yt=e=>!!e&&Number.isInteger(Number(e)),Bo=e=>e.endsWith("%")&&ne(e.slice(0,-1)),Pt=e=>Vu.test(e),$u=()=>!0,Bu=e=>ju.test(e)&&!zu.test(e),nl=()=>!1,Gu=e=>Yu.test(e),Wu=e=>Hu.test(e),Ku=e=>!H(e)&&!$(e),qu=e=>wn(e,al,nl),H=e=>el.test(e),Jt=e=>wn(e,ll,Bu),Go=e=>wn(e,eh,ne),rl=e=>wn(e,sl,nl),Xu=e=>wn(e,il,Wu),jr=e=>wn(e,cl,Gu),$=e=>tl.test(e),cr=e=>Nn(e,ll),Zu=e=>Nn(e,th),ol=e=>Nn(e,sl),Ju=e=>Nn(e,al),Qu=e=>Nn(e,il),zr=e=>Nn(e,cl,!0),wn=(e,t,n)=>{const r=el.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},Nn=(e,t,n=!1)=>{const r=tl.exec(e);return r?r[1]?t(r[1]):n:!1},sl=e=>e==="position"||e==="percentage",il=e=>e==="image"||e==="url",al=e=>e==="length"||e==="size"||e==="bg-size",ll=e=>e==="length",eh=e=>e==="number",th=e=>e==="family-name",cl=e=>e==="shadow",nh=()=>{const e=je("color"),t=je("font"),n=je("text"),r=je("font-weight"),o=je("tracking"),i=je("leading"),s=je("breakpoint"),a=je("container"),l=je("spacing"),d=je("radius"),h=je("shadow"),u=je("inset-shadow"),p=je("text-shadow"),_=je("drop-shadow"),f=je("blur"),g=je("perspective"),b=je("aspect"),m=je("ease"),E=je("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"],x=()=>[...k(),$,H],T=()=>["auto","hidden","clip","visible","scroll"],C=()=>["auto","contain","none"],S=()=>[$,H,l],v=()=>[vn,"full","auto",...S()],N=()=>[Yt,"none","subgrid",$,H],P=()=>["auto",{span:["full",Yt,$,H]},Yt,$,H],B=()=>[Yt,"auto",$,H],G=()=>["auto","min","max","fr",$,H],he=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],pe=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...S()],Ee=()=>[vn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...S()],V=()=>[e,$,H],le=()=>[...k(),ol,rl,{position:[$,H]}],Re=()=>["no-repeat",{repeat:["","x","y","space","round"]}],te=()=>["auto","cover","contain",Ju,qu,{size:[$,H]}],Q=()=>[Bo,cr,Jt],I=()=>["","none","full",d,$,H],W=()=>["",ne,cr,Jt],re=()=>["solid","dashed","dotted","double"],ve=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],K=()=>[ne,Bo,ol,rl],Ae=()=>["","none",f,$,H],He=()=>["none",ne,$,H],ae=()=>["none",ne,$,H],Pe=()=>[ne,$,H],De=()=>[vn,"full",...S()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Pt],breakpoint:[Pt],color:[$u],container:[Pt],"drop-shadow":[Pt],ease:["in","out","in-out"],font:[Ku],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Pt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Pt],shadow:[Pt],spacing:["px",ne],text:[Pt],"text-shadow":[Pt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",vn,H,$,b]}],container:["container"],columns:[{columns:[ne,H,$,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:x()}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:v()}],"inset-x":[{"inset-x":v()}],"inset-y":[{"inset-y":v()}],start:[{start:v()}],end:[{end:v()}],top:[{top:v()}],right:[{right:v()}],bottom:[{bottom:v()}],left:[{left:v()}],visibility:["visible","invisible","collapse"],z:[{z:[Yt,"auto",$,H]}],basis:[{basis:[vn,"full","auto",a,...S()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[ne,vn,"auto","initial","none",H]}],grow:[{grow:["",ne,$,H]}],shrink:[{shrink:["",ne,$,H]}],order:[{order:[Yt,"first","last","none",$,H]}],"grid-cols":[{"grid-cols":N()}],"col-start-end":[{col:P()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":N()}],"row-start-end":[{row:P()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":G()}],"auto-rows":[{"auto-rows":G()}],gap:[{gap:S()}],"gap-x":[{"gap-x":S()}],"gap-y":[{"gap-y":S()}],"justify-content":[{justify:[...he(),"normal"]}],"justify-items":[{"justify-items":[...pe(),"normal"]}],"justify-self":[{"justify-self":["auto",...pe()]}],"align-content":[{content:["normal",...he()]}],"align-items":[{items:[...pe(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...pe(),{baseline:["","last"]}]}],"place-content":[{"place-content":he()}],"place-items":[{"place-items":[...pe(),"baseline"]}],"place-self":[{"place-self":["auto",...pe()]}],p:[{p:S()}],px:[{px:S()}],py:[{py:S()}],ps:[{ps:S()}],pe:[{pe:S()}],pt:[{pt:S()}],pr:[{pr:S()}],pb:[{pb:S()}],pl:[{pl:S()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":S()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":S()}],"space-y-reverse":["space-y-reverse"],size:[{size:Ee()}],w:[{w:[a,"screen",...Ee()]}],"min-w":[{"min-w":[a,"screen","none",...Ee()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...Ee()]}],h:[{h:["screen","lh",...Ee()]}],"min-h":[{"min-h":["screen","lh","none",...Ee()]}],"max-h":[{"max-h":["screen","lh",...Ee()]}],"font-size":[{text:["base",n,cr,Jt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,$,Go]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Bo,H]}],"font-family":[{font:[Zu,H,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,$,H]}],"line-clamp":[{"line-clamp":[ne,"none",$,Go]}],leading:[{leading:[i,...S()]}],"list-image":[{"list-image":["none",$,H]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",$,H]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:V()}],"text-color":[{text:V()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...re(),"wavy"]}],"text-decoration-thickness":[{decoration:[ne,"from-font","auto",$,Jt]}],"text-decoration-color":[{decoration:V()}],"underline-offset":[{"underline-offset":[ne,"auto",$,H]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:S()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",$,H]}],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",$,H]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:le()}],"bg-repeat":[{bg:Re()}],"bg-size":[{bg:te()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Yt,$,H],radial:["",$,H],conic:[Yt,$,H]},Qu,Xu]}],"bg-color":[{bg:V()}],"gradient-from-pos":[{from:Q()}],"gradient-via-pos":[{via:Q()}],"gradient-to-pos":[{to:Q()}],"gradient-from":[{from:V()}],"gradient-via":[{via:V()}],"gradient-to":[{to:V()}],rounded:[{rounded:I()}],"rounded-s":[{"rounded-s":I()}],"rounded-e":[{"rounded-e":I()}],"rounded-t":[{"rounded-t":I()}],"rounded-r":[{"rounded-r":I()}],"rounded-b":[{"rounded-b":I()}],"rounded-l":[{"rounded-l":I()}],"rounded-ss":[{"rounded-ss":I()}],"rounded-se":[{"rounded-se":I()}],"rounded-ee":[{"rounded-ee":I()}],"rounded-es":[{"rounded-es":I()}],"rounded-tl":[{"rounded-tl":I()}],"rounded-tr":[{"rounded-tr":I()}],"rounded-br":[{"rounded-br":I()}],"rounded-bl":[{"rounded-bl":I()}],"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:[...re(),"hidden","none"]}],"divide-style":[{divide:[...re(),"hidden","none"]}],"border-color":[{border:V()}],"border-color-x":[{"border-x":V()}],"border-color-y":[{"border-y":V()}],"border-color-s":[{"border-s":V()}],"border-color-e":[{"border-e":V()}],"border-color-t":[{"border-t":V()}],"border-color-r":[{"border-r":V()}],"border-color-b":[{"border-b":V()}],"border-color-l":[{"border-l":V()}],"divide-color":[{divide:V()}],"outline-style":[{outline:[...re(),"none","hidden"]}],"outline-offset":[{"outline-offset":[ne,$,H]}],"outline-w":[{outline:["",ne,cr,Jt]}],"outline-color":[{outline:V()}],shadow:[{shadow:["","none",h,zr,jr]}],"shadow-color":[{shadow:V()}],"inset-shadow":[{"inset-shadow":["none",u,zr,jr]}],"inset-shadow-color":[{"inset-shadow":V()}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:V()}],"ring-offset-w":[{"ring-offset":[ne,Jt]}],"ring-offset-color":[{"ring-offset":V()}],"inset-ring-w":[{"inset-ring":W()}],"inset-ring-color":[{"inset-ring":V()}],"text-shadow":[{"text-shadow":["none",p,zr,jr]}],"text-shadow-color":[{"text-shadow":V()}],opacity:[{opacity:[ne,$,H]}],"mix-blend":[{"mix-blend":[...ve(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ve()}],"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":[ne]}],"mask-image-linear-from-pos":[{"mask-linear-from":K()}],"mask-image-linear-to-pos":[{"mask-linear-to":K()}],"mask-image-linear-from-color":[{"mask-linear-from":V()}],"mask-image-linear-to-color":[{"mask-linear-to":V()}],"mask-image-t-from-pos":[{"mask-t-from":K()}],"mask-image-t-to-pos":[{"mask-t-to":K()}],"mask-image-t-from-color":[{"mask-t-from":V()}],"mask-image-t-to-color":[{"mask-t-to":V()}],"mask-image-r-from-pos":[{"mask-r-from":K()}],"mask-image-r-to-pos":[{"mask-r-to":K()}],"mask-image-r-from-color":[{"mask-r-from":V()}],"mask-image-r-to-color":[{"mask-r-to":V()}],"mask-image-b-from-pos":[{"mask-b-from":K()}],"mask-image-b-to-pos":[{"mask-b-to":K()}],"mask-image-b-from-color":[{"mask-b-from":V()}],"mask-image-b-to-color":[{"mask-b-to":V()}],"mask-image-l-from-pos":[{"mask-l-from":K()}],"mask-image-l-to-pos":[{"mask-l-to":K()}],"mask-image-l-from-color":[{"mask-l-from":V()}],"mask-image-l-to-color":[{"mask-l-to":V()}],"mask-image-x-from-pos":[{"mask-x-from":K()}],"mask-image-x-to-pos":[{"mask-x-to":K()}],"mask-image-x-from-color":[{"mask-x-from":V()}],"mask-image-x-to-color":[{"mask-x-to":V()}],"mask-image-y-from-pos":[{"mask-y-from":K()}],"mask-image-y-to-pos":[{"mask-y-to":K()}],"mask-image-y-from-color":[{"mask-y-from":V()}],"mask-image-y-to-color":[{"mask-y-to":V()}],"mask-image-radial":[{"mask-radial":[$,H]}],"mask-image-radial-from-pos":[{"mask-radial-from":K()}],"mask-image-radial-to-pos":[{"mask-radial-to":K()}],"mask-image-radial-from-color":[{"mask-radial-from":V()}],"mask-image-radial-to-color":[{"mask-radial-to":V()}],"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":[ne]}],"mask-image-conic-from-pos":[{"mask-conic-from":K()}],"mask-image-conic-to-pos":[{"mask-conic-to":K()}],"mask-image-conic-from-color":[{"mask-conic-from":V()}],"mask-image-conic-to-color":[{"mask-conic-to":V()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:le()}],"mask-repeat":[{mask:Re()}],"mask-size":[{mask:te()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",$,H]}],filter:[{filter:["","none",$,H]}],blur:[{blur:Ae()}],brightness:[{brightness:[ne,$,H]}],contrast:[{contrast:[ne,$,H]}],"drop-shadow":[{"drop-shadow":["","none",_,zr,jr]}],"drop-shadow-color":[{"drop-shadow":V()}],grayscale:[{grayscale:["",ne,$,H]}],"hue-rotate":[{"hue-rotate":[ne,$,H]}],invert:[{invert:["",ne,$,H]}],saturate:[{saturate:[ne,$,H]}],sepia:[{sepia:["",ne,$,H]}],"backdrop-filter":[{"backdrop-filter":["","none",$,H]}],"backdrop-blur":[{"backdrop-blur":Ae()}],"backdrop-brightness":[{"backdrop-brightness":[ne,$,H]}],"backdrop-contrast":[{"backdrop-contrast":[ne,$,H]}],"backdrop-grayscale":[{"backdrop-grayscale":["",ne,$,H]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[ne,$,H]}],"backdrop-invert":[{"backdrop-invert":["",ne,$,H]}],"backdrop-opacity":[{"backdrop-opacity":[ne,$,H]}],"backdrop-saturate":[{"backdrop-saturate":[ne,$,H]}],"backdrop-sepia":[{"backdrop-sepia":["",ne,$,H]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":S()}],"border-spacing-x":[{"border-spacing-x":S()}],"border-spacing-y":[{"border-spacing-y":S()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",$,H]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[ne,"initial",$,H]}],ease:[{ease:["linear","initial",m,$,H]}],delay:[{delay:[ne,$,H]}],animate:[{animate:["none",E,$,H]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[g,$,H]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:He()}],"rotate-x":[{"rotate-x":He()}],"rotate-y":[{"rotate-y":He()}],"rotate-z":[{"rotate-z":He()}],scale:[{scale:ae()}],"scale-x":[{"scale-x":ae()}],"scale-y":[{"scale-y":ae()}],"scale-z":[{"scale-z":ae()}],"scale-3d":["scale-3d"],skew:[{skew:Pe()}],"skew-x":[{"skew-x":Pe()}],"skew-y":[{"skew-y":Pe()}],transform:[{transform:[$,H,"","none","gpu","cpu"]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:De()}],"translate-x":[{"translate-x":De()}],"translate-y":[{"translate-y":De()}],"translate-z":[{"translate-z":De()}],"translate-none":["translate-none"],accent:[{accent:V()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:V()}],"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",$,H]}],"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":S()}],"scroll-mx":[{"scroll-mx":S()}],"scroll-my":[{"scroll-my":S()}],"scroll-ms":[{"scroll-ms":S()}],"scroll-me":[{"scroll-me":S()}],"scroll-mt":[{"scroll-mt":S()}],"scroll-mr":[{"scroll-mr":S()}],"scroll-mb":[{"scroll-mb":S()}],"scroll-ml":[{"scroll-ml":S()}],"scroll-p":[{"scroll-p":S()}],"scroll-px":[{"scroll-px":S()}],"scroll-py":[{"scroll-py":S()}],"scroll-ps":[{"scroll-ps":S()}],"scroll-pe":[{"scroll-pe":S()}],"scroll-pt":[{"scroll-pt":S()}],"scroll-pr":[{"scroll-pr":S()}],"scroll-pb":[{"scroll-pb":S()}],"scroll-pl":[{"scroll-pl":S()}],"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",$,H]}],fill:[{fill:["none",...V()]}],"stroke-w":[{stroke:[ne,cr,Jt,Go]}],stroke:[{stroke:["none",...V()]}],"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"]}},rh=Lu(nh);function L(...e){return rh(Ga(e))}function Qt(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 oh=e=>{switch(e){case M.SYNAPSE_COMPONENTS.DOCTOR_CARD:case M.SYNAPSE_COMPONENTS.CARD:return!0;default:return!1}},sh=e=>new Promise(t=>setTimeout(t,e)),dl=ee(({className:e,children:t,...n},r)=>c(Di,{ref:r,className:L("relative overflow-hidden",e),...n,children:[c(qd,{className:"h-full w-full rounded-[inherit] overscroll-contain",children:t}),c(ul,{}),c(Xd,{})]}));dl.displayName=Di.displayName;const ul=ee(({className:e,orientation:t="vertical",...n},r)=>c(Io,{ref:r,orientation:t,className:L("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:c(Oi,{className:"relative flex-1 rounded-full bg-border"})}));ul.displayName=Io.displayName;var ih=Symbol.for("react.lazy"),Yr=Oo[" use ".trim().toString()];function ah(e){return typeof e=="object"&&e!==null&&"then"in e}function hl(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===ih&&"_payload"in e&&ah(e._payload)}function ml(e){const t=ch(e),n=ee((r,o)=>{let{children:i,...s}=r;hl(i)&&typeof Yr=="function"&&(i=Yr(i._payload));const a=st.toArray(i),l=a.find(uh);if(l){const d=l.props.children,h=a.map(u=>u===l?st.count(d)>1?st.only(null):it(d)?d.props.children:null:u);return c(t,{...s,ref:o,children:it(d)?Ft(d,void 0,h):null})}return c(t,{...s,ref:o,children:i})});return n.displayName=`${e}.Slot`,n}var lh=ml("Slot");function ch(e){const t=ee((n,r)=>{let{children:o,...i}=n;if(hl(o)&&typeof Yr=="function"&&(o=Yr(o._payload)),it(o)){const s=mh(o),a=hh(i,o.props);return o.type!==me&&(a.ref=r?Ro(r,s):s),Ft(o,a)}return st.count(o)>1?st.only(null):null});return t.displayName=`${e}.SlotClone`,t}var dh=Symbol("radix.slottable");function uh(e){return it(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===dh}function hh(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 mh(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 pl=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,fl=Ga,ph=(e,t)=>n=>{var r;if(t?.variants==null)return fl(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 p=pl(h)||pl(u);return o[d][p]}),a=n&&Object.entries(n).reduce((d,h)=>{let[u,p]=h;return p===void 0||(d[u]=p),d},{}),l=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:u,className:p,..._}=h;return Object.entries(_).every(f=>{let[g,b]=f;return Array.isArray(b)?b.includes({...i,...a}[g]):{...i,...a}[g]===b})?[...d,u,p]:d},[]);return fl(e,s,l,n?.class,n?.className)},fh=ph("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"}}),Se=ee(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>c(r?lh:"button",{className:L(fh({variant:t,size:n,className:e})),ref:i,...o}));Se.displayName="Button";const gh=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),_h=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),gl=e=>{const t=_h(e);return t.charAt(0).toUpperCase()+t.slice(1)},_l=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Eh=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var yh={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 Sh=ee(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>tt("svg",{ref:l,...yh,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:_l("lucide",o),...!i&&!Eh(a)&&{"aria-hidden":"true"},...a},[...s.map(([d,h])=>tt(d,h)),...Array.isArray(i)?i:[i]])),Ye=(e,t)=>{const n=ee(({className:r,...o},i)=>tt(Sh,{ref:i,iconNode:t,className:_l(`lucide-${gh(gl(e))}`,`lucide-${e}`,r),...o}));return n.displayName=gl(e),n},bh=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Wo=Ye("chevron-down",bh),vh=[["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"}]],wh=Ye("ellipsis-vertical",vh),Nh=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],El=Ye("file-text",Nh),Th=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],yl=Ye("info",Th),xh=[["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"}]],Ch=Ye("maximize-2",xh),kh=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],Oh=Ye("menu",kh),Rh=[["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"}]],dr=Ye("message-square-plus",Rh),Ah=[["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"}]],Ko=Ye("mic",Ah),Ih=[["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"}]],Mh=Ye("minimize-2",Ih),Ph=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Sl=Ye("plus",Ph),Dh=[["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"}]],Lh=Ye("rotate-ccw",Dh),Uh=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],bl=Ye("square",Uh),Fh=[["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"}]],vl=Ye("thumbs-up",Fh),Vh=[["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"}]],wl=Ye("thumbs-down",Vh),jh=[["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"}]],zh=Ye("triangle-alert",jh),Yh=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Tn=Ye("x",Yh),Hh=[["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"}]],$h=Ye("zoom-in",Hh),Nl=e=>{let t;const n=new Set,r=(a,l)=>{const d=typeof a=="function"?a(t):a;if(!Object.is(d,t)){const h=t;t=l??(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},Bh=(e=>e?Nl(e):Nl),Gh=e=>e;function Wh(e,t=Gh){const n=Vn.useSyncExternalStore(e.subscribe,Vn.useCallback(()=>t(e.getState()),[e,t]),Vn.useCallback(()=>t(e.getInitialState()),[e,t]));return Vn.useDebugValue(n),n}const Kh=e=>{const t=Bh(e),n=r=>Wh(t,r);return Object.assign(n,t),n},qh=(e=>Kh);function Xh(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 qo=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qo(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qo(r)(n)}}}},Zh=(e,t)=>(n,r,o)=>{let i={storage:Xh(()=>localStorage),partialize:g=>g,version:0,merge:(g,b)=>({...b,...g}),...t},s=!1;const a=new Set,l=new Set;let d=i.storage;if(!d)return e((...g)=>{n(...g)},r,o);const h=()=>{const g=i.partialize({...r()});return d.setItem(i.name,{state:g,version:i.version})},u=o.setState;o.setState=(g,b)=>(u(g,b),h());const p=e((...g)=>(n(...g),h()),r,o);o.getInitialState=()=>p;let _;const f=()=>{var g,b;if(!d)return;s=!1,a.forEach(E=>{var y;return E((y=r())!=null?y:p)});const m=((b=i.onRehydrateStorage)==null?void 0:b.call(i,(g=r())!=null?g:p))||void 0;return qo(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,x]=E;if(_=i.merge(x,(y=r())!=null?y:p),n(_,!0),k)return h()}).then(()=>{m?.(_,void 0),_=r(),s=!0,l.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:()=>f(),hasHydrated:()=>s,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(l.add(g),()=>{l.delete(g)})},i.skipHydration||f(),_||p},Jh=Zh,Ne={USER:"user",ASSISTANT:"assistant"};var be=(e=>(e.IDLE="idle",e.LISTENING="listening",e.ERROR="error",e.PROCESSING="processing",e.TRANSCRIBING="transcribing",e))(be||{}),_e=(e=>(e.CONNECTED="connected",e.NOT_CONNECTED="not_connected",e.CONNECTING="connecting",e))(_e||{});let ut="";const ur=e=>`med-assist-store-${e}`,Qh=e=>{xn(),ut=ur(e)},em=200;let _t=null,hr=null;function xn(){if(hr&&(clearTimeout(hr),hr=null),!!_t){try{sessionStorage.setItem(_t.key,JSON.stringify(_t.value))}catch{}_t=null}}typeof window<"u"&&(window.addEventListener("pagehide",xn),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&xn()}));const tm={getItem:()=>{if(!ut)return null;if(_t?.key===ut)return _t.value;try{const e=sessionStorage.getItem(ut);return e?JSON.parse(e):null}catch{return null}},setItem:(e,t)=>{ut&&(_t&&_t.key!==ut&&xn(),_t={key:ut,value:t},hr||(hr=setTimeout(xn,em)))},removeItem:()=>{_t?.key===ut&&(_t=null),ut&&sessionStorage.removeItem(ut)}},Tl={sessionId:"",isStreaming:!1,recordingStatus:be.IDLE,isWaitingForResponse:!1,error:null,startNewConnection:!1,showRetryButton:!1,chats:{},connectionStatus:_e.CONNECTING,progressMessage:null,fileUploadPerSession:0,elicitationState:{},toastMessage:null,sessionInitialMessages:{}},xl={...Tl,initialMessage:null,sessToken:"",refreshToken:"",userId:"",level:"",context:null},j=qh()(Jh((e,t)=>({sessionId:"",setSessionId:n=>e({sessionId:n}),refreshToken:"",setRefreshToken:n=>e({refreshToken:n}),level:"",setLevel:n=>e({level:n}),sessToken:"",setSessToken:n=>e({sessToken:n}),initialMessage:null,setInitialMessage:n=>e({initialMessage:n}),sessionInitialMessages:{},setSessionInitialMessage:(n,r)=>e(o=>({sessionInitialMessages:{...o.sessionInitialMessages,[n]:r}})),agentId:"",setAgentId:n=>e({agentId:n}),userId:"",setUserId:n=>e({userId:n}),context:null,setContext:n=>e({context:n}),connectionStatus:_e.CONNECTING,setConnectionStatus:n=>e({connectionStatus:n}),isStreaming:!1,setIsStreaming:n=>e({isStreaming:n}),isWaitingForResponse:!1,setIsWaitingForResponse:n=>e({isWaitingForResponse:n}),progressMessage:null,setProgressMessage:n=>e({progressMessage:n}),recordingStatus:be.IDLE,setRecordingStatus:n=>e({recordingStatus:n}),startNewConnection:!1,setStartNewConnection:n=>e({startNewConnection:n}),fileUploadPerSession:0,setFileUploadPerSession:n=>e({fileUploadPerSession:n}),elicitationState:{},setElicitationState:n=>e({elicitationState:n}),upsertElicitationState:(n,r)=>{const o=t().elicitationState;e({elicitationState:{...o,[n]:r}})},toastMessage:null,setToastMessage:n=>e({toastMessage:n}),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}})),error:null,setError:n=>e({error:n}),clearError:()=>e({error:null,showRetryButton:!1,startNewConnection:!1}),showRetryButton:!1,setShowRetryButton:n=>e({showRetryButton:n}),clearSession:async()=>{e(Tl),await sessionStorage.removeItem(ut||ur(t().agentId))},clearUser:()=>{e(xl),sessionStorage.removeItem(ut||ur(t().agentId))}}),{name:"med-assist-store",storage:tm,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})})),nm=e=>{const t=ur(e);xn();let n=null;try{const r=sessionStorage.getItem(t);if(r){const o=JSON.parse(r);o?.state&&(n=o.state)}}catch{}j.setState(xl),n&&j.setState(n)},Xo=vt(null),rm=({children:e})=>{const[t,n]=F(null);return c(Xo.Provider,{value:{synapse:t,setSynapse:n},children:e})},om=()=>{const e=wt(Xo);if(!e)throw new Error("useSynapse must be used within a SynapseProvider");return e.synapse},sm=()=>{const e=wt(Xo);if(!e)throw new Error("useSynapseSetter must be used within a SynapseProvider");return e.setSynapse},im=()=>{const[e,t]=F(M.VOICE_AGENT_STATE.IDLE),[n,r]=F(!1),o=om(),i=j(h=>h.setError);Y(()=>{if(!o)return;const h=o.voice,u=_=>{t(_)},p=()=>{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,p),()=>{h.off(M.VOICE_AGENT_EVENTS.STATE_CHANGED,u),h.off(M.VOICE_AGENT_EVENTS.ERROR,p)}},[o,i]);const s=de(async()=>{if(!o){i({title:"Voice connection failed. Please try again."});return}await o.voice.connect()},[o,i]),a=de(()=>{o?.voice.disconnect(),n&&r(!1)},[o]),l=de(()=>{o?.voice.reset(),n&&r(!1)},[o]),d=de(()=>{r(h=>!h),o?.voice.toggleMute()},[o]);return{state:e,isMuted:n,connect:s,disconnect:a,reset:l,toggleMute:d}},en=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("rounded-xl bg-elicitationBg text-card-foreground shadow",e),...t}));en.displayName="Card";const Cl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex flex-col space-y-1.5 p-6",e),...t}));Cl.displayName="CardHeader";const kl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("font-semibold leading-none tracking-tight",e),...t}));kl.displayName="CardTitle";const am=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("text-sm text-muted-foreground",e),...t}));am.displayName="CardDescription";const Ol=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("p-6 pt-0",e),...t}));Ol.displayName="CardContent";const Rl=ee(({className:e,...t},n)=>c("div",{ref:n,className:L("flex items-center p-6 pt-0",e),...t}));Rl.displayName="CardFooter";const Zo=5,Al=3,Il=10*1024*1024,Hr={width:384,height:600},$r=20,lm=400,cm=320,dm=560,um=150;function hm({defaultPosition:e,enabled:t=!0,onDragStart:n,onDragEnd:r}={}){const o=de(()=>typeof window>"u"?{x:0,y:0}:{x:window.innerWidth-Hr.width-$r,y:window.innerHeight-Hr.height-$r},[]),[i,s]=F(()=>e??o()),[a,l]=F(!1),d=X({x:0,y:0}),h=X(null),u=X(!1);Y(()=>{t||(u.current=!1)},[t]),ft(()=>{!t||u.current||typeof window>"u"||(s(e||o()),u.current=!0)},[t,e,o]),Y(()=>{if(!t||typeof window>"u")return;let g=null;const b=()=>{s(E=>{const y=Math.max(0,window.innerWidth-Hr.width-$r),k=Math.max(0,window.innerHeight-Hr.height-$r),x=Math.max(0,Math.min(E.x,y)),T=Math.max(0,Math.min(E.y,k));return x===E.x&&T===E.y?E:{x,y:T}})},m=()=>{g!==null&&clearTimeout(g),g=setTimeout(b,um)};return window.addEventListener("resize",m),()=>{window.removeEventListener("resize",m),g!==null&&clearTimeout(g)}},[t]);const p=de(g=>{if(!t)return;if(!g.target.closest(".synapse-chat-widget-header")){l(!1);return}g.preventDefault(),l(!0);const b=h.current;if(b){const m=b.getBoundingClientRect();d.current={x:g.clientX-m.left,y:g.clientY-m.top}}else d.current={x:g.clientX-i.x,y:g.clientY-i.y};n?.()},[t,i.x,i.y,n]),_=de(g=>{if(!t||!a)return;const b=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(b,E)),x=Math.max(0,Math.min(m,y));s({x:k,y:x})},[a,t]),f=de(()=>{!t||!a||(l(!1),r?.())},[a,r]);return Y(()=>{if(!t)return;const g=h.current;if(g)return g.addEventListener("mousedown",p),()=>{g.removeEventListener("mousedown",p)}},[t,p]),Y(()=>{if(a)return document.addEventListener("mousemove",_),document.addEventListener("mouseup",f),document.body.style.cursor="grabbing",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",f),document.body.style.cursor="",document.body.style.userSelect=""}},[a,_,f]),{position:i,isDragging:a,elementRef:h,setPosition:s}}const Jo="#6B5CE0",mm="#F0F0F0",Br={background:mm,backgroundImage:void 0,primary:Jo,textColor:"black"},pm="rgba(0, 0, 0, 0.4)",fm="24px";function gm(e){if(e==="dark")return"white";if(e==="light")return"black"}function _m(e){const t=e?.primary??e?.primaryColor??Br.primary,n=e?.textColor??gm(e?.mode);return{background:e?.background??Br.background,backgroundImage:e?.backgroundImage??Br.backgroundImage,primary:t,primaryColor:t,textColor:n??Br.textColor,mode:e?.mode,headerTinted:e?.headerTinted,secondaryColor:e?.secondaryColor,tertiaryColor:e?.tertiaryColor}}function Em(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 l=(o+i)/2;if(o!==i){const h=o-i;switch(a=l>.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(l*100);return`${s} ${a}% ${d}%`}function ym(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,l=0;const d=(i+s)/2;if(i!==s){const u=i-s;switch(l=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),l=Math.round(l*100);const h=Math.round(d*100);return`${a} ${l}% ${h}%`}function Sm(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 Qo(e){if(!e||typeof e!="string")throw new Error("Color must be a non-empty string");const t=e.trim();if(t.startsWith("#"))return Em(t);if(t.startsWith("rgb"))return ym(t);if(t.startsWith("hsl"))return Sm(t);if(/^\d+\s+\d+%\s+\d+%$/.test(t))return t;throw new Error(`Unsupported color format: ${e}`)}function Ml(e){const t=e.match(/(\d+)\s+(\d+)%\s+(\d+)%/);return t?parseInt(t[3],10)/100:.5}function es(e){return Ml(e)>.5?"0 0% 9%":"0 0% 98%"}function bm(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 vm(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 Pl(e,t){const n=t.primary??Jo,r=t.textColor??"black",o=!!t.backgroundImage,i=t.mode==="dark"||r==="white",s=t.headerTinted??!1,a=(_,f)=>{const g=e instanceof ShadowRoot?e.host:e;g instanceof HTMLElement&&g.style.setProperty(_,f)};let l;try{l=Qo(n)}catch{l=Qo(Jo)}a("--primary",l),a("--primary-foreground",es(l)),a("--ring",l),a("--border-primary",l);const d=vm(l);for(const[_,f]of Object.entries(d))a(`--primary-${_}`,f);const h=es(l);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",Qo(_))}catch{a("--background",i?"0 0% 10%":"0 0% 94.1%")}a("--widget-bg-overlay",`hsl(${l} / ${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",bm(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(${l})`),a("--header-stroke",`hsl(${l} / 0.3)`)):(a("--header-bg",i?"var(--black-700)":"var(--white-700)"),a("--header-stroke",`hsl(${l} / 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(${l} / 0.3)`)),s&&!o){const _=Ml(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",l):a("--popover",i?"0 0% 0% / 0.7":"0 0% 100% / 0.7");const p=i?"white":"black";for(const _ of[50,100,200,300,400,500,600,700,800,900,1e3])a(`--popover-${_}`,`var(--${p}-${_})`);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",l),a("--accent-foreground",es(l)),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",fm),a("--theme-background-overlay",pm),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 tn({className:e,style:t}){return c("div",{className:L("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 ts(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function Dl(){return c("div",{className:"px-3 pb-2 pt-1",children:[c(ts,{}),c("div",{className:"flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"4px 8px"},children:[c("div",{className:"px-2 pt-2 pb-1",children:c(tn,{className:"h-5 w-3/5 rounded-md"})}),c("div",{className:"flex items-center justify-between px-1 py-1",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c("div",{className:"flex items-center gap-2",children:[c(tn,{className:"h-9 w-9 rounded-full"}),c(tn,{className:"h-10 w-10 rounded-full"})]})]})]})]})}function wm(){const e=[{role:Ne.ASSISTANT,size:"h-16 w-[70%]"},{role:Ne.USER,size:"h-9 w-[45%]"},{role:Ne.ASSISTANT,size:"h-24 w-[75%]"},{role:Ne.USER,size:"h-9 w-[35%]"},{role:Ne.ASSISTANT,size:"h-16 w-[65%]"}];return c("div",{className:"space-y-3",role:"status","aria-label":"Loading conversation",children:[c(ts,{}),e.map((t,n)=>c("div",{className:L("flex",t.role===Ne.USER?"justify-end":"justify-start"),children:c(tn,{className:L("rounded-lg",t.size)})},n))]})}function Nm({rows:e=5}){const t=["w-4/5","w-3/5","w-11/12","w-2/3","w-3/4"];return c("div",{"aria-hidden":"true",children:[c(ts,{}),Array.from({length:e},(n,r)=>c("div",{className:"flex flex-col gap-1 w-full px-4 py-3",children:[c(tn,{className:L("h-5 rounded-md",t[r%t.length])}),c(tn,{className:"h-3.5 w-16 rounded-md"})]},r))]})}function Tm(e,t=[]){let n=[];function r(i,s){const a=vt(s);a.displayName=i+"Context";const l=n.length;n=[...n,s];const d=u=>{const{scope:p,children:_,...f}=u,g=p?.[e]?.[l]||a,b=ie(()=>f,Object.values(f));return c(g.Provider,{value:b,children:_})};d.displayName=i+"Provider";function h(u,p){const _=p?.[e]?.[l]||a,f=wt(_);if(f)return f;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 ie(()=>({[`__scope${e}`]:{...s,[e]:a}}),[s,a])}};return o.scopeName=e,[r,xm(o,...t)]}function xm(...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:l})=>{const d=a(o)[`__scope${l}`];return{...s,...d}},{});return ie(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var Cm=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ns=Cm.reduce((e,t)=>{const n=ml(`Primitive.${t}`),r=ee((o,i)=>{const{asChild:s,...a}=o,l=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),c(l,{...a,ref:i})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Ll={exports:{}},rs={};const km=Zd(Oo);var Ul;function Om(){if(Ul)return rs;Ul=1;var e=km;function t(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,o=e.useEffect,i=e.useLayoutEffect,s=e.useDebugValue;function a(u,p){var _=p(),f=r({inst:{value:_,getSnapshot:p}}),g=f[0].inst,b=f[1];return i(function(){g.value=_,g.getSnapshot=p,l(g)&&b({inst:g})},[u,_,p]),o(function(){return l(g)&&b({inst:g}),u(function(){l(g)&&b({inst:g})})},[u]),s(_),_}function l(u){var p=u.getSnapshot;u=u.value;try{var _=p();return!n(u,_)}catch{return!0}}function d(u,p){return p()}var h=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:a;return rs.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:h,rs}var Fl;function Rm(){return Fl||(Fl=1,Ll.exports=Om()),Ll.exports}var Am=Rm();function Im(){return Am.useSyncExternalStore(Mm,()=>!0,()=>!1)}function Mm(){return()=>{}}var os="Avatar",[Pm]=Tm(os),[Dm,Vl]=Pm(os),jl=ee((e,t)=>{const{__scopeAvatar:n,...r}=e,[o,i]=F("idle");return c(Dm,{scope:n,imageLoadingStatus:o,onImageLoadingStatusChange:i,children:c(ns.span,{...r,ref:t})})});jl.displayName=os;var zl="AvatarImage",Yl=ee((e,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:o=()=>{},...i}=e,s=Vl(zl,n),a=Lm(r,i),l=jt(d=>{o(d),s.onImageLoadingStatusChange(d)});return Zt(()=>{a!=="idle"&&l(a)},[a,l]),a==="loaded"?c(ns.img,{...i,ref:t,src:r}):null});Yl.displayName=zl;var Hl="AvatarFallback",$l=ee((e,t)=>{const{__scopeAvatar:n,delayMs:r,...o}=e,i=Vl(Hl,n),[s,a]=F(r===void 0);return Y(()=>{if(r!==void 0){const l=window.setTimeout(()=>a(!0),r);return()=>window.clearTimeout(l)}},[r]),s&&i.imageLoadingStatus!=="loaded"?c(ns.span,{...o,ref:t}):null});$l.displayName=Hl;function Bl(e,t){return e?t?(e.src!==t&&(e.src=t),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function Lm(e,{referrerPolicy:t,crossOrigin:n}){const r=Im(),o=X(null),i=r?(o.current||(o.current=new window.Image),o.current):null,[s,a]=F(()=>Bl(i,e));return Zt(()=>{a(Bl(i,e))},[i,e]),Zt(()=>{const l=u=>()=>{a(u)};if(!i)return;const d=l("loaded"),h=l("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 Gl=jl,Wl=Yl,Kl=$l;const ss=ee(({className:e,...t},n)=>c(Gl,{ref:n,className:L("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));ss.displayName=Gl.displayName;const ql=ee(({className:e,...t},n)=>c(Wl,{ref:n,className:L("aspect-square h-full w-full",e),...t}));ql.displayName=Wl.displayName;const is=ee(({className:e,...t},n)=>c(Kl,{ref:n,className:L("flex h-full w-full items-center justify-center rounded-full bg-muted",e),...t}));is.displayName=Kl.displayName;const Xl=vt(!1);function Um({enabled:e,children:t}){return c(Xl.Provider,{value:e,children:t})}function Fm(){return wt(Xl)}const Zl="(max-width: 768px), (pointer: coarse)",Jl=/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;function Vm(){if(typeof window>"u")return!1;const e=window.matchMedia?.(Zl)?.matches??!1,t=Jl.test(navigator?.userAgent??"");return e||t}function Ql(){const[e,t]=F(Vm);return Y(()=>{if(typeof window>"u"||!window.matchMedia)return;const n=window.matchMedia(Zl),r=Jl.test(navigator?.userAgent??""),o=()=>t(n.matches||r);return o(),n.addEventListener("change",o),()=>n.removeEventListener("change",o)},[]),e}function jm({onClose:e,showCloseButton:t=!0,title:n,titleImg:r,tagline:o,iconUrl:i,startNewConversation:s,voiceAgentState:a="idle",headerTinted:l=!1,onToggleDisplayMode:d,onOpenSessionDrawer:h}){const u=Ql(),p=Fm(),_=j(N=>N.displayMode)==="side_panel",f=p&&!u&&!_,g=j(N=>N.displayMode)==="full",b=j(N=>N.initialDisplayMode)==="full",m=!g&&l?"text-primary-foreground hover:text-white hover:bg-black-100":"text-foreground",E=j(N=>N.connectionStatus),y=j(N=>N.level)==="user",[k,x]=F(!1),T=X(null),C=ie(()=>a===M.VOICE_AGENT_STATE.CONNECTED||a===M.VOICE_AGENT_STATE.CONNECTING||a===M.VOICE_AGENT_STATE.LISTENING||a===M.VOICE_AGENT_STATE.SPEAKING||a===M.VOICE_AGENT_STATE.THINKING,[a]),S=de(()=>{k||(x(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{T.current=null,x(!1)},6e3),s())},[k,s]);Y(()=>{E===_e.CONNECTED&&(x(!1),T.current&&clearTimeout(T.current))},[E]);const v=(()=>{switch(E){case _e.CONNECTED:return{dotColor:"bg-green-500",text:o||"Online",textColor:"text-green-600"};case _e.CONNECTING:return{dotColor:"bg-amber-500",text:"Connecting",textColor:"text-amber-600"};case _e.NOT_CONNECTED:return{dotColor:"bg-red-500",text:"Not Connected",textColor:"text-red-600"};default:return{dotColor:"bg-text-tertiary",text:"Not Connected",textColor:"text-text-secondary"}}})();return c("div",{className:"px-6 py-3",children:c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center gap-3",children:[c("div",{className:"relative flex-shrink-0",children:[c(ss,{className:"w-12 h-12 bg-gradient-to-br from-primary to-primary flex-shrink-0 shadow-md ring-0",children:c(is,{className:"text-primary-foreground font-bold text-lg bg-transparent",children:i?c("img",{src:i,alt:"Bot Icon",width:48,height:48,fetchPriority:"high",className:"w-12 h-12 rounded-full object-cover"}):c("span",{className:"text-primary-foreground font-bold text-lg bg-transparent",children:"MC"})})}),c("div",{className:L("absolute bottom-0 right-0 w-3.5 h-3.5 rounded-full border-2 border-white shadow-sm",v.dotColor,E===_e.CONNECTING&&"animate-pulse")})]}),c("div",{className:"flex flex-col",children:[r?c("img",{src:r,alt:"",width:96,height:24,fetchPriority:"high",decoding:"sync",className:"h-6 w-auto object-contain"}):c("p",{className:L("font-semibold synapse-header-title",n?.length>21?"text-sm ":"text-lg",m),children:n||"Health Assist"}),c("div",{className:"flex items-center gap-1.5",children:c("span",{className:"text-xs font-medium",style:{color:"var(--header-tagline)"},children:v.text})})]})]}),c("div",{className:L("flex items-center",!f&&"gap-1"),children:[!C&&!y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Start New Chat",onClick:S,disabled:k,className:L("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",m),children:c(dr,{className:"w-5 h-5"})}),h&&y&&c(Se,{type:"button",variant:"ghost",size:"icon",title:"Chat history",onClick:h,className:L("h-8 w-8 p-1.5 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(wh,{className:"w-5 h-5"})}),f&&c(Se,{onClick:d,type:"button",variant:"ghost",size:"icon",title:g?"Exit fullscreen":"Enter fullscreen",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:g?c(Mh,{className:"w-8 h-8"}):c(Ch,{className:"w-8 h-8"})}),(t||!b)&&c(Se,{onClick:e,type:"button",variant:"ghost",size:"icon",title:"Close",className:L("h-8 w-8 hover:bg-primary hover:text-primary-foreground rounded-full transition-all duration-200",m),children:c(Tn,{className:"w-8 h-8"})})]})]})})}const as=ee(({className:e,...t},n)=>c("textarea",{className:L("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}));as.displayName="Textarea";function ec({file:e,onRemove:t,isPreview:n=!0,className:r=""}){const[o,i]=F(!1),[s,a]=F(""),l=e?.type?.startsWith("image/")??!1,d=e?.type==="application/pdf";Y(()=>{if(l){const p=URL.createObjectURL(e);return a(p),()=>URL.revokeObjectURL(p)}},[e,l]),Y(()=>{i(!1)},[e]);const h=()=>l?"text-green-600":"text-text-secondary",u=p=>{if(p===0)return"0 B";const _=1024,f=["B","KB","MB","GB"],g=Math.floor(Math.log(p)/Math.log(_));return`${(p/Math.pow(_,g)).toFixed(1)} ${f[g]}`.toLowerCase()};return!l||o?c("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:[c("div",{className:`flex-shrink-0 ${h()}`,children:c(El,{className:"h-5 w-5"})}),c("div",{className:"flex-1 min-w-0 max-w-[200px]",children:[e?.name&&c("div",{className:"text-sm font-medium text-[var(--color-foreground)] truncate",children:e.name}),e?.size&&c("div",{className:"text-xs text-[var(--color-muted-foreground)]",children:u(e.size)})]}),n&&t&&c("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:c(Tn,{className:"h-3 w-3"})})]}):c("div",{className:`relative group flex-shrink-0 ${r}`,children:[c("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&&c("img",{src:s,alt:e.name,className:"w-full h-full object-cover",onError:()=>i(!0)})}),n&&t&&c("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:c(Tn,{className:"h-3 w-3"})})]})}function ls({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 c("div",{className:`flex flex-wrap justify-end gap-2 max-w-full ${r}`,children:[i.map(s=>{const a=e.indexOf(s);return c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)}),o.length>0&&c("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 c(ec,{file:s,onRemove:t?()=>t(a):void 0,isPreview:n},`${s.name}-${s.size}-${a}`)})})]})}const cs=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("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"})}),tc=()=>import("./medassist-widget-ElicitationInput-DKEz5EVH.js"),zm=e=>{const t=()=>e.forEach(n=>void n().catch(()=>{}));typeof requestIdleCallback=="function"?requestIdleCallback(t,{timeout:1500}):setTimeout(t,1500)},nc=({className:e})=>c("svg",{width:"17",height:"16",viewBox:"0 0 17 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:c("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"})}),Ym=nt(()=>tc().then(e=>({default:e.ElicitationInput})));function Hm({value:e,onChange:t,onSend:n,onFileChange:r,onRemoveFile:o,onRecording:i,isRecording:s,hasAttachment:a,attachmentFiles:l,isDisabled:d,placeholder:h,isMobile:u,recordingStatus:p,theme:_,allowed:f,showStartNewChatButton:g,onStartNewChat:b,isVoiceAgentActive:m,handleVoiceMode:E,isAuthComponent:y,activeElicitationState:k,isFullScreen:x,showAttention:T}){const C=X(null),S=X(null),v=T?c("span",{className:"synapse-composer-ring","data-testid":"composer-attention-ring","aria-hidden":"true"}):null,N=e.trim().length>0||a,P=!f||f.includes(M.SYNAPSE_CONVERSATION.AUDIO),B=!f||f.includes(M.SYNAPSE_CONVERSATION.VOICE),G=N||!P,he=N,pe=!f||f.includes(M.SYNAPSE_CONVERSATION.FILE),se=(d||p!==be.IDLE)&&!s,Ee=L("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)]":se?"text-primary/50 cursor-not-allowed shadow-none":"text-foreground hover:bg-primary hover:text-primary-foreground"),V=I=>{const W=Array.from(I.target.files||[]);W.length>0&&r(W)},le=()=>{d||(C.current&&(C.current.value=""),C.current?.click())},Re=I=>{I.key==="Enter"&&!I.shiftKey&&he&&!d&&(I.preventDefault(),n())},te=I=>{I.style.height="auto",I.style.overflow="hidden";const W=I.scrollHeight,re=x?20:28,ve=120,K=Math.max(re,Math.min(W,ve));I.style.height=K+"px",W>ve?I.style.overflow="auto":I.style.overflow="hidden"},Q=I=>{te(I.currentTarget)};return Y(()=>{S.current&&te(S.current)},[e]),Y(()=>{d||S.current?.focus()},[d]),g&&b?c("div",{className:"px-4 py-2 flex justify-unset",children:c("button",{type:"button",onClick:b,className:L("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:[c("span",{children:"Start new chat"}),c(dr,{className:"w-5 h-5","aria-hidden":!0})]})}):c(me,{children:y?c(Xe,{fallback:c(Dl,{}),children:c(Ym,{elicitationEntry:k,value:e,onChange:t,isDisabled:d,theme:_,isMobile:u,onSend:n})}):x?c("div",{className:"mx-3 mb-3","data-name":"reply-box",children:c("div",{className:"relative flex flex-col items-stretch w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.5)",borderRadius:24,padding:8},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"flex items-center justify-between w-full",style:{padding:"12px 8px"},"data-name":"text-frame",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:I=>t(I.target.value),rows:1,maxLength:1e3,autoFocus:!0,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:Re,title:"Enter your message","aria-label":"Enter your message",className:L("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")})}),c("div",{className:"flex items-center justify-between w-full","data-name":"cta-row",children:[c("div",{className:"flex items-start shrink-0","data-name":"input-left-cta",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("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:c(Sl,{className:"w-6 h-6",strokeWidth:1.5})})}),c("div",{className:"flex gap-2 items-center shrink-0","data-name":"input-right-cta",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("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:c(bl,{className:"w-4 h-4"})}):P&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0 p-2",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-6 h-6",strokeWidth:1.5})}),G&&!s?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0 p-2",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):P&&B&&!s&&c(Se,{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:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})}):c("div",{className:"px-3 pt-1",children:[c("input",{ref:C,type:"file",multiple:!0,max:3,accept:"image/jpeg, image/png, image/jpg, application/pdf",className:"hidden",onChange:V,disabled:d,title:"Attach file","aria-label":"Attach file"}),c("div",{className:"relative flex flex-col w-full bg-elicitationBg",style:{border:"1px solid hsl(var(--primary) / 0.3)",borderRadius:20,padding:"8px 8px"},children:[v,a&&l.length>0&&c("div",{className:"mb-2 pb-2 border-b border-border-subtle",children:c(ls,{files:l,onRemoveFile:o,isPreview:!0})}),c("div",{className:"px-1 pt-1 pb-0",children:c(as,{ref:S,onInput:Q,placeholder:h,value:e,onChange:I=>t(I.target.value),rows:1,maxLength:1e3,autoFocus:!0,style:{wordBreak:"break-word",overflowWrap:"anywhere",minHeight:"28px",maxHeight:"120px",fontSize:"16px",lineHeight:"1.4"},onKeyPress:Re,title:"Enter your message","aria-label":"Enter your message",className:L("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")})}),c("div",{className:"flex items-center justify-between",children:[c("div",{className:"flex items-center shrink-0",children:pe&&p===be.IDLE&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:le,disabled:d,className:L("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:c(Sl,{className:"w-5 h-5",strokeWidth:1.5})})}),c("div",{className:"flex items-center gap-2 shrink-0",children:[s?c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,className:L("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:c(bl,{className:"w-4 h-4"})}):G?c(Se,{type:"button",size:"icon",onClick:()=>n(),disabled:d||!he,variant:"ghost",className:L("h-10 w-10 rounded-full transition-all duration-200 shadow-lg shrink-0",he?"bg-primary hover:bg-primary/90 hover:shadow-xl hover:scale-105 active:scale-95":"bg-primary/40"),title:he?"Send message":"Type a message to send","aria-label":he?"Send message":"Type a message to send",children:c(cs,{className:"w-4 h-4 text-primary-foreground"})}):P&&c(Se,{type:"button",variant:"ghost",size:"icon",onClick:i,disabled:se,className:L("h-10 w-10 shrink-0",Ee),title:"Start recording","aria-label":"Start recording",children:c(Ko,{className:"w-5 h-5",strokeWidth:1.5})}),P&&B&&!s&&c(Se,{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:c(nc,{className:"w-4 h-4 text-primary-foreground"})})]})]})]})]})})}const $m=Xt(Hm),rc=vt(null),oc=rc.Provider;function Bm(){const e=wt(rc);if(!e)throw new Error("useWidgetHeader must be used inside WidgetHeaderProvider (mounted by ChatWidget)");return e}function Gm({message:e,onDismiss:t}){return c(me,{children:[c("div",{className:"pointer-events-none absolute inset-0 z-[55] bg-black-600","aria-hidden":!0}),c("div",{className:"pointer-events-none absolute inset-x-3 top-3 z-[60]",role:"presentation",children:c("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:[c("p",{id:"synapse-disp-toast-msg",className:"min-w-0 flex-1 text-sm font-medium whitespace-pre-wrap",children:e}),c("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:c(Tn,{className:"h-4 w-4",strokeWidth:2.5})})]})})]})}function Wm(){const e=j(r=>r.toastMessage),t=j(r=>r.setToastMessage),n=de(()=>{t(null)},[t]);return Y(()=>{if(!e)return;const r=window.setTimeout(n,3e3);return()=>window.clearTimeout(r)},[e,n]),e?c(Gm,{message:e,onDismiss:n}):null}function ds({isOpen:e,children:t,align:n="center",onClose:r}){return e?c("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:c("div",{onClick:o=>o.stopPropagation(),children:t})}):null}const Km="Before we begin",qm=e=>`A quick note on how ${e} works and handles your information.`,Xm=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 Zm(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 sc=(e,t)=>{if(t){const n=Zm(t,e);if(n.length)return n}return Xm(e)},Jm="I agree and consent",Qm="By continuing, you consent to the above.",ep="Continue";function ic({botName:e,consentContent:t,isFullScreen:n}){return c(me,{children:[c("div",{className:"flex flex-col gap-1",children:[c("h2",{className:L("font-semibold text-foreground text-left text-pretty",n?"text-2xl":"text-lg"),children:Km}),c("p",{className:L("text-muted-foreground text-left text-pretty",n?"text-sm leading-5":"text-xs leading-4"),children:qm(e)})]}),c("div",{className:L("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:sc(e,t).map((r,o)=>c("p",{className:L("text-foreground/80 text-left text-pretty",n?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:r},o))})]})}function tp({isOpen:e,onClose:t,botName:n,explicitDisclaimer:r,consentContent:o,isFullScreen:i}){const s=!!r&&!!i;return c(ds,{isOpen:e,onClose:t,children:c("div",{className:L("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?c(ic,{botName:n,consentContent:o,isFullScreen:s}):c("div",{className:"flex flex-col gap-2",children:[c("h2",{className:"text-xl font-semibold text-foreground text-left text-pretty",children:"AI responses are not medical advice"}),sc(n,o).map((a,l)=>c("p",{className:L("text-foreground/80 text-left text-pretty",i?"text-sm leading-[22px]":"text-xs leading-[18px]"),children:a},l))]}),c(Se,{onClick:t,className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground",s&&"h-11 text-base"),children:"Got it"})]})})}function np({isOpen:e,botName:t,consentContent:n,onAccept:r,isFullScreen:o}){const[i,s]=F(!1);return e?c(ds,{isOpen:e,children:c("div",{role:"dialog","aria-modal":"true","aria-label":"Consent",className:L("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:[c(ic,{botName:t,consentContent:n,isFullScreen:o}),c("div",{className:"flex flex-col gap-1.5",children:[c("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[c("input",{type:"checkbox",checked:i,onChange:()=>s(a=>!a),className:"sr-only peer"}),c("div",{"aria-hidden":"true",className:L("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&&c("svg",{width:o?"11":"9",height:o?"9":"7",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"currentColor",className:"text-primary-foreground",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})}),c("span",{className:L("text-foreground cursor-pointer",o?"text-base":"text-sm"),children:Jm})]}),c("p",{className:L("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:Qm})]}),c(Se,{disabled:!i,onClick:()=>i&&r(),className:L("w-full bg-primary hover:bg-primary/90 text-primary-foreground disabled:opacity-50",o&&"h-11 text-base"),children:ep})]})}):null}const rp=nt(()=>import("./medassist-widget-mood-angry-BQqxy8gg.js").then(e=>({default:e.MoodAngry}))),op=nt(()=>import("./medassist-widget-mood-bad-BBDRkdRc.js").then(e=>({default:e.MoodBad}))),sp=nt(()=>import("./medassist-widget-mood-neutral-CbcKAQbC.js").then(e=>({default:e.MoodNeutral}))),ip=nt(()=>import("./medassist-widget-mood-poor-t4w5iE4B.js").then(e=>({default:e.MoodPoor}))),ap=nt(()=>import("./medassist-widget-mood-happy-oLG7NUhq.js").then(e=>({default:e.MoodHappy}))),lp=[{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"}],cp=[{Icon:rp,label:"Bad",score:1},{Icon:op,label:"Poor",score:2},{Icon:sp,label:"Okay",score:3},{Icon:ip,label:"Good",score:4},{Icon:ap,label:"Great!",score:5}];function dp(e,t){return e<=2?t.form?.detractors??[]:e===3?t.form?.passives??[]:t.form?.promoters??[]}function up({isOpen:e,config:t,onSubmit:n,onSkip:r,onClose:o,onDontShowAgain:i}){const s=t.type==="nps",[a,l]=F(null),[d,h]=F(new Set),[u,p]=F(!1),_=s&&a!==null?dp(a,t):t.form?.default?.length?t.form.default:lp,f=E=>{h(y=>{const k=new Set(y);return k.has(E)?k.delete(E):k.add(E),k})},g=E=>{l(E),h(new Set)},b=d?.size>0||a!==null||u,m=()=>{s&&a!==null&&n([...d],a),u&&i?.(),s||n([...d]),r()};return e?c(ds,{isOpen:e,onClose:o,children:c("div",{className:"flex flex-col items-end gap-1 mx-4 w-full max-w-xs",children:[c("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"}),c("div",{className:"bg-elicitationBg rounded-2xl shadow-xl p-5 w-full flex flex-col gap-4 border border-primary/50",children:[c("div",{className:"flex flex-col gap-1",children:[t.title&&c("h2",{className:"text-base font-semibold text-balance text-foreground text-center",children:t.title}),t.description&&c("p",{className:"text-xs text-muted-foreground leading-4 text-center",children:t.description})]}),s&&c("div",{className:"flex items-center justify-between gap-1",children:cp.map(({Icon:E,label:y,score:k})=>{const x=a===k,T=a!==null&&!x;return c("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:[c("div",{className:`rounded-xl p-1 transition-all ${x?"border-2 border-primary bg-primary/15":"border-2 border-transparent"} ${T?"opacity-50":""}`,style:x?{filter:"brightness(1.25)"}:void 0,children:c(Xe,{fallback:c("div",{className:"w-10 h-10 rounded-xl bg-surface-secondary"}),children:c(E,{})})}),c("span",{className:`text-[10px] leading-none transition-colors ${x?"text-primary/50 font-medium":T?"text-primary/50":"text-primary"}`,children:y})]},k)})}),(!s||a!==null)&&_.length>0&&c("div",{className:"flex flex-col gap-2",children:_.map(E=>c("div",{onClick:()=>f(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))}),c(Se,{disabled:!b,onClick:m,className:"w-full bg-primary hover:bg-primary/90 text-primary-foreground",children:"Submit & exit"}),c("label",{className:"flex items-center justify-center gap-1.5 cursor-pointer select-none",onClick:()=>p(E=>!E),children:[c("div",{className:"relative w-3 h-3 shrink-0",children:c("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&&c("svg",{width:"7",height:"6",viewBox:"0 0 10 8",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:c("path",{d:"M1 3.5L3.8 6.5L9 1",stroke:"black",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})}),c("span",{className:"text-xs text-muted-foreground",children:"Don't show again"})]})]})]})}):null}function ac({isOpen:e,children:t,sidebar:n,sessionDrawer:r,fullScreenEmptyState:o,sessionId:i,chatComposer:s,environment:a,mode:l,sidePanelMode:d,sidePanelWidth:h,side:u,onSidePanelPushChange:p,isAuthComponent:_,activeElicitation:f,voiceAgentState:g,theme:b,feedbackModal:m,consentModal:E}){const{onClose:y,showCloseButton:k=!0,title:x,titleImg:T,tagline:C,iconUrl:S,onStartNewSession:v,showStartNewChatButton:N,onToggleDisplayMode:P,onOpenSessionDrawer:B}=Bm(),[G,he]=F(!1),[pe,se]=F(!1),[Ee,V]=F(!1),le=X(null),Re=j(z=>z.level),te=l,Q=te==="full",I=te==="side_panel",W=X(null),[re,ve]=F("");Y(()=>{W.current!==null&&W.current!==te&&ve(te==="full"?"Switched to fullscreen mode":te==="side_panel"?"Switched to side panel mode":te==="widget"?"Switched to widget mode":"Switched to mobile layout"),W.current=te},[te]);const K=ie(()=>_m(b),[b]),Ae=j(z=>z.setIsMobile),He=!!_,ae=de(async z=>{if(!(!s?.onSend||pe)){se(!0);try{await s.onSend(z)}finally{se(!1)}}},[s?.onSend,pe]);ft(()=>{if(!le.current)return;const z=te==="full"?{...K,headerTinted:!1}:K;Pl(le.current,z),te==="full"&&!K.backgroundImage?(le.current.style.setProperty("--background","0 0% 100%"),le.current.style.setProperty("--widget-bg-overlay","transparent")):(le.current.style.removeProperty("--background"),le.current.style.removeProperty("--widget-bg-overlay"),Pl(le.current,K))},[K,te]),Y(()=>{const z=()=>{const Ie=window?.innerWidth??0,we=navigator?.userAgent?.toLowerCase()??"",Le=Ie<768||/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(we);he(Le),Ae(Le)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),ft(()=>{if(!e||!G||!le.current)return;const z=le.current;let Ie=null,we=null,Le=null,qe=window.visualViewport?.offsetTop??0,Ue=0;const Et=2,ht=80;if(window.visualViewport){const ze=()=>{if(z&&window.visualViewport){const Ge=window.visualViewport.height,Oe=window.visualViewport.offsetTop;Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Oe}px`,z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height=`${Ge}px`,z.style.maxHeight=`${Ge}px`,z.style.minHeight=`${Ge}px`,we&&clearTimeout(we),we=setTimeout(()=>{z.style.transition=""},100)})}},rt=()=>{ze()},Be=()=>{if(!z||!window.visualViewport)return;const Ge=window.visualViewport.offsetTop,Oe=Date.now();Math.abs(Ge-qe)<Et||Oe-Ue<ht||(Ue=Oe,qe=Ge,Ie=requestAnimationFrame(()=>{z.style.transition="none",z.style.top=`${Ge}px`,Le&&clearTimeout(Le),Le=setTimeout(()=>{z.style.transition=""},150)}))};return window.visualViewport.addEventListener("resize",rt),window.visualViewport.addEventListener("scroll",Be),ze(),()=>{Ie&&cancelAnimationFrame(Ie),we&&clearTimeout(we),Le&&clearTimeout(Le),window.visualViewport?.removeEventListener("resize",rt),window.visualViewport?.removeEventListener("scroll",Be),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.minHeight="",z.style.transition="")}}else{const ze=()=>{z&&(z.style.transition="none",z.style.top="0",z.style.left="0",z.style.right="0",z.style.bottom="auto",z.style.width="100vw",z.style.height="100svh",z.style.maxHeight="100svh",setTimeout(()=>{z.style.transition=""},100))};return window.addEventListener("resize",ze),ze(),()=>{window.removeEventListener("resize",ze),z&&(z.style.width="",z.style.height="",z.style.maxHeight="",z.style.transition="")}}},[e,G]),Y(()=>{if(e&&!(I&&d==="push")){const z=le.current,Ie=window.scrollY,we=document.body.style.cssText,Le=document.documentElement.style.overflow,qe=window.innerWidth-document.documentElement.clientWidth;document.body.style.position="fixed",document.body.style.top=`-${Ie}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",qe>0&&!G&&(document.body.style.paddingRight=`${qe}px`);let Ue=0;const Et=ze=>{Ue=ze.touches[0].clientY},ht=ze=>{if(ze.touches.length!==1)return;const rt=Ue-ze.touches[0].clientY;Ue=ze.touches[0].clientY;let Be=ze.target;for(;Be&&Be!==z;){const{overflowY:Ge}=window.getComputedStyle(Be);if((Ge==="auto"||Ge==="scroll")&&Be.scrollHeight>Be.clientHeight){const{scrollTop:Oe,scrollHeight:Bt,clientHeight:yt}=Be,an=Oe<=0&&rt<0,ln=Oe+yt>=Bt-1&&rt>0;if(!an&&!ln)return;break}Be=Be.parentElement}ze.preventDefault()};return z&&(z.addEventListener("touchstart",Et,{passive:!0}),z.addEventListener("touchmove",ht,{passive:!1})),()=>{z&&(z.removeEventListener("touchstart",Et),z.removeEventListener("touchmove",ht)),document.body.style.cssText=we,document.documentElement.style.overflow=Le,window.scrollTo(0,Ie)}}},[e,G,I,d]),Y(()=>{if(!(!I||d!=="push"||!e))return p?.(!0,h??0,u??"right"),()=>{p?.(!1,h??0,u??"right")}},[e,I,d,h,u,p]);const{position:Pe,elementRef:De}=hm({enabled:e&&!G&&!Q&&!I});Y(()=>{le.current&&(De.current=le.current)},[De]);const xt=L("synapse-chat-widget-container","fixed m-0 p-0","box-border",!G&&!Q&&!I?"transition-all duration-300":"",G?"w-screen h-[100svh]":Q?"w-screen h-screen":I?"h-screen":"w-96 h-[600px]","z-[2147483647]",e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none scale-95"),$t=L("w-full h-full relative","bg-background","shadow-2xl","flex","overflow-hidden",K.backgroundImage?"theme-with-background":"",G?"rounded-none border-0 flex-col":Q?"rounded-none border-0 flex-row":I?"rounded-none border-0 flex-col":"rounded-3xl flex-col");return c("div",{ref:le,"data-mode":te,className:xt,style:{margin:0,padding:0,border:"none",outline:"none",position:"fixed",zIndex:2147483647,fontSize:"16px",lineHeight:"2.5",userSelect:"auto",...Q&&e&&{top:0,left:0,right:0,bottom:0,width:"100vw",height:"100vh"},...Q&&!e&&{display:"none"},...I&&e&&{top:0,bottom:0,[u==="left"?"left":"right"]:0,[u==="left"?"right":"left"]:"auto",width:`${h}px`,height:"100vh"},...I&&!e&&{display:"none"},...!G&&!Q&&!I&&{left:`${Pe.x}px`,top:`${Pe.y}px`,bottom:"auto",right:"auto"},...G&&{top:0,left:0,right:0,bottom:0,width:"100vw",maxHeight:"100svh",height:"100svh",backgroundColor:K.backgroundImage?"transparent":"hsl(var(--background))"}},children:[c("style",{children:`
|
|
2
2
|
/* Isolate widget from host website styles */
|
|
3
3
|
.synapse-chat-widget-container,
|
|
4
4
|
.synapse-chat-widget-container *,
|
|
@@ -35,25 +35,25 @@ var vd=Object.defineProperty;var wd=(e,t,n)=>t in e?vd(e,t,{enumerable:!0,config
|
|
|
35
35
|
.synapse-chat-widget-container [data-radix-scroll-area-viewport] {
|
|
36
36
|
overscroll-behavior: contain;
|
|
37
37
|
}
|
|
38
|
-
`}),c(nn,{className:Ct,"data-text-color":q.textColor,style:W?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[c("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:re}),!q.backgroundImage&&c("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),q.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${q.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),q.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:q.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),c(Nm,{isOpen:me,onClose:()=>F(!1),botName:N,explicitDisclaimer:w?.explicitDisclaimer,consentContent:w?.consentContent,isFullScreen:Z}),g?.isOpen&&c(Cm,{isOpen:!0,botName:N,consentContent:w?.consentContent,onAccept:g.onAccept,isFullScreen:Z}),u?.isOpen&&c(Lm,{isOpen:u.isOpen,config:u.config,onSubmit:u.onSubmit,onSkip:u.onSkip,onClose:u.onClose,onDontShowAgain:u.onDontShowAgain}),Z&&n,Ie==="user"&&!Z&&r,c("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[c("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...Z?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!W&&!Z&&!$&&{cursor:e?"grab":"default"}},children:c(dm,{onClose:_,showCloseButton:b,title:N,titleImg:T,tagline:O,iconUrl:y,startNewConversation:v,voiceAgentState:S,headerTinted:Z?!1:q.headerTinted,onToggleDisplayMode:P,onOpenSessionDrawer:Z?void 0:G})}),(()=>{const z=Z&&!!o,Fe=s&&S===M.VOICE_AGENT_STATE.IDLE?c(Ke,{fallback:c(rc,{}),children:c(mm,{value:s.value,onChange:s.onChange,onSend:Ne?Oe:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||Ne&&de,isMobile:W,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:q,onStartNewChat:v,showStartNewChatButton:x,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:m,activeElicitationState:E,isFullScreen:Z&&!z,showAttention:s.showAttention})}):null,ye={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Pe=c(_e,{children:[i&&a==="development"&&c("div",{className:"px-6 flex justify-center items-center",children:c("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),Z?c("div",{onClick:()=>F(!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:c("span",{className:"text-[10px] leading-[14px]",style:ye,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):w?.explicitDisclaimer?c("div",{onClick:()=>F(!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:[w?.hideWatermark!==!0&&c("div",{className:"flex justify-center items-center gap-1",children:[c("span",{className:"text-[10px] leading-[14px]",style:ye,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:ye,children:"Eka Care"})]}),c("span",{className:"text-[10px] leading-[14px]",style:ye,children:["AI can make mistakes. ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):c("div",{onClick:()=>F(!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:[w?.hideWatermark!==!0&&c(_e,{children:[c("span",{className:"text-[10px] leading-[14px]",style:ye,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:ye,children:"Eka Care"})]}),c(zl,{className:"w-3 h-3"})]})]}),Xe=o&&Z?o({composer:z?Fe:null,composerFooter:z?Pe:null}):null;return c(_e,{children:[c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[Xe??t,c(_m,{})]}),s&&!z&&c("div",{className:D("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[c("div",{className:D(Z&&"max-w-2xl mx-auto w-full"),children:Fe}),Pe]})]})})()]})]})]})}function Dm(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Um(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 Fm(e){const t=new Date(e.c_at),n=Um(t),r=Dm(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function Vm(){return c("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 jm({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=Fm(e);return c("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[c("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),c("div",{className:"flex items-center gap-2 w-full min-w-0",children:[c("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&c(Vm,{})]})]})}function kc({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?c(Kp,{}):e.length===0?c("div",{className:"flex items-center justify-center h-full px-4 text-center",children:c("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):c(_e,{children:e.map(o=>c(jm,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function Ac(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:l,onClose:d}=e;return c(_e,{children:[c("div",{className:D("absolute inset-0 z-[60] transition-opacity duration-200",l?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),c("div",{className:D("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",l?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:"flex items-center justify-between",children:[c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:c(An,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[c("div",{className:"pr-2 shrink-0",children:c(Sr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),c("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(kc,{sessions:t,activeSessionId:n,onSelectSession:p=>{r(p),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return c("div",{id:"synapse-session-sidebar","data-collapsed":s,className:D("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"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:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:D("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:c(Qh,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?c("button",{type:"button",onClick:o,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:c(Sr,{className:"w-6 h-6"})}):c("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[c("div",{className:"pr-2 shrink-0",children:c(Sr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&c("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(kc,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function zm(){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 $m=180;function Hm({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=l=>{const d=l.label||l.value||"";d&&n({message:l.value||d,messageId:Date.now().toString()})};return c("div",{className:"flex-1 flex flex-col overflow-y-auto",children:c("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[c("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=$m&&c("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:zm()}),e&&c("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&c("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((l,d)=>{const p=l.label||l.value||"";return p?c("button",{type:"button",onClick:()=>a(l),disabled:r,className:D("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:p},`${p}-${d}`):null})}),s,o&&c("div",{children:[o,i]})]})})}const on={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Mn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function Ym(e,t){return`${e}:${t}`}function Ic(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}let Mc;const vs=new Set,oo={get:()=>Mc,set:e=>{Mc=e,vs.forEach(t=>t(e??[]))},subscribe:e=>(vs.add(e),()=>vs.delete(e))};function Bm(e){const t=e.title??e.name;switch(e.type){case"call":return`${t}\u2026`;case"progress":return e.total!==void 0?`${e.message} (${e.progress}/${e.total})`:e.message;case"result":return"error"in e.result||e.result.isError?`Couldn't complete: ${t}`:`Done: ${t}`}}function Pc(){const[e,t]=U(typeof navigator<"u"?navigator.onLine:!0);return j(()=>{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 Lc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Gm=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",Wm=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}},Km=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},Dc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},qm=({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),l=n||a,d=n&&r?Zm(n,r):i?31:3;return Array.from({length:d},(p,h)=>({date:Dc(l,h),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const l=a.date?s.findIndex(d=>d.date===a.date):-1;if(l===-1)s.push({...a});else{const d=s[l];s[l]={...d,...Lc(a),slots:a.slots??d.slots}}}return s},Xm=(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,l=s.end_date||o.end_date;r[i]={...s,...Lc(o),availability:qm({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:l,format:n})}}}return r},Uc=e=>!!e&&Array.isArray(e.doctors),Jm=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!Uc(e)||!Uc(t))return e;const r=e.format||t.format;return{...t,doctors:Xm(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Zm=(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},Fc=(e,t)=>`${e}::${t}`,Qm=e=>e<1e12?e*1e3:e,ef=(e,t)=>`${e}::${t}::answer`,tf=e=>!!e?.tool_id&&!!e?.component;function nf(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(tf),i=r.timestamp?tn(Qm(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===we.USER?we.USER:we.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>Fc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[Fc(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:ef(r.id,s.tool_id),content:s.answer,role:we.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const rf=Math.round(ec/(1024*1024)),Vc=(e,t=0)=>e.length+t>Ql?{title:`You can only upload up to ${Ql} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>ec?{title:`Total file size limit of ${rf} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,jc="initial-bot-message",sn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},of=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s,tools:a})=>{const[l,d]=U([]),p=X([]),[h,f]=U(!1),[m,E]=U(!1),S=X(new Map),w=X(0),[u,g]=U(!1),_=X([]),b=X(null),N=X({}),T=X({}),O=X(null),y=Rp(),v=X(null),{isOnline:x}=Pc(),P=X(!1),G=X([]),W=V(C=>C.agentId),ne=V(C=>C.sessionId),de=V(C=>C.isStreaming),ue=V(C=>C.isWaitingForResponse),me=V(C=>C.initialMessage),F=V(C=>C.userId),le=V(C=>C.fileUploadPerSession),{setSessionId:Ie,setRefreshToken:te,setSessToken:Z,setLevel:$,setError:H,setConnectionStatus:re,setShowRetryButton:he,setStartNewConnection:q,setIsStreaming:et,setIsWaitingForResponse:Ne,setProgressMessage:Oe,setRecordingStatus:fe,clearSession:Me,clearUser:Dt,addMessageToSession:Ct,getMessagesForSession:z,setMessagesForSession:Fe,updateMessageInSession:ye,setUserId:Pe,setFileUploadPerSession:Xe,setToastMessage:tt,upsertElicitationState:$e,setElicitationState:pt,setInitialMessage:Ve,setSessionInitialMessage:xt}=V.getState();j(()=>{if(!x)H({title:"No internet connection",description:"Please check your internet connection."}),re(Se.NOT_CONNECTED);else if(!u)re(Se.CONNECTING);else if(Ge())re(Se.CONNECTED),St();else{const{showRetryButton:C,startNewConnection:k,error:I}=V.getState();(C||k||I)&&!Ge()&&St(),O.current!==null&&!k&&!Nr()&&Le(V.getState().sessionId||void 0)}},[x,u]),j(()=>{ne&&(d(C=>{const k=new Set(C.map(A=>A.id)),I=[...C];for(const A of z(ne)||[])k.has(A.id)||(k.add(A.id),I.push(A));return I}),_.current=[])},[ne]),j(()=>{if(g(!1),!W)return;const C=a??oo.get(),k=new M.SynapseSDK({agentId:W,...o&&{authToken:o},...C?.length&&{clientTools:C},...V.getState().refreshToken&&{refreshToken:V.getState().refreshToken},...V.getState().sessToken&&{sessToken:V.getState().sessToken},...V.getState().level&&{level:V.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:F,callbacks:{onError:I=>{if(Cr(I),typeof navigator<"u"&&!navigator.onLine){re(Se.NOT_CONNECTED),H({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(I.reason)switch(I.reason){case M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{V.getState().level!=="user"?(Dt(),b.current?.clearTokens(),hn()):qt();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:qt();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:H(null),re(Se.NOT_CONNECTED),q(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:re(Se.CONNECTING);return}switch(I.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const A=I;A.status===404||A?.context?.status===404?q(!0):(re(Se.NOT_CONNECTED),H({title:"Something went wrong!",description:sn(I)}),he(!0));break}case M.SynapseErrorCode.RECORDING:H({title:"Recording failed",description:sn(I)});break;case M.SynapseErrorCode.CONNECTION:Ge()||(re(Se.NOT_CONNECTED),w.current<2?(w.current=w.current+1,Le(V.getState().sessionId||void 0)):(he(!0),H({title:"Trying to connect...",description:sn(I)})));break;default:H({title:"Something went wrong",description:sn(I)}),he(!0);break}},onTokenExchange:I=>{const A=V.getState().userId;(I?.user_id&&A&&I.user_id!==A||I?.userid_change_detected)&&Me(),I?.refresh_token&&te(I.refresh_token),I?.sess_token&&Z(I.sess_token),I?.level&&$(I.level),I?.user_id&&Pe(I.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return b.current=k,y(k),g(!0),()=>{g(!1),Kt(),b.current=null,y(null),v.current&&(clearTimeout(v.current),v.current=null)}},[W,e,o]),j(()=>{p.current=l},[l]),j(()=>{const C=p.current[p.current.length-1];if(!C?.role||!ne)return;const k=()=>d(I=>I.map(A=>A.id===C.id&&A.role===C.role?{...A,isStored:!0}:A));C?.role===we.USER&&!C.isStored?(k(),Ct(ne,{...C,isStored:!0})):!de&&!C.isStored&&(k(),Ct(ne,{...C,isStored:!0}))},[l,de]),j(()=>()=>{const C=p.current[p.current.length-1],k=V.getState().sessionId;C&&!C?.isStored&&k&&((V.getState().chats[k]||[]).some(I=>I.id===C.id)||Ct(k,{...C,isStored:!0}))},[]),j(()=>(v.current&&(clearTimeout(v.current),v.current=null),ue&&!de?v.current=setTimeout(()=>{Ne(!1),v.current=null},3e4):de&&v.current&&(clearTimeout(v.current),v.current=null),()=>{v.current&&(clearTimeout(v.current),v.current=null)}),[ue,de,Ne]);const Le=async C=>{O.current=performance.now();try{const k=await b.current?.startSession(C?{session_id:C}:void 0);if(k?.session_id&&(k.session_id in T.current||(T.current[k.session_id]=k.session_id===C),Ie(k.session_id)),k?.user_id&&Pe(k.user_id),k?.initial_message){Ve(k.initial_message);const I=k.session_id||C;I&&xt(I,k.initial_message)}k?.error?.msg&&tt(k.error.msg)}catch(k){if(k?.reason)return;const I=k;I.status===404||I.context?.status==404?(H(null),re(Se.NOT_CONNECTED),q(!0)):(H({title:"Connection Lost!",description:sn(k)}),he(!0))}},Je=async C=>{const k=V.getState().chats[C];if(k?.length)return d(k),k;const I=S.current.get(C);if(I)return I;const A=(async()=>{try{const K=await b.current?.getSessionMessages(C);if(!K?.length)return[];const{messages:oe,elicitations:ae}=nf(K);return Object.keys(ae).length&&pt({...V.getState().elicitationState,...ae}),Fe(C,oe),d(oe),oe}catch{return[]}finally{S.current.delete(C)}})();S.current.set(C,A),E(!0);try{return await A}finally{E(!1)}},nt=async({forceNewSession:C=!1,sessionId:k}={})=>{try{if(!b.current){H({title:"SDK not initialized",description:"Please ensure agentId is configured"}),f(!1);return}if(f(!0),C){re(Se.CONNECTING),d([]),await Me(),await b?.current?.endSession(),St(),await Le(),kr();return}const I=V.getState()?.sessionId,A=k||I||void 0;A!==I&&(Kt(),d([]),A&&await Je(A)),await Le(A),kr()}catch{}finally{f(!1)}},Ge=()=>b.current?.isConnected()??!1,Kt=()=>{b.current?.endSession()},St=()=>{w.current=0;const{showRetryButton:C,startNewConnection:k,error:I}=V.getState();C&&he(!1),k&&q(!1),I&&H(null)},cn=()=>{Dn(on.CONNECTION_ESTABLISHED)},Ln=()=>{let C;try{C=b.current?.getSessionConfig()?.session_id}catch{C=void 0}return C||V.getState().sessionId||void 0},Nr=()=>{try{return!!b.current?.getSessionConfig()?.session_id}catch{return!1}},Dn=(C,k={})=>{const I=Ln();!I||N.current[C]===I||(N.current[C]=I,Ic(C,{sessionId:I,resumed:T.current[I]??!1,...k}))},po=(C,k={})=>{const I=Ln();Ic(C,{...I&&{sessionId:I},...k})},Ot=(C,k,I={})=>{po(on.SESSION_ERROR,{reason:Ym(C,k),...I})},Cr=C=>{if(Ge())return;const k=C?.code,I=[M.SynapseErrorCode.RECORDING,M.SynapseErrorCode.FILE,M.SynapseErrorCode.MESSAGE,M.SynapseErrorCode.VALIDATION,M.SynapseErrorCode.CONFIGURATION,M.SynapseErrorCode.STORE];if(k&&I.includes(k))return;const A=typeof C?.status=="number"?C.status:void 0,K=C?.error,oe=typeof K?.code=="string"?K.code:typeof K?.type=="string"?K.type:void 0,ae={...A!==void 0&&{status:A}};if(C?.reason===M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||C?.reason===M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||k===M.SynapseErrorCode.AUTH||A===401||A===403){Ot(Mn.AUTH,C?.reason??oe??k??"auth_error",ae);return}const ie=k===M.SynapseErrorCode.API&&A===void 0;if(k===M.SynapseErrorCode.CONNECTION||A===0||ie){Ot(Mn.CONNECTION,C?.reason??oe??(ie?"timeout":k)??"connection_error",ae);return}Ot(Mn.SESSION,C?.reason??oe??k??"session_error",ae)},dn=C=>{switch(C){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Ot(Mn.SESSION,C);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Ot(Mn.CONNECTION,C);return}},xr=()=>{Dn(on.FIRST_MESSAGE_SENT)},mo=[on.CONNECTION_ESTABLISHED,on.FIRST_MESSAGE_SENT,on.FIRST_BOT_REPLY],fo=()=>{for(const C of mo)delete N.current[C];Ge()&&Nr()&&cn()},Or=C=>{C!==jc&&Dn(on.FIRST_BOT_REPLY,{messageId:C})},Rr=X(a);j(()=>{a!==Rr.current&&(Rr.current=a,b.current?.registerClientTools(a??[]))},[a]),j(()=>oo.subscribe(C=>{b.current?.registerClientTools(C)}),[]);const un=C=>{const{messageId:k,data:I}=C??{};if(!k||!I)return;P.current=!0;const A=Bm(I);d(K=>{const oe=K.findIndex(be=>be.id===k&&be.role===we.ASSISTANT),ae=V.getState().sessionId;if(oe===-1)return I.type!=="call"?K:[...K,{id:k,content:"",role:we.ASSISTANT,isStored:!1,toolCallStatus:A}];const ie=[...K];return ie[oe]={...K[oe],toolCallStatus:A},ae&&ye(ae,k,{toolCallStatus:A}),ie})},kr=()=>{const C=b.current;if(!C)return;for(const[I,A]of G.current)C.off(I,A);G.current=[];const k=(I,A)=>{C.on(I,A),G.current.push([I,A])};k(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,I=>{const A=I;if(A.data?.text&&A.messageId){const K=V.getState();K.isStreaming||(Ne(!1),et(!0),St()),K.connectionStatus!==Se.CONNECTED&&Ge()&&re(Se.CONNECTED);const oe=A.data.text,ae=A.messageId,ie=P.current;P.current=!1;const be=p.current[p.current.length-1];!(be&&be.id===ae&&be.role===we.ASSISTANT)&&Or(ae),d(Ye=>{const De=Ye[Ye.length-1];if(De&&De.id===ae&&De.role===we.ASSISTANT){const Re=[...Ye],rt=ie&&De.content.length>0&&!/\s$/.test(De.content)&&!/^\s/.test(oe)?`
|
|
38
|
+
`}),c(en,{className:$t,"data-text-color":K.textColor,style:G?void 0:{border:"1.5px solid hsl(var(--primary) / 0.5)"},children:[c("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:re}),!K.backgroundImage&&c("div",{className:"absolute inset-0 pointer-events-none",style:{backgroundColor:"var(--widget-bg-overlay)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundImage:`url(${K.backgroundImage})`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",transform:"scale(1.1)"}}),K.backgroundImage&&c("div",{className:"absolute inset-0 -z-10",style:{backgroundColor:K.textColor==="white"?"rgba(0, 0, 0, 0.4)":"rgba(255, 255, 255, 0.4)"}}),c(tp,{isOpen:Ee,onClose:()=>V(!1),botName:x,explicitDisclaimer:b?.explicitDisclaimer,consentContent:b?.consentContent,isFullScreen:Q}),E?.isOpen&&c(np,{isOpen:!0,botName:x,consentContent:b?.consentContent,onAccept:E.onAccept,isFullScreen:Q}),m?.isOpen&&c(up,{isOpen:m.isOpen,config:m.config,onSubmit:m.onSubmit,onSkip:m.onSkip,onClose:m.onClose,onDontShowAgain:m.onDontShowAgain}),Q&&n,Re==="user"&&!Q&&r,c("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 h-full",children:[c("div",{className:"flex-shrink-0 sticky top-0 z-50 synapse-chat-widget-header",style:{...Q?{background:"transparent"}:{backgroundColor:"hsl(var(--background))",backgroundImage:"linear-gradient(var(--header-bg), var(--header-bg))"},borderBottom:"0.5px solid var(--header-stroke)",...!G&&!Q&&!I&&{cursor:e?"grab":"default"}},children:c(jm,{onClose:y,showCloseButton:k,title:x,titleImg:T,tagline:C,iconUrl:S,startNewConversation:v,voiceAgentState:g,headerTinted:Q?!1:K.headerTinted,onToggleDisplayMode:P,onOpenSessionDrawer:Q?void 0:B})}),(()=>{const z=Q&&!!o,Ie=s&&g===M.VOICE_AGENT_STATE.IDLE?c(Xe,{fallback:c(Dl,{}),children:c($m,{value:s.value,onChange:s.onChange,onSend:He?ae:s.onSend,onFileChange:s.onFileChange,onRemoveFile:s.onRemoveFile,onRecording:s.onRecording,isRecording:s.isRecording,hasAttachment:s.hasAttachment,attachmentFiles:s.attachmentFiles,isDisabled:s.isDisabled||He&&pe,isMobile:G,placeholder:s.placeholder,recordingStatus:s.recordingStatus,theme:K,onStartNewChat:v,showStartNewChatButton:N,isVoiceAgentActive:s.isVoiceAgentActive,handleVoiceMode:s.handleVoiceMode,allowed:s.allowed,isAuthComponent:_,activeElicitationState:f,isFullScreen:Q&&!z,showAttention:s.showAttention})}):null,we={fontFamily:"Inter, system-ui, -apple-system, sans-serif",fontWeight:400,fontStyle:"normal",letterSpacing:"0%"},Le=c(me,{children:[i&&a==="development"&&c("div",{className:"px-6 flex justify-center items-center",children:c("p",{className:"text-[8px] text-text-secondary font-mono opacity-50",children:["Session ID: ",i]})}),Q?c("div",{onClick:()=>V(!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:c("span",{className:"text-[10px] leading-[14px]",style:we,children:["This is an AI chatbot and can make mistake. Please double check responses."," ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})}):b?.explicitDisclaimer?c("div",{onClick:()=>V(!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:[b?.hideWatermark!==!0&&c("div",{className:"flex justify-center items-center gap-1",children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:["AI can make mistakes. ",c("span",{className:"underline underline-offset-2",children:"Terms & privacy"})]})]}):c("div",{onClick:()=>V(!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:[b?.hideWatermark!==!0&&c(me,{children:[c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Powered by"}),c("span",{className:"text-[10px] leading-[14px]",style:we,children:"Eka Care"})]}),c(yl,{className:"w-3 h-3"})]})]}),qe=o&&Q?o({composer:z?Ie:null,composerFooter:z?Le:null}):null;return c(me,{children:[c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col relative",children:[qe??t,c(Wm,{})]}),s&&!z&&c("div",{className:L("flex-shrink-0 sticky bottom-0 z-50"),style:{},children:[c("div",{className:L(Q&&"max-w-2xl mx-auto w-full"),children:Ie}),Le]})]})})()]})]})]})}function hp(e){return e.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function mp(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 pp(e){const t=new Date(e.c_at),n=mp(t),r=hp(t),o=!!e.topic&&!e.topic.startsWith("Chat on");return{title:o?e.topic:`Chat at ${r}`,subtitle:o?`${n}, ${r}`:n}}function fp(){return c("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 gp({session:e,isActive:t,onSelectSession:n}){const{title:r,subtitle:o}=pp(e);return c("button",{type:"button",onClick:()=>n(e.session_id),"aria-current":t?"true":void 0,className:"flex flex-col gap-1 w-full text-left px-4 py-3 transition-colors hover:bg-secondary",style:t?{backgroundImage:"linear-gradient(90deg, hsl(var(--primary) / 0.1) 0%, hsl(var(--primary) / 0.1) 100%)"}:void 0,children:[c("p",{className:"text-sm font-medium leading-5 truncate w-full text-foreground",children:r}),c("div",{className:"flex items-center gap-2 w-full min-w-0",children:[c("span",{className:"text-[10px] font-normal leading-[14px] truncate text-muted-foreground",children:o}),t&&c(fp,{})]})]})}function lc({sessions:e,activeSessionId:t,onSelectSession:n,isLoading:r}){return r&&e.length===0?c(Nm,{}):e.length===0?c("div",{className:"flex items-center justify-center h-full px-4 text-center",children:c("p",{className:"text-xs text-muted-foreground",children:"No past chats"})}):c(me,{children:e.map(o=>c(gp,{session:o,isActive:o.session_id===t,onSelectSession:n},o.session_id))})}function cc(e){const{sessions:t,activeSessionId:n,onSelectSession:r,onNewChat:o,isLoading:i}=e;if(e.variant==="drawer"){const{isOpen:l,onClose:d}=e;return c(me,{children:[c("div",{className:L("absolute inset-0 z-[60] transition-opacity duration-200",l?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"),style:{backgroundColor:"var(--black-200)"},onClick:d}),c("div",{className:L("absolute top-0 bottom-0 right-0 z-[61] w-[280px] flex flex-col","bg-elicitationBg transition-transform duration-200",l?"translate-x-0":"translate-x-full"),style:{borderLeft:"1px solid hsl(var(--border-subtle))"},children:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:"flex items-center justify-between",children:[c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{onClick:d,className:"p-2 rounded-full text-foreground hover:bg-secondary transition-colors","aria-label":"Close chats drawer",children:c(Tn,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("button",{onClick:()=>{o(),d()},className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),c("div",{className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:h=>{r(h),d()},isLoading:i})})]})]})}const{isCollapsed:s,onToggle:a}=e;return c("div",{id:"synapse-session-sidebar","data-collapsed":s,className:L("flex flex-col shrink-0 h-full overflow-hidden transition-[width] duration-200","bg-elicitationBg",s?"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:[c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:c("div",{className:L("flex items-center w-full",s?"justify-center":"justify-between"),children:[!s&&c("p",{className:"text-base font-medium leading-6 truncate text-foreground",children:"Chats"}),c("button",{type:"button",onClick:a,className:"flex items-center justify-center p-2 rounded-full text-foreground hover:bg-secondary transition-colors",title:s?"Expand chats":"Collapse chats","aria-label":s?"Expand chats":"Collapse chats","aria-expanded":!s,"aria-controls":"synapse-session-list",children:c(Oh,{className:"w-6 h-6"})})]})}),c("div",{className:"flex flex-col gap-2 p-4 shrink-0",style:s?void 0:{borderBottom:"1px solid hsl(var(--border-subtle))"},children:s?c("button",{type:"button",onClick:o,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:c(dr,{className:"w-6 h-6"})}):c("button",{type:"button",onClick:o,className:"flex items-center w-full px-3 py-3 rounded-lg overflow-hidden bg-primary hover:opacity-90 transition-opacity",children:[c("div",{className:"pr-2 shrink-0",children:c(dr,{className:"w-4 h-4 text-primary-foreground"})}),c("span",{className:"text-sm font-normal leading-5 text-primary-foreground truncate",children:"Start new chat"})]})}),!s&&c("div",{id:"synapse-session-list",className:"flex-1 min-h-0 overflow-x-hidden overflow-y-auto",children:c(lc,{sessions:t,activeSessionId:n,onSelectSession:r,isLoading:i})})]})}function _p(){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 Ep=180;function yp({description:e,suggestions:t,onSendMessage:n,disabled:r,composer:o,composerFooter:i,connectionBanner:s}){const a=l=>{const d=l.label||l.value||"";d&&n({message:l.value||d,messageId:Date.now().toString()})};return c("div",{className:"flex-1 flex flex-col overflow-y-auto",children:c("div",{className:"flex flex-col items-stretch gap-6 w-full max-w-2xl mx-auto my-auto px-4 py-6",children:[c("div",{className:"flex flex-col px-3 gap-2 items-start",children:[e&&e?.trim?.()?.length<=Ep&&c("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:_p()}),e&&c("p",{className:"text-text-primary",style:{fontFamily:"Inter, sans-serif",fontSize:16,lineHeight:"24px",fontWeight:400,margin:0},children:e})]}),t&&t.length>0&&c("div",{className:"content-center px-3 flex flex-wrap gap-4 items-center",children:t.map((l,d)=>{const h=l.label||l.value||"";return h?c("button",{type:"button",onClick:()=>a(l),disabled:r,className:L("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&&c("div",{children:[o,i]})]})})}const nn={SESSION_ERROR:"session_error",CONNECTION_ESTABLISHED:"connection_established",FIRST_MESSAGE_SENT:"first_message_sent",FIRST_BOT_REPLY:"first_bot_reply"},Cn={AUTH:"auth_failed",SESSION:"session_failed",CONNECTION:"connection_failed"};function Sp(e,t){return`${e}:${t}`}function dc(e,t={}){if(!(typeof window>"u")&&typeof window.trackWidgetEvent=="function")try{window.trackWidgetEvent(e,t)}catch{}}function uc(){const[e,t]=F(typeof navigator<"u"?navigator.onLine:!0);return Y(()=>{const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n),window.addEventListener("offline",r),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}},[]),{isOnline:e}}const hc=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),bp=e=>e?e.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"DR",vp=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}},wp=e=>{const t=new Date(e);return isNaN(t.getTime())?e:t.toLocaleDateString("en-GB",{day:"numeric",month:"long",year:"numeric"})},mc=(e,t)=>{const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)},Np=({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),l=n||a,d=n&&r?Cp(n,r):i?31:3;return Array.from({length:d},(h,u)=>({date:mc(l,u),slots:[]}))}if(!e.length)return t;if(!t.length)return e;const s=e.map(a=>({...a}));for(const a of t){const l=a.date?s.findIndex(d=>d.date===a.date):-1;if(l===-1)s.push({...a});else{const d=s[l];s[l]={...d,...hc(a),slots:a.slots??d.slots}}}return s},Tp=(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,l=s.end_date||o.end_date;r[i]={...s,...hc(o),availability:Np({prev:s.availability??[],next:o.availability??[],startDate:a,endDate:l,format:n})}}}return r},pc=e=>!!e&&Array.isArray(e.doctors),xp=(e,t,n)=>{if(!e)return t;if(!t)return e;if(n!==M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return t;if(!pc(e)||!pc(t))return e;const r=e.format||t.format;return{...t,doctors:Tp(e.doctors,t.doctors,r),doctor_details:{...e.doctor_details||{},...t.doctor_details||{}}}},Cp=(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},fc=(e,t)=>`${e}::${t}`,kp=e=>e<1e12?e*1e3:e,Op=(e,t)=>`${e}::${t}::answer`,Rp=e=>!!e?.tool_id&&!!e?.component;function Ap(e){const t=[],n={};for(const r of e||[]){const o=(r.elicitations||[]).filter(Rp),i=r.timestamp?Qt(kp(r.timestamp)):void 0;t.push({id:r.id,content:r.content,role:r.role===Ne.USER?Ne.USER:Ne.ASSISTANT,isStored:!0,...i&&{timestamp:i},...o.length&&{tool_keys:o.map(s=>fc(r.id,s.tool_id)),isResponseFromTool:!0}});for(const s of o)n[fc(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:Op(r.id,s.tool_id),content:s.answer,role:Ne.USER,isStored:!0,...i&&{timestamp:i}})}return{messages:t,elicitations:n}}const Ip=Math.round(Il/(1024*1024)),gc=(e,t=0)=>e.length+t>Al?{title:`You can only upload up to ${Al} files at a time`,description:"Please remove some files and try again."}:e.reduce((n,r)=>n+r.size,0)>Il?{title:`Total file size limit of ${Ip} MB exceeded`,description:"Please reduce the size of the files or try again with less files"}:null,_c="initial-bot-message",rn=e=>{const t=e;return t?.message?t.error?.msg||t.message:e instanceof Error?e.message:"An unexpected error occurred"},Mp=({environment:e,connectionType:t,baseUrl:n,context:r,authToken:o,force:i,channel:s})=>{const[a,l]=F([]),d=X([]),[h,u]=F(!1),[p,_]=F(!1),f=X(new Map),g=X(0),[b,m]=F(!1),E=X([]),y=X(null),k=X({}),x=X({}),T=X(null),C=sm(),S=X(null),{isOnline:v}=uc(),N=X(!1),P=X([]),B=j(w=>w.agentId),G=j(w=>w.sessionId),he=j(w=>w.isStreaming),pe=j(w=>w.isWaitingForResponse),se=j(w=>w.initialMessage),Ee=j(w=>w.userId),V=j(w=>w.fileUploadPerSession),{setSessionId:le,setRefreshToken:Re,setSessToken:te,setLevel:Q,setError:I,setConnectionStatus:W,setShowRetryButton:re,setStartNewConnection:ve,setIsStreaming:K,setIsWaitingForResponse:Ae,setProgressMessage:He,setRecordingStatus:ae,clearSession:Pe,clearUser:De,addMessageToSession:xt,getMessagesForSession:$t,setMessagesForSession:z,updateMessageInSession:Ie,setUserId:we,setFileUploadPerSession:Le,setToastMessage:qe,upsertElicitationState:Ue,setElicitationState:Et,setInitialMessage:ht,setSessionInitialMessage:ze}=j.getState();Y(()=>{if(!v)I({title:"No internet connection",description:"Please check your internet connection."}),W(_e.NOT_CONNECTED);else if(!b)W(_e.CONNECTING);else if(Oe())W(_e.CONNECTED),yt();else{const{showRetryButton:w,startNewConnection:O,error:D}=j.getState();(w||O||D)&&!Oe()&&yt(),T.current!==null&&!O&&!On()&&rt(j.getState().sessionId||void 0)}},[v,b]),Y(()=>{G&&(l(w=>{const O=new Set(w.map(A=>A.id)),D=[...w];for(const A of $t(G)||[])O.has(A.id)||(O.add(A.id),D.push(A));return D}),E.current=[])},[G]),Y(()=>{if(m(!1),!B)return;const w=new M.SynapseSDK({agentId:B,...o&&{authToken:o},...j.getState().refreshToken&&{refreshToken:j.getState().refreshToken},...j.getState().sessToken&&{sessToken:j.getState().sessToken},...j.getState().level&&{level:j.getState().level},...i&&{force:i},...s&&{channel:s},environment:e,...t&&{connectionType:t},userId:Ee,callbacks:{onError:O=>{if(gr(O),typeof navigator<"u"&&!navigator.onLine){W(_e.NOT_CONNECTED),I({title:"No internet connection",description:"Will reconnect automatically when internet is restored."});return}if(O.reason)switch(O.reason){case M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN:{j.getState().level!=="user"?(De(),y.current?.clearTokens(),cn()):wr();return}case M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED:wr();return;case M.SYNAPSE_RECOVERY_REASON.SESSION_NOT_FOUND:I(null),W(_e.NOT_CONNECTED),ve(!0);return;case M.SYNAPSE_RECOVERY_REASON.RETRY_LATER:W(_e.CONNECTING);return}switch(O.code){case M.SynapseErrorCode.API:case M.SynapseErrorCode.SESSION:{const D=O;D.status===404||D?.context?.status===404?ve(!0):(W(_e.NOT_CONNECTED),I({title:"Something went wrong!",description:rn(O)}),re(!0));break}case M.SynapseErrorCode.RECORDING:I({title:"Recording failed",description:rn(O)});break;case M.SynapseErrorCode.CONNECTION:Oe()||(W(_e.NOT_CONNECTED),g.current<2?(g.current=g.current+1,rt(j.getState().sessionId||void 0)):(re(!0),I({title:"Trying to connect...",description:rn(O)})));break;default:I({title:"Something went wrong",description:rn(O)}),re(!0);break}},onTokenExchange:O=>{const D=j.getState().userId;(O?.user_id&&D&&O.user_id!==D||O?.userid_change_detected)&&Pe(),O?.refresh_token&&Re(O.refresh_token),O?.sess_token&&te(O.sess_token),O?.level&&Q(O.level),O?.user_id&&we(O.user_id)}},...n&&{serverUrl:n},...r&&{context:r}});return y.current=w,C(w),m(!0),()=>{m(!1),Bt(),y.current=null,C(null),S.current&&(clearTimeout(S.current),S.current=null)}},[B,e,o]),Y(()=>{d.current=a},[a]),Y(()=>{const w=d.current[d.current.length-1];if(!w?.role||!G)return;const O=()=>l(D=>D.map(A=>A.id===w.id&&A.role===w.role?{...A,isStored:!0}:A));w?.role===Ne.USER&&!w.isStored?(O(),xt(G,{...w,isStored:!0})):!he&&!w.isStored&&(O(),xt(G,{...w,isStored:!0}))},[a,he]),Y(()=>()=>{const w=d.current[d.current.length-1],O=j.getState().sessionId;w&&!w?.isStored&&O&&((j.getState().chats[O]||[]).some(D=>D.id===w.id)||xt(O,{...w,isStored:!0}))},[]),Y(()=>(S.current&&(clearTimeout(S.current),S.current=null),pe&&!he?S.current=setTimeout(()=>{Ae(!1),S.current=null},3e4):he&&S.current&&(clearTimeout(S.current),S.current=null),()=>{S.current&&(clearTimeout(S.current),S.current=null)}),[pe,he,Ae]);const rt=async w=>{T.current=performance.now();try{const O=await y.current?.startSession(w?{session_id:w}:void 0);if(O?.session_id&&(O.session_id in x.current||(x.current[O.session_id]=O.session_id===w),le(O.session_id)),O?.user_id&&we(O.user_id),O?.initial_message){ht(O.initial_message);const D=O.session_id||w;D&&ze(D,O.initial_message)}O?.error?.msg&&qe(O.error.msg)}catch(O){if(O?.reason)return;const D=O;D.status===404||D.context?.status==404?(I(null),W(_e.NOT_CONNECTED),ve(!0)):(I({title:"Connection Lost!",description:rn(O)}),re(!0))}},Be=async w=>{const O=j.getState().chats[w];if(O?.length)return l(O),O;const D=f.current.get(w);if(D)return D;const A=(async()=>{try{const q=await y.current?.getSessionMessages(w);if(!q?.length)return[];const{messages:oe,elicitations:ce}=Ap(q);return Object.keys(ce).length&&Et({...j.getState().elicitationState,...ce}),z(w,oe),l(oe),oe}catch{return[]}finally{f.current.delete(w)}})();f.current.set(w,A),_(!0);try{return await A}finally{_(!1)}},Ge=async({forceNewSession:w=!1,sessionId:O}={})=>{try{if(!y.current){I({title:"SDK not initialized",description:"Please ensure agentId is configured"}),u(!1);return}if(u(!0),w){W(_e.CONNECTING),l([]),await Pe(),await y?.current?.endSession(),yt(),await rt(),yr();return}const D=j.getState()?.sessionId,A=O||D||void 0;A!==D&&(Bt(),l([]),A&&await Be(A)),await rt(A),yr()}catch{}finally{u(!1)}},Oe=()=>y.current?.isConnected()??!1,Bt=()=>{y.current?.endSession()},yt=()=>{g.current=0;const{showRetryButton:w,startNewConnection:O,error:D}=j.getState();w&&re(!1),O&&ve(!1),D&&I(null)},an=()=>{Rn(nn.CONNECTION_ESTABLISHED)},ln=()=>{let w;try{w=y.current?.getSessionConfig()?.session_id}catch{w=void 0}return w||j.getState().sessionId||void 0},On=()=>{try{return!!y.current?.getSessionConfig()?.session_id}catch{return!1}},Rn=(w,O={})=>{const D=ln();!D||k.current[w]===D||(k.current[w]=D,dc(w,{sessionId:D,resumed:x.current[D]??!1,...O}))},Qr=(w,O={})=>{const D=ln();dc(w,{...D&&{sessionId:D},...O})},Lt=(w,O,D={})=>{Qr(nn.SESSION_ERROR,{reason:Sp(w,O),...D})},gr=w=>{if(Oe())return;const O=w?.code,D=[M.SynapseErrorCode.RECORDING,M.SynapseErrorCode.FILE,M.SynapseErrorCode.MESSAGE,M.SynapseErrorCode.VALIDATION,M.SynapseErrorCode.CONFIGURATION,M.SynapseErrorCode.STORE];if(O&&D.includes(O))return;const A=typeof w?.status=="number"?w.status:void 0,q=w?.error,oe=typeof q?.code=="string"?q.code:typeof q?.type=="string"?q.type:void 0,ce={...A!==void 0&&{status:A}};if(w?.reason===M.SYNAPSE_RECOVERY_REASON.AUTH_EXPIRED||w?.reason===M.SYNAPSE_RECOVERY_REASON.SESSION_FORBIDDEN||O===M.SynapseErrorCode.AUTH||A===401||A===403){Lt(Cn.AUTH,w?.reason??oe??O??"auth_error",ce);return}const ue=O===M.SynapseErrorCode.API&&A===void 0;if(O===M.SynapseErrorCode.CONNECTION||A===0||ue){Lt(Cn.CONNECTION,w?.reason??oe??(ue?"timeout":O)??"connection_error",ce);return}Lt(Cn.SESSION,w?.reason??oe??O??"session_error",ce)},_r=w=>{switch(w){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:Lt(Cn.SESSION,w);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:Lt(Cn.CONNECTION,w);return}},Gt=()=>{Rn(nn.FIRST_MESSAGE_SENT)},eo=[nn.CONNECTION_ESTABLISHED,nn.FIRST_MESSAGE_SENT,nn.FIRST_BOT_REPLY],to=()=>{for(const w of eo)delete k.current[w];Oe()&&On()&&an()},Er=w=>{w!==_c&&Rn(nn.FIRST_BOT_REPLY,{messageId:w})},yr=()=>{const w=y.current;if(!w)return;for(const[D,A]of P.current)w.off(D,A);P.current=[];const O=(D,A)=>{w.on(D,A),P.current.push([D,A])};O(M.SYNAPSE_REALTIME_EVENTS.MESSAGE_CHUNK,D=>{const A=D;if(A.data?.text&&A.messageId){const q=j.getState();q.isStreaming||(Ae(!1),K(!0),yt()),q.connectionStatus!==_e.CONNECTED&&Oe()&&W(_e.CONNECTED);const oe=A.data.text,ce=A.messageId,ue=N.current;N.current=!1;const Me=d.current[d.current.length-1];!(Me&&Me.id===ce&&Me.role===Ne.ASSISTANT)&&Er(ce),l(We=>{const Te=We[We.length-1];if(Te&&Te.id===ce&&Te.role===Ne.ASSISTANT){const xe=[...We],Je=ue&&Te.content.length>0&&!/\s$/.test(Te.content)&&!/^\s/.test(oe)?`
|
|
39
39
|
|
|
40
|
-
`:"";return Re[Re.length-1]={...De,content:De.content+rt+oe},Re}else return[...Ye,{id:ae,content:oe,role:we.ASSISTANT,timestamp:tn(Date.now()),isStored:!1}]})}}),k(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{P.current=!1,et(!1),Oe(null),Ne(!1)}),k(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{St(),re(Se.CONNECTED),cn()}),k(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,I=>{P.current=!0;const A=I;if(!A?.messageId||!A?.data||!A?.data?.details?.component||!A?.data?.tool_id)return;V.getState().isWaitingForResponse&&Ne(!1);const{messageId:K,data:oe}=A,ae=oe.tool_id,ie=`${K}::${ae}`,be=V.getState().elicitationState[ie],Ye=oe.details?.component,De=A?.data?.details?._meta?.tool_result,Re=oe.details?.input,rt=Jm(be?.input,Re,Ye);let Rt=A.data.details?._meta?.disp_toast_msg;const kt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Q=A?.data?.details?.input||{},ct=kt.reduce((Vt,At)=>(Q[At]!==void 0&&(Vt[At]=Q[At]),Vt),{}),We={...be?.server_input||{},...ct},mt=kt.filter(Vt=>!We[Vt]),ft=A.data.details?._meta?.mcp_meta_fields||[];$e(ie,{tool_id:ae,active:!0,disabled:!1,input:rt,server_input:We,messageId:K,required:kt,component:Ye,pattern:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.pattern,minLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.minLength,maxLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.maxLength,type:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.type,disp_toast_msg:A.data.details?._meta?.disp_toast_msg,description:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.description,tool_result:De,orientation:A.data.details?._meta?.orientation,...ft.length&&{mcp_meta_fields:ft},...mt?{toolSelectionNames:mt}:{},...be?.hide_show_more!==void 0?{hide_show_more:be.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{$e(ie,{...be||{},tool_id:ae,disabled:!0,active:Oh(Ye),messageId:K,component:Ye,input:rt,tool_result:De,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{$e(ie,{...be||{},tool_id:ae,active:!1,messageId:K,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:De,disabled:!0});break}default:$e(ie,{tool_id:ae,disabled:!1,active:!1,messageId:K,tool_result:De,input:rt,component:Ye})}Rt&&tt(Rt);const lt=A?.data?.details?._meta?.user_hint;d(Q=>{let ct=Q[Q.length-1]?.id===K?Q.length-1:Q.findIndex?.(We=>We.id===K);if(ct==-1){const We={id:K,content:A.data?.details?.input?.text||"",role:we.ASSISTANT,tool_keys:[ie],isResponseFromTool:!0,isStored:!1,...lt?{userHint:lt}:{}};return[...Q,We]}else{const We={...Q[ct],isResponseFromTool:!0,tool_keys:[...new Set([...Q[ct].tool_keys||[],ie])],...lt?{userHint:lt}:{}},mt=V.getState().sessionId;mt&&ye(mt,K,We);const ft=[...Q];return ft[ct]=We,ft}});const pn=A?.data?.details?._meta?.disp_message,ot=V.getState().elicitationState;if((!ot[ie]?.active||ot[ie]?.send_to_llm)&&(pn||Object.keys(De||{}).length))try{Ut({message:pn||"",tool_result:De,toolCalled:!0,tool_key:ie})}catch{}}),k(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,I=>{if(I?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const A=I;Ot(Mn.CONNECTION,A?.reason??"unknown",{...typeof A?.code=="number"&&{closeCode:A.code}}),O.current=performance.now();const K=typeof navigator<"u"&&!navigator.onLine;if(re(Se.NOT_CONNECTED),K){H({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),he(!1);return}w.current<2?(w.current=w.current+1,he(!0),H({title:"Something went wrong!",description:"Please try again."})):(H({title:"Something went wrong!",description:"Please start a new Chat."}),q(!0))}),k(M.SYNAPSE_REALTIME_EVENTS.ERROR,I=>{const A=I?.data?.code;switch(dn(A),A){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:q(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:H({title:"Session not found",description:"Please start a new chat from onError callback"}),q(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:hn();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(w.current<1){w.current++,Un();return}H({title:"Error parsing request",description:"please try again"}),he(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:H({title:"Request timed out",description:"please try again"}),he(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:H({title:"Something went wrong",description:"please try again"}),he(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:H({title:"Something went wrong",description:"please try again"}),he(!0),fe(Te.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:H({title:"Something went wrong",description:"please try again"}),he(!0),fe(Te.IDLE);return;default:H({title:"Something went wrong",description:"please try again"}),he(!0),fe(Te.IDLE);return}}),k(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async I=>{const A=I;A?.data?.text&&(d(K=>[...K,{id:Date.now().toString(),content:A.data.text||"",role:we.USER,timestamp:tn(Date.now()),isStored:!0}]),fe(Te.IDLE)),et(!1),Ne(!1),Oe(null)}),k(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,I=>{P.current=!0;const A=I;A.data?.text&&(Ne(!1),Oe(A.data.text))}),k(M.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_CALL,un),k(M.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_PROGRESS,un),k(M.SYNAPSE_REALTIME_EVENTS.CLIENT_TOOL_RESULT,un),k(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,I=>{P.current=!0;const A=I;if(A.data?.name&&A.messageId){const K=A.messageId;d(oe=>{const ae=oe[oe.length-1];if(ae&&ae.id===K&&ae.role===we.ASSISTANT){const ie=[...oe];ie[ie.length-1]={...ae,toolCallStatus:`Calling tool: ${A.data.name}...`};const be=V.getState().sessionId;return be&&ye(be,K,{toolCallStatus:`Calling tool: ${A.data.name}...`}),ie}return oe})}}),k(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,I=>{P.current=!0;const A=I;if(A.data?.name&&A.messageId){const K=A.messageId;d(oe=>{const ae=oe[oe.length-1];if(ae&&ae.id===K&&ae.role===we.ASSISTANT){const ie=[...oe];ie[ie.length-1]={...ae,toolCallStatus:"Tool call completed."};const be=V.getState().sessionId;return be&&ye(be,K,{toolCallStatus:"Tool call completed."}),ie}return oe})}})},Ut=async({message:C,files:k,audio:I,toolCalled:A,selectedComponent:K,resend:oe,tool_declined:ae,tool_result:ie,tool_key:be})=>{const Ye=V.getState().elicitationState,De=Object.values(Ye).some(Re=>Re.active);if(!(!A&&(!k||k.length===0)&&!C?.trim()&&!I?.audio&&!K&&!De&&!ie&&!Object.keys(ie||{}).length)){if(k&&k.length>0){const Re=Vc(k);if(Re){H(Re);return}}if(k&&k.length>0&&k.length+le>ls){const Re=ls-le;H({title:`You can only upload up to ${ls} files per session`,description:`${Re<=0?"Maximum file upload limit reached":`You have ${Re} file${Re===1?"":"s"} upload${Re===1?"":"s"} left`}`});return}else k&&k.length&&Xe(le+k.length);H(null),he(!1),Ge()&&re(Se.CONNECTED);try{const Re=l.length<=2&&_.current.length==1?_.current:null;let rt=null,Rt=null;const kt=l.length-1,lt=kt>=0?l[kt]:null,pn=V.getState().elicitationState,ot=be||null,Q=ot?pn[ot]:void 0,ct=Q?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||Q?.component===M.SYNAPSE_COMPONENTS.CARD?!!Q&&!ie&&!!Q.active:!!Q?.active,We=!!(k||[]).length||!!I?.audio||!!ae||!ct||!A,mt=K?K.label:void 0,ft=Q?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof mt=="string"?mt:null;if(!We&&ct&&ot&&Q?.messageId){const L=Q.toolSelectionNames?.length?Q.toolSelectionNames:Q.required?.filter(Ae=>!Q.server_input?.[Ae])??[],ge=L.reduce((Ae,Ce)=>{if(K){const jn=K[Ce];jn!==void 0&&(Ae[Ce]=jn)}else L.length===1&&(Ae[Ce]=C);return Ae},{}),ke=Q.mcp_meta_fields?.reduce((Ae,Ce)=>(L.includes(Ce)?Ae[Ce]=ge[Ce]:Q.server_input?.[Ce]&&(Ae[Ce]=Q.server_input[Ce]),oe&&!Ae.is_resend&&(Ae.is_resend=oe),Ae),{}),yt=Object.keys(Q.server_input||{})?.reduce((Ae,Ce)=>{const jn=!Object.keys(ke||{})?.includes(Ce),Ds=!!Q.server_input?.[Ce];return(oe?jn&&Ds:jn&&Q.required?.includes(Ce)&&Ds)&&(Ae[Ce]=Q.server_input?.[Ce]),Ae},{}),Fn=oe?{}:(Q.required||L).reduce((Ae,Ce)=>(Object.keys(ke||{}).includes(Ce)||(ge[Ce]!==void 0?Ae[Ce]=ge[Ce]:K&&K[Ce]!==void 0&&(Ae[Ce]=K[Ce])),Ae),{}),Vn={...yt||{},...Fn,...Object.keys(ke||{}).length&&{mcp_meta_fields:ke}};if(!Object.keys(Vn).length)return;await $e(ot,{...Q,server_input:{...Q.server_input||{},...Vn}});try{await Pr(Q.tool_id,Q.messageId,Vn),rt=!0}catch(Ae){await b.current?.sendMessage({tool_result:{...Q.tool_result,error:`Tool call failed: ${sn(Ae)}`}}),Rt="Tool call failed",$e(ot,{...Q,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${sn(Ae)}`}})}}else{const L=lt?.id,ge=L?Object.entries(Ye).filter(([yt,Fn])=>{const[Vn]=yt.split("::");return Vn===L&&Fn.active}):[],ke=ie??Q?.tool_result;await b.current?.sendMessage({message:C??"",files:k,audio:I,...Re&&{initial_prompts:Re},...ae||ge.length>0?{tool_declined:!0,tool_id:Q?.tool_id||""}:{},...ke&&{tool_result:ke}})}(C||k&&k.length>0||I?.audio||ft||Rt)&&(rt||xr(),d(L=>{if(rt)return L;const ge=L.length===0&&me?.text?[{id:jc,content:me.text,role:we.ASSISTANT,timestamp:tn(Date.now()),isStored:!1}]:[];return[...L,...ge,{id:Date.now().toString(),content:ft||Rt||C||"",files:k||[],audio:I,role:we.USER,timestamp:tn(Date.now()),isStored:!1}]}),rt||Ne(!0),rt=null);const Vt=V.getState().elicitationState,At=new Set;ot&&At.add(ot),lt?.tool_keys?.forEach(L=>At.add(L)),At.forEach(L=>{const ge=Vt[L];ge&&$e(L,{...ge,...We&&{active:!1,disabled:!0},...L===ot?{response_value:{...ge?.response_value||{},label:ft||C||""}}:{}})})}catch{}}},Ar=C=>C.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(C.type)?(H({title:`File type not supported: ${C.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):C.size>3*1024*1024?(H({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,Ir=async()=>{try{await b.current?.startRecording({onChunks:async C=>{fe(Te.PROCESSING),await Ut({audio:C}),fe(Te.TRANSCRIBING)},onError(C){fe(Te.IDLE)}}),fe(Te.LISTENING)}catch(C){throw fe(Te.IDLE),C}},Mr=()=>{b.current?.endRecording()},Pr=async(C,k,I)=>{try{if(!Ge())throw new Error("Not connected to the server");await b.current?.callTool(C,k,I)}catch(A){throw A}},hn=async()=>{St(),await Me(),await nt({forceNewSession:!0})},Ft=async()=>{await nt({forceNewSession:!0})},qt=()=>{Dt(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),re(Se.NOT_CONNECTED),H({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},Un=async()=>{if(Ge()){re(Se.CONNECTED);const C=p.current[p.current.length-1];if(C&&C.role===we.USER)try{b.current?.sendMessage({message:C.content,files:C.files||[],messageId:C.id,audio:C.audio})}catch{}}else if(re(Se.NOT_CONNECTED),w.current<2){w.current++;const{sessionId:C}=V.getState();await Le(C)}else w.current===2?(w.current++,he(!0),H({title:"Trying to connect..."})):(H({title:"Something went wrong!",description:"Please start a new chat."}),q(!0))};return{sendMessage:Ut,startSession:nt,incomingMessages:l,loading:h,isLoadingSessionMessages:m,endSession:Kt,isReady:u,startRecording:Ir,stopRecording:Mr,getPastSessions:async()=>{try{const C=await b.current?.getPastSessions();return!C||!C?.data?.length?[]:C.data}catch{return[]}},handleRetry:Un,isValidFile:Ar,handleStartNewConnection:hn,startNewChat:Ft,callTool:Pr,handleInitialTaskClick:async C=>{const{message:k}=C;if(!me?.suggestions?.length||!k)return;const I=me.suggestions.find(K=>K.value===k);if(_.current=[{role:"assistant",text:`${me.text} ${I?.response||""}`}],!I||!I.response){await Ut(C);return}xr(),d(K=>[...K,{id:Date.now().toString(),content:k,role:we.USER,timestamp:tn(Date.now()),isStored:!1}]),Ne(!0),await Rh(1e3),Ne(!1);const A=Date.now().toString();Or(A),d(K=>[...K,{id:A,content:I.response||"Please try again",role:we.ASSISTANT,timestamp:tn(Date.now()),isStored:!1}])},sendMessageFeedback:async(C,k,I)=>{if(Ge())try{await b.current?.sendMessageFeedback(k,C,I)}catch{}},sendSessionFeedback:async(C,k)=>{if(!(!Ge()||!C?.length&&!k))try{await b.current?.sendSessionFeedback(C,k)}catch{}},clearElicitationState:async(C,k)=>{const I=V.getState().elicitationState,A=C?I[C]:void 0;try{await Ut({message:k||"User aborted elicitation",tool_declined:!0,tool_result:A?.tool_result,tool_key:C})}catch{}finally{C&&A&&$e(C,{...A,active:!1,disabled:!0})}},markWidgetOpened:fo}};function Be(e){const t=X(e);return j(()=>{t.current=e}),pe(((...n)=>t.current(...n)),[])}function sf(e){return e==="full"?M.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?M.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":M.SYNAPSE_CHANNELS?.WIDGET??"widget"}const af=32,lf=100,cf=320;function df(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function uf({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=U(!1),l=X(null),d=X(!1),p=X("auto"),h=X(!0),f=pe(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),m=pe(w=>df()?"auto":w,[]),E=pe(w=>{const u=f();u&&(u.scrollTo({top:u.scrollHeight,behavior:m(w)}),a(!1))},[f,m]),S=pe(w=>{d.current=!0,p.current=w,l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,d.current&&(d.current=!1,E(p.current))}))},[E]);return j(()=>()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),d.current=!1},[]),j(()=>{e&&S(t||n?"auto":"smooth")},[e,t,n,S]),j(()=>{if(!e||!h.current)return;const w=setTimeout(()=>S("auto"),cf);return()=>clearTimeout(w)},[r,e,S]),j(()=>{let w=!1,u=null,g=null,_=0;const b=()=>{if(w)return;const N=f(),T=i.current?.parentElement;if(!N||!T){requestAnimationFrame(b);return}const O=()=>{const{scrollTop:x,scrollHeight:P,clientHeight:G}=N;return P-x-G<=af};h.current=!0;let y=0;const v=()=>{if(y>0){y--;return}h.current=O()};N.addEventListener("scroll",v,{passive:!0}),g=()=>N.removeEventListener("scroll",v),u=new ResizeObserver(()=>{if(!h.current)return;const x=Date.now();x-_<lf||(_=x,y++,S("auto"))}),u.observe(T)};return b(),()=>{w=!0,u?.disconnect(),g?.()}},[f,S]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:E,scheduleScrollToBottom:S}}const hf=["Type a reply\u2026","Ask me anything\u2026","Tell me what's on your mind\u2026","Short messages are fine\u2026","You can type in any language\u2026","Not sure what to ask? Just say hi\u2026"],pf=3500;function mf(e,t=hf){if(t.length===0)return"";const n=(e%t.length+t.length)%t.length;return t[n]}const ws="eka-medassist-agent-config",zc="feedback_hidden",Ts="upfront_consent_accepted",ff=4e3;function Ns(e,t){try{const n=localStorage.getItem(ws);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function $c(e,t){try{const n=localStorage.getItem(ws),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(ws,JSON.stringify(r))}catch{}}function gf({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:l}=kp(),d=Be(()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()}),p=r!==M.VOICE_AGENT_STATE.IDLE,[h,f]=U(""),[m,E]=U(!1),[S,w]=U(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),u=pe(()=>w(L=>L==="full"?"widget":"full"),[]),g=bc()?"mobile":S,_=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),b=Math.min(Math.max(n.sidePanelWidth??Ip,Mp),Pp),N=n.sidePanelMode??"push",[T,O]=U([]),y=X(!1),[v,x]=U(!1),[P,G]=U(!1),[W,ne]=U(()=>!!n.theme?.upfrontConsent&&!Ns(t,Ts)),de=X(null),ue=V(L=>L.startNewConnection),me=V(L=>L.showRetryButton),F=V(L=>L.clearError),le=V(L=>L.error),Ie=V(L=>L.connectionStatus),te=V(L=>L.recordingStatus),Z=V(L=>L.isWaitingForResponse),$=V(L=>L.isStreaming),H=V(L=>L.setError),re=V(L=>L.sessionId),he=V(L=>L.initialMessage),q=V(L=>L.sessionInitialMessages),et=V(L=>L.elicitationState),Ne=V(L=>L.level),{incomingMessages:Oe,isLoadingSessionMessages:fe,sendMessage:Me,handleInitialTaskClick:Dt,markWidgetOpened:Ct,startSession:z,startNewChat:Fe,isReady:ye,startRecording:Pe,stopRecording:Xe,handleRetry:tt,isValidFile:$e,sendMessageFeedback:pt,clearElicitationState:Ve,sendSessionFeedback:xt,getPastSessions:Le}=of({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:sf(n.displayMode),...n.tools&&{tools:n.tools}}),Je=Be(tt),nt=Be(pt),Ge=Be(Ve),Kt=Be(L=>{z({sessionId:L})}),St=Be(()=>{Fe()}),[cn,Ln]=U(!1),[Nr,Dn]=U([]),[po,Ot]=U(!0),Cr=X(Le);j(()=>{Cr.current=Le});const dn=pe(async()=>{Ot(!0);try{const L=await Cr.current();Dn(L)}catch{}finally{Ot(!1)}},[]),xr=pe(async()=>{Ln(!0),await dn()},[dn]),mo=pe(()=>{Ln(!1)},[]),[fo,Or]=U(!1),Rr=pe(()=>Or(L=>!L),[]);j(()=>{g!=="full"||Ne!=="user"||dn()},[g,Ne,re,dn]),j(()=>{if(t){if(de.current!==t){const L=V.getState();wp(t),Cp(t),L.setAgentId(t),n.force&&L.clearSession(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(L.setDisplayMode(n.displayMode),L.setInitialDisplayMode(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&L.setContext(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&L.setInitialMessage(n.initialMessage),de.current=t}e&&ye&&!y.current&&(y.current=!0,z({forceNewSession:!1}))}},[e,ye,t]),j(()=>{e&&Ct()},[e]),j(()=>{um([wc])},[]),j(()=>()=>{s()},[]),j(()=>{!n.theme?.upfrontConsent||!t||Ns(t,Ts)||ne(!0)},[n.theme?.upfrontConsent,t]);const un=pe(()=>{$c(t,Ts),ne(!1)},[t]),kr=Be(()=>{n.feedback&&!Ns(t,zc)?G(!0):n.onClose()}),Ut=Be(async(L,ge)=>{await xt(L,ge),G(!1),n.onClose()}),Ar=Be(()=>{G(!1),n.onClose()}),Ir=Be(()=>{$c(t,zc),G(!1),n.onClose()}),Mr=pe(()=>{G(!1)},[]),Pr=Oe.length>0,hn=Oe.length===1,Ft=ce(()=>{const L=Oe[Oe.length-1],ge=L?.tool_keys?.[L.tool_keys.length-1];if(!ge)return null;const ke=et[ge];return ke?.active?{...ke,tool_key:ge}:null},[Oe,et]),qt=ce(()=>(re?q[re]:void 0)??he??n?.initialMessage??null,[re,q,he,n?.initialMessage]),Un=ce(()=>!!qt?.text||!!qt?.suggestions?.length,[qt]),C=ce(()=>Un&&Oe?.length===0&&!fe,[Oe,Un,fe]),k=ce(()=>Ft?Ft.component===M.SYNAPSE_COMPONENTS.MOBILE||Ft.component===M.SYNAPSE_COMPONENTS.OTP||Ft.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[Ft]),{scrollAreaRef:I,messagesEndRef:A,showScrollButton:K,scrollToBottom:oe}=uf({messageCount:Oe.length,isStreaming:$,isFirstMessage:hn,resolvedMode:g}),ae=Ie===Se.CONNECTED,ie=Z||$,be=!ie&&ae&&!le&&!p&&!m&&te===Te.IDLE&&!v&&h.trim().length===0,[Ye,De]=U(!1);j(()=>{if(!be){De(!1);return}const L=setTimeout(()=>De(!0),ff);return()=>clearTimeout(L)},[be]);const Re=ce(()=>te===Te.IDLE?null:te===Te.LISTENING?"Listening...":te===Te.PROCESSING?"Processing...":te===Te.TRANSCRIBING?"Transcribing...":null,[te]),[rt,Rt]=U(0);j(()=>{if(!be){Rt(0);return}const L=setInterval(()=>Rt(ge=>ge+1),pf);return()=>clearInterval(L)},[be]);const kt=Re&&te!==Te.IDLE?Re:Z||$?"Please wait for the response...":mf(rt),lt=Be(async(L,ge)=>{if(ie)return;const ke=ge?Dt:Me,yt=L?.message??h;T.length>0?(await ke({files:T,message:yt.trim()}),O([]),x(!1)):yt.trim()?await ke({...L,message:yt.trim()}):L?.resend?await ke(L):L&&await ke(L),f(""),E(!1),x(!1)}),pn=Be(L=>lt(L,C)),ot=Be(L=>lt(L,!0)),Q=Be(L=>{if(L&&L.length>0){const ge=L.filter(yt=>$e(yt));if(ge.length===0)return;const ke=Vc(ge,T.length);if(ke){H(ke);return}L=ge}O(ge=>(x((ge?.length??0)+(L?.length??0)>0),[...ge,...L]))}),ct=pe(L=>{O(ge=>{const ke=ge.filter((yt,Fn)=>Fn!==L);return x(ke.length>0),ke})},[]),We=Be(async()=>{if(m)await Xe(),E(!1);else{if(ie)return;try{await Pe(),E(!0)}catch{}}}),mt=Be(L=>{f(L)}),ft=ce(()=>({value:h,onChange:mt,onSend:lt,onFileChange:Q,onRemoveFile:ct,onRecording:We,isRecording:m,hasAttachment:v,attachmentFiles:T,isDisabled:ie,placeholder:kt,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:p,handleVoiceMode:d,showAttention:Ye}),[h,mt,lt,Q,ct,We,m,v,T,ie,kt,te,n.allowed,p,d,Ye]),Vt=ce(()=>n.feedback?{isOpen:P,config:n.feedback,onSubmit:Ut,onSkip:Ar,onClose:Mr,onDontShowAgain:Ir}:void 0,[n.feedback,P,Ut,Ar,Mr,Ir]),At=ce(()=>n.theme?.upfrontConsent?{isOpen:W,onAccept:un}:void 0,[n.theme?.upfrontConsent,W,un]);return{showScrollButton:K,toggleDisplayMode:u,resolvedMode:g,sidePanelMode:N,sidePanelWidth:b,side:_,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:I,messagesEndRef:A,startNewConnection:ue,showRetryButton:me,clearError:F,error:le,sessionId:re,activeElicitation:Ft,inConversation:Pr,isFirstMessage:hn,isEmptyChat:C,isAuthComponent:k,isConnected:ae,isComposerDisabled:ie,isLoadingSessionMessages:fe,initialMessage:qt,incomingMessages:Oe,sendMessageFeedback:nt,clearElicitationState:Ge,handleRetry:Je,handleChatSendMessage:pn,handleEmptyStateSendMessage:ot,handleSelectSession:Kt,handleStartNewChat:St,scrollToBottom:oe,handleClose:kr,chatComposerProps:ft,feedbackModalProps:Vt,consentModalProps:At,isSessionDrawerOpen:cn,pastSessions:Nr,isLoadingPastSessions:po,openSessionDrawer:xr,closeSessionDrawer:mo,userLevel:Ne,isSidebarCollapsed:fo,toggleSidebar:Rr,voiceAgentState:r,isMuted:o,isVoiceAgentActive:p,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:l}}function Hc({bare:e}){return c("div",{className:"flex justify-start synapse-message-in",children:c(nn,{className:D("px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",e&&"!bg-transparent !shadow-none !px-0 !backdrop-blur-none"),children:c("div",{className:"flex items-center gap-1.5 h-5",role:"status","aria-label":"Bot is typing",children:[0,1,2].map(t=>c("span",{className:"synapse-typing-dot w-2 h-2 rounded-full bg-foreground",style:{animationDelay:`${t*160}ms`}},t))})})})}function an(){return an=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},an.apply(this,arguments)}const _f=["children","options"],Yc=["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"}),Bc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Ef=["style","script","pre"],Sf=["src","href","data","formAction","srcDoc","action"],yf=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,bf=/\n{2,}$/,Gc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,vf=/^ *> ?/gm,wf=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Tf=/^ {2,}\n/,Nf=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Wc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Kc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,Cf=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,xf=/^(?:\n *)*\n/,Of=/\r\n?/g,Rf=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,kf=/^\[\^([^\]]+)]/,Af=/\f/g,If=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,Mf=/^\s*?\[(x|\s)\]/,qc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Xc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Jc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,Cs=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,Pf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Zc=/^<!--[\s\S]*?(?:-->)/,Lf=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,xs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,Df=/^\{.*\}$/,Uf=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,Ff=/^<([^ >]+[:@\/][^ >]+)>/,Vf=/-([a-z])?/gi,Qc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,jf=/^[^\n]+(?: \n|\n{2,})/,zf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,$f=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Hf=/^\[([^\]]*)\] ?\[([^\]]*)\]/,Yf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Bf=/\t/g,Gf=/(^ *\||\| *$)/g,Wf=/^ *:-+: *$/,Kf=/^ *:-+ *$/,qf=/^ *-+: *$/,so=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,io="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Xf=RegExp(`^([*_])\\1${so(1)}${io}\\1\\1(?!\\1)`),Jf=RegExp(`^([*_])${so(0)}${io}\\1(?!\\1)`),Zf=RegExp(`^(==)${so(0)}${io}\\1`),Qf=RegExp(`^(~~)${so(0)}${io}\\1`),eg=/^(:[a-zA-Z0-9-_]+:)/,tg=/^\\([^0-9A-Za-z\s])/,ng=/\\([^0-9A-Za-z\s])/g,rg=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,og=/^\n+/,sg=/^([ \t]*)/,ig=/(?:^|\n)( *)$/,Os="(?:\\d+\\.)",Rs="(?:[*+-])";function ed(e){return"( *)("+(e===1?Os:Rs)+") +"}const td=ed(1),nd=ed(2);function rd(e){return RegExp("^"+(e===1?td:nd))}const ag=rd(1),lg=rd(2);function od(e){return RegExp("^"+(e===1?td:nd)+"[^\\n]*(?:\\n(?!\\1"+(e===1?Os:Rs)+" )[^\\n]*)*(\\n|$)","gm")}const cg=od(1),dg=od(2);function sd(e){const t=e===1?Os:Rs;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const id=sd(1),ad=sd(2);function ld(e,t){const n=t===1,r=n?id:ad,o=n?cg:dg,i=n?ag:lg;return{t:s=>i.test(s),o:Pn(function(s,a){const l=ig.exec(a.prevCapture);return l&&(a.list||!a.inline&&!a.simple)?r.exec(s=l[1]+s):null}),i:1,u(s,a,l){const d=n?+s[2]:void 0,p=s[0].replace(bf,`
|
|
41
|
-
`).match(o);let
|
|
40
|
+
`:"";return xe[xe.length-1]={...Te,content:Te.content+Je+oe},xe}else return[...We,{id:ce,content:oe,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]})}}),O(M.SYNAPSE_REALTIME_EVENTS.END_OF_STREAM,()=>{N.current=!1,K(!1),He(null),Ae(!1)}),O(M.SYNAPSE_REALTIME_EVENTS.CONNECTED,()=>{yt(),W(_e.CONNECTED),an()}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_CALL,D=>{N.current=!0;const A=D;if(!A?.messageId||!A?.data||!A?.data?.details?.component||!A?.data?.tool_id)return;j.getState().isWaitingForResponse&&Ae(!1);const{messageId:q,data:oe}=A,ce=oe.tool_id,ue=`${q}::${ce}`,Me=j.getState().elicitationState[ue],We=oe.details?.component,Te=A?.data?.details?._meta?.tool_result,xe=oe.details?.input,Je=xp(Me?.input,xe,We);let Ct=A.data.details?._meta?.disp_toast_msg;const kt=oe?.details?._meta?.schema?.required||[];switch(oe?.details?.status){case M.SYNAPSE_EICITATION_STATUS.PROGRESS:{const Z=A?.data?.details?.input||{},mt=kt.reduce((Rt,St)=>(Z[St]!==void 0&&(Rt[St]=Z[St]),Rt),{}),et={...Me?.server_input||{},...mt},pt=kt.filter(Rt=>!et[Rt]),lt=A.data.details?._meta?.mcp_meta_fields||[];Ue(ue,{tool_id:ce,active:!0,disabled:!1,input:Je,server_input:et,messageId:q,required:kt,component:We,pattern:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.pattern,minLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.minLength,maxLength:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.maxLength,type:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.type,disp_toast_msg:A.data.details?._meta?.disp_toast_msg,description:A.data.details?._meta?.schema?.properties?.[A.data.details?.component]?.description,tool_result:Te,orientation:A.data.details?._meta?.orientation,...lt.length&&{mcp_meta_fields:lt},...pt?{toolSelectionNames:pt}:{},...Me?.hide_show_more!==void 0?{hide_show_more:Me.hide_show_more}:{}});break}case M.SYNAPSE_EICITATION_STATUS.SUCCESS:{Ue(ue,{...Me||{},tool_id:ce,disabled:!0,active:oh(We),messageId:q,component:We,input:Je,tool_result:Te,send_to_llm:!0});break}case M.SYNAPSE_EICITATION_STATUS.FAILURE:{Ue(ue,{...Me||{},tool_id:ce,active:!1,messageId:q,response_value:{label:oe?.details?._meta?.disp_message||"Tool call failed"},tool_result:Te,disabled:!0});break}default:Ue(ue,{tool_id:ce,disabled:!1,active:!1,messageId:q,tool_result:Te,input:Je,component:We})}Ct&&qe(Ct);const Ot=A?.data?.details?._meta?.user_hint;l(Z=>{let mt=Z[Z.length-1]?.id===q?Z.length-1:Z.findIndex?.(et=>et.id===q);if(mt==-1){const et={id:q,content:A.data?.details?.input?.text||"",role:Ne.ASSISTANT,tool_keys:[ue],isResponseFromTool:!0,isStored:!1,...Ot?{userHint:Ot}:{}};return[...Z,et]}else{const et={...Z[mt],isResponseFromTool:!0,tool_keys:[...new Set([...Z[mt].tool_keys||[],ue])],...Ot?{userHint:Ot}:{}},pt=j.getState().sessionId;pt&&Ie(pt,q,et);const lt=[...Z];return lt[mt]=et,lt}});const Kt=A?.data?.details?._meta?.disp_message,Qe=j.getState().elicitationState;if((!Qe[ue]?.active||Qe[ue]?.send_to_llm)&&(Kt||Object.keys(Te||{}).length))try{Wt({message:Kt||"",tool_result:Te,toolCalled:!0,tool_key:ue})}catch{}}),O(M.SYNAPSE_REALTIME_EVENTS.DISCONNECTED,D=>{if(D?.reason===M.DisconnectionReason.CLIENT_CLOSED)return;const A=D;Lt(Cn.CONNECTION,A?.reason??"unknown",{...typeof A?.code=="number"&&{closeCode:A.code}}),T.current=performance.now();const q=typeof navigator<"u"&&!navigator.onLine;if(W(_e.NOT_CONNECTED),q){I({title:"No internet connection",description:"Will reconnect automatically when internet is restored."}),re(!1);return}g.current<2?(g.current=g.current+1,re(!0),I({title:"Something went wrong!",description:"Please try again."})):(I({title:"Something went wrong!",description:"Please start a new Chat."}),ve(!0))}),O(M.SYNAPSE_REALTIME_EVENTS.ERROR,D=>{const A=D?.data?.code;switch(_r(A),A){case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_INACTIVE:ve(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_TOKEN_MISMATCH:I({title:"Session not found",description:"Please start a new chat from onError callback"}),ve(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SESSION_NOT_OWNED:cn();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++,In();return}I({title:"Error parsing request",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.TIMEOUT:I({title:"Request timed out",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.PROMPT_FETCH_ERROR:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.INVALID_FILE_REQUEST:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;case M.SYNAPSE_REALTIME_ERROR_CODES.SERVER_ERROR:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return;default:I({title:"Something went wrong",description:"please try again"}),re(!0),ae(be.IDLE);return}}),O(M.SYNAPSE_REALTIME_EVENTS.AUDIO_TRANSCRIPT,async D=>{const A=D;A?.data?.text&&(l(q=>[...q,{id:Date.now().toString(),content:A.data.text||"",role:Ne.USER,timestamp:Qt(Date.now()),isStored:!0}]),ae(be.IDLE)),K(!1),Ae(!1),He(null)}),O(M.SYNAPSE_REALTIME_EVENTS.PROGRESS_MESSAGE,D=>{N.current=!0;const A=D;A.data?.text&&(Ae(!1),He(A.data.text))}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_START,D=>{N.current=!0;const A=D;if(A.data?.name&&A.messageId){const q=A.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:`Calling tool: ${A.data.name}...`};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:`Calling tool: ${A.data.name}...`}),ue}return oe})}}),O(M.SYNAPSE_REALTIME_EVENTS.TOOL_END,D=>{N.current=!0;const A=D;if(A.data?.name&&A.messageId){const q=A.messageId;l(oe=>{const ce=oe[oe.length-1];if(ce&&ce.id===q&&ce.role===Ne.ASSISTANT){const ue=[...oe];ue[ue.length-1]={...ce,toolCallStatus:"Tool call completed."};const Me=j.getState().sessionId;return Me&&Ie(Me,q,{toolCallStatus:"Tool call completed."}),ue}return oe})}})},Wt=async({message:w,files:O,audio:D,toolCalled:A,selectedComponent:q,resend:oe,tool_declined:ce,tool_result:ue,tool_key:Me})=>{const We=j.getState().elicitationState,Te=Object.values(We).some(xe=>xe.active);if(!(!A&&(!O||O.length===0)&&!w?.trim()&&!D?.audio&&!q&&!Te&&!ue&&!Object.keys(ue||{}).length)){if(O&&O.length>0){const xe=gc(O);if(xe){I(xe);return}}if(O&&O.length>0&&O.length+V>Zo){const xe=Zo-V;I({title:`You can only upload up to ${Zo} files per session`,description:`${xe<=0?"Maximum file upload limit reached":`You have ${xe} file${xe===1?"":"s"} upload${xe===1?"":"s"} left`}`});return}else O&&O.length&&Le(V+O.length);I(null),re(!1),Oe()&&W(_e.CONNECTED);try{const xe=a.length<=2&&E.current.length==1?E.current:null;let Je=null,Ct=null;const kt=a.length-1,Ot=kt>=0?a[kt]:null,Kt=j.getState().elicitationState,Qe=Me||null,Z=Qe?Kt[Qe]:void 0,mt=Z?.component===M.SYNAPSE_COMPONENTS.DOCTOR_CARD||Z?.component===M.SYNAPSE_COMPONENTS.CARD?!!Z&&!ue&&!!Z.active:!!Z?.active,et=!!(O||[]).length||!!D?.audio||!!ce||!mt||!A,pt=q?q.label:void 0,lt=Z?.component===M.SYNAPSE_COMPONENTS.PILL&&typeof pt=="string"?pt:null;if(!et&&mt&&Qe&&Z?.messageId){const Fe=Z.toolSelectionNames?.length?Z.toolSelectionNames:Z.required?.filter(fe=>!Z.server_input?.[fe])??[],ot=Fe.reduce((fe,ye)=>{if(q){const Mn=q[ye];Mn!==void 0&&(fe[ye]=Mn)}else Fe.length===1&&(fe[ye]=w);return fe},{}),At=Z.mcp_meta_fields?.reduce((fe,ye)=>(Fe.includes(ye)?fe[ye]=ot[ye]:Z.server_input?.[ye]&&(fe[ye]=Z.server_input[ye]),oe&&!fe.is_resend&&(fe.is_resend=oe),fe),{}),U=Object.keys(Z.server_input||{})?.reduce((fe,ye)=>{const Mn=!Object.keys(At||{})?.includes(ye),Ns=!!Z.server_input?.[ye];return(oe?Mn&&Ns:Mn&&Z.required?.includes(ye)&&Ns)&&(fe[ye]=Z.server_input?.[ye]),fe},{}),ke=oe?{}:(Z.required||Fe).reduce((fe,ye)=>(Object.keys(At||{}).includes(ye)||(ot[ye]!==void 0?fe[ye]=ot[ye]:q&&q[ye]!==void 0&&(fe[ye]=q[ye])),fe),{}),Ve={...U||{},...ke,...Object.keys(At||{}).length&&{mcp_meta_fields:At}};if(!Object.keys(Ve).length)return;await Ue(Qe,{...Z,server_input:{...Z.server_input||{},...Ve}});try{await An(Z.tool_id,Z.messageId,Ve),Je=!0}catch(fe){await y.current?.sendMessage({tool_result:{...Z.tool_result,error:`Tool call failed: ${rn(fe)}`}}),Ct="Tool call failed",Ue(Qe,{...Z,active:!1,disabled:!0,response_value:{label:`Tool call failed: ${rn(fe)}`}})}}else{const Fe=Ot?.id,ot=Fe?Object.entries(We).filter(([U,ke])=>{const[Ve]=U.split("::");return Ve===Fe&&ke.active}):[],At=ue??Z?.tool_result;await y.current?.sendMessage({message:w??"",files:O,audio:D,...xe&&{initial_prompts:xe},...ce||ot.length>0?{tool_declined:!0,tool_id:Z?.tool_id||""}:{},...At&&{tool_result:At}})}(w||O&&O.length>0||D?.audio||lt||Ct)&&(Je||Gt(),l(Fe=>{if(Je)return Fe;const ot=Fe.length===0&&se?.text?[{id:_c,content:se.text,role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}]:[];return[...Fe,...ot,{id:Date.now().toString(),content:lt||Ct||w||"",files:O||[],audio:D,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]}),Je||Ae(!0),Je=null);const Rt=j.getState().elicitationState,St=new Set;Qe&&St.add(Qe),Ot?.tool_keys?.forEach(Fe=>St.add(Fe)),St.forEach(Fe=>{const ot=Rt[Fe];ot&&Ue(Fe,{...ot,...et&&{active:!1,disabled:!0},...Fe===Qe?{response_value:{...ot?.response_value||{},label:lt||w||""}}:{}})})}catch{}}},Sr=w=>w.type.toLowerCase()&&!["application/pdf","image/jpeg","image/jpg","image/png"].includes(w.type)?(I({title:`File type not supported: ${w.name}`,description:"Only PDF, images (JPG, JPEG, PNG) are allowed."}),!1):w.size>3*1024*1024?(I({title:"File size limit of 3MB exceeded",description:"Please reduce the size of the file or try again with a smaller file"}),!1):!0,no=async()=>{try{await y.current?.startRecording({onChunks:async w=>{ae(be.PROCESSING),await Wt({audio:w}),ae(be.TRANSCRIBING)},onError(w){ae(be.IDLE)}}),ae(be.LISTENING)}catch(w){throw ae(be.IDLE),w}},br=()=>{y.current?.endRecording()},An=async(w,O,D)=>{try{if(!Oe())throw new Error("Not connected to the server");await y.current?.callTool(w,O,D)}catch(A){throw A}},cn=async()=>{yt(),await Pe(),await Ge({forceNewSession:!0})},vr=async()=>{await Ge({forceNewSession:!0})},wr=()=>{De(),window.postMessage({type:"AUTH_EXPIRED",message:"Authentication expired"},"*"),W(_e.NOT_CONNECTED),I({title:"Session expired",description:"Your session has expired. Please reload the page to continue."})},In=async()=>{if(Oe()){W(_e.CONNECTED);const w=d.current[d.current.length-1];if(w&&w.role===Ne.USER)try{y.current?.sendMessage({message:w.content,files:w.files||[],messageId:w.id,audio:w.audio})}catch{}}else if(W(_e.NOT_CONNECTED),g.current<2){g.current++;const{sessionId:w}=j.getState();await rt(w)}else g.current===2?(g.current++,re(!0),I({title:"Trying to connect..."})):(I({title:"Something went wrong!",description:"Please start a new chat."}),ve(!0))};return{sendMessage:Wt,startSession:Ge,incomingMessages:a,loading:h,isLoadingSessionMessages:p,endSession:Bt,isReady:b,startRecording:no,stopRecording:br,getPastSessions:async()=>{try{const w=await y.current?.getPastSessions();return!w||!w?.data?.length?[]:w.data}catch{return[]}},handleRetry:In,isValidFile:Sr,handleStartNewConnection:cn,startNewChat:vr,callTool:An,handleInitialTaskClick:async w=>{const{message:O}=w;if(!se?.suggestions?.length||!O)return;const D=se.suggestions.find(q=>q.value===O);if(E.current=[{role:"assistant",text:`${se.text} ${D?.response||""}`}],!D||!D.response){await Wt(w);return}Gt(),l(q=>[...q,{id:Date.now().toString(),content:O,role:Ne.USER,timestamp:Qt(Date.now()),isStored:!1}]),Ae(!0),await sh(1e3),Ae(!1);const A=Date.now().toString();Er(A),l(q=>[...q,{id:A,content:D.response||"Please try again",role:Ne.ASSISTANT,timestamp:Qt(Date.now()),isStored:!1}])},sendMessageFeedback:async(w,O,D)=>{if(Oe())try{await y.current?.sendMessageFeedback(O,w,D)}catch{}},sendSessionFeedback:async(w,O)=>{if(!(!Oe()||!w?.length&&!O))try{await y.current?.sendSessionFeedback(w,O)}catch{}},clearElicitationState:async(w,O)=>{const D=j.getState().elicitationState,A=w?D[w]:void 0;try{await Wt({message:O||"User aborted elicitation",tool_declined:!0,tool_result:A?.tool_result,tool_key:w})}catch{}finally{w&&A&&Ue(w,{...A,active:!1,disabled:!0})}},markWidgetOpened:to}};function Ke(e){const t=X(e);return Y(()=>{t.current=e}),de(((...n)=>t.current(...n)),[])}function Pp(e){return e==="full"?M.SYNAPSE_CHANNELS?.WEB??"web":e==="side_panel"?M.SYNAPSE_CHANNELS?.SIDE_PANEL??"side_panel":M.SYNAPSE_CHANNELS?.WIDGET??"widget"}const Dp=32,Lp=100,Up=320;function Fp(){return typeof window>"u"||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Vp({messageCount:e,isStreaming:t,isFirstMessage:n,resolvedMode:r}){const o=X(null),i=X(null),[s,a]=F(!1),l=X(null),d=X(!1),h=X("auto"),u=X(!0),p=de(()=>o.current?.querySelector("[data-radix-scroll-area-viewport]")||null,[]),_=de(b=>Fp()?"auto":b,[]),f=de(b=>{const m=p();m&&(m.scrollTo({top:m.scrollHeight,behavior:_(b)}),a(!1))},[p,_]),g=de(b=>{d.current=!0,h.current=b,l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null,d.current&&(d.current=!1,f(h.current))}))},[f]);return Y(()=>()=>{l.current!==null&&(cancelAnimationFrame(l.current),l.current=null),d.current=!1},[]),Y(()=>{e&&g(t||n?"auto":"smooth")},[e,t,n,g]),Y(()=>{if(!e||!u.current)return;const b=setTimeout(()=>g("auto"),Up);return()=>clearTimeout(b)},[r,e,g]),Y(()=>{let b=!1,m=null,E=null,y=0;const k=()=>{if(b)return;const x=p(),T=i.current?.parentElement;if(!x||!T){requestAnimationFrame(k);return}const C=()=>{const{scrollTop:N,scrollHeight:P,clientHeight:B}=x;return P-N-B<=Dp};u.current=!0;let S=0;const v=()=>{if(S>0){S--;return}u.current=C()};x.addEventListener("scroll",v,{passive:!0}),E=()=>x.removeEventListener("scroll",v),m=new ResizeObserver(()=>{if(!u.current)return;const N=Date.now();N-y<Lp||(y=N,S++,g("auto"))}),m.observe(T)};return k(),()=>{b=!0,m?.disconnect(),E?.()}},[p,g]),{scrollAreaRef:o,messagesEndRef:i,showScrollButton:s,scrollToBottom:f,scheduleScrollToBottom:g}}const jp=["Type a reply\u2026","Ask me anything\u2026","Tell me what's on your mind\u2026","Short messages are fine\u2026","You can type in any language\u2026","Not sure what to ask? Just say hi\u2026"],zp=3500;function Yp(e,t=jp){if(t.length===0)return"";const n=(e%t.length+t.length)%t.length;return t[n]}const us="eka-medassist-agent-config",Ec="feedback_hidden",hs="upfront_consent_accepted",Hp=4e3;function ms(e,t){try{const n=localStorage.getItem(us);return(n?JSON.parse(n):{})[e]?.[t]===!0}catch{return!1}}function yc(e,t){try{const n=localStorage.getItem(us),r=n?JSON.parse(n):{};r[e]||(r[e]={}),r[e][t]=!0,localStorage.setItem(us,JSON.stringify(r))}catch{}}function $p({isOpen:e,agentId:t,config:n}){const{state:r,isMuted:o,connect:i,disconnect:s,reset:a,toggleMute:l}=im(),d=Ke(()=>{r===M.VOICE_AGENT_STATE.IDLE&&i()}),h=r!==M.VOICE_AGENT_STATE.IDLE,[u,p]=F(""),[_,f]=F(!1),[g,b]=F(n.displayMode==="full"?"full":n.displayMode==="side_panel"?"side_panel":"widget"),m=de(()=>b(U=>U==="full"?"widget":"full"),[]),E=Ql()?"mobile":g,y=n.side??(typeof document<"u"&&document.dir==="rtl"?"left":"right"),k=Math.min(Math.max(n.sidePanelWidth??lm,cm),dm),x=n.sidePanelMode??"push",[T,C]=F([]),S=X(!1),[v,N]=F(!1),[P,B]=F(!1),[G,he]=F(()=>!!n.theme?.upfrontConsent&&!ms(t,hs)),pe=X(null),se=j(U=>U.startNewConnection),Ee=j(U=>U.showRetryButton),V=j(U=>U.clearError),le=j(U=>U.error),Re=j(U=>U.connectionStatus),te=j(U=>U.recordingStatus),Q=j(U=>U.isWaitingForResponse),I=j(U=>U.isStreaming),W=j(U=>U.setError),re=j(U=>U.sessionId),ve=j(U=>U.initialMessage),K=j(U=>U.sessionInitialMessages),Ae=j(U=>U.elicitationState),He=j(U=>U.level),{incomingMessages:ae,isLoadingSessionMessages:Pe,sendMessage:De,handleInitialTaskClick:xt,markWidgetOpened:$t,startSession:z,startNewChat:Ie,isReady:we,startRecording:Le,stopRecording:qe,handleRetry:Ue,isValidFile:Et,sendMessageFeedback:ht,clearElicitationState:ze,sendSessionFeedback:rt,getPastSessions:Be}=Mp({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:Pp(n.displayMode)}),Ge=Ke(Ue),Oe=Ke(ht),Bt=Ke(ze),yt=Ke(U=>{z({sessionId:U})}),an=Ke(()=>{Ie()}),[ln,On]=F(!1),[Rn,Qr]=F([]),[Lt,gr]=F(!0),_r=X(Be);Y(()=>{_r.current=Be});const Gt=de(async()=>{gr(!0);try{const U=await _r.current();Qr(U)}catch{}finally{gr(!1)}},[]),eo=de(async()=>{On(!0),await Gt()},[Gt]),to=de(()=>{On(!1)},[]),[Er,yr]=F(!1),Wt=de(()=>yr(U=>!U),[]);Y(()=>{E!=="full"||He!=="user"||Gt()},[E,He,re,Gt]),Y(()=>{if(t){if(pe.current!==t){const U=j.getState();Qh(t),nm(t),U.setAgentId(t),n.force&&U.clearSession(),(n.displayMode==="full"||n.displayMode==="widget"||n.displayMode==="side_panel")&&(U.setDisplayMode(n.displayMode),U.setInitialDisplayMode(n.displayMode)),n?.context&&Object.keys(n?.context||{}).length&&U.setContext(n.context),(n?.initialMessage?.text||n?.initialMessage?.suggestions?.length)&&U.setInitialMessage(n.initialMessage),pe.current=t}e&&we&&!S.current&&(S.current=!0,z({forceNewSession:!1}))}},[e,we,t]),Y(()=>{e&&$t()},[e]),Y(()=>{zm([tc])},[]),Y(()=>()=>{s()},[]),Y(()=>{!n.theme?.upfrontConsent||!t||ms(t,hs)||he(!0)},[n.theme?.upfrontConsent,t]);const Sr=de(()=>{yc(t,hs),he(!1)},[t]),no=Ke(()=>{n.feedback&&!ms(t,Ec)?B(!0):n.onClose()}),br=Ke(async(U,ke)=>{await rt(U,ke),B(!1),n.onClose()}),An=Ke(()=>{B(!1),n.onClose()}),cn=Ke(()=>{yc(t,Ec),B(!1),n.onClose()}),vr=de(()=>{B(!1)},[]),wr=ae.length>0,In=ae.length===1,w=ie(()=>{const U=ae[ae.length-1],ke=U?.tool_keys?.[U.tool_keys.length-1];if(!ke)return null;const Ve=Ae[ke];return Ve?.active?{...Ve,tool_key:ke}:null},[ae,Ae]),O=ie(()=>(re?K[re]:void 0)??ve??n?.initialMessage??null,[re,K,ve,n?.initialMessage]),D=ie(()=>!!O?.text||!!O?.suggestions?.length,[O]),A=ie(()=>D&&ae?.length===0&&!Pe,[ae,D,Pe]),q=ie(()=>w?w.component===M.SYNAPSE_COMPONENTS.MOBILE||w.component===M.SYNAPSE_COMPONENTS.OTP||w.component===M.SYNAPSE_COMPONENTS.EMAIL:!1,[w]),{scrollAreaRef:oe,messagesEndRef:ce,showScrollButton:ue,scrollToBottom:Me}=Vp({messageCount:ae.length,isStreaming:I,isFirstMessage:In,resolvedMode:E}),We=Re===_e.CONNECTED,Te=Q||I,xe=!Te&&We&&!le&&!h&&!_&&te===be.IDLE&&!v&&u.trim().length===0,[Je,Ct]=F(!1);Y(()=>{if(!xe){Ct(!1);return}const U=setTimeout(()=>Ct(!0),Hp);return()=>clearTimeout(U)},[xe]);const kt=ie(()=>te===be.IDLE?null:te===be.LISTENING?"Listening...":te===be.PROCESSING?"Processing...":te===be.TRANSCRIBING?"Transcribing...":null,[te]),[Ot,Kt]=F(0);Y(()=>{if(!xe){Kt(0);return}const U=setInterval(()=>Kt(ke=>ke+1),zp);return()=>clearInterval(U)},[xe]);const Qe=kt&&te!==be.IDLE?kt:Q||I?"Please wait for the response...":Yp(Ot),Z=Ke(async(U,ke)=>{if(Te)return;const Ve=ke?xt:De,fe=U?.message??u;T.length>0?(await Ve({files:T,message:fe.trim()}),C([]),N(!1)):fe.trim()?await Ve({...U,message:fe.trim()}):U?.resend?await Ve(U):U&&await Ve(U),p(""),f(!1),N(!1)}),mt=Ke(U=>Z(U,A)),et=Ke(U=>Z(U,!0)),pt=Ke(U=>{if(U&&U.length>0){const ke=U.filter(fe=>Et(fe));if(ke.length===0)return;const Ve=gc(ke,T.length);if(Ve){W(Ve);return}U=ke}C(ke=>(N((ke?.length??0)+(U?.length??0)>0),[...ke,...U]))}),lt=de(U=>{C(ke=>{const Ve=ke.filter((fe,ye)=>ye!==U);return N(Ve.length>0),Ve})},[]),Rt=Ke(async()=>{if(_)await qe(),f(!1);else{if(Te)return;try{await Le(),f(!0)}catch{}}}),St=Ke(U=>{p(U)}),Fe=ie(()=>({value:u,onChange:St,onSend:Z,onFileChange:pt,onRemoveFile:lt,onRecording:Rt,isRecording:_,hasAttachment:v,attachmentFiles:T,isDisabled:Te,placeholder:Qe,recordingStatus:te,allowed:n.allowed,isVoiceAgentActive:h,handleVoiceMode:d,showAttention:Je}),[u,St,Z,pt,lt,Rt,_,v,T,Te,Qe,te,n.allowed,h,d,Je]),ot=ie(()=>n.feedback?{isOpen:P,config:n.feedback,onSubmit:br,onSkip:An,onClose:vr,onDontShowAgain:cn}:void 0,[n.feedback,P,br,An,vr,cn]),At=ie(()=>n.theme?.upfrontConsent?{isOpen:G,onAccept:Sr}:void 0,[n.theme?.upfrontConsent,G,Sr]);return{showScrollButton:ue,toggleDisplayMode:m,resolvedMode:E,sidePanelMode:x,sidePanelWidth:k,side:y,onSidePanelPushChange:n.onSidePanelPushChange,scrollAreaRef:oe,messagesEndRef:ce,startNewConnection:se,showRetryButton:Ee,clearError:V,error:le,sessionId:re,activeElicitation:w,inConversation:wr,isFirstMessage:In,isEmptyChat:A,isAuthComponent:q,isConnected:We,isComposerDisabled:Te,isLoadingSessionMessages:Pe,initialMessage:O,incomingMessages:ae,sendMessageFeedback:Oe,clearElicitationState:Bt,handleRetry:Ge,handleChatSendMessage:mt,handleEmptyStateSendMessage:et,handleSelectSession:yt,handleStartNewChat:an,scrollToBottom:Me,handleClose:no,chatComposerProps:Fe,feedbackModalProps:ot,consentModalProps:At,isSessionDrawerOpen:ln,pastSessions:Rn,isLoadingPastSessions:Lt,openSessionDrawer:eo,closeSessionDrawer:to,userLevel:He,isSidebarCollapsed:Er,toggleSidebar:Wt,voiceAgentState:r,isMuted:o,isVoiceAgentActive:h,disconnectVoiceAgent:s,resetVoiceAgent:a,toggleMute:l}}function Sc({bare:e}){return c("div",{className:"flex justify-start synapse-message-in",children:c(en,{className:L("px-4 py-2 rounded-lg shadow-none bg-botMessage backdrop-blur-sm text-text-primary shadow-sm",e&&"!bg-transparent !shadow-none !px-0 !backdrop-blur-none"),children:c("div",{className:"flex items-center gap-1.5 h-5",role:"status","aria-label":"Bot is typing",children:[0,1,2].map(t=>c("span",{className:"synapse-typing-dot w-2 h-2 rounded-full bg-foreground",style:{animationDelay:`${t*160}ms`}},t))})})})}function on(){return on=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},on.apply(this,arguments)}const Bp=["children","options"],bc=["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"}),vc={amp:"&",apos:"'",gt:">",lt:"<",nbsp:"\xA0",quot:"\u201C"},Gp=["style","script","pre"],Wp=["src","href","data","formAction","srcDoc","action"],Kp=/([-A-Z0-9_:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|(?:\{((?:\\.|{[^}]*?}|[^}])*)\})))?/gi,qp=/\n{2,}$/,wc=/^(\s*>[\s\S]*?)(?=\n\n|$)/,Xp=/^ *> ?/gm,Zp=/^(?:\[!([^\]]*)\]\n)?([\s\S]*)/,Jp=/^ {2,}\n/,Qp=/^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/,Nc=/^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/,Tc=/^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/,ef=/^(`+)((?:\\`|(?!\1)`|[^`])+)\1/,tf=/^(?:\n *)*\n/,nf=/\r\n?/g,rf=/^\[\^([^\]]+)](:(.*)((\n+ {4,}.*)|(\n(?!\[\^).+))*)/,of=/^\[\^([^\]]+)]/,sf=/\f/g,af=/^---[ \t]*\n(.|\n)*\n---[ \t]*\n/,lf=/^\s*?\[(x|\s)\]/,xc=/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,Cc=/^ *(#{1,6}) +([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/,kc=/^([^\n]+)\n *(=|-)\2{2,} *\n/,ps=/^ *(?!<[a-z][^ >/]* ?\/>)<([a-z][^ >/]*) ?((?:[^>]*[^/])?)>\n?(\s*(?:<\1[^>]*?>[\s\S]*?<\/\1>|(?!<\1\b)[\s\S])*?)<\/\1>(?!<\/\1>)\n*/i,cf=/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi,Oc=/^<!--[\s\S]*?(?:-->)/,df=/^(data|aria|x)-[a-z_][a-z\d_.-]*$/,fs=/^ *<([a-z][a-z0-9:]*)(?:\s+((?:<.*?>|[^>])*))?\/?>(?!<\/\1>)(\s*\n)?/i,uf=/^\{.*\}$/,hf=/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,mf=/^<([^ >]+[:@\/][^ >]+)>/,pf=/-([a-z])?/gi,Rc=/^(\|.*)\n(?: *(\|? *[-:]+ *\|[-| :]*)\n((?:.*\|.*\n)*))?\n?/,ff=/^[^\n]+(?: \n|\n{2,})/,gf=/^\[([^\]]*)\]:\s+<?([^\s>]+)>?\s*("([^"]*)")?/,_f=/^!\[([^\]]*)\] ?\[([^\]]*)\]/,Ef=/^\[([^\]]*)\] ?\[([^\]]*)\]/,yf=/(\n|^[-*]\s|^#|^ {2,}|^-{2,}|^>\s)/,Sf=/\t/g,bf=/(^ *\||\| *$)/g,vf=/^ *:-+: *$/,wf=/^ *:-+ *$/,Nf=/^ *-+: *$/,Gr=e=>`(?=[\\s\\S]+?\\1${e?"\\1":""})`,Wr="((?:\\[.*?\\][([].*?[)\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\1|[\\s\\S])+?)",Tf=RegExp(`^([*_])\\1${Gr(1)}${Wr}\\1\\1(?!\\1)`),xf=RegExp(`^([*_])${Gr(0)}${Wr}\\1(?!\\1)`),Cf=RegExp(`^(==)${Gr(0)}${Wr}\\1`),kf=RegExp(`^(~~)${Gr(0)}${Wr}\\1`),Of=/^(:[a-zA-Z0-9-_]+:)/,Rf=/^\\([^0-9A-Za-z\s])/,Af=/\\([^0-9A-Za-z\s])/g,If=/^[\s\S](?:(?! \n|[0-9]\.|http)[^=*_~\-\n:<`\\\[!])*/,Mf=/^\n+/,Pf=/^([ \t]*)/,Df=/(?:^|\n)( *)$/,gs="(?:\\d+\\.)",_s="(?:[*+-])";function Ac(e){return"( *)("+(e===1?gs:_s)+") +"}const Ic=Ac(1),Mc=Ac(2);function Pc(e){return RegExp("^"+(e===1?Ic:Mc))}const Lf=Pc(1),Uf=Pc(2);function Dc(e){return RegExp("^"+(e===1?Ic:Mc)+"[^\\n]*(?:\\n(?!\\1"+(e===1?gs:_s)+" )[^\\n]*)*(\\n|$)","gm")}const Ff=Dc(1),Vf=Dc(2);function Lc(e){const t=e===1?gs:_s;return RegExp("^( *)("+t+") [\\s\\S]+?(?:\\n{2,}(?! )(?!\\1"+t+" (?!"+t+" ))\\n*|\\s*\\n*$)")}const Uc=Lc(1),Fc=Lc(2);function Vc(e,t){const n=t===1,r=n?Uc:Fc,o=n?Ff:Vf,i=n?Lf:Uf;return{t:s=>i.test(s),o:kn(function(s,a){const l=Df.exec(a.prevCapture);return l&&(a.list||!a.inline&&!a.simple)?r.exec(s=l[1]+s):null}),i:1,u(s,a,l){const d=n?+s[2]:void 0,h=s[0].replace(qp,`
|
|
41
|
+
`).match(o);let u=!1;return{items:h.map(function(p,_){const f=i.exec(p)[0].length,g=RegExp("^ {1,"+f+"}","gm"),b=p.replace(g,"").replace(i,""),m=_===h.length-1,E=b.indexOf(`
|
|
42
42
|
|
|
43
|
-
`)!==-1||u
|
|
43
|
+
`)!==-1||m&&u;u=E;const y=l.inline,k=l.list;let x;l.list=!0,E?(l.inline=!1,x=mr(b)+`
|
|
44
44
|
|
|
45
|
-
`):(l.inline=!0,
|
|
46
|
-
`).map(function(d){return
|
|
45
|
+
`):(l.inline=!0,x=mr(b));const T=a(x,l);return l.inline=y,l.list=k,T}),ordered:n,start:d}},l:(s,a,l)=>e(s.ordered?"ol":"ul",{key:l.key,start:s.type==="20"?s.start:void 0},s.items.map(function(d,h){return e("li",{key:h},a(d,l))}))}}const jf=RegExp(`^\\[((?:\\[[^\\[\\]]*(?:\\[[^\\[\\]]*\\][^\\[\\]]*)*\\]|[^\\[\\]])*)\\]\\(\\s*<?((?:\\([^)]*\\)|[^\\s\\\\]|\\\\.)*?)>?(?:\\s+['"]([\\s\\S]*?)['"])?\\s*\\)`),zf=/^!\[(.*?)\]\( *((?:\([^)]*\)|[^() ])*) *"?([^)"]*)?"?\)/;function jc(e){return typeof e=="string"}function mr(e){let t=e.length;for(;t>0&&e[t-1]<=" ";)t--;return e.slice(0,t)}function Kr(e,t){return e.startsWith(t)}function Yf(e,t,n){if(Array.isArray(n)){for(let r=0;r<n.length;r++)if(Kr(e,n[r]))return!0;return!1}return n(e,t)}function pr(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 Hf(e){return Nf.test(e)?"right":vf.test(e)?"center":wf.test(e)?"left":null}function zc(e,t,n,r){const o=n.inTable;n.inTable=!0;let i=[[]],s="";function a(){if(!s)return;const l=i[i.length-1];l.push.apply(l,t(s,n)),s=""}return e.trim().split(/(`[^`]*`|\\\||\|)/).filter(Boolean).forEach((l,d,h)=>{l.trim()==="|"&&(a(),r)?d!==0&&d!==h.length-1&&i.push([]):s+=l}),a(),n.inTable=o,i}function $f(e,t,n){n.inline=!0;const r=e[2]?e[2].replace(bf,"").split("|").map(Hf):[],o=e[3]?(function(s,a,l){return s.trim().split(`
|
|
46
|
+
`).map(function(d){return zc(d,a,l,!0)})})(e[3],t,n):[],i=zc(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 Yc(e,t){return e.align[t]==null?{}:{textAlign:e.align[t]}}function kn(e){return e.inline=1,e}function sn(e){return kn(function(t,n){return n.inline?e.exec(t):null})}function Ht(e){return kn(function(t,n){return n.inline||n.simple?e.exec(t):null})}function Dt(e){return function(t,n){return n.inline||n.simple?null:e.exec(t)}}function qr(e){return kn(function(t){return e.exec(t)})}const Bf=/(javascript|vbscript|data(?!:image)):/i;function Gf(e){try{const t=decodeURIComponent(e).replace(/[^A-Za-z0-9/:]/g,"");if(Bf.test(t))return null}catch{return null}return e}function Tt(e){return e&&e.replace(Af,"$1")}function Xr(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 Wf(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 Kf(e,t,n){const r=n.inline||!1;n.inline=!1;const o=e(t,n);return n.inline=r,o}const Es=(e,t,n)=>({children:Xr(t,e[2],n)});function ys(){return{}}function Ss(){return null}function qf(...e){return e.filter(Boolean).join(" ")}function bs(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 Xf(e="",t={}){t.overrides=t.overrides||{},t.namedCodesToUnicode=t.namedCodesToUnicode?on({},vc,t.namedCodesToUnicode):vc;const n=t.slugify||pr,r=t.sanitizer||Gf,o=t.createElement||tt,i=[wc,Nc,Tc,t.enforceAtxHeadings?Cc:xc,kc,Rc,Uc,Fc],s=[...i,ff,ps,Oc,fs];function a(m,E){for(let y=0;y<m.length;y++)if(m[y].test(E))return!0;return!1}function l(m,E,...y){const k=bs(t.overrides,m+".props",{});return o((function(x,T){const C=bs(T,x);return C?typeof C=="function"||typeof C=="object"&&"render"in C?C:bs(T,x+".component",x):x})(m,t.overrides),on({},E,k,{className:qf(E?.className,k.className)||void 0}),...y)}function d(m){m=m.replace(af,"");let E=!1;t.forceInline?E=!0:t.forceBlock||(E=yf.test(m)===!1);const y=g(f(E?m:mr(m).replace(Mf,"")+`
|
|
47
47
|
|
|
48
|
-
`,{inline:
|
|
49
|
-
`);return
|
|
50
|
-
`],o:
|
|
51
|
-
`},21:{o:
|
|
48
|
+
`,{inline:E}));for(;jc(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 x;if(y.length>1||t.forceWrapper)x=y;else{if(y.length===1)return x=y[0],typeof x=="string"?l("span",{key:"outer"},x):x;x=null}return o(k,{key:"outer"},x)}function h(m,E){if(!E||!E.trim())return null;const y=E.match(Kp);return y?y.reduce(function(k,x){const T=x.indexOf("=");if(T!==-1){const C=(function(P){return P.indexOf("-")!==-1&&P.match(df)===null&&(P=P.replace(pf,function(B,G){return G.toUpperCase()})),P})(x.slice(0,T)).trim(),S=(function(P){const B=P[0];return(B==='"'||B==="'")&&P.length>=2&&P[P.length-1]===B?P.slice(1,-1):P})(x.slice(T+1).trim()),v=bc[C]||C;if(v==="ref")return k;const N=k[v]=(function(P,B,G,he){return B==="style"?(function(pe){const se=[];let Ee="",V=!1,le=!1,Re="";if(!pe)return se;for(let Q=0;Q<pe.length;Q++){const I=pe[Q];if(I!=='"'&&I!=="'"||V||(le?I===Re&&(le=!1,Re=""):(le=!0,Re=I)),I==="("&&Ee.endsWith("url")?V=!0:I===")"&&V&&(V=!1),I!==";"||le||V)Ee+=I;else{const W=Ee.trim();if(W){const re=W.indexOf(":");if(re>0){const ve=W.slice(0,re).trim(),K=W.slice(re+1).trim();se.push([ve,K])}}Ee=""}}const te=Ee.trim();if(te){const Q=te.indexOf(":");if(Q>0){const I=te.slice(0,Q).trim(),W=te.slice(Q+1).trim();se.push([I,W])}}return se})(G).reduce(function(pe,[se,Ee]){return pe[se.replace(/(-[a-z])/g,V=>V[1].toUpperCase())]=he(Ee,P,se),pe},{}):Wp.indexOf(B)!==-1?he(Tt(G),P,B):(G.match(uf)&&(G=Tt(G.slice(1,G.length-1))),G==="true"||G!=="false"&&G)})(m,C,S,r);typeof N=="string"&&(ps.test(N)||fs.test(N))&&(k[v]=d(N.trim()))}else x!=="style"&&(k[bc[x]||x]=!0);return k},{}):null}const u=[],p={},_={0:{t:[">"],o:Dt(wc),i:1,u(m,E,y){const[,k,x]=m[0].replace(Xp,"").match(Zp);return{alert:k,children:E(x,y)}},l(m,E,y){const k={key:y.key};return m.alert&&(k.className="markdown-alert-"+n(m.alert.toLowerCase(),pr),m.children.unshift({attrs:{},children:[{type:"27",text:m.alert}],noInnerParse:!0,type:"11",tag:"header"})),l("blockquote",k,E(m.children,y))}},1:{t:[" "],o:qr(Jp),i:1,u:ys,l:(m,E,y)=>l("br",{key:y.key})},2:{t:["--","__","**","- ","* ","_ "],o:Dt(Qp),i:1,u:ys,l:(m,E,y)=>l("hr",{key:y.key})},3:{t:[" "],o:Dt(Tc),i:0,u:m=>({lang:void 0,text:Tt(mr(m[0].replace(/^ {4}/gm,"")))}),l:(m,E,y)=>l("pre",{key:y.key},l("code",on({},m.attrs,{className:m.lang?"lang-"+m.lang:""}),m.text))},4:{t:["```","~~~"],o:Dt(Nc),i:0,u:m=>({attrs:h("code",m[3]||""),lang:m[2]||void 0,text:m[4],type:"3"})},5:{t:["`"],o:Ht(ef),i:3,u:m=>({text:Tt(m[2])}),l:(m,E,y)=>l("code",{key:y.key},m.text)},6:{t:["[^"],o:Dt(rf),i:0,u:m=>(u.push({footnote:m[2],identifier:m[1]}),{}),l:Ss},7:{t:["[^"],o:sn(of),i:1,u:m=>({target:"#"+n(m[1],pr),text:m[1]}),l:(m,E,y)=>l("a",{key:y.key,href:r(m.target,"a","href")},l("sup",{key:y.key},m.text))},8:{t:["[ ]","[x]"],o:sn(lf),i:1,u:m=>({completed:m[1].toLowerCase()==="x"}),l:(m,E,y)=>l("input",{checked:m.completed,key:y.key,readOnly:!0,type:"checkbox"})},9:{t:["#"],o:Dt(t.enforceAtxHeadings?Cc:xc),i:1,u:(m,E,y)=>({children:Xr(E,m[2],y),id:n(m[2],pr),level:m[1].length}),l:(m,E,y)=>l("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:Dt(kc),i:1,u:(m,E,y)=>({children:Xr(E,m[1],y),level:m[2]==="="?1:2,type:"9"})},11:{t:["<"],o:qr(ps),i:1,u(m,E,y){const[,k]=m[3].match(Pf),x=RegExp("^"+k,"gm"),T=m[3].replace(x,""),C=a(s,T)?Kf:Xr,S=m[1].toLowerCase(),v=Gp.indexOf(S)!==-1,N=(v?S:m[1]).trim(),P={attrs:h(N,m[2]),noInnerParse:v,tag:N};if(y.inAnchor=y.inAnchor||S==="a",v)P.text=m[3];else{const B=y.inHTML;y.inHTML=!0,P.children=C(E,T,y),y.inHTML=B}return y.inAnchor=!1,P},l:(m,E,y)=>l(m.tag,on({key:y.key},m.attrs),m.text||(m.children?E(m.children,y):""))},13:{t:["<"],o:qr(fs),i:1,u(m){const E=m[1].trim();return{attrs:h(E,m[2]||""),tag:E}},l:(m,E,y)=>l(m.tag,on({},m.attrs,{key:y.key}))},12:{t:["<!--"],o:qr(Oc),i:1,u:()=>({}),l:Ss},14:{t:["!["],o:Ht(zf),i:1,u:m=>({alt:Tt(m[1]),target:Tt(m[2]),title:Tt(m[3])}),l:(m,E,y)=>l("img",{key:y.key,alt:m.alt||void 0,title:m.title||void 0,src:r(m.target,"img","src")})},15:{t:["["],o:sn(jf),i:3,u:(m,E,y)=>({children:Wf(E,m[1],y),target:Tt(m[2]),title:Tt(m[3])}),l:(m,E,y)=>l("a",{key:y.key,href:r(m.target,"a","href"),title:m.title},E(m.children,y))},16:{t:["<"],o:sn(mf),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&&(Kr(m,"http://")||Kr(m,"https://")),o:sn(hf),i:0,u:m=>({children:[{text:m[1],type:"27"}],target:m[1],title:void 0,type:"15"})},20:Vc(l,1),33:Vc(l,2),19:{t:[`
|
|
50
|
+
`],o:Dt(tf),i:3,u:ys,l:()=>`
|
|
51
|
+
`},21:{o:kn(function(m,E){if(E.inline||E.simple||E.inHTML&&m.indexOf(`
|
|
52
52
|
|
|
53
|
-
`)===-1&&
|
|
53
|
+
`)===-1&&E.prevCapture.indexOf(`
|
|
54
54
|
|
|
55
|
-
`)===-1)return null;let
|
|
56
|
-
`,
|
|
57
|
-
`).replace(Af,"").replace(Bf," ")})(b),N)}})(m),S=(function(u,g){return function _(b,N={}){if(Array.isArray(b)){const T=N.key,O=[];let y=!1;for(let v=0;v<b.length;v++){N.key=v;const x=_(b[v],N),P=cd(x);P&&y?O[O.length-1]+=x:x!==null&&O.push(x),y=P}return N.key=T,O}return(function(T,O,y){const v=u[T.type].l;return g?g(()=>v(T,O,y),T,O,y):v(T,O,y)})(b,_,N)}})(m,t.renderRule),w=d(e);return h.length?l("div",null,w,l("footer",{key:"footer"},h.map(function(u){return l("div",{id:n(u.identifier,wr),key:u.identifier},u.identifier,S(E(u.footnote,{inline:!0})))}))):w}const vg=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,l={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(l[s]=o[s]);return l})(e,_f);return zt(bg(t??"",n),r)},wg={disableParsingRawHTML:!0,forceBlock:!0};function Tg({children:e}){return c(vg,{options:wg,children:e})}const uo=Jt(Tg),Ng=45,Cg=8,xg=15,Og=25,Rg=16,kg=4,Ag=1200,Ig=5e3,Mg=/\s*\S+\s*/g;function hd(){return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function pd(e,t,n){const[r]=U(hd),o=t&&!r,[i,s]=U(()=>o&&n?0:e.length),a=o?Math.min(i,e.length):e.length,l=a>=e.length;return j(()=>{if(!o||l)return;const d=e.slice(a).match(Mg)??[],p=n&&!/\s$/.test(e)?d.slice(0,-1):d;if(!p.length)return;const h=Math.max(1,Math.ceil(p.length/(n?Og:kg))),f=n?Ng+Math.max(0,Cg-p.length)*xg:Rg,m=a+p.slice(0,h).join("").length,E=setTimeout(()=>s(m),f);return()=>clearTimeout(E)},[o,l,e,a,n]),{displayedText:e.slice(0,a),caughtUp:l}}function Pg(e,t){const[n,r]=U(0);return j(()=>{if(r(0),!e)return;const o=setTimeout(()=>r(1),Ag),i=setTimeout(()=>r(2),Ig);return()=>{clearTimeout(o),clearTimeout(i)}},[e,t]),e?n:0}function md({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?c("div",{onClick:i?void 0:o,className:D("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&&c("span",{className:s?"text-primary-foreground":"text-primary",children:r}),c("span",{className:"block whitespace-normal",children:e})]}):null}const Lg=Qe(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),Dg=Qe(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),Ug=Qe(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),Fg=Qe(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),Vg=Qe(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function He({className:e}){return c("div",{className:D("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 Tr({variant:e}){return e==="pill"?c("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[c(ho,{}),c(He,{className:"h-8 w-20 rounded-full"}),c(He,{className:"h-8 w-24 rounded-full"}),c(He,{className:"h-8 w-16 rounded-full"})]}):e==="media"?c("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[c(ho,{}),c(He,{className:"h-24 w-full rounded-lg"}),c("div",{className:"mt-3 space-y-2",children:[c(He,{className:"h-3 w-3/4 rounded"}),c(He,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?c("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[c(ho,{}),c(He,{className:"h-3 w-32 rounded mb-3"}),c("div",{className:"space-y-2",children:[c(He,{className:"h-9 w-full rounded-lg"}),c(He,{className:"h-9 w-full rounded-lg"}),c(He,{className:"h-9 w-full rounded-lg"})]}),c(He,{className:"mt-4 h-9 w-full rounded-lg"})]}):c("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[c(ho,{}),c("div",{className:"flex items-center gap-3",children:[c(He,{className:"h-10 w-10 rounded-full"}),c("div",{className:"flex-1 space-y-2",children:[c(He,{className:"h-3 w-3/4 rounded"}),c(He,{className:"h-3 w-1/2 rounded"})]})]}),c("div",{className:"mt-4 space-y-2",children:[c(He,{className:"h-3 w-full rounded"}),c(He,{className:"h-3 w-5/6 rounded"})]}),c(He,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function ho(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function jg({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=U([]),[a,l]=U({}),[d,p]=U(!1),[h,f]=U(5),m=n.component,E=n.disabled,S=ce(()=>n.input,[n.input]);j(()=>{m===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&S?.doctor_details&&l(S.doctor_details)},[m,S?.doctor_details]),j(()=>{n.disabled||(p(!1),f(5),s([]))},[S,n.disabled]);const w=async v=>{p(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},u=async(v,x,P,G=!0)=>{await r({toolCalled:G,selectedComponent:v,selected_id:v.doctor_id,message:x,tool_key:t,messageId:e,...P&&{tool_result:P}})},g=async()=>{await r({message:"show more",tool_declined:!0})},_=async()=>{i.length!==0&&await r({message:i.join(", "),messageId:e,toolCalled:!0,tool_key:t})},b=()=>{const v=m===M.SYNAPSE_COMPONENTS.MULTI&&S?.options;return v?Array.isArray(v)?v.map((x,P)=>({id:`option-${P}`,label:x.label,value:x.value})):Object.keys(v).map((x,P)=>({id:`option-${P}`,label:x,value:x})):[]},N=ce(()=>{if(m===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return S?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[m,S?.doctors]);if(!m)return null;const T=m===M.SYNAPSE_COMPONENTS.PILL?S?.options:void 0,O=m===M.SYNAPSE_COMPONENTS.CARD?S?.cards:void 0,y=m===M.SYNAPSE_COMPONENTS.MEDIA_CARD?S?.media_card:void 0;return c("div",{className:"flex justify-end",children:[T&&c("div",{className:`flex ${T.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[T.slice(0,h).map((v,x)=>c(md,{disabled:E||o||d,text:v?.label||"",onClick:()=>w(v),className:"cursor-pointer"},x)),T.length>h&&c("button",{type:"button",disabled:E||o||d,onClick:()=>f(v=>v+5),className:D("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:[c(os,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,T.length-h)," more"]})]}),m===M.SYNAPSE_COMPONENTS.MULTI&&S?.options&&c(Ke,{fallback:c(Tr,{variant:"input"}),children:c("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:[c("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),c(Lg,{options:b(),selectedValues:i,onSelectionChange:s,disabled:E||o}),c(ve,{onClick:_,disabled:i.length===0||E||o,className:D("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"})]})}),N&&N.length>0?c(Ke,{fallback:c(Tr,{variant:"card"}),children:c(Dg,{count:N.length>1?N.length+1:N.length,renderItem:(v,x)=>{if(N.length>1&&v===N.length&&n?.hide_show_more!==!0)return c("button",{type:"button",onClick:g,disabled:o||E,className:D("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:[c("span",{className:D("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:c(mp,{className:"w-4 h-4 text-primary"})}),c("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const P=N[v];return c(Ke,{fallback:c(Tr,{variant:"card"}),children:c(Ug,{doctor:P,doctorDetails:a?.[P.doctor_id],disabled:o,onSelect:u,isActive:x})},P.doctor_id)}})}):null,O&&c(Ke,{fallback:c(Tr,{variant:"card"}),children:c(Fg,{cards:O,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:E||o})}),y&&c(Ke,{fallback:c(Tr,{variant:"media"}),children:c("div",{className:"mt-3",children:c(Vg,{card:y})})})]})}function fd({userFeedback:e,onToggleFeedback:t}){if(e===M.USER_FEEDBACK.NONE)return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c("div",{className:"flex items-center gap-1",children:[c(ve,{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:()=>t(M.USER_FEEDBACK.LIKE),children:c(Yl,{className:"h-3 w-3"})}),c(ve,{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:()=>t(M.USER_FEEDBACK.DISLIKE),children:c(Bl,{className:"h-3 w-3"})})]})});if(e===M.USER_FEEDBACK.LIKE||e===M.USER_FEEDBACK.DISLIKE){const n=e===M.USER_FEEDBACK.LIKE?Yl:Bl;return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(ve,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:c(n,{className:"h-3 w-3"})})})}return null}function zg({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:l,toolCallStatus:d,onSendMessage:p,onToggleFeedback:h,disabled:f,onClearElicitationState:m,isAuthComponent:E,isFullScreen:S}){const w=t===we.USER,[u,g]=U(M.USER_FEEDBACK.NONE),_=V(G=>G.isStreaming),b=!w&&!!o,N=b&&_,{displayedText:T,caughtUp:O}=pd(n||"",b,N),y=N||!O,v=Pg(N&&!i,T.length),x=G=>{g(G),h(G,e)},P=!!(n?.trim()||r&&r.length>0||d||i||a);return c(_e,{children:[P&&c("div",{className:D("flex",w?"justify-end":"justify-start"),children:c("div",{className:D("flex gap-3",w?"flex-row-reverse":"flex-row",w?"max-w-[60%]":S?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(nn,{className:D("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",w?"bg-primary text-primary-foreground shadow-sm":D("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),S&&!w&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!w&&c("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!w&&o&&c("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),T&&c("div",{className:D("markdown-content",S&&!w?"text-base leading-6":"text-sm",y&&"synapse-streaming"),children:c(uo,{children:T})}),T&&v>0&&c("p",{className:"synapse-shimmer-text mt-1.5 text-xs font-medium text-muted-foreground",role:"status",children:v===1?"Thinking\u2026":"Still working on it\u2026"},v),r&&r.length>0&&c("div",{className:"mt-2",children:c(Ss,{files:r,isPreview:!1,className:""})}),i&&!w&&o&&c("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!w&&!y&&o&&(n||u!==M.USER_FEEDBACK.NONE)&&c(fd,{userFeedback:u,onToggleFeedback:x}),E&&o&&s?.length?c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(ve,{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 G=s[s.length-1];G&&l[G]?.active&&m(G,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(G=>{const W=l[G];return W?c(jg,{messageId:e,tool_key:G,entry:W,onSendMessage:p,disabled:f||W.disabled},G):null}),a&&!w&&c("div",{className:"flex justify-start",children:c("div",{className:D("flex gap-3 flex-row",S?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(nn,{className:D("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",S&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:c("div",{className:D("markdown-content",S?"text-base leading-6":"text-sm"),children:c(uo,{children:a})})}),!y&&o&&c(fd,{userFeedback:u,onToggleFeedback:x})]})})})]})}const $g=Jt(zg),Ps=3,Hg=700,Yg=450,Bg=70;function Gg(e=""){const t=(e.includes("```")?[e]:e.split(/\n\s*\n/)).filter(n=>n.trim());return t.length>Ps?[...t.slice(0,Ps-1),t.slice(Ps-1).join(`
|
|
55
|
+
`)===-1)return null;let y="",k=0;for(;;){const T=m.indexOf(`
|
|
56
|
+
`,k),C=m.slice(k,T===-1?void 0:T+1);if(a(i,C)||(y+=C,T===-1||!C.trim()))break;k=T+1}const x=mr(y);return x===""?null:[y,,x]}),i:3,u:Es,l:(m,E,y)=>l("p",{key:y.key},E(m.children,y))},22:{t:["["],o:sn(gf),i:0,u:m=>(p[m[1]]={target:m[2],title:m[4]},{}),l:Ss},23:{t:["!["],o:Ht(_f),i:0,u:m=>({alt:m[1]?Tt(m[1]):void 0,ref:m[2]}),l:(m,E,y)=>p[m.ref]?l("img",{key:y.key,alt:m.alt,src:r(p[m.ref].target,"img","src"),title:p[m.ref].title}):null},24:{t:m=>m[0]==="["&&m.indexOf("](")===-1,o:sn(Ef),i:0,u:(m,E,y)=>({children:E(m[1],y),fallbackChildren:m[0],ref:m[2]}),l:(m,E,y)=>p[m.ref]?l("a",{key:y.key,href:r(p[m.ref].target,"a","href"),title:p[m.ref].title},E(m.children,y)):l("span",{key:y.key},m.fallbackChildren)},25:{t:["|"],o:Dt(Rc),i:1,u:$f,l(m,E,y){const k=m;return l("table",{key:y.key},l("thead",null,l("tr",null,k.header.map(function(x,T){return l("th",{key:T,style:Yc(k,T)},E(x,y))}))),l("tbody",null,k.cells.map(function(x,T){return l("tr",{key:T},x.map(function(C,S){return l("td",{key:S,style:Yc(k,S)},E(C,y))}))})))}},27:{o:kn(function(m,E){let y;return Kr(m,":")&&(y=Of.exec(m)),y||If.exec(m)}),i:4,u(m){const E=m[0];return{text:E.indexOf("&")===-1?E:E.replace(cf,(y,k)=>t.namedCodesToUnicode[k]||y)}},l:m=>m.text},28:{t:["**","__"],o:Ht(Tf),i:2,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>l("strong",{key:y.key},E(m.children,y))},29:{t:m=>{const E=m[0];return(E==="*"||E==="_")&&m[1]!==E},o:Ht(xf),i:3,u:(m,E,y)=>({children:E(m[2],y)}),l:(m,E,y)=>l("em",{key:y.key},E(m.children,y))},30:{t:["\\"],o:Ht(Rf),i:1,u:m=>({text:m[1],type:"27"})},31:{t:["=="],o:Ht(Cf),i:3,u:Es,l:(m,E,y)=>l("mark",{key:y.key},E(m.children,y))},32:{t:["~~"],o:Ht(kf),i:3,u:Es,l:(m,E,y)=>l("del",{key:y.key},E(m.children,y))}};t.disableParsingRawHTML===!0&&(delete _[11],delete _[13]);const f=(function(m){var E=Object.keys(m);function y(k,x){var T=[];if(x.prevCapture=x.prevCapture||"",k.trim())for(;k;)for(var C=0;C<E.length;){var S=E[C],v=m[S];if(!v.t||Yf(k,x,v.t)){var N=v.o(k,x);if(N&&N[0]){k=k.substring(N[0].length);var P=v.u(N,y,x);x.prevCapture+=N[0],P.type||(P.type=S),T.push(P);break}C++}else C++}return x.prevCapture="",T}return E.sort(function(k,x){return m[k].i-m[x].i||(k<x?-1:1)}),function(k,x){return y((function(T){return T.replace(nf,`
|
|
57
|
+
`).replace(sf,"").replace(Sf," ")})(k),x)}})(_),g=(function(m,E){return function y(k,x={}){if(Array.isArray(k)){const T=x.key,C=[];let S=!1;for(let v=0;v<k.length;v++){x.key=v;const N=y(k[v],x),P=jc(N);P&&S?C[C.length-1]+=N:N!==null&&C.push(N),S=P}return x.key=T,C}return(function(T,C,S){const v=m[T.type].l;return E?E(()=>v(T,C,S),T,C,S):v(T,C,S)})(k,y,x)}})(_,t.renderRule),b=d(e);return u.length?l("div",null,b,l("footer",{key:"footer"},u.map(function(m){return l("div",{id:n(m.identifier,pr),key:m.identifier},m.identifier,g(f(m.footnote,{inline:!0})))}))):b}const Zf=e=>{let{children:t,options:n}=e,r=(function(o,i){if(o==null)return{};var s,a,l={},d=Object.keys(o);for(a=0;a<d.length;a++)i.indexOf(s=d[a])>=0||(l[s]=o[s]);return l})(e,Bp);return Ft(Xf(t??"",n),r)},Jf={disableParsingRawHTML:!0,forceBlock:!0};function Qf({children:e}){return c(Zf,{options:Jf,children:e})}const Zr=Xt(Qf),eg=45,tg=8,ng=15,rg=25,og=16,sg=4,ig=1200,ag=5e3,lg=/\s*\S+\s*/g;function Hc(){return typeof window<"u"&&!!window.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function $c(e,t,n){const[r]=F(Hc),o=t&&!r,[i,s]=F(()=>o&&n?0:e.length),a=o?Math.min(i,e.length):e.length,l=a>=e.length;return Y(()=>{if(!o||l)return;const d=e.slice(a).match(lg)??[],h=n&&!/\s$/.test(e)?d.slice(0,-1):d;if(!h.length)return;const u=Math.max(1,Math.ceil(h.length/(n?rg:sg))),p=n?eg+Math.max(0,tg-h.length)*ng:og,_=a+h.slice(0,u).join("").length,f=setTimeout(()=>s(_),p);return()=>clearTimeout(f)},[o,l,e,a,n]),{displayedText:e.slice(0,a),caughtUp:l}}function cg(e,t){const[n,r]=F(0);return Y(()=>{if(r(0),!e)return;const o=setTimeout(()=>r(1),ig),i=setTimeout(()=>r(2),ag);return()=>{clearTimeout(o),clearTimeout(i)}},[e,t]),e?n:0}function Bc({text:e,maxWidth:t="200px",className:n="",icon:r,onClick:o,disabled:i=!1,selected:s=!1}){return e?c("div",{onClick:i?void 0:o,className:L("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&&c("span",{className:s?"text-primary-foreground":"text-primary",children:r}),c("span",{className:"block whitespace-normal",children:e})]}):null}const dg=nt(()=>import("./medassist-widget-MultiSelect-zx2GZY3z.js").then(e=>({default:e.MultiSelectGroup}))),ug=nt(()=>import("./medassist-widget-FocusCarousel-af7aMXWo.js").then(e=>({default:e.FocusCarousel}))),hg=nt(()=>import("./medassist-widget-DoctorCard-B_xw-xWd.js").then(e=>({default:e.DoctorCard}))),mg=nt(()=>import("./medassist-widget-CardList-ST569rut.js").then(e=>({default:e.CardList}))),pg=nt(()=>import("./medassist-widget-MediaCard-CLipu6gc.js").then(e=>({default:e.MediaCard})));function $e({className:e}){return c("div",{className:L("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 fr({variant:e}){return e==="pill"?c("div",{className:"flex flex-wrap gap-2 mt-3","aria-busy":!0,"aria-label":"Loading options",children:[c(Jr,{}),c($e,{className:"h-8 w-20 rounded-full"}),c($e,{className:"h-8 w-24 rounded-full"}),c($e,{className:"h-8 w-16 rounded-full"})]}):e==="media"?c("div",{className:"mt-3 w-56 rounded-xl border border-border-subtle bg-surface p-3","aria-busy":!0,"aria-label":"Loading media",children:[c(Jr,{}),c($e,{className:"h-24 w-full rounded-lg"}),c("div",{className:"mt-3 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}):e==="input"?c("div",{className:"mt-3 w-full rounded-xl border border-primary/30 bg-elicitationBg p-4","aria-busy":!0,"aria-label":"Loading input",children:[c(Jr,{}),c($e,{className:"h-3 w-32 rounded mb-3"}),c("div",{className:"space-y-2",children:[c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"}),c($e,{className:"h-9 w-full rounded-lg"})]}),c($e,{className:"mt-4 h-9 w-full rounded-lg"})]}):c("div",{className:"mt-3 w-72 rounded-xl border border-border-subtle bg-surface p-4","aria-busy":!0,"aria-label":"Loading card",children:[c(Jr,{}),c("div",{className:"flex items-center gap-3",children:[c($e,{className:"h-10 w-10 rounded-full"}),c("div",{className:"flex-1 space-y-2",children:[c($e,{className:"h-3 w-3/4 rounded"}),c($e,{className:"h-3 w-1/2 rounded"})]})]}),c("div",{className:"mt-4 space-y-2",children:[c($e,{className:"h-3 w-full rounded"}),c($e,{className:"h-3 w-5/6 rounded"})]}),c($e,{className:"mt-4 h-9 w-28 rounded-lg"})]})}function Jr(){return c("style",{children:"@keyframes shimmer { 100% { transform: translateX(100%); } }"})}function fg({messageId:e,tool_key:t,entry:n,onSendMessage:r,disabled:o}){const[i,s]=F([]),[a,l]=F({}),[d,h]=F(!1),[u,p]=F(5),_=n.component,f=n.disabled,g=ie(()=>n.input,[n.input]);Y(()=>{_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD&&g?.doctor_details&&l(g.doctor_details)},[_,g?.doctor_details]),Y(()=>{n.disabled||(h(!1),p(5),s([]))},[g,n.disabled]);const b=async v=>{h(!0),await r({message:v.value,messageId:e,toolCalled:!0,selectedComponent:v,tool_key:t})},m=async(v,N,P,B=!0)=>{await r({toolCalled:B,selectedComponent:v,selected_id:v.doctor_id,message:N,tool_key:t,messageId:e,...P&&{tool_result:P}})},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 v=_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options;return v?Array.isArray(v)?v.map((N,P)=>({id:`option-${P}`,label:N.label,value:N.value})):Object.keys(v).map((N,P)=>({id:`option-${P}`,label:N,value:N})):[]},x=ie(()=>{if(_===M.SYNAPSE_COMPONENTS.DOCTOR_CARD)return g?.doctors?.filter(v=>!!v&&!!v.doctor_id)},[_,g?.doctors]);if(!_)return null;const T=_===M.SYNAPSE_COMPONENTS.PILL?g?.options:void 0,C=_===M.SYNAPSE_COMPONENTS.CARD?g?.cards:void 0,S=_===M.SYNAPSE_COMPONENTS.MEDIA_CARD?g?.media_card:void 0;return c("div",{className:"flex justify-end",children:[T&&c("div",{className:`flex ${T.length>3?"flex-col":"flex-wrap"} gap-2 mt-3`,children:[T.slice(0,u).map((v,N)=>c(Bc,{disabled:f||o||d,text:v?.label||"",onClick:()=>b(v),className:"cursor-pointer"},N)),T.length>u&&c("button",{type:"button",disabled:f||o||d,onClick:()=>p(v=>v+5),className:L("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:[c(Wo,{className:"w-3.5 h-3.5"}),"Show ",Math.min(5,T.length-u)," more"]})]}),_===M.SYNAPSE_COMPONENTS.MULTI&&g?.options&&c(Xe,{fallback:c(fr,{variant:"input"}),children:c("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:[c("h3",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Select multiple options:"}),c(dg,{options:k(),selectedValues:i,onSelectionChange:s,disabled:f||o}),c(Se,{onClick:y,disabled:i.length===0||f||o,className:L("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"})]})}),x&&x.length>0?c(Xe,{fallback:c(fr,{variant:"card"}),children:c(ug,{count:x.length>1?x.length+1:x.length,renderItem:(v,N)=>{if(x.length>1&&v===x.length&&n?.hide_show_more!==!0)return c("button",{type:"button",onClick:E,disabled:o||f,className:L("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:[c("span",{className:L("flex items-center justify-center","w-10 h-10 rounded-full bg-elicitationBg shadow-sm"),children:c($h,{className:"w-4 h-4 text-primary"})}),c("span",{className:"text-primary font-semibold text-sm",children:"Show more"})]});const P=x[v];return c(Xe,{fallback:c(fr,{variant:"card"}),children:c(hg,{doctor:P,doctorDetails:a?.[P.doctor_id],disabled:o,onSelect:m,isActive:N})},P.doctor_id)}})}):null,C&&c(Xe,{fallback:c(fr,{variant:"card"}),children:c(mg,{cards:C,onSelect:async v=>{await r({...v,toolCalled:!0,tool_key:t,messageId:e})},orientation:n.orientation,disabled:f||o})}),S&&c(Xe,{fallback:c(fr,{variant:"media"}),children:c("div",{className:"mt-3",children:c(pg,{card:S})})})]})}function Gc({userFeedback:e,onToggleFeedback:t}){if(e===M.USER_FEEDBACK.NONE)return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c("div",{className:"flex items-center gap-1",children:[c(Se,{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:()=>t(M.USER_FEEDBACK.LIKE),children:c(vl,{className:"h-3 w-3"})}),c(Se,{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:()=>t(M.USER_FEEDBACK.DISLIKE),children:c(wl,{className:"h-3 w-3"})})]})});if(e===M.USER_FEEDBACK.LIKE||e===M.USER_FEEDBACK.DISLIKE){const n=e===M.USER_FEEDBACK.LIKE?vl:wl;return c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-muted text-primary",disabled:!0,children:c(n,{className:"h-3 w-3"})})})}return null}function gg({id:e,role:t,content:n,files:r,isLastMessage:o,progressMessage:i,toolKeys:s,userHint:a,elicitationState:l,toolCallStatus:d,onSendMessage:h,onToggleFeedback:u,disabled:p,onClearElicitationState:_,isAuthComponent:f,isFullScreen:g}){const b=t===Ne.USER,[m,E]=F(M.USER_FEEDBACK.NONE),y=j(B=>B.isStreaming),k=!b&&!!o,x=k&&y,{displayedText:T,caughtUp:C}=$c(n||"",k,x),S=x||!C,v=cg(x&&!i,T.length),N=B=>{E(B),u(B,e)},P=!!(n?.trim()||r&&r.length>0||d||i||a);return c(me,{children:[P&&c("div",{className:L("flex",b?"justify-end":"justify-start"),children:c("div",{className:L("flex gap-3",b?"flex-row-reverse":"flex-row",b?"max-w-[60%]":g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col min-w-0",children:[c(en,{className:L("px-4 py-2 rounded-lg shadow-none break-words overflow-wrap-anywhere whitespace-pre-wrap",b?"bg-primary text-primary-foreground shadow-sm":L("text-foreground shadow-sm bg-botMessage blur-xs border border-black-200 dark:border-white-200"),g&&!b&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none"),children:[d&&!b&&c("div",{className:"text-xs text-muted-foreground mb-2 pb-2 border-b border-border-subtle",children:d}),!d&&i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground pb-2",children:i}),T&&c("div",{className:L("markdown-content",g&&!b?"text-base leading-6":"text-sm",S&&"synapse-streaming"),children:c(Zr,{children:T})}),T&&v>0&&c("p",{className:"synapse-shimmer-text mt-1.5 text-xs font-medium text-muted-foreground",role:"status",children:v===1?"Thinking\u2026":"Still working on it\u2026"},v),r&&r.length>0&&c("div",{className:"mt-2",children:c(ls,{files:r,isPreview:!1,className:""})}),i&&!b&&o&&c("p",{className:"text-sm font-medium text-muted-foreground",children:i})]}),!a&&!b&&!S&&o&&(n||m!==M.USER_FEEDBACK.NONE)&&c(Gc,{userFeedback:m,onToggleFeedback:N}),f&&o&&s?.length?c("div",{className:"flex items-center gap-2 self-start mt-1",children:c(Se,{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 B=s[s.length-1];B&&l[B]?.active&&_(B,"Cancel OTP Verification")},children:"Cancel OTP Verification"})}):null]})})}),s?.map(B=>{const G=l[B];return G?c(fg,{messageId:e,tool_key:B,entry:G,onSendMessage:h,disabled:p||G.disabled},B):null}),a&&!b&&c("div",{className:"flex justify-start",children:c("div",{className:L("flex gap-3 flex-row",g?"w-full":"max-w-xs"),children:c("div",{className:"flex flex-col",children:[c(en,{className:L("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:c("div",{className:L("markdown-content",g?"text-base leading-6":"text-sm"),children:c(Zr,{children:a})})}),!S&&o&&c(Gc,{userFeedback:m,onToggleFeedback:N})]})})})]})}const _g=Xt(gg),vs=3,Eg=700,yg=450,Sg=70;function bg(e=""){const t=(e.includes("```")?[e]:e.split(/\n\s*\n/)).filter(n=>n.trim());return t.length>vs?[...t.slice(0,vs-1),t.slice(vs-1).join(`
|
|
58
58
|
|
|
59
|
-
`)]:t}function Wg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){const i=ce(()=>Gg(e),[e]),[s]=U(hd),[a,l]=U(s?1/0:0),d=a<i.length*2,p=d&&a%2===0;if(j(()=>{if(!p)return;const f=setTimeout(()=>l(a+1),a?Yg:Hg);return()=>clearTimeout(f)},[p,a]),!i.length&&!t?.length)return null;const h=f=>{const m=f.value||f.label||"";m&&n({message:m})};return c(_e,{children:[i.length>0&&c("div",{className:"flex flex-col items-start gap-1.5","aria-live":"polite","aria-busy":d,children:[i.slice(0,Math.ceil(a/2)).map((f,m)=>c(Kg,{text:f,isFullScreen:o,onDone:()=>l(E=>E===m*2+1?E+1:E)},m)),p&&c(Hc,{bare:o})]}),!d&&t&&t.length>0&&c("div",{className:"flex justify-end",children:c("div",{className:D("flex gap-2 mt-3 justify-end",t.length>3?"flex-col items-end":"flex-wrap"),children:t.map((f,m)=>c("div",{className:D("flex",!s&&"synapse-pill-in"),style:s?void 0:{animationDelay:`${120+m*Bg}ms`},children:c(md,{text:f.label||"",onClick:()=>h(f),disabled:r,className:"cursor-pointer"})},m))})})]})}function Kg({text:e,isFullScreen:t,onDone:n}){const{displayedText:r,caughtUp:o}=pd(`${e} `,!0,!0);return j(()=>{o&&n()},[o]),c("div",{className:D("flex gap-3 flex-row synapse-message-in",t?"w-full":"max-w-xs"),children:c(nn,{className:D("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",t&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:c("div",{className:D("markdown-content",t?"text-base leading-6":"text-sm"),children:c(uo,{children:r})})})})}const qg=[];function Xg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const l=V(h=>h.isWaitingForResponse),d=V(h=>h.elicitationState),p=V(h=>h.progressMessage);return e.length===0&&!p?c(Wg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):c(_e,{children:[(e&&e.length>0||p)&&c(_e,{children:e.map((h,f)=>c("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":h.role,"data-message-id":h.id,id:f===e.length-1?"last-message":void 0,children:c($g,{id:h.id,role:h.role,content:h.content,files:h.files||qg,toolKeys:h.tool_keys,userHint:h.userHint,elicitationState:d,onSendMessage:t,isLastMessage:f===e.length-1,progressMessage:f===e.length-1?p:null,toolCallStatus:h.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},h.id))}),l&&c(Hc,{})]})}const Jg=Jt(Xg);function gd({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=Pc(),[l,d]=U(!0);return j(()=>{if(!r&&!n&&i&&a){d(!0);const p=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(p)}d(!0)},[i,r,n,a]),r?c("div",{className:D("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:c("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?c("div",{className:D("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),c("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),c("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:[c("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c("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&&!l||!s&&!i?.title&&a?null:c("div",{className:D("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),c("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&&c("div",{className:"flex-shrink-0",children:c("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const Zg=Qe(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function Qg({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:l,showRetryButton:d,clearError:p,error:h,sessionId:f,activeElicitation:m,isAuthComponent:E,isConnected:S,inConversation:w,isFirstMessage:u,isEmptyChat:g,isLoadingSessionMessages:_,initialMessage:b,incomingMessages:N,sendMessageFeedback:T,clearElicitationState:O,handleRetry:y,scrollToBottom:v,chatComposerProps:x,isComposerDisabled:P,voiceAgentState:G,isMuted:W,isVoiceAgentActive:ne,disconnectVoiceAgent:de,resetVoiceAgent:ue,toggleMute:me,handleClose:F,isSessionDrawerOpen:le,pastSessions:Ie,isLoadingPastSessions:te,openSessionDrawer:Z,closeSessionDrawer:$,userLevel:H,isSidebarCollapsed:re,toggleSidebar:he,feedbackModalProps:q,consentModalProps:et,handleChatSendMessage:Ne,handleEmptyStateSendMessage:Oe,handleSelectSession:fe,handleStartNewChat:Me,sidePanelMode:Dt,sidePanelWidth:Ct,side:z,onSidePanelPushChange:Fe}=gf({isOpen:e,agentId:t,config:n});j(()=>{N.length||v("auto")},[N.length,v]);const ye=ce(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Pe=ce(()=>o==="full"&&H==="user"?c(Ac,{variant:"sidebar",sessions:Ie,activeSessionId:f,onSelectSession:fe,onNewChat:Me,isCollapsed:re,onToggle:he,isLoading:te}):void 0,[o,H,Ie,f,fe,Me,re,he,te]),Xe=ce(()=>({onRetry:y,showRetryButton:d,startNewConnection:l,clearError:p,error:h,isConnected:S}),[y,d,l,p,h,S]),tt=ce(()=>({onClose:F,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:Me,showStartNewChatButton:l,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:Z}),[F,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,Me,l,n.resize,r,Z]),$e=ce(()=>c(Ac,{variant:"drawer",isOpen:le,onClose:$,sessions:Ie,activeSessionId:f,onSelectSession:fe,onNewChat:Me,isLoading:te}),[le,$,Ie,f,fe,Me,te]);return c(am,{enabled:!!n.resize,children:c(Cc,{value:tt,children:c(Rc,{isOpen:e,feedbackModal:q,consentModal:et,sessionId:f,environment:n.environment,mode:o,sidePanelMode:Dt,sidePanelWidth:Ct,side:z,onSidePanelPushChange:Fe,theme:n.theme,isAuthComponent:E,activeElicitation:m,voiceAgentState:G,chatComposer:x,sessionDrawer:$e,sidebar:Pe,fullScreenEmptyState:g?pt=>c(Hm,{title:n.title,description:b?.text,suggestions:b?.suggestions,onSendMessage:Oe,disabled:P,composer:pt.composer,composerFooter:pt.composerFooter,connectionBanner:c(gd,{...Xe})}):void 0,children:ne?c(Ke,{fallback:c(_d,{}),children:c(Zg,{state:G,isMuted:W,onEndCall:de,onClose:ue,onToggleMute:me,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):c(Ke,{fallback:c(_d,{}),children:c("div",{className:D("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[c("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:c(Il,{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:[c("div",{className:"flex-1"}),c("div",{className:D("min-w-0 overflow-x-hidden",w?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[_?c(Wp,{}):c(_e,{children:[u&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!u&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:ye}),c(Jg,{messages:N,onSendMessage:Ne,onToggleFeedback:T,onClearElicitationState:O,isAuthComponent:E,isFullScreen:o==="full",initialMessage:b??n.initialMessage,disabled:!S})]}),c("div",{ref:s})]})]})}),a&&c("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:c(ve,{onClick:()=>v("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:c(os,{className:"w-5 h-5 text-text-primary"})})}),c(gd,{className:"mt-2",...Xe})]})})})})})}function _d(){return c("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[c("div",{className:"flex-1 p-6 space-y-4",children:[c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),c("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function Ed(e){return!!e&&e.startsWith("ResizeObserver loop")}function Ls(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 e_ extends dt{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:Ls(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?c(r_,{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 t_({error:e}){throw e}function n_(e){const[t,n]=U(null);return j(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||Ed(i?.message)||Ed(i?.error?.message)||(i?.error?n(Ls(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(Ls(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),c(e_,{...e,children:t?c(t_,{error:t}):e.children})}function r_({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:l}){const d=()=>{typeof window<"u"&&window.location.reload()},p=t??"Medi Clinic",h=s??"production",f=ce(()=>l?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[l?.textColor]),m=ce(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:p,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,p,n,r]);return c(Cc,{value:m,children:c(Rc,{isOpen:!0,environment:h,mode:a??"widget",theme:l,children:c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:c("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:c("div",{className:"w-full max-w-[320px] text-center",children:[c("div",{className:"mx-auto mb-4 grid place-items-center",children:c("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:c(up,{className:"h-8 w-8",style:{color:l?.primary??"hsl(var(--primary))"}})})}),c("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),c("div",{className:["mt-2 text-sm",f].join(" "),children:"Something went wrong. Please try again."}),c("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)}),c("div",{className:"mt-5 flex items-center justify-center gap-3",children:c(ve,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:l?.primary??void 0},children:[c(ip,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function o_({agentId:e,config:t}){const[n,r]=U(t.displayMode==="full");j(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return c(n_,{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:c(xp,{children:c(Qg,{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 Sd=(e,t,n)=>{const r=n||{};r.tools&&oo.set(r.tools);const o=Gd(e);return o.render(c(_e,{children:c(o_,{agentId:t,config:r})})),o},s_=e=>{try{const t=sessionStorage.getItem(yr(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{}}},yd=e=>{const{refreshToken:t,sessToken:n}=s_(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},bd=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Sd,window.fetchAgentConfig=bd,window.prefetchAuth=yd,window.registerMedAssistTools=e=>oo.set(e));export{X as A,ve as B,os as C,ee as D,jl as F,zl as I,ss as M,Jt as N,En as P,zo as R,ys as S,ce as T,An as X,gt as _,M as a,D as b,ze as c,U as d,_e as e,Zt as f,bd as fetchAgentConfig,Mi as g,Sn as h,$t as i,Yt as j,Wm as k,ql as l,gs as m,_c as n,_s as o,Gm as p,yd as prefetchAuth,pe as q,Jl as r,Sd as renderMedAssist,uo as s,Dc as t,c as u,nn as v,Km as w,Xl as x,j as y,Zl as z};
|
|
59
|
+
`)]:t}function vg({text:e,suggestions:t,onSendMessage:n,disabled:r,isFullScreen:o}){const i=ie(()=>bg(e),[e]),[s]=F(Hc),[a,l]=F(s?1/0:0),d=a<i.length*2,h=d&&a%2===0;if(Y(()=>{if(!h)return;const p=setTimeout(()=>l(a+1),a?yg:Eg);return()=>clearTimeout(p)},[h,a]),!i.length&&!t?.length)return null;const u=p=>{const _=p.value||p.label||"";_&&n({message:_})};return c(me,{children:[i.length>0&&c("div",{className:"flex flex-col items-start gap-1.5","aria-live":"polite","aria-busy":d,children:[i.slice(0,Math.ceil(a/2)).map((p,_)=>c(wg,{text:p,isFullScreen:o,onDone:()=>l(f=>f===_*2+1?f+1:f)},_)),h&&c(Sc,{bare:o})]}),!d&&t&&t.length>0&&c("div",{className:"flex justify-end",children:c("div",{className:L("flex gap-2 mt-3 justify-end",t.length>3?"flex-col items-end":"flex-wrap"),children:t.map((p,_)=>c("div",{className:L("flex",!s&&"synapse-pill-in"),style:s?void 0:{animationDelay:`${120+_*Sg}ms`},children:c(Bc,{text:p.label||"",onClick:()=>u(p),disabled:r,className:"cursor-pointer"})},_))})})]})}function wg({text:e,isFullScreen:t,onDone:n}){const{displayedText:r,caughtUp:o}=$c(`${e} `,!0,!0);return Y(()=>{o&&n()},[o]),c("div",{className:L("flex gap-3 flex-row synapse-message-in",t?"w-full":"max-w-xs"),children:c(en,{className:L("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",t&&"!bg-transparent !shadow-none !border-0 !rounded-none !px-0 !py-0 !backdrop-blur-none !blur-none text-black-900"),children:c("div",{className:L("markdown-content",t?"text-base leading-6":"text-sm"),children:c(Zr,{children:r})})})})}const Ng=[];function Tg({messages:e,onSendMessage:t,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i,initialMessage:s,disabled:a}){const l=j(u=>u.isWaitingForResponse),d=j(u=>u.elicitationState),h=j(u=>u.progressMessage);return e.length===0&&!h?c(vg,{text:s?.text,suggestions:s?.suggestions,onSendMessage:t,isFullScreen:i}):c(me,{children:[(e&&e.length>0||h)&&c(me,{children:e.map((u,p)=>c("div",{className:"scroll-mt-[16px] min-w-0 overflow-hidden","data-role":u.role,"data-message-id":u.id,id:p===e.length-1?"last-message":void 0,children:c(_g,{id:u.id,role:u.role,content:u.content,files:u.files||Ng,toolKeys:u.tool_keys,userHint:u.userHint,elicitationState:d,onSendMessage:t,isLastMessage:p===e.length-1,progressMessage:p===e.length-1?h:null,toolCallStatus:u.toolCallStatus,disabled:a,onToggleFeedback:n,onClearElicitationState:r,isAuthComponent:o,isFullScreen:i})},u.id))}),l&&c(Sc,{})]})}const xg=Xt(Tg);function Wc({className:e="",onRetry:t,showRetryButton:n,startNewConnection:r,clearError:o,error:i,isConnected:s}){const{isOnline:a}=uc(),[l,d]=F(!0);return Y(()=>{if(!r&&!n&&i&&a){d(!0);const h=setTimeout(()=>d(!1),5e3);return()=>clearTimeout(h)}d(!0)},[i,r,n,a]),r?c("div",{className:L("flex flex-col items-center synapse-chat-widget-footer px-3 pt-3 pb-2 ",e),children:c("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?c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-[#F7B500] rounded-lg",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-[#F7B500] rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:i?.title}),c("div",{className:"text-text-secondary text-xs mt-1",children:i?.description??"Please check your connection and try again"})]}),c("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:[c("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:c("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&&!l||!s&&!i?.title&&a?null:c("div",{className:L("mx-4 mb-3 p-2 bg-surface border border-border-subtle rounded-lg transition-opacity duration-500",e),children:c("div",{className:"flex items-center gap-3",children:[c("div",{className:"w-5 h-5 bg-primary rounded-full flex items-center justify-center flex-shrink-0",children:c("span",{className:"text-primary-foreground text-sm font-bold",children:"!"})}),c("div",{className:"flex-1",children:[c("div",{className:"text-text-primary font-semibold text-sm",children:a?i?.title:"No internet connection"}),c("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&&c("div",{className:"flex-shrink-0",children:c("div",{className:"w-6 h-6 border-2 border-primary border-t-transparent rounded-full animate-spin"})})]})})}const Cg=nt(()=>import("./medassist-widget-VoiceAgentScreen-BK0p37RC.js"));function kg({isOpen:e,agentId:t,config:n}){const{toggleDisplayMode:r,resolvedMode:o,scrollAreaRef:i,messagesEndRef:s,showScrollButton:a,startNewConnection:l,showRetryButton:d,clearError:h,error:u,sessionId:p,activeElicitation:_,isAuthComponent:f,isConnected:g,inConversation:b,isFirstMessage:m,isEmptyChat:E,isLoadingSessionMessages:y,initialMessage:k,incomingMessages:x,sendMessageFeedback:T,clearElicitationState:C,handleRetry:S,scrollToBottom:v,chatComposerProps:N,isComposerDisabled:P,voiceAgentState:B,isMuted:G,isVoiceAgentActive:he,disconnectVoiceAgent:pe,resetVoiceAgent:se,toggleMute:Ee,handleClose:V,isSessionDrawerOpen:le,pastSessions:Re,isLoadingPastSessions:te,openSessionDrawer:Q,closeSessionDrawer:I,userLevel:W,isSidebarCollapsed:re,toggleSidebar:ve,feedbackModalProps:K,consentModalProps:Ae,handleChatSendMessage:He,handleEmptyStateSendMessage:ae,handleSelectSession:Pe,handleStartNewChat:De,sidePanelMode:xt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie}=$p({isOpen:e,agentId:t,config:n});Y(()=>{x.length||v("auto")},[x.length,v]);const we=ie(()=>new Date().toLocaleString("en-US",{weekday:"long",hour:"2-digit",minute:"2-digit",hour12:!0}),[]),Le=ie(()=>o==="full"&&W==="user"?c(cc,{variant:"sidebar",sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isCollapsed:re,onToggle:ve,isLoading:te}):void 0,[o,W,Re,p,Pe,De,re,ve,te]),qe=ie(()=>({onRetry:S,showRetryButton:d,startNewConnection:l,clearError:h,error:u,isConnected:g}),[S,d,l,h,u,g]),Ue=ie(()=>({onClose:V,showCloseButton:n.showCloseButton,title:n.title,titleImg:n.theme?.titleImg,tagline:n.theme?.tagline,iconUrl:n.iconUrl,onStartNewSession:De,showStartNewChatButton:l,onToggleDisplayMode:n.resize?r:void 0,onOpenSessionDrawer:Q}),[V,n.showCloseButton,n.title,n.theme?.titleImg,n.theme?.tagline,n.iconUrl,De,l,n.resize,r,Q]),Et=ie(()=>c(cc,{variant:"drawer",isOpen:le,onClose:I,sessions:Re,activeSessionId:p,onSelectSession:Pe,onNewChat:De,isLoading:te}),[le,I,Re,p,Pe,De,te]);return c(Um,{enabled:!!n.resize,children:c(oc,{value:Ue,children:c(ac,{isOpen:e,feedbackModal:K,consentModal:Ae,sessionId:p,environment:n.environment,mode:o,sidePanelMode:xt,sidePanelWidth:$t,side:z,onSidePanelPushChange:Ie,theme:n.theme,isAuthComponent:f,activeElicitation:_,voiceAgentState:B,chatComposer:N,sessionDrawer:Et,sidebar:Le,fullScreenEmptyState:E?ht=>c(yp,{title:n.title,description:k?.text,suggestions:k?.suggestions,onSendMessage:ae,disabled:P,composer:ht.composer,composerFooter:ht.composerFooter,connectionBanner:c(Wc,{...qe})}):void 0,children:he?c(Xe,{fallback:c(Kc,{}),children:c(Cg,{state:B,isMuted:G,onEndCall:pe,onClose:se,onToggleMute:Ee,agentName:n.title,iconUrl:n.iconUrl,textColor:n.theme?.textColor})}):c(Xe,{fallback:c(Kc,{}),children:c("div",{className:L("flex-1 flex flex-col min-h-0 overflow-hidden relative synapse-chat-window"),children:[c("div",{className:"relative flex min-h-0 flex-1 flex-col overflow-hidden",children:c(dl,{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:[c("div",{className:"flex-1"}),c("div",{className:L("min-w-0 overflow-x-hidden",b?"pt-4 px-4 space-y-3":"pt-4 px-4 space-y-4",o==="full"&&"max-w-2xl mx-auto w-full"),children:[y?c(wm,{}):c(me,{children:[m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center mb-2",children:"Just now"}),!m&&c("div",{className:"text-xs text-[var(--color-muted-foreground)] text-center",children:we}),c(xg,{messages:x,onSendMessage:He,onToggleFeedback:T,onClearElicitationState:C,isAuthComponent:f,isFullScreen:o==="full",initialMessage:k??n.initialMessage,disabled:!g})]}),c("div",{ref:s})]})]})}),a&&c("div",{className:"absolute bottom-[10px] left-1/2 transform -translate-x-1/2 z-10",children:c(Se,{onClick:()=>v("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:c(Wo,{className:"w-5 h-5 text-text-primary"})})}),c(Wc,{className:"mt-2",...qe})]})})})})})}function Kc(){return c("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden bg-surface backdrop-blur-2xl animate-pulse",children:[c("div",{className:"flex-1 p-6 space-y-4",children:[c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"}),c("div",{className:"h-16 bg-surface/80 rounded-2xl border border-border-subtle/50"})]}),c("div",{className:"h-24 border-t border-border-subtle bg-surface/80"})]})}function qc(e){return!!e&&e.startsWith("ResizeObserver loop")}function ws(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 Og extends ct{constructor(){super(...arguments);R(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:ws(n)}}componentDidCatch(n,r){this.setState({componentStack:r?.componentStack})}render(){return this.state.error?c(Ig,{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 Rg({error:e}){throw e}function Ag(e){const[t,n]=F(null);return Y(()=>{if(typeof window>"u")return;const r=i=>{!i?.error&&!i?.filename&&i?.message==="Script error."||qc(i?.message)||qc(i?.error?.message)||(i?.error?n(ws(i.error)):i?.message&&n(new Error(i.message)))},o=i=>{n(ws(i.reason))};return window.addEventListener("error",r),window.addEventListener("unhandledrejection",o),()=>{window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",o)}},[]),c(Og,{...e,children:t?c(Rg,{error:t}):e.children})}function Ig({error:e,title:t,titleImg:n,iconUrl:r,onClose:o,showCloseButton:i,environment:s,displayMode:a,theme:l}){const d=()=>{typeof window<"u"&&window.location.reload()},h=t??"Medi Clinic",u=s??"production",p=ie(()=>l?.textColor==="white"?"text-white/60":"text-[var(--color-muted-foreground)]",[l?.textColor]),_=ie(()=>({onClose:o??(()=>{}),showCloseButton:i??!1,title:h,titleImg:n,iconUrl:r,onStartNewSession:d}),[o,i,h,n,r]);return c(oc,{value:_,children:c(ac,{isOpen:!0,environment:u,mode:a??"widget",theme:l,children:c("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:c("div",{className:"flex-1 min-h-0 flex items-center justify-center p-6",children:c("div",{className:"w-full max-w-[320px] text-center",children:[c("div",{className:"mx-auto mb-4 grid place-items-center",children:c("div",{className:"h-16 w-16 rounded-3xl bg-surface backdrop-blur border border-border-subtle grid place-items-center",children:c(zh,{className:"h-8 w-8",style:{color:l?.primary??"hsl(var(--primary))"}})})}),c("div",{className:"text-2xl font-semibold text-text-primary",children:"Uh-oh!"}),c("div",{className:["mt-2 text-sm",p].join(" "),children:"Something went wrong. Please try again."}),c("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",p].join(" "),children:e?.message||String(e)}),c("div",{className:"mt-5 flex items-center justify-center gap-3",children:c(Se,{type:"button",onClick:d,className:"rounded-2xl",style:{backgroundColor:l?.primary??void 0},children:[c(Lh,{className:"h-4 w-4 mr-2"}),"Retry"]})})]})})})})})}function Mg({agentId:e,config:t}){const[n,r]=F(t.displayMode==="full");Y(()=>{r(!0)},[]);const o=()=>{r(!1),t?.onClose?.()};return c(Ag,{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:c(rm,{children:c(kg,{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 Xc=(e,t,n)=>{const r=n||{},o=wd(e);return o.render(c(me,{children:c(Mg,{agentId:t,config:r})})),o},Pg=e=>{try{const t=sessionStorage.getItem(ur(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{}}},Zc=e=>{const{refreshToken:t,sessToken:n}=Pg(e.agentId);return t&&n?Promise.resolve(null):M.prefetchTokenExchange({...e,refreshToken:t,sessToken:n})},Jc=e=>M.prefetchAgentConfig(e);typeof window<"u"&&(window.renderMedAssist=Xc,window.fetchAgentConfig=Jc,window.prefetchAuth=Zc);export{X as A,Se as B,Wo as C,ee as D,El as F,yl as I,Ko as M,Xt as N,pn as P,Oo as R,cs as S,ie as T,Tn as X,ft as _,M as a,L as b,Ye as c,F as d,me as e,Zt as f,Jc as fetchAgentConfig,bi as g,fn as h,Vt as i,zt as j,vp as k,Cl as l,ss as m,ql as n,is as o,bp as p,Zc as prefetchAuth,de as q,Ol as r,Xc as renderMedAssist,Zr as s,mc as t,c as u,en as v,wp as w,kl as x,Y as y,Rl as z};
|