@evelan/jexity-widget 0.11.0 → 0.11.1

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/widget.js CHANGED
@@ -1,8 +1,8 @@
1
- (function(){"use strict";var Me,x,Mn,Ln,ue,On,Nn,zn,Bn,qt,Mt,Lt,Qn,Le={},Fn=[],Zi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Oe=Array.isArray;function K(t,e){for(var n in e)t[n]=e[n];return t}function Ot(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function B(t,e,n){var r,i,s,o={};for(s in e)s=="key"?r=e[s]:s=="ref"?i=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?Me.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return Ne(t,o,r,i,null)}function Ne(t,e,n,r,i){var s={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Mn,__i:-1,__u:0};return i==null&&x.vnode!=null&&x.vnode(s),s}function Yi(){return{current:null}}function N(t){return t.children}function V(t,e){this.props=t,this.context=e}function _e(t,e){if(e==null)return t.__?_e(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?_e(t):null}function Dn(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Dn(t)}}function Nt(t){(!t.__d&&(t.__d=!0)&&ue.push(t)&&!at.__r++||On!=x.debounceRendering)&&((On=x.debounceRendering)||Nn)(at)}function at(){for(var t,e,n,r,i,s,o,l=1;ue.length;)ue.length>l&&ue.sort(zn),t=ue.shift(),l=ue.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,s=[],o=[],e.__P&&((n=K({},r)).__v=r.__v+1,x.vnode&&x.vnode(n),zt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,s,i??_e(r),!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Jn(s,n,o),r.__e=r.__=null,n.__e!=i&&Dn(n)));at.__r=0}function Un(t,e,n,r,i,s,o,l,a,c,d){var h,f,p,g,m,b,_,v=r&&r.__k||Fn,E=e.length;for(a=Xi(n,e,v,a,E),h=0;h<E;h++)(p=n.__k[h])!=null&&(f=p.__i==-1?Le:v[p.__i]||Le,p.__i=h,b=zt(t,p,f,i,s,o,l,a,c,d),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&Qt(f.ref,null,p),d.push(p.ref,p.__c||g,p)),m==null&&g!=null&&(m=g),(_=!!(4&p.__u))||f.__k===p.__k?a=Vn(p,a,t,_):typeof p.type=="function"&&b!==void 0?a=b:g&&(a=g.nextSibling),p.__u&=-7);return n.__e=m,a}function Xi(t,e,n,r,i){var s,o,l,a,c,d=n.length,h=d,f=0;for(t.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(a=s+f,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Ne(null,o,null,null,null):Oe(o)?Ne(N,{children:o},null,null,null):o.constructor==null&&o.__b>0?Ne(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,l=null,(c=o.__i=es(o,n,a,h))!=-1&&(h--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(i>d?f--:i<d&&f++),typeof o.type!="function"&&(o.__u|=4)):c!=a&&(c==a-1?f--:c==a+1?f++:(c>a?f--:f++,o.__u|=4))):t.__k[s]=null;if(h)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=_e(l)),Kn(l,l));return r}function Vn(t,e,n,r){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Vn(i[s],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=_e(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Z(t,e){return e=e||[],t==null||typeof t=="boolean"||(Oe(t)?t.some(function(n){Z(n,e)}):e.push(t)),e}function es(t,e,n,r){var i,s,o,l=t.key,a=t.type,c=e[n],d=c!=null&&(2&c.__u)==0;if(c===null&&t.key==null||d&&l==c.key&&a==c.type)return n;if(r>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<e.length;)if((c=e[o=i>=0?i--:s++])!=null&&(2&c.__u)==0&&l==c.key&&a==c.type)return o}return-1}function Wn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Zi.test(e)?n:n+"px"}function lt(t,e,n,r,i){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof r=="string"&&(t.style.cssText=r=""),r)for(e in r)n&&e in n||Wn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Wn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Bn,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?r?n.u=r.u:(n.u=qt,t.addEventListener(e,s?Lt:Mt,s)):t.removeEventListener(e,s?Lt:Mt,s);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Hn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=qt++;else if(e.t<n.u)return;return n(x.event?x.event(e):e)}}}function zt(t,e,n,r,i,s,o,l,a,c){var d,h,f,p,g,m,b,_,v,E,U,ce,G,Ki,Pt,ot,In,ne=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),s=[l=e.__e=n.__e]),(d=x.__b)&&d(e);e:if(typeof ne=="function")try{if(_=e.props,v="prototype"in ne&&ne.prototype.render,E=(d=ne.contextType)&&r[d.__c],U=d?E?E.props.value:d.__:r,n.__c?b=(h=e.__c=n.__c).__=h.__E:(v?e.__c=h=new ne(_,U):(e.__c=h=new V(_,U),h.constructor=ne,h.render=ns),E&&E.sub(h),h.props=_,h.state||(h.state={}),h.context=U,h.__n=r,f=h.__d=!0,h.__h=[],h._sb=[]),v&&h.__s==null&&(h.__s=h.state),v&&ne.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=K({},h.__s)),K(h.__s,ne.getDerivedStateFromProps(_,h.__s))),p=h.props,g=h.state,h.__v=e,f)v&&ne.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),v&&h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(v&&ne.getDerivedStateFromProps==null&&_!==p&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(_,U),!h.__e&&h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(_,h.__s,U)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(h.props=_,h.state=h.__s,h.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(qe){qe&&(qe.__=e)}),ce=0;ce<h._sb.length;ce++)h.__h.push(h._sb[ce]);h._sb=[],h.__h.length&&o.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(_,h.__s,U),v&&h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(p,g,m)})}if(h.context=U,h.props=_,h.__P=t,h.__e=!1,G=x.__r,Ki=0,v){for(h.state=h.__s,h.__d=!1,G&&G(e),d=h.render(h.props,h.state,h.context),Pt=0;Pt<h._sb.length;Pt++)h.__h.push(h._sb[Pt]);h._sb=[]}else do h.__d=!1,G&&G(e),d=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++Ki<25);h.state=h.__s,h.getChildContext!=null&&(r=K(K({},r),h.getChildContext())),v&&!f&&h.getSnapshotBeforeUpdate!=null&&(m=h.getSnapshotBeforeUpdate(p,g)),ot=d,d!=null&&d.type===N&&d.key==null&&(ot=Gn(d.props.children)),l=Un(t,Oe(ot)?ot:[ot],e,n,r,i,s,o,l,a,c),h.base=e.__e,e.__u&=-161,h.__h.length&&o.push(h),b&&(h.__E=h.__=null)}catch(qe){if(e.__v=null,a||s!=null)if(qe.then){for(e.__u|=a?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,e.__e=l}else{for(In=s.length;In--;)Ot(s[In]);Bt(e)}else e.__e=n.__e,e.__k=n.__k,qe.then||Bt(e);x.__e(qe,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=ts(n.__e,e,n,r,i,s,o,a,c);return(d=x.diffed)&&d(e),128&e.__u?void 0:l}function Bt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Bt)}function Jn(t,e,n){for(var r=0;r<n.length;r++)Qt(n[r],n[++r],n[++r]);x.__c&&x.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(s){s.call(i)})}catch(s){x.__e(s,i.__v)}})}function Gn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Oe(t)?t.map(Gn):K({},t)}function ts(t,e,n,r,i,s,o,l,a){var c,d,h,f,p,g,m,b=n.props,_=e.props,v=e.type;if(v=="svg"?i="http://www.w3.org/2000/svg":v=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((p=s[c])&&"setAttribute"in p==!!v&&(v?p.localName==v:p.nodeType==3)){t=p,s[c]=null;break}}if(t==null){if(v==null)return document.createTextNode(_);t=document.createElementNS(i,v,_.is&&_),l&&(x.__m&&x.__m(e,s),l=!1),s=null}if(v==null)b===_||l&&t.data==_||(t.data=_);else{if(s=s&&Me.call(t.childNodes),b=n.props||Le,!l&&s!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")h=p;else if(!(c in _)){if(c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _)continue;lt(t,c,null,p,i)}}for(c in _)p=_[c],c=="children"?f=p:c=="dangerouslySetInnerHTML"?d=p:c=="value"?g=p:c=="checked"?m=p:l&&typeof p!="function"||b[c]===p||lt(t,c,p,b[c],i);if(d)l||h&&(d.__html==h.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(h&&(t.innerHTML=""),Un(e.type=="template"?t.content:t,Oe(f)?f:[f],e,n,r,v=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:n.__k&&_e(n,0),l,a),s!=null)for(c=s.length;c--;)Ot(s[c]);l||(c="value",v=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[c]||v=="progress"&&!g||v=="option"&&g!=b[c])&&lt(t,c,g,b[c],i),c="checked",m!=null&&m!=t[c]&&lt(t,c,m,b[c],i))}return t}function Qt(t,e,n){try{if(typeof t=="function"){var r=typeof t.__u=="function";r&&t.__u(),r&&e==null||(t.__u=t(e))}else t.current=e}catch(i){x.__e(i,n)}}function Kn(t,e,n){var r,i;if(x.unmount&&x.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Qt(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(s){x.__e(s,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&Kn(r[i],e,n||typeof t.type!="function");n||Ot(t.__e),t.__c=t.__=t.__e=void 0}function ns(t,e,n){return this.constructor(t,n)}function he(t,e,n){var r,i,s,o;e==document&&(e=document.documentElement),x.__&&x.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],zt(e,t=(!r&&n||e).__k=B(N,null,[t]),i||Le,Le,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?Me.call(e.childNodes):null,s,!r&&n?n:i?i.__e:e.firstChild,r,o),Jn(s,t,o)}function Zn(t,e){he(t,e,Zn)}function rs(t,e,n){var r,i,s,o,l=K({},t.props);for(s in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)s=="key"?r=e[s]:s=="ref"?i=e[s]:l[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?Me.call(arguments,2):n),Ne(t.type,l,r||t.key,i||t.ref,null)}function is(t){function e(n){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&r.forEach(function(o){o.__e=!0,Nt(o)})},this.sub=function(s){r.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){r&&r.delete(s),o&&o.call(s)}}),n.children}return e.__c="__cC"+Qn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}Me=Fn.slice,x={__e:function(t,e,n,r){for(var i,s,o;e=e.__;)if((i=e.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(t)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),o=i.__d),o)return i.__E=i}catch(l){t=l}throw t}},Mn=0,Ln=function(t){return t!=null&&t.constructor==null},V.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=K({},this.state),typeof t=="function"&&(t=t(K({},n),this.props)),t&&K(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Nt(this))},V.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Nt(this))},V.prototype.render=N,ue=[],Nn=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,zn=function(t,e){return t.__v.__b-e.__v.__b},at.__r=0,Bn=/(PointerCapture)$|Capture$/i,qt=0,Mt=Hn(!1),Lt=Hn(!0),Qn=0;var ss=0;function u(t,e,n,r,i,s){e||(e={});var o,l,a=e;if("ref"in a)for(l in a={},e)l=="ref"?o=e[l]:a[l]=e[l];var c={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ss,__i:-1,__u:0,__source:i,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)a[l]===void 0&&(a[l]=o[l]);return x.vnode&&x.vnode(c),c}var se,S,Ft,Yn,we=0,Xn=[],j=x,er=j.__b,tr=j.__r,nr=j.diffed,rr=j.__c,ir=j.unmount,sr=j.__;function ke(t,e){j.__h&&j.__h(S,t,we||e),we=0;var n=S.__H||(S.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return we=1,Dt(ur,t)}function Dt(t,e,n){var r=ke(se++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):ur(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,l);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=S,!S.__f)){var i=function(l,a,c){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!s||s.call(this,l,a,c);var h=r.__c.props!==l;return d.forEach(function(f){if(f.__N){var p=f.__[0];f.__=f.__N,f.__N=void 0,p!==f.__[0]&&(h=!0)}}),s&&s.call(this,l,a,c)||h};S.__f=!0;var s=S.shouldComponentUpdate,o=S.componentWillUpdate;S.componentWillUpdate=function(l,a,c){if(this.__e){var d=s;s=void 0,i(l,a,c),s=d}o&&o.call(this,l,a,c)},S.shouldComponentUpdate=i}return r.__N||r.__}function $(t,e){var n=ke(se++,3);!j.__s&&Vt(n.__H,e)&&(n.__=t,n.u=e,S.__H.__h.push(n))}function ze(t,e){var n=ke(se++,4);!j.__s&&Vt(n.__H,e)&&(n.__=t,n.u=e,S.__h.push(n))}function de(t){return we=5,Q(function(){return{current:t}},[])}function or(t,e,n){we=6,ze(function(){if(typeof t=="function"){var r=t(e());return function(){t(null),r&&typeof r=="function"&&r()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function Q(t,e){var n=ke(se++,7);return Vt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Se(t,e){return we=8,Q(function(){return t},e)}function ct(t){var e=S.context[t.__c],n=ke(se++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(S)),e.props.value):t.__}function ar(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function lr(){var t=ke(se++,11);if(!t.__){for(var e=S.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function os(){for(var t;t=Xn.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ut),t.__H.__h.forEach(Ut),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){S=null,er&&er(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),sr&&sr(t,e)},j.__r=function(t){tr&&tr(t),se=0;var e=(S=t.__c).__H;e&&(Ft===S?(e.__h=[],S.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ut),e.__h.forEach(Ut),e.__h=[],se=0)),Ft=S},j.diffed=function(t){nr&&nr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Xn.push(e)!==1&&Yn===j.requestAnimationFrame||((Yn=j.requestAnimationFrame)||as)(os)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ft=S=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ut),n.__h=n.__h.filter(function(r){return!r.__||Ut(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),rr&&rr(t,e)},j.unmount=function(t){ir&&ir(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{ut(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var cr=typeof requestAnimationFrame=="function";function as(t){var e,n=function(){clearTimeout(r),cr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);cr&&(e=requestAnimationFrame(n))}function ut(t){var e=S,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),S=e}function Ut(t){var e=S;t.__c=t.__(),S=e}function Vt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function ur(t,e){return typeof e=="function"?e(t):e}function hr(t,e){for(var n in e)t[n]=e[n];return t}function Wt(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var r in e)if(r!=="__source"&&t[r]!==e[r])return!0;return!1}function dr(t,e){var n=e(),r=C({t:{__:n,u:e}}),i=r[0].t,s=r[1];return ze(function(){i.__=n,i.u=e,Ht(i)&&s({t:i})},[t,n,e]),$(function(){return Ht(i)&&s({t:i}),t(function(){Ht(i)&&s({t:i})})},[t]),n}function Ht(t){var e,n,r=t.u,i=t.__;try{var s=r();return!((e=i)===(n=s)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function fr(t){t()}function pr(t){return t}function gr(){return[!1,fr]}var mr=ze;function Jt(t,e){this.props=t,this.context=e}function ls(t,e){function n(i){var s=this.props.ref,o=s==i.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,i)||!o:Wt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,B(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Jt.prototype=new V).isPureReactComponent=!0,Jt.prototype.shouldComponentUpdate=function(t,e){return Wt(this.props,t)||Wt(this.state,e)};var xr=x.__b;x.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),xr&&xr(t)};var cs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function us(t){function e(n){var r=hr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=cs,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var br=function(t,e){return t==null?null:Z(Z(t).map(e))},hs={map:br,forEach:br,count:function(t){return t?Z(t).length:0},only:function(t){var e=Z(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Z},ds=x.__e;x.__e=function(t,e,n,r){if(t.then){for(var i,s=e;s=s.__;)if((i=s.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}ds(t,e,n,r)};var yr=x.unmount;function vr(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),t.__c.__H=null),(t=hr({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(r){return vr(r,e,n)})),t}function _r(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return _r(r,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function ht(){this.__u=0,this.o=null,this.__b=null}function wr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function fs(t){var e,n,r;function i(s){if(e||(e=t()).then(function(o){n=o.default||o},function(o){r=o}),r)throw r;if(!n)throw e;return B(n,s)}return i.displayName="Lazy",i.__f=!0,i}function Be(){this.i=null,this.l=null}x.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),yr&&yr(t)},(ht.prototype=new V).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=wr(r.__v),s=!1,o=function(){s||(s=!0,n.__R=null,i?i(l):l())};n.__R=o;var l=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=_r(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(o,o)},ht.prototype.componentWillUnmount=function(){this.o=[]},ht.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=vr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&B(N,null,t.fallback);return i&&(i.__u&=-33),[B(N,null,e.__a?null:t.children),i]};var kr=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function ps(t){return this.getChildContext=function(){return t.context},t.children}function gs(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){he(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var r=e.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},insertBefore:function(i,s){this.childNodes.push(i),e.h.insertBefore(i,s)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}he(B(ps,{context:e.context},t.__v),e.v)}function ms(t,e){var n=B(gs,{__v:t,h:e});return n.containerInfo=e,n}(Be.prototype=new V).__a=function(t){var e=this,n=wr(e.__v),r=e.l.get(t);return r[0]++,function(i){var s=function(){e.props.revealOrder?(r.push(i),kr(e,t,r)):i()};n?n(s):s()}},Be.prototype.render=function(t){this.i=null,this.l=new Map;var e=Z(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Be.prototype.componentDidUpdate=Be.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){kr(t,n,e)})};var Sr=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,xs=/^(?: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]/,bs=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ys=/[A-Z0-9]/g,vs=typeof document<"u",_s=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function ws(t,e,n){return e.__k==null&&(e.textContent=""),he(t,e),typeof n=="function"&&n(),t?t.__c:null}function ks(t,e,n){return Zn(t,e),typeof n=="function"&&n(),t?t.__c:null}V.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(V.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var jr=x.event;function Ss(){}function js(){return this.cancelBubble}function Cs(){return this.defaultPrevented}x.event=function(t){return jr&&(t=jr(t)),t.persist=Ss,t.isPropagationStopped=js,t.isDefaultPrevented=Cs,t.nativeEvent=t};var Gt,Ts={enumerable:!1,configurable:!0,get:function(){return this.class}},Cr=x.vnode;x.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},s=r.indexOf("-")===-1;for(var o in n){var l=n[o];if(!(o==="value"&&"defaultValue"in n&&l==null||vs&&o==="children"&&r==="noscript"||o==="class"||o==="className")){var a=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&l===!0?l="":a==="translate"&&l==="no"?l=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?o="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||_s(n.type)?a==="onfocus"?o="onfocusin":a==="onblur"?o="onfocusout":bs.test(o)&&(o=a):a=o="oninput":s&&xs.test(o)?o=o.replace(ys,"-$&").toLowerCase():l===null&&(l=void 0),a==="oninput"&&i[o=a]&&(o="oninputCapture"),i[o]=l}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=Z(n.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=Z(n.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",Ts)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=Sr,Cr&&Cr(t)};var Tr=x.__r;x.__r=function(t){Tr&&Tr(t),Gt=t.__c};var Rr=x.diffed;x.diffed=function(t){Rr&&Rr(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Gt=null};var Rs={ReactCurrentDispatcher:{current:{readContext:function(t){return Gt.__n[t.__c].props.value},useCallback:Se,useContext:ct,useDebugValue:ar,useDeferredValue:pr,useEffect:$,useId:lr,useImperativeHandle:or,useInsertionEffect:mr,useLayoutEffect:ze,useMemo:Q,useReducer:Dt,useRef:de,useState:C,useSyncExternalStore:dr,useTransition:gr}}};function $s(t){return B.bind(null,t)}function dt(t){return!!t&&t.$$typeof===Sr}function As(t){return dt(t)&&t.type===N}function Es(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function Is(t){return dt(t)?rs.apply(null,arguments):t}function Ps(t){return!!t.__k&&(he(null,t),!0)}function qs(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var Ms=function(t,e){return t(e)},Ls=function(t,e){return t(e)},Os=N,Ns=dt,Kt={useState:C,useId:lr,useReducer:Dt,useEffect:$,useLayoutEffect:ze,useInsertionEffect:mr,useTransition:gr,useDeferredValue:pr,useSyncExternalStore:dr,startTransition:fr,useRef:de,useImperativeHandle:or,useMemo:Q,useCallback:Se,useContext:ct,useDebugValue:ar,version:"18.3.1",Children:hs,render:ws,hydrate:ks,unmountComponentAtNode:Ps,createPortal:ms,createElement:B,createContext:is,createFactory:$s,cloneElement:Is,createRef:Yi,Fragment:N,isValidElement:dt,isElement:Ns,isFragment:As,isMemo:Es,findDOMNode:qs,Component:V,PureComponent:Jt,memo:ls,forwardRef:us,flushSync:Ls,unstable_batchedUpdates:Ms,StrictMode:Os,Suspense:ht,SuspenseList:Be,lazy:fs,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Rs},Y=[],F=[],zs=Uint8Array,Zt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",je=0,Bs=Zt.length;je<Bs;++je)Y[je]=Zt[je],F[Zt.charCodeAt(je)]=je;F[45]=62,F[95]=63;function Qs(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Fs(t,e,n){return(e+n)*3/4-n}function Qe(t){var e,n=Qs(t),r=n[0],i=n[1],s=new zs(Fs(t,r,i)),o=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=F[t.charCodeAt(a)]<<18|F[t.charCodeAt(a+1)]<<12|F[t.charCodeAt(a+2)]<<6|F[t.charCodeAt(a+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=F[t.charCodeAt(a)]<<2|F[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=F[t.charCodeAt(a)]<<10|F[t.charCodeAt(a+1)]<<4|F[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ds(t){return Y[t>>18&63]+Y[t>>12&63]+Y[t>>6&63]+Y[t&63]}function Us(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Ds(r));return i.join("")}function Fe(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,l=n-r;o<l;o+=s)i.push(Us(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(Y[e>>2]+Y[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(Y[e>>10]+Y[e>>4&63]+Y[e<<2&63]+"=")),i.join("")}function re(t){if(t===void 0)return{};if(!$r(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function Vs(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function $r(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const Ar=!0,Ce=BigInt("-9223372036854775808"),Yt=BigInt("9223372036854775807"),Xt=BigInt("0"),Ws=BigInt("8"),Hs=BigInt("256");function Er(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Js(t){t<Xt&&(t-=Ce+Ce);let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new Uint8Array(new ArrayBuffer(8));let r=0;for(const i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=Ws;return Fe(n)}function Gs(t){const e=Qe(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Xt,r=Xt;for(const i of e)n+=BigInt(i)*Hs**r,r++;return n>Yt&&(n+=Ce+Ce),n}function Ks(t){if(t<Ce||Yt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);const e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),Fe(new Uint8Array(e))}function Zs(t){const e=Qe(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}const Ys=DataView.prototype.setBigInt64?Ks:Js,Xs=DataView.prototype.getBigInt64?Zs:Gs,Ir=1024;function Pr(t){if(t.length>Ir)throw new Error(`Field name ${t} exceeds maximum field name length ${Ir}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){const n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}function Te(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Te(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);const e=Object.entries(t);if(e.length===1){const r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return Qe(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return Xs(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=Qe(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const o=new DataView(i.buffer).getFloat64(0,Ar);if(!Er(o))throw new Error(`Float ${o} should be encoded as a number`);return o}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,i]of Object.entries(t))Pr(r),n[r]=Te(i);return n}const qr=16384;function De(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>qr){const n="[...truncated]";let r=qr-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function en(t,e,n,r){if(t===void 0){const o=n&&` (present at path ${n} in original object ${De(e)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<Ce||Yt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Ys(t)}}if(typeof t=="number")if(Er(t)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,t,Ar),{$float:Fe(new Uint8Array(o))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:Fe(new Uint8Array(t))};if(Array.isArray(t))return t.map((o,l)=>en(o,e,n+`[${l}]`));if(t instanceof Set)throw new Error(tn(n,"Set",[...t],e));if(t instanceof Map)throw new Error(tn(n,"Map",[...t],e));if(!$r(t)){const o=t?.constructor?.name,l=o?`${o} `:"";throw new Error(tn(n,l,t,e))}const i={},s=Object.entries(t);s.sort(([o,l],[a,c])=>o===a?0:o<a?-1:1);for(const[o,l]of s)l!==void 0&&(Pr(o),i[o]=en(l,e,n+`.${o}`));return i}function tn(t,e,n,r){return t?`${e}${De(n)} is not a supported Convex type (present at path ${t} in original object ${De(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${De(n)} is not a supported Convex type.`}function X(t){return en(t,t,"")}var eo=Object.defineProperty,to=(t,e,n)=>e in t?eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nn=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n),Mr,Lr;const no=Symbol.for("ConvexError");class rn extends(Lr=Error,Mr=no,Lr){constructor(e){super(typeof e=="string"?e:De(e)),nn(this,"name","ConvexError"),nn(this,"data"),nn(this,Mr,!0),this.data=e}}const Or=()=>Array.from({length:4},()=>0);Or(),Or();const Nr="1.38.0";var ro=Object.defineProperty,io=(t,e,n)=>e in t?ro(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zr=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);const so="color:rgb(0, 145, 255)";function Br(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Qr{constructor(e){zr(this,"_onLogLineFuncs"),zr(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(const n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(const n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(const n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(const n of Object.values(this._onLogLineFuncs))n("error",...e)}}function Fr(t){const e=new Qr(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}function Dr(t){return new Qr(t)}function ft(t,e,n,r,i){const s=Br(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const o=i.match(/^\[.*?\] /);if(o===null){t.error(`[CONVEX ${s}(${r})] Could not parse console.log`);return}const l=i.slice(1,o[0].length-2),a=i.slice(o[0].length);t.log(`%c[CONVEX ${s}(${r})] [${l}]`,so,a)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}function oo(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Re(t,e,n){return`[CONVEX ${Br(t)}(${e})] ${n.errorMessage}
2
- Called by client`}function sn(t,e){return e.data=t.errorData,e}function fe(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function pe(t,e){return JSON.stringify({udfPath:fe(t),args:X(e)})}function Ur(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:fe(t),args:X(e),options:X({initialNumItems:r,id:i})})}var ao=Object.defineProperty,lo=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ee=(t,e,n)=>lo(t,typeof e!="symbol"?e+"":e,n);class co{constructor(){ee(this,"nextQueryId"),ee(this,"querySetVersion"),ee(this,"querySet"),ee(this,"queryIdToToken"),ee(this,"identityVersion"),ee(this,"auth"),ee(this,"outstandingQueriesOlderThanRestart"),ee(this,"outstandingAuthOlderThanRestart"),ee(this,"paused"),ee(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const s=fe(e),o=pe(s,n),l=this.querySet.get(o);if(l!==void 0)return l.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{const a=this.nextQueryId++,c={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,c),this.queryIdToToken.set(a,o);const d=this.querySetVersion,h=this.querySetVersion+1,f={type:"Add",queryId:a,udfPath:s,args:[X(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,f):this.querySetVersion=h,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:h,modifications:[f]},unsubscribe:()=>this.removeSubscriber(o)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=fe(e),i=pe(r,n),s=this.querySet.get(i);return s!==void 0?s.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const e=[];for(const i of this.querySet.values()){const s={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[X(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(s),this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const n={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[n,void 0];this.outstandingAuthOlderThanRestart=!0;const r={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[n,r]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,s={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,s):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[s]}}}}var uo=Object.defineProperty,ho=(t,e,n)=>e in t?uo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pt=(t,e,n)=>ho(t,typeof e!="symbol"?e+"":e,n);class fo{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,pt(this,"inflightRequests"),pt(this,"requestsOlderThanRestart"),pt(this,"inflightMutationsCount",0),pt(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const s=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:s,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const a of e.logLines)ft(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:Te(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:c}=e;ft(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:c!==void 0?Te(c):void 0,logLines:e.logLines},l=()=>s.onResult(o)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:o}):(n.status={status:"Completed",result:o,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const s=i.status;s.status==="Completed"&&s.ts.lessThanOrEqual(e)&&(s.onResolve(),n.set(r,s.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Ue=Symbol.for("functionName"),Vr=Symbol.for("toReferencePath");function po(t){return t[Vr]??null}function go(t){return t.startsWith("function://")}function mo(t){let e;if(typeof t=="string")go(t)?e={functionHandle:t}:e={name:t};else if(t[Ue])e={name:t[Ue]};else{const n=po(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function M(t){const e=mo(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Ue];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Wr(t){return{[Ue]:t}}function Hr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Hr(i)}else if(r===Ue){if(t.length<2){const o=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${o}\``)}const i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const xo=Hr();var bo=Object.defineProperty,yo=(t,e,n)=>e in t?bo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gt=(t,e,n)=>yo(t,typeof e!="symbol"?e+"":e,n);class Ve{constructor(e){gt(this,"queryResults"),gt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=re(n[0]),i=M(e),s=this.queryResults.get(pe(i,r));if(s!==void 0)return Ve.queryValue(s.result)}getAllQueries(e){const n=[],r=M(e);for(const i of this.queryResults.values())i.udfPath===fe(r)&&n.push({args:i.args,value:Ve.queryValue(i.result)});return n}setQuery(e,n,r){const i=re(n),s=M(e),o=pe(s,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:s,args:i,result:l};this.queryResults.set(o,a),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class vo{constructor(){gt(this,"queryResults"),gt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(o=>!n.has(o.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new Ve(this.queryResults);for(const o of this.optimisticUpdates)o.update(i);const s=[];for(const[o,l]of this.queryResults){const a=r.get(o);(a===void 0||a.result!==l.result)&&s.push(o)}return s}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Ve(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){const n=this.queryResults.get(e);if(n!==void 0)return n.result}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?sn(r,new rn(Re("query",n.udfPath,r))):new Error(Re("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var _o=Object.defineProperty,wo=(t,e,n)=>e in t?_o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,on=(t,e,n)=>wo(t,typeof e!="symbol"?e+"":e,n);class L{constructor(e,n){on(this,"low"),on(this,"high"),on(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new L(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?Jr:e>=ko?So:new L(e%We|0,e/We|0)}toString(){return(BigInt(this.high)*BigInt(We)+BigInt(this.low)).toString()}equals(e){return L.isLong(e)||(e=L.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return L.isLong(e)||(e=L.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?L.fromNumber(e):new L(e.low,e.high)}}const Jr=new L(0,0),Gr=65536,We=Gr*Gr,ko=We*We,So=new L(-1,-1);var jo=Object.defineProperty,Co=(t,e,n)=>e in t?jo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mt=(t,e,n)=>Co(t,typeof e!="symbol"?e+"":e,n);class Kr{constructor(e,n){mt(this,"version"),mt(this,"remoteQuerySet"),mt(this,"queryPath"),mt(this,"logger"),this.version={querySet:0,ts:L.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ft(this.logger,"info","query",i,o);const s=Te(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:s,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ft(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?Te(s):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function an(t){const e=Qe(t);return L.fromBytesLE(Array.from(e))}function To(t){const e=new Uint8Array(t.toBytesLE());return Fe(e)}function Zr(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:an(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:an(t.startVersion.ts)},endVersion:{...t.endVersion,ts:an(t.endVersion.ts)}}}}function Ro(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:To(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var $o=Object.defineProperty,Ao=(t,e,n)=>e in t?$o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,T=(t,e,n)=>Ao(t,typeof e!="symbol"?e+"":e,n);const Eo=1e3,Io=1001,Po=1005,qo=4040;let xt;function $e(){return xt===void 0&&(xt=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(xt+performance.now())}function Yr(){return`t=${Math.round(($e()-xt)/100)/10}s`}const Xr={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Mo(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Xr))if(t.startsWith(e))return e;return"Unknown"}class Lo{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,T(this,"socket"),T(this,"connectionCount"),T(this,"_hasEverConnected",!1),T(this,"lastCloseReason"),T(this,"transitionChunkBuffer",null),T(this,"defaultInitialBackoff"),T(this,"maxBackoff"),T(this,"retries"),T(this,"serverInactivityThreshold"),T(this,"reconnectDueToServerInactivityTimeout"),T(this,"scheduledReconnect",null),T(this,"networkOnlineHandler",null),T(this,"pendingNetworkRecoveryInfo",null),T(this,"uri"),T(this,"onOpen"),T(this,"onResume"),T(this,"onMessage"),T(this,"webSocketConstructor"),T(this,"logger"),T(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=Zr(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:$e()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Yr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Yr())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){const{timeSavedMs:n}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:n}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(n/1e3)}s of waiting`)}},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let i=Zr(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const o=this.assembleTransition(i);if(!o)return;i=o,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==Eo&&n.code!==Io&&n.code!==Po&&n.code!==qo){let i=`WebSocket closed with code ${n.code}`;n.reason&&(i+=`: ${n.reason}`),this.logger.log(i),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(i)}const r=Mo(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=Ro(e),i=JSON.stringify(r);let s=!1;try{this.socket.ws.send(i),s=!0}catch(o){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${o}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${s?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=$e(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},n);this.scheduledReconnect={timeout:i,scheduledAt:r,backoffMs:n}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){const n=$e()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-n),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(n)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=e!==null?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:$e()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:Xr[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),s=i*(Math.random()-.5);return i+s}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=$e()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,s=`${Math.round(n/1e4)/100}MB`,o=n/(r/1e3),l=`${Math.round(o/1e4)/100}MB per second`;this._logVerbose(`received ${s} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${s}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${s} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function Oo(){return No()}function No(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class He extends Error{}He.prototype.name="InvalidTokenError";function zo(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function Bo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return zo(e)}catch{return atob(e)}}function ei(t,e){if(typeof t!="string")throw new He("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new He(`Invalid token specified: missing part #${n+1}`);let i;try{i=Bo(r)}catch(s){throw new He(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new He(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var Qo=Object.defineProperty,Fo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e,n)=>Fo(t,typeof e!="symbol"?e+"":e,n);const Do=480*60*60*1e3,ti=2;class Uo{constructor(e,n,r){D(this,"authState",{state:"noAuth"}),D(this,"configVersion",0),D(this,"syncState"),D(this,"authenticate"),D(this,"stopSocket"),D(this,"tryRestartSocket"),D(this,"pauseSocket"),D(this,"resumeSocket"),D(this,"clearAuth"),D(this,"logger"),D(this,"refreshTokenLeewaySeconds"),D(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=ti){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${ti-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const s=i-r;if(s<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let o=Math.min(Do,(s-this.refreshTokenLeewaySeconds)*1e3);o<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${s}s`),o=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},o);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${o}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return ei(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const Vo=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Wo(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function Ho(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Jo(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of Vo){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(Ho)}var Go=Object.defineProperty,Ko=(t,e,n)=>e in t?Go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,R=(t,e,n)=>Ko(t,typeof e!="symbol"?e+"":e,n);class Zo{constructor(e,n,r){if(R(this,"address"),R(this,"state"),R(this,"requestManager"),R(this,"webSocketManager"),R(this,"authenticationManager"),R(this,"remoteQuerySet"),R(this,"optimisticQueryResults"),R(this,"_transitionHandlerCounter",0),R(this,"_nextRequestId"),R(this,"_onTransitionFns",new Map),R(this,"_sessionId"),R(this,"firstMessageReceived",!1),R(this,"debug"),R(this,"logger"),R(this,"maxObservedTimestamp"),R(this,"connectionStateSubscribers",new Map),R(this,"nextConnectionStateSubscriberId",0),R(this,"_lastPublishedConnectionState"),R(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const p=this.connectionState();if(JSON.stringify(p)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=p;for(const g of this.connectionStateSubscribers.values())g(p)}})}),R(this,"mark",p=>{this.debug&&Wo(p,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&Vs(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let s=r.webSocketConstructor;if(!s&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");s=s||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Dr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Fr({verbose:r.verbose??!1});const o=e.search("://");if(o===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(o+3),a=e.substring(0,o);let c;if(a==="http")c="ws";else if(a==="https")c="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${c}://${l}/api/${Nr}/sync`;this.state=new co,this.remoteQuerySet=new Kr(p=>this.state.queryPath(p),this.logger),this.requestManager=new fo(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Uo(this.state,{authenticate:p=>{const g=this.state.setAuth(p);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new vo,this.addOnTransitionHandler(p=>{n(p.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=Oo();const{unsavedChangesWarning:f}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(f===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else f!==!1&&window.addEventListener("beforeunload",p=>{if(this.requestManager.hasIncompleteRequests()){p.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(p||window.event).returnValue=g,g}});this.webSocketManager=new Lo(d,{onOpen:p=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...p,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Kr(b=>this.state.queryPath(b),this.logger);const[g,m]=this.state.restart();m&&this.webSocketManager.sendMessage(m),this.webSocketManager.sendMessage(g);for(const b of this.requestManager.restart())this.webSocketManager.sendMessage(b)},onResume:()=>{const[p,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),p&&this.webSocketManager.sendMessage(p);for(const m of this.requestManager.resume())this.webSocketManager.sendMessage(m)},onMessage:p=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),p.type){case"Transition":{this.observedTimestamp(p.endVersion.ts),this.authenticationManager.onTransition(p),this.remoteQuerySet.transition(p),this.state.transition(p);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{p.success&&this.observedTimestamp(p.ts);const g=this.requestManager.onResponse(p);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(p);break}case"AuthError":{this.authenticationManager.onAuthError(p);break}case"FatalError":{const g=oo(this.logger,p.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},s,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[s,o]of n){const l=this.state.queryToken(s);if(l!==null){const a={result:o,udfPath:this.state.queryPath(s),args:this.state.queryArgs(s)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(s=>{const o=this.optimisticQueryResults.rawQueryResult(s);return{token:s,modification:{kind:"Updated",result:o}}}),reflectedMutations:Array.from(e).map(([s,o])=>({requestId:s,result:o})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?ei(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const i=re(n),{modification:s,queryToken:o,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return s!==null&&this.webSocketManager.sendMessage(s),{queryToken:o,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=re(n),i=pe(e,r);return this.optimisticQueryResults.queryResult(i)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=re(n),i=pe(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=re(n),i=pe(e,r);return this.state.queryJournal(i)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const i=await this.mutationInternal(e,n,r);if(!i.success)throw i.errorData!==void 0?sn(i,new rn(Re("mutation",e,i))):new Error(Re("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:s}=this.enqueueMutation(e,n,r,i);return s}enqueueMutation(e,n,r,i){const s=re(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const h=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},p=this.optimisticQueryResults.applyOptimisticUpdate(h,o).map(g=>{const m=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:m===void 0?void 0:{success:!0,value:m,logLines:[]}}}});this.handleTransition({queries:p,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[X(s)]},a=this.webSocketManager.sendMessage(l),c=this.requestManager.request(l,a);return{requestId:o,mutationPromise:c}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?sn(r,new rn(Re("action",e,r))):new Error(Re("action",e,r));return r.value}async actionInternal(e,n,r){const i=re(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[X(i)]},l=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=Jo(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${Nr}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function ln(t){if(typeof t!="object"||t===null||!Array.isArray(t.page)||typeof t.isDone!="boolean"||typeof t.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${t?.toString()}`);return t}var Yo=Object.defineProperty,Xo=(t,e,n)=>e in t?Yo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ni=(t,e,n)=>Xo(t,typeof e!="symbol"?e+"":e,n);class ea{constructor(e,n){this.client=e,this.onTransition=n,ni(this,"paginatedQuerySet",new Map),ni(this,"lastTransitionTs"),this.lastTransitionTs=L.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=fe(e),s=Ur(i,n,r),o=()=>this.removePaginatedQuerySubscriber(s),l=this.paginatedQuerySet.get(s);return l?(l.numSubscribers+=1,{paginatedQueryToken:s,unsubscribe:o}):(this.paginatedQuerySet.set(s,{token:s,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(s,null,r.initialNumItems),{paginatedQueryToken:s,unsubscribe:o})}localQueryResult(e,n,r){const i=fe(e),s=Ur(i,n,r);return this.localQueryResultByToken(s)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)};let i=[],s=!1,o=!1;for(const a of r){const c=this.client.localQueryResultByToken(a);if(c===void 0){s=!0,o=!1;continue}const d=ln(c);i=i.concat(d.page),o=!!d.isDone}let l;return s?l=i.length===0?"LoadingFirstPage":"LoadingMore":o?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(o=>o.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,o=>this.client.localQueryResultByToken(o)),i=r.map(o=>({token:o,modification:{kind:"Updated",result:this.localQueryResultByToken(o)}})));const s={...e,paginatedQueries:i};this.onTransition(s)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const s=ln(i);if(s.isDone)return!1;this.addPageToPaginatedQuery(e,s.continueCursor,n);const o={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(o),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,s]of this.paginatedQuerySet)for(const o of this.allQueryTokens(s))if(r.has(o)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:s,pageKeyToQuery:o,pageKeys:l}=i;for(const[a,[c,d]]of s)n(o.get(c).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,c,d);for(const a of l){if(s.has(a))continue;const c=o.get(a).queryToken,d=n(c);if(!d)continue;const h=ln(d);h.splitCursor&&(h.pageStatus==="SplitRecommended"||h.pageStatus==="SplitRequired"||h.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const s=e.nextPageKey++,o=e.nextPageKey++,l={cursor:i,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:null,endCursor:r}});e.pageKeyToQuery.set(s,a);const c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,c),e.ongoingSplits.set(n,[s,o])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),s=i.nextPageKey++,o={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:o},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(s),i.pageKeyToQuery.set(s,a),a}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const s=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const o=e.pageKeys.indexOf(n);e.pageKeys.splice(o,1,r,i),e.ongoingSplits.delete(n),s.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function ta({getCurrentValue:t,subscribe:e}){const[n,r]=C(()=>({getCurrentValue:t,subscribe:e,value:t()}));let i=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(i=t(),r({getCurrentValue:t,subscribe:e,value:i})),$(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const c=t();return a.value===c?a:{...a,value:c}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var na=Object.defineProperty,ra=(t,e,n)=>e in t?na(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ie=(t,e,n)=>ra(t,typeof e!="symbol"?e+"":e,n);const ia=5e3;if(typeof Kt>"u")throw new Error("Required dependency 'react' not found");function ri(t,e,n){function r(i){return la(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(s){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${M(t)}`);return ri(t,e,s)},r}class sa{constructor(e,n){if(ie(this,"address"),ie(this,"cachedSync"),ie(this,"cachedPaginatedQueryClient"),ie(this,"listeners"),ie(this,"options"),ie(this,"closed",!1),ie(this,"_logger"),ie(this,"adminAuth"),ie(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?Dr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Fr({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new Zo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new ea(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,s=M(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),c=this.listeners.get(l);return c!==void 0?c.add(o):this.listeners.set(l,new Set([o])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(o),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(s,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(s,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(s,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??ia,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=M(e);return{onUpdate:s=>{const{paginatedQueryToken:o,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(o);return a!==void 0?a.add(s):this.listeners.set(o,new Set([s])),()=>{if(this.closed)return;const c=this.listeners.get(o);c.delete(s),c.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=M(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=M(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((s,o)=>{const l=r.onUpdate(()=>{l();try{s(r.localQueryResult())}catch(a){o(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){const n=e.queries.map(i=>i.token),r=e.paginatedQueries.map(i=>i.token);this.transition([...n,...r])}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const i of r)i()}}}const cn=Kt.createContext(void 0);function oa(){return ct(cn)}const aa=({client:t,children:e})=>Kt.createElement(cn.Provider,{value:t},e);function ii(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:re(e[0]),i=typeof t=="string"?Wr(t):t,s=M(i),o=Q(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(X(r)),s,n]),a=da(o).query;if(a instanceof Error)throw a;return a}function Je(t){const e=typeof t=="string"?Wr(t):t,n=ct(cn);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return Q(()=>ri(e,n),[n,M(e)])}function la(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var ca=Object.defineProperty,ua=(t,e,n)=>e in t?ca(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,un=(t,e,n)=>ua(t,typeof e!="symbol"?e+"":e,n);class ha{constructor(e){un(this,"createWatch"),un(this,"queries"),un(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:s}=e[n];if(M(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(M(r)!==M(o.query)||JSON.stringify(X(i))!==JSON.stringify(X(o.args))||JSON.stringify(s)!==JSON.stringify(o.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,s?{paginationOptions:s}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:s}=e[r],o=e[r].paginationOptions;M(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(c){if(c instanceof Error)a=c;else throw c}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:s,paginationOptions:o}=this.queries[n],l="journal"in s?s.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...o?{paginationOptions:o}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:s}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const o=this.createWatch(n,r,{...s?{journal:s}:[],...i?{paginationOptions:i}:{}}),l=o.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:o,unsubscribe:l,...i?{paginationOptions:i}:{}}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function da(t){const e=oa();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=Q(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return fa(t,n)}function fa(t,e){const[n]=C(()=>new ha(e));n.createWatch!==e&&n.setCreateWatch(e),$(()=>()=>n.destroy(),[n]);const r=Q(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return ta(r)}var pa=Symbol.for("preact-signals");function bt(){if(oe>1)oe--;else{for(var t,e=!1;Ge!==void 0;){var n=Ge;for(Ge=void 0,hn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&ai(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(hn=0,oe--,e)throw t}}function ga(t){if(oe>0)return t();oe++;try{return t()}finally{bt()}}var w=void 0;function si(t){var e=w;w=void 0;try{return t()}finally{w=e}}var Ge=void 0,oe=0,hn=0,yt=0;function oi(t){if(w!==void 0){var e=t.n;if(e===void 0||e.t!==w)return e={i:0,S:t,p:w.s,n:void 0,t:w,e:void 0,x:void 0,r:e},w.s!==void 0&&(w.s.n=e),w.s=e,t.n=e,32&w.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=w.s,e.n=void 0,w.s.n=e,w.s=e),e}}function A(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}A.prototype.brand=pa,A.prototype.h=function(){return!0},A.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:si(function(){var r;(r=e.W)==null||r.call(e)}))},A.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&si(function(){var i;(i=e.Z)==null||i.call(e)}))}},A.prototype.subscribe=function(t){var e=this;return Ke(function(){var n=e.value,r=w;w=void 0;try{t(n)}finally{w=r}},{name:"sub"})},A.prototype.valueOf=function(){return this.value},A.prototype.toString=function(){return this.value+""},A.prototype.toJSON=function(){return this.value},A.prototype.peek=function(){var t=w;w=void 0;try{return this.value}finally{w=t}},Object.defineProperty(A.prototype,"value",{get:function(){var t=oi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(hn>100)throw new Error("Cycle detected");this.v=t,this.i++,yt++,oe++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{bt()}}}});function O(t,e){return new A(t,e)}function ai(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function li(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function ci(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function ge(t,e){A.call(this,void 0),this.x=t,this.s=void 0,this.g=yt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ge.prototype=new A,ge.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===yt))return!0;if(this.g=yt,this.f|=1,this.i>0&&!ai(this))return this.f&=-2,!0;var t=w;try{li(this),w=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return w=t,ci(this),this.f&=-2,!0},ge.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}A.prototype.S.call(this,t)},ge.prototype.U=function(t){if(this.t!==void 0&&(A.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ge.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ge.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=oi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function vt(t,e){return new ge(t,e)}function ui(t){var e=t.u;if(t.u=void 0,typeof e=="function"){oe++;var n=w;w=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,dn(t),r}finally{w=n,bt()}}}function dn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ui(t)}function ma(t){if(w!==this)throw new Error("Out-of-order effect");ci(this),w=t,this.f&=-2,8&this.f&&dn(this),bt()}function Ae(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ae.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ae.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ui(this),li(this),oe++;var t=w;return w=this,ma.bind(this,t)},Ae.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ge,Ge=this)},Ae.prototype.d=function(){this.f|=8,1&this.f||dn(this)},Ae.prototype.dispose=function(){this.d()};function Ke(t,e){var n=new Ae(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var hi,_t,wt,xa=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,di=[];Ke(function(){hi=this.N})();function Ee(t,e){x[t]=e.bind(null,x[t]||function(){})}function kt(t){if(wt){var e=wt;wt=void 0,e()}wt=t&&t.S()}function fi(t){var e=this,n=t.data,r=Ze(n);r.value=n;var i=Q(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var c=vt(function(){var p=r.value.value;return p===0?0:p===!0?"":p||""}),d=vt(function(){return!Array.isArray(c.value)&&!Ln(c.value)}),h=Ke(function(){if(this.N=pi,d.value){var p=c.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=p)}}),f=e.__$u.d;return e.__$u.d=function(){h(),f.call(this)},[d,c]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}fi.displayName="ReactiveTextNode",Object.defineProperties(A.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:fi},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Ee("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var s=r[i];s instanceof A&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Ee("__r",function(t,e){if(t(e),e.type!==N){kt();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,s){var o;return Ke(function(){o=this},{name:s}),o.c=i,o})(function(){var i;xa&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),_t=r,kt(n)}}),Ee("__e",function(t,e,n,r){kt(),_t=void 0,t(e,n,r)}),Ee("diffed",function(t,e){kt(),_t=void 0;var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var s=n.U;if(s)for(var o in s){var l=s[o];l!==void 0&&!(o in r)&&(l.d(),s[o]=void 0)}else s={},n.U=s;for(var a in r){var c=s[a],d=r[a];c===void 0?(c=ba(n,a,d,i),s[a]=c):c.o(d,i)}}}t(e)});function ba(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=O(n);return{o:function(o,l){s.value=o,r=l},d:Ke(function(){this.N=pi;var o=s.value.value;r[e]!==o&&(r[e]=o,i?t[e]=o:o!=null&&(o!==!1||e[4]==="-")?t.setAttribute(e,o):t.removeAttribute(e))})}}Ee("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var s=r[i];s&&s.d()}}}}else{var o=e.__c;if(o){var l=o.__$u;l&&(o.__$u=void 0,l.d())}}t(e)}),Ee("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),V.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(r||s||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Ze(t,e){return Q(function(){return O(t,e)},[])}function ya(t,e){var n=de(t);return n.current=t,_t.__$f|=4,Q(function(){return vt(function(){return n.current()},e)},[])}var va=function(t){queueMicrotask(function(){queueMicrotask(t)})};function _a(){ga(function(){for(var t;t=di.shift();)hi.call(t)})}function pi(){di.push(this)===1&&(x.requestAnimationFrame||va)(_a)}const I=O(!1),St=O(void 0),Ye=O(void 0);function wa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function fn(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function ka(t,e){const n=t.title??e?.title??"Assistant";return{title:n,greeting:t.greeting??e?.welcomeMessage??`Hi! I'm ${n}. How can I help?`,locale:t.locale??e?.locale,position:t.position??e?.position,colorScheme:t.colorScheme??e?.colorScheme,hideBranding:t.hideBranding??e?.hideBranding??!1,triggerIcon:t.triggerIcon??e?.triggerIcon??"chat",triggerRadius:t.triggerRadius??e?.triggerRadius??"full",triggerLabel:t.triggerLabel??e?.triggerLabel??"Chatte mit uns",mode:t.mode??"floating",primaryColor:t.primaryColor??e?.primaryColor,accentColor:t.accentColor??e?.accentColor,fontFamily:t.fontFamily??e?.fontFamily,fontSize:t.fontSize??e?.fontSize,borderRadius:t.borderRadius??e?.borderRadius,windowWidth:t.windowWidth??e?.windowWidth,windowHeight:t.windowHeight??e?.windowHeight}}async function Sa(t,e,n,r){const i=new URL(`${t}/widget/config`);i.searchParams.set("orgSlug",e),r&&i.searchParams.set("projSlug",r);const s=await fetch(i.toString(),{signal:n});return s.ok?s.json():null}function ja(t,e,n){const[r,i]=C(null);return $(()=>{i(null);const s=n??"https://festive-mouse-978.eu-west-1.convex.cloud",o=s?fn(s):void 0;if(!o||!t)return;const l=new AbortController;async function a(c){try{const d=await Sa(c,t,l.signal,e);d&&i(d)}catch(d){if(d instanceof Error&&d.name==="AbortError")return}}return a(o),()=>{l.abort()}},[t,e,n]),r}async function gi(t,e,n){try{const r=await fetch(`${e}/widget/bootstrap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{orgSlug:t,projSlug:n}:{orgSlug:t}),credentials:"omit"});if(r.ok){const i=await r.json();return{ok:!0,token:i.token,excludePaths:i.excludePaths}}return r.status===403?{ok:!1,error:"unauthorized"}:r.status===404?{ok:!1,error:"not_found"}:r.status===429?{ok:!1,error:"rate_limited",retryAfterSec:Number(r.headers.get("Retry-After"))||60}:{ok:!1,error:"network"}}catch{return{ok:!1,error:"network"}}}function Ca(t,e,n,r){$(()=>{if(n)return;const i=r??"https://festive-mouse-978.eu-west-1.convex.cloud",s=i?fn(i):void 0;if(!s||!t)return;let o=!1;return(async()=>{const l=await gi(t,s,e);if(!o)if(l.ok)Ye.value=l.token;else{const a=e?`project '${t}/${e}'`:`org '${t}'`;l.error==="unauthorized"?console.error(`[JexityChat] This domain is not authorized for ${a}. Check the widget's domain rules.`):l.error==="not_found"?console.error(`[JexityChat] No active widget config found for ${a}.`):l.error==="rate_limited"?console.error(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${l.retryAfterSec??60}s.`):console.error(`[JexityChat] Bootstrap failed: ${l.error}`)}})(),()=>{o=!0}},[t,e,n,r])}const mi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",errorRateLimited:"Too many messages. Try again in {seconds}s.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resuming conversation…",startingConversation:"Starting conversation…",sessionNotFound:"Your previous session was not found. Starting a new conversation.",startNewConversation:"Start new conversation",chatWith:"Chat with {title}",haveReferenceNumber:"Have a reference number?",referencePlaceholder:"e.g. JEX-A3B7C2",resume:"Resume",howCanWeHelp:"How can we help?",getInstantHelp:"Get instant help",submitTicket:"Submit a ticket",replyByEmail:"We'll reply by email",ticketSubmitted:"Ticket submitted",yourReferenceNumber:"Your reference number:",sentToEmailHint:"We've sent it to your email. Use this number to follow up.",done:"Done",submittingTicket:"Submitting your ticket…",yourName:"Your name",yourEmail:"Your email",submit:"Submit",back:"Go back",escalationFormTitle:"Leave your details",escalationSubtitle:"Our team will get back to you by email so you don’t have to wait here.",escalationNameLabel:"Your name",escalationEmailLabel:"Your email",escalationSubmit:"Send to team",escalationSubmitting:"Sending…",escalationSubmitted:"Request submitted",escalationConsent:"We’ll only use your email to respond to this conversation.",escalationSkip:"Skip, I’ll wait here",escalationPromptTitle:"Talk to our team",escalationPromptSubtitle:"We can notify you by email when our team replies.",escalationPromptSubmit:"Leave details",escalationSubmitFailed:"Failed to submit. Please try again.",sessionNotFoundPrompt:"Session not found. Would you like to start a new conversation?",sessionResolved:"This conversation has been resolved.",tryAgain:"Try again",goBack:"Go back",somethingWentWrong:"Something went wrong",fabLabel:"Chat with us",chatNoLongerAvailable:"This chat is no longer available.",talkToHuman:"Talk to human",talkToHumanAria:"Talk to a human agent",handoffPending:"Connecting you to a human agent…",handoffFailed:"Could not request a human agent. Try again.",handoffRateLimited:"You requested an agent recently. Please wait before trying again.",resumeListLabel:"Continue conversation",resumeListTimestamp:"{minutes}m ago"},Ta={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",errorRateLimited:"Zu viele Nachrichten. Bitte in {seconds} Sek. erneut versuchen.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch wird fortgesetzt…",startingConversation:"Konversation wird gestartet…",sessionNotFound:"Ihre vorherige Sitzung wurde nicht gefunden. Ein neues Gespräch wird gestartet.",startNewConversation:"Neues Gespräch beginnen",chatWith:"Chatte mit {title}",haveReferenceNumber:"Hast du eine Referenznummer?",referencePlaceholder:"z.B. JEX-A3B7C2",resume:"Fortsetzen",howCanWeHelp:"Wie können wir helfen?",getInstantHelp:"Soforthilfe erhalten",submitTicket:"Ticket einreichen",replyByEmail:"Wir antworten per E-Mail",ticketSubmitted:"Ticket eingereicht",yourReferenceNumber:"Deine Referenznummer:",sentToEmailHint:"Wir haben sie an deine E-Mail gesendet. Verwende diese Nummer für Rückfragen.",done:"Fertig",submittingTicket:"Dein Ticket wird übermittelt…",yourName:"Dein Name",yourEmail:"Deine E-Mail",submit:"Absenden",back:"Zurück",escalationFormTitle:"Hinterlassen Sie Ihre Daten",escalationSubtitle:"Unser Team meldet sich per E-Mail bei Ihnen — Sie müssen nicht hier warten.",escalationNameLabel:"Ihr Name",escalationEmailLabel:"Ihre E-Mail",escalationSubmit:"An Team senden",escalationSubmitting:"Wird gesendet…",escalationSubmitted:"Anfrage gesendet",escalationConsent:"Wir verwenden Ihre E-Mail nur, um auf diese Unterhaltung zu antworten.",escalationSkip:"Überspringen, ich warte hier",escalationPromptTitle:"Sprechen Sie mit unserem Team",escalationPromptSubtitle:"Wir benachrichtigen Sie per E-Mail, wenn wir antworten.",escalationPromptSubmit:"Daten hinterlassen",escalationSubmitFailed:"Senden fehlgeschlagen. Bitte versuche es erneut.",sessionNotFoundPrompt:"Sitzung nicht gefunden. Möchten Sie ein neues Gespräch beginnen?",sessionResolved:"Diese Unterhaltung wurde abgeschlossen.",tryAgain:"Erneut versuchen",goBack:"Zurück",somethingWentWrong:"Etwas ist schiefgelaufen",fabLabel:"Chatte mit uns",chatNoLongerAvailable:"Dieser Chat ist nicht mehr verfügbar.",talkToHuman:"Mit Mitarbeiter sprechen",talkToHumanAria:"Mit einem menschlichen Mitarbeiter sprechen",handoffPending:"Sie werden mit einem Mitarbeiter verbunden…",handoffFailed:"Anfrage konnte nicht gesendet werden. Erneut versuchen.",handoffRateLimited:"Sie haben kürzlich einen Mitarbeiter angefragt. Bitte warten Sie.",resumeListLabel:"Unterhaltung fortsetzen",resumeListTimestamp:"vor {minutes} Min."},Ra=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],$a="de",Aa="jex-locale",pn=O("de"),Ea={en:mi,de:Ta};function P(){return Ea[pn.value]??mi}function gn(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return Ra.some(r=>r.value===e)?e:null}function xi(t){const e=gn(t);if(e)return e;try{const n=gn(localStorage.getItem(Aa));if(n)return n}catch{}if(typeof navigator<"u"){const n=gn(navigator.language);if(n)return n}return $a}function Ia(t){$(()=>{function e(n){const r=t??window.location.origin;if(n.origin!==r||n.data?.type!=="jexity:config")return;const{locale:i}=n.data.payload;i&&(pn.value=xi(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const bi="jex-session-history",Pa=900*1e3,W=O([]),Xe=O(null),yi=vt(()=>W.value.length>0),et=O(null);function qa(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function Ma(t){try{const e=sessionStorage.getItem(bi);if(!e)return[];const n=JSON.parse(e);return n.v!==1||!Array.isArray(n.entries)?[]:n.entries.filter(r=>t-r.lastActivityAt<=Pa)}catch{return[]}}function jt(t){try{const e={v:1,entries:t};sessionStorage.setItem(bi,JSON.stringify(e))}catch{}}function La(){const t=Date.now(),e=Ma(t);W.value=e,jt(e),Xe.value=e.length>0?e[e.length-1].ref:null}function vi(){const t=qa(),e=Date.now(),n=[...W.value,{ref:t,startedAt:e,lastActivityAt:e}];return W.value=n,Xe.value=t,jt(n),t}function _i(t){const e=Date.now(),n=W.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);W.value=n,Xe.value=t,jt(n)}function mn(t){if(!t)return;const e=Date.now(),n=W.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);W.value=n,jt(n)}const z=O(wi());function wi(){return yi.value?[{id:"home"}]:[{id:"chat"}]}function Oa(){z.value=wi()}const Na=O("screen");function me(t){z.value=[...z.value,t]}function Ct(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function xn(t){z.value=[...z.value.slice(0,-1),t]}function za(t){const e={},{primaryColor:n,theme:r}=t;if(n&&(e["--jex-primary"]=n,e["--jex-bg-trigger"]=n,e["--jex-bg-header"]=n,e["--jex-bg-msg-user"]=n,e["--jex-bg-send-btn"]=n),t.accentColor&&(e["--jex-accent"]=t.accentColor),r?.bg){const i=r.bg;i.trigger&&(e["--jex-bg-trigger"]=i.trigger),i.header&&(e["--jex-bg-header"]=i.header),i.msgUser&&(e["--jex-bg-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-bg-msg-bot"]=i.msgBot),i.window&&(e["--jex-bg-window"]=i.window),i.sendBtn&&(e["--jex-bg-send-btn"]=i.sendBtn)}if(r?.text){const i=r.text;i.header&&(e["--jex-text-header"]=i.header),i.msgUser&&(e["--jex-text-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-text-msg-bot"]=i.msgBot),i.main&&(e["--jex-text-main"]=i.main),i.muted&&(e["--jex-text-muted"]=i.muted)}if(r?.border){const i=r.border;i.window&&(e["--jex-border-window"]=i.window),i.input&&(e["--jex-border-input"]=i.input)}return t.fontFamily&&(e["--jex-font-family"]=t.fontFamily),t.fontSize&&(e["--jex-font-size"]=`${t.fontSize}px`),t.borderRadius&&(e["--jex-radius"]=t.borderRadius),t.windowWidth&&(e["--jex-window-width"]=`${t.windowWidth}px`),t.windowHeight&&(e["--jex-window-height"]=`${t.windowHeight}px`),Object.keys(e).length>0?e:void 0}function bn({size:t=24}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M12 8V4H8"}),u("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),u("path",{d:"M2 14h2"}),u("path",{d:"M20 14h2"}),u("path",{d:"M15 13v2"}),u("path",{d:"M9 13v2"})]})}function ki({title:t,rightAction:e}){const n=P(),r=z.value.length>1;return u("header",{class:"jex-chat-header",children:[r&&u("button",{class:"jex-header-back",onClick:Ct,"aria-label":n.back||"Go back",children:u("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"m15 18-6-6 6-6"})})}),!r&&u(bn,{size:24}),u("div",{class:"jex-header-info",children:[u("h3",{children:t}),u("p",{children:n.statusOnline})]}),e&&u("div",{class:"jex-header-right",children:e})]})}function Ba({size:t=14}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"})})}function Si(){return u("div",{class:"jex-widget-footer",children:u("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[u(Ba,{size:14}),u("span",{children:["Powered by ",u("strong",{children:"Jexity"})]})]})})}function ji({size:t=28}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Qa({size:t=28}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M18 6 6 18"}),u("path",{d:"m6 6 12 12"})]})}function Fa({size:t=24,...e}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...e,children:u("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})})}const Da={chat:u(ji,{size:28}),bot:u(bn,{size:28}),sparkles:u(Fa,{size:28})},Ua={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Va({radius:t="full",iconOption:e="chat",label:n}){const r=P(),i=n??r.fabLabel,s=i!=="";return u("button",{class:`jex-floating-button ${!I.value&&s?"jex-has-label":""}`,style:{borderRadius:Ua[t]??"9999px"},onClick:()=>{I.value=!I.value},"aria-label":I.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:I.value?u(Qa,{size:28}):u("div",{class:"jex-fab-inner",children:[Da[e],s&&u("span",{class:"jex-fab-label",children:i})]})})}function Wa({title:t,onStartFresh:e,onResetSession:n}){const r=P(),[i,s]=C("");function o(){et.value="fresh",e(),me({id:"chat"})}function l(c){et.value="resume",n(),_i(c),me({id:"chat"})}function a(c){c.preventDefault();const d=i.trim().toUpperCase();d&&(et.value="resume",n(),_i(d),me({id:"chat"}))}return u("div",{class:"jex-home",children:[u("div",{class:"jex-home-hero",children:[u("div",{class:"jex-home-avatar",children:[u(ji,{size:24}),u("span",{class:"jex-home-status-dot"})]}),u("div",{class:"jex-home-hero-text",children:[u("h2",{class:"jex-home-title",children:t}),u("span",{class:"jex-home-status",children:r.statusOnline})]})]}),u("form",{class:"jex-home-lookup",onSubmit:a,children:[u("input",{class:"jex-home-lookup-input",type:"text",placeholder:r.referencePlaceholder,value:i,onInput:c=>{s(c.currentTarget.value)}}),u("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!i.trim(),children:r.resume})]}),u("div",{class:"jex-home-actions",children:[W.value.length>0&&u("div",{class:"jex-home-history",children:W.value.slice().reverse().map(c=>u("button",{class:"jex-home-resume-card",onClick:()=>{l(c.ref)},children:[u("div",{class:"jex-home-resume-top",children:[u("span",{class:"jex-home-resume-label",children:r.resumeListLabel}),u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:u("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),u("span",{class:"jex-home-resume-ref",children:c.ref}),u("span",{class:"jex-home-resume-meta",children:r.resumeListTimestamp.replace("{minutes}",String(Math.max(1,Math.round((Date.now()-c.lastActivityAt)/6e4))))})]},c.ref))}),u("button",{class:"jex-home-new-btn",onClick:o,children:W.value.length>0?r.startNewConversation:r.chatWith.replace("{title}",t)})]})]})}function Ha({title:t}){const e=P();return u("div",{class:"jex-selection",children:[u("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),u("div",{class:"jex-selection-options",children:[u("button",{class:"jex-selection-option",onClick:()=>me({id:"chat"}),children:[u("span",{class:"jex-selection-icon",children:"💬"}),u("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),u("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),u("button",{class:"jex-selection-option",onClick:()=>me({id:"form"}),children:[u("span",{class:"jex-selection-icon",children:"📝"}),u("span",{class:"jex-selection-label",children:e.submitTicket}),u("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function Ci(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return Ci(t,s)}else if(i===Vr){if(e.length<1){const s=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${s}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const Ja=()=>Ci("components",[]),xe=xo;Ja();const Ga=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const Ti=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const Ka=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Ri=t=>{const e=Ka(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Za={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};const Ya=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Xa=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,children:i,iconNode:s,class:o="",...l})=>B("svg",{...Za,width:String(e),height:e,stroke:t,"stroke-width":r?Number(n)*24/Number(e):n,class:["lucide",o].join(" "),...!i&&!Ya(l)&&{"aria-hidden":"true"},...l},[...s.map(([a,c])=>B(a,c)),...Z(i)]);const el=(t,e)=>{const n=({class:r="",className:i="",children:s,...o})=>B(Xa,{...o,iconNode:e,class:Ga(`lucide-${Ti(Ri(t))}`,`lucide-${Ti(t)}`,r,i)},s);return n.displayName=Ri(t),n};const tl=el("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]);function yn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var be=yn();function $i(t){be=t}var ye={exec:()=>null};function y(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(q.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var nl=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),q={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},rl=/^(?:[ \t]*(?:\n|$))+/,il=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,sl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ol=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,vn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ai=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ei=y(Ai).replace(/bull/g,vn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),al=y(Ai).replace(/bull/g,vn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_n=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ll=/^[^\n]+/,wn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,cl=y(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ul=y(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,vn).getRegex(),Tt="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",kn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,hl=y("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",kn).replace("tag",Tt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ii=y(_n).replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex(),dl=y(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ii).getRegex(),Sn={blockquote:dl,code:il,def:cl,fences:sl,heading:ol,hr:tt,html:hl,lheading:Ei,list:ul,newline:rl,paragraph:Ii,table:ye,text:ll},Pi=y("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex(),fl={...Sn,lheading:al,table:Pi,paragraph:y(_n).replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pi).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex()},pl={...Sn,html:y(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",kn).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ye,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:y(_n).replace("hr",tt).replace("heading",` *#{1,6} *[^
3
- ]`).replace("lheading",Ei).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},gl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ml=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qi=/^( {2,}|\\)\n(?!\s*$)/,xl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ie=/[\p{P}\p{S}]/u,Rt=/[\s\p{P}\p{S}]/u,jn=/[^\s\p{P}\p{S}]/u,bl=y(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Rt).getRegex(),Mi=/(?!~)[\p{P}\p{S}]/u,yl=/(?!~)[\s\p{P}\p{S}]/u,vl=/(?:[^\s\p{P}\p{S}]|~)/u,_l=y(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",nl?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Li=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,wl=y(Li,"u").replace(/punct/g,Ie).getRegex(),kl=y(Li,"u").replace(/punct/g,Mi).getRegex(),Oi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Sl=y(Oi,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Ie).getRegex(),jl=y(Oi,"gu").replace(/notPunctSpace/g,vl).replace(/punctSpace/g,yl).replace(/punct/g,Mi).getRegex(),Cl=y("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Ie).getRegex(),Tl=y(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ie).getRegex(),Rl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$l=y(Rl,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Ie).getRegex(),Al=y(/\\(punct)/,"gu").replace(/punct/g,Ie).getRegex(),El=y(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Il=y(kn).replace("(?:-->|$)","-->").getRegex(),Pl=y("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Il).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),$t=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ql=y(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",$t).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ni=y(/^!?\[(label)\]\[(ref)\]/).replace("label",$t).replace("ref",wn).getRegex(),zi=y(/^!?\[(ref)\](?:\[\])?/).replace("ref",wn).getRegex(),Ml=y("reflink|nolink(?!\\()","g").replace("reflink",Ni).replace("nolink",zi).getRegex(),Bi=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Cn={_backpedal:ye,anyPunctuation:Al,autolink:El,blockSkip:_l,br:qi,code:ml,del:ye,delLDelim:ye,delRDelim:ye,emStrongLDelim:wl,emStrongRDelimAst:Sl,emStrongRDelimUnd:Cl,escape:gl,link:ql,nolink:zi,punctuation:bl,reflink:Ni,reflinkSearch:Ml,tag:Pl,text:xl,url:ye},Ll={...Cn,link:y(/^!?\[(label)\]\((.*?)\)/).replace("label",$t).getRegex(),reflink:y(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$t).getRegex()},Tn={...Cn,emStrongRDelimAst:jl,emStrongLDelim:kl,delLDelim:Tl,delRDelim:$l,url:y(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Bi).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:y(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Bi).getRegex()},Ol={...Tn,br:y(qi).replace("{2,}","*").getRegex(),text:y(Tn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},At={normal:Sn,gfm:fl,pedantic:pl},nt={normal:Cn,gfm:Tn,breaks:Ol,pedantic:Ll},Nl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Qi=t=>Nl[t];function te(t,e){if(e){if(q.escapeTest.test(t))return t.replace(q.escapeReplace,Qi)}else if(q.escapeTestNoEncode.test(t))return t.replace(q.escapeReplaceNoEncode,Qi);return t}function Fi(t){try{t=encodeURI(t).replace(q.percentDecode,"%")}catch{return null}return t}function Di(t,e){let n=t.replace(q.findPipe,(s,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),r=n.split(q.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(q.slashPipe,"|");return r}function rt(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r&&t.charAt(r-i-1)===e;)i++;return t.slice(0,r-i)}function zl(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function Bl(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=i,n++;return r}function Ui(t,e,n,r,i){let s=e.href,o=e.title||null,l=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function Ql(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
1
+ (function(){"use strict";var Le,x,Mn,Ln,ue,On,Nn,zn,Bn,qt,Mt,Lt,Qn,Oe={},Fn=[],Zi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ne=Array.isArray;function K(t,e){for(var n in e)t[n]=e[n];return t}function Ot(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function B(t,e,n){var r,i,s,o={};for(s in e)s=="key"?r=e[s]:s=="ref"?i=e[s]:o[s]=e[s];if(arguments.length>2&&(o.children=arguments.length>3?Le.call(arguments,2):n),typeof t=="function"&&t.defaultProps!=null)for(s in t.defaultProps)o[s]===void 0&&(o[s]=t.defaultProps[s]);return ze(t,o,r,i,null)}function ze(t,e,n,r,i){var s={type:t,props:e,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++Mn,__i:-1,__u:0};return i==null&&x.vnode!=null&&x.vnode(s),s}function Yi(){return{current:null}}function N(t){return t.children}function V(t,e){this.props=t,this.context=e}function we(t,e){if(e==null)return t.__?we(t.__,t.__i+1):null;for(var n;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null)return n.__e;return typeof t.type=="function"?we(t):null}function Dn(t){var e,n;if((t=t.__)!=null&&t.__c!=null){for(t.__e=t.__c.base=null,e=0;e<t.__k.length;e++)if((n=t.__k[e])!=null&&n.__e!=null){t.__e=t.__c.base=n.__e;break}return Dn(t)}}function Nt(t){(!t.__d&&(t.__d=!0)&&ue.push(t)&&!at.__r++||On!=x.debounceRendering)&&((On=x.debounceRendering)||Nn)(at)}function at(){for(var t,e,n,r,i,s,o,l=1;ue.length;)ue.length>l&&ue.sort(zn),t=ue.shift(),l=ue.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,s=[],o=[],e.__P&&((n=K({},r)).__v=r.__v+1,x.vnode&&x.vnode(n),zt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,s,i??we(r),!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Jn(s,n,o),r.__e=r.__=null,n.__e!=i&&Dn(n)));at.__r=0}function Un(t,e,n,r,i,s,o,l,a,c,d){var h,f,p,g,m,b,_,v=r&&r.__k||Fn,E=e.length;for(a=Xi(n,e,v,a,E),h=0;h<E;h++)(p=n.__k[h])!=null&&(f=p.__i==-1?Oe:v[p.__i]||Oe,p.__i=h,b=zt(t,p,f,i,s,o,l,a,c,d),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&Qt(f.ref,null,p),d.push(p.ref,p.__c||g,p)),m==null&&g!=null&&(m=g),(_=!!(4&p.__u))||f.__k===p.__k?a=Vn(p,a,t,_):typeof p.type=="function"&&b!==void 0?a=b:g&&(a=g.nextSibling),p.__u&=-7);return n.__e=m,a}function Xi(t,e,n,r,i){var s,o,l,a,c,d=n.length,h=d,f=0;for(t.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(a=s+f,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?ze(null,o,null,null,null):Ne(o)?ze(N,{children:o},null,null,null):o.constructor==null&&o.__b>0?ze(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,l=null,(c=o.__i=es(o,n,a,h))!=-1&&(h--,(l=n[c])&&(l.__u|=2)),l==null||l.__v==null?(c==-1&&(i>d?f--:i<d&&f++),typeof o.type!="function"&&(o.__u|=4)):c!=a&&(c==a-1?f--:c==a+1?f++:(c>a?f--:f++,o.__u|=4))):t.__k[s]=null;if(h)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=we(l)),Kn(l,l));return r}function Vn(t,e,n,r){var i,s;if(typeof t.type=="function"){for(i=t.__k,s=0;i&&s<i.length;s++)i[s]&&(i[s].__=t,e=Vn(i[s],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=we(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function Z(t,e){return e=e||[],t==null||typeof t=="boolean"||(Ne(t)?t.some(function(n){Z(n,e)}):e.push(t)),e}function es(t,e,n,r){var i,s,o,l=t.key,a=t.type,c=e[n],d=c!=null&&(2&c.__u)==0;if(c===null&&t.key==null||d&&l==c.key&&a==c.type)return n;if(r>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<e.length;)if((c=e[o=i>=0?i--:s++])!=null&&(2&c.__u)==0&&l==c.key&&a==c.type)return o}return-1}function Wn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Zi.test(e)?n:n+"px"}function lt(t,e,n,r,i){var s,o;e:if(e=="style")if(typeof n=="string")t.style.cssText=n;else{if(typeof r=="string"&&(t.style.cssText=r=""),r)for(e in r)n&&e in n||Wn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Wn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Bn,"$1")),o=e.toLowerCase(),e=o in t||e=="onFocusOut"||e=="onFocusIn"?o.slice(2):e.slice(2),t.l||(t.l={}),t.l[e+s]=n,n?r?n.u=r.u:(n.u=qt,t.addEventListener(e,s?Lt:Mt,s)):t.removeEventListener(e,s?Lt:Mt,s);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in t)try{t[e]=n??"";break e}catch{}typeof n=="function"||(n==null||n===!1&&e[4]!="-"?t.removeAttribute(e):t.setAttribute(e,e=="popover"&&n==1?"":n))}}function Hn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=qt++;else if(e.t<n.u)return;return n(x.event?x.event(e):e)}}}function zt(t,e,n,r,i,s,o,l,a,c){var d,h,f,p,g,m,b,_,v,E,U,ce,G,Ki,Pt,ot,In,ne=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),s=[l=e.__e=n.__e]),(d=x.__b)&&d(e);e:if(typeof ne=="function")try{if(_=e.props,v="prototype"in ne&&ne.prototype.render,E=(d=ne.contextType)&&r[d.__c],U=d?E?E.props.value:d.__:r,n.__c?b=(h=e.__c=n.__c).__=h.__E:(v?e.__c=h=new ne(_,U):(e.__c=h=new V(_,U),h.constructor=ne,h.render=ns),E&&E.sub(h),h.props=_,h.state||(h.state={}),h.context=U,h.__n=r,f=h.__d=!0,h.__h=[],h._sb=[]),v&&h.__s==null&&(h.__s=h.state),v&&ne.getDerivedStateFromProps!=null&&(h.__s==h.state&&(h.__s=K({},h.__s)),K(h.__s,ne.getDerivedStateFromProps(_,h.__s))),p=h.props,g=h.state,h.__v=e,f)v&&ne.getDerivedStateFromProps==null&&h.componentWillMount!=null&&h.componentWillMount(),v&&h.componentDidMount!=null&&h.__h.push(h.componentDidMount);else{if(v&&ne.getDerivedStateFromProps==null&&_!==p&&h.componentWillReceiveProps!=null&&h.componentWillReceiveProps(_,U),!h.__e&&h.shouldComponentUpdate!=null&&h.shouldComponentUpdate(_,h.__s,U)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(h.props=_,h.state=h.__s,h.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Me){Me&&(Me.__=e)}),ce=0;ce<h._sb.length;ce++)h.__h.push(h._sb[ce]);h._sb=[],h.__h.length&&o.push(h);break e}h.componentWillUpdate!=null&&h.componentWillUpdate(_,h.__s,U),v&&h.componentDidUpdate!=null&&h.__h.push(function(){h.componentDidUpdate(p,g,m)})}if(h.context=U,h.props=_,h.__P=t,h.__e=!1,G=x.__r,Ki=0,v){for(h.state=h.__s,h.__d=!1,G&&G(e),d=h.render(h.props,h.state,h.context),Pt=0;Pt<h._sb.length;Pt++)h.__h.push(h._sb[Pt]);h._sb=[]}else do h.__d=!1,G&&G(e),d=h.render(h.props,h.state,h.context),h.state=h.__s;while(h.__d&&++Ki<25);h.state=h.__s,h.getChildContext!=null&&(r=K(K({},r),h.getChildContext())),v&&!f&&h.getSnapshotBeforeUpdate!=null&&(m=h.getSnapshotBeforeUpdate(p,g)),ot=d,d!=null&&d.type===N&&d.key==null&&(ot=Gn(d.props.children)),l=Un(t,Ne(ot)?ot:[ot],e,n,r,i,s,o,l,a,c),h.base=e.__e,e.__u&=-161,h.__h.length&&o.push(h),b&&(h.__E=h.__=null)}catch(Me){if(e.__v=null,a||s!=null)if(Me.then){for(e.__u|=a?160:128;l&&l.nodeType==8&&l.nextSibling;)l=l.nextSibling;s[s.indexOf(l)]=null,e.__e=l}else{for(In=s.length;In--;)Ot(s[In]);Bt(e)}else e.__e=n.__e,e.__k=n.__k,Me.then||Bt(e);x.__e(Me,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=ts(n.__e,e,n,r,i,s,o,a,c);return(d=x.diffed)&&d(e),128&e.__u?void 0:l}function Bt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Bt)}function Jn(t,e,n){for(var r=0;r<n.length;r++)Qt(n[r],n[++r],n[++r]);x.__c&&x.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(s){s.call(i)})}catch(s){x.__e(s,i.__v)}})}function Gn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ne(t)?t.map(Gn):K({},t)}function ts(t,e,n,r,i,s,o,l,a){var c,d,h,f,p,g,m,b=n.props,_=e.props,v=e.type;if(v=="svg"?i="http://www.w3.org/2000/svg":v=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(c=0;c<s.length;c++)if((p=s[c])&&"setAttribute"in p==!!v&&(v?p.localName==v:p.nodeType==3)){t=p,s[c]=null;break}}if(t==null){if(v==null)return document.createTextNode(_);t=document.createElementNS(i,v,_.is&&_),l&&(x.__m&&x.__m(e,s),l=!1),s=null}if(v==null)b===_||l&&t.data==_||(t.data=_);else{if(s=s&&Le.call(t.childNodes),b=n.props||Oe,!l&&s!=null)for(b={},c=0;c<t.attributes.length;c++)b[(p=t.attributes[c]).name]=p.value;for(c in b)if(p=b[c],c!="children"){if(c=="dangerouslySetInnerHTML")h=p;else if(!(c in _)){if(c=="value"&&"defaultValue"in _||c=="checked"&&"defaultChecked"in _)continue;lt(t,c,null,p,i)}}for(c in _)p=_[c],c=="children"?f=p:c=="dangerouslySetInnerHTML"?d=p:c=="value"?g=p:c=="checked"?m=p:l&&typeof p!="function"||b[c]===p||lt(t,c,p,b[c],i);if(d)l||h&&(d.__html==h.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(h&&(t.innerHTML=""),Un(e.type=="template"?t.content:t,Ne(f)?f:[f],e,n,r,v=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:n.__k&&we(n,0),l,a),s!=null)for(c=s.length;c--;)Ot(s[c]);l||(c="value",v=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[c]||v=="progress"&&!g||v=="option"&&g!=b[c])&&lt(t,c,g,b[c],i),c="checked",m!=null&&m!=t[c]&&lt(t,c,m,b[c],i))}return t}function Qt(t,e,n){try{if(typeof t=="function"){var r=typeof t.__u=="function";r&&t.__u(),r&&e==null||(t.__u=t(e))}else t.current=e}catch(i){x.__e(i,n)}}function Kn(t,e,n){var r,i;if(x.unmount&&x.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Qt(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(s){x.__e(s,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&Kn(r[i],e,n||typeof t.type!="function");n||Ot(t.__e),t.__c=t.__=t.__e=void 0}function ns(t,e,n){return this.constructor(t,n)}function he(t,e,n){var r,i,s,o;e==document&&(e=document.documentElement),x.__&&x.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],zt(e,t=(!r&&n||e).__k=B(N,null,[t]),i||Oe,Oe,e.namespaceURI,!r&&n?[n]:i?null:e.firstChild?Le.call(e.childNodes):null,s,!r&&n?n:i?i.__e:e.firstChild,r,o),Jn(s,t,o)}function Zn(t,e){he(t,e,Zn)}function rs(t,e,n){var r,i,s,o,l=K({},t.props);for(s in t.type&&t.type.defaultProps&&(o=t.type.defaultProps),e)s=="key"?r=e[s]:s=="ref"?i=e[s]:l[s]=e[s]===void 0&&o!=null?o[s]:e[s];return arguments.length>2&&(l.children=arguments.length>3?Le.call(arguments,2):n),ze(t.type,l,r||t.key,i||t.ref,null)}function is(t){function e(n){var r,i;return this.getChildContext||(r=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){r=null},this.shouldComponentUpdate=function(s){this.props.value!=s.value&&r.forEach(function(o){o.__e=!0,Nt(o)})},this.sub=function(s){r.add(s);var o=s.componentWillUnmount;s.componentWillUnmount=function(){r&&r.delete(s),o&&o.call(s)}}),n.children}return e.__c="__cC"+Qn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}Le=Fn.slice,x={__e:function(t,e,n,r){for(var i,s,o;e=e.__;)if((i=e.__c)&&!i.__)try{if((s=i.constructor)&&s.getDerivedStateFromError!=null&&(i.setState(s.getDerivedStateFromError(t)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(t,r||{}),o=i.__d),o)return i.__E=i}catch(l){t=l}throw t}},Mn=0,Ln=function(t){return t!=null&&t.constructor==null},V.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=K({},this.state),typeof t=="function"&&(t=t(K({},n),this.props)),t&&K(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),Nt(this))},V.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),Nt(this))},V.prototype.render=N,ue=[],Nn=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,zn=function(t,e){return t.__v.__b-e.__v.__b},at.__r=0,Bn=/(PointerCapture)$|Capture$/i,qt=0,Mt=Hn(!1),Lt=Hn(!0),Qn=0;var ss=0;function u(t,e,n,r,i,s){e||(e={});var o,l,a=e;if("ref"in a)for(l in a={},e)l=="ref"?o=e[l]:a[l]=e[l];var c={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--ss,__i:-1,__u:0,__source:i,__self:s};if(typeof t=="function"&&(o=t.defaultProps))for(l in o)a[l]===void 0&&(a[l]=o[l]);return x.vnode&&x.vnode(c),c}var se,S,Ft,Yn,ke=0,Xn=[],j=x,er=j.__b,tr=j.__r,nr=j.diffed,rr=j.__c,ir=j.unmount,sr=j.__;function Se(t,e){j.__h&&j.__h(S,t,ke||e),ke=0;var n=S.__H||(S.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function C(t){return ke=1,Dt(ur,t)}function Dt(t,e,n){var r=Se(se++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):ur(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],c=r.t(a,l);a!==c&&(r.__N=[c,r.__[1]],r.__c.setState({}))}],r.__c=S,!S.__f)){var i=function(l,a,c){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(f){return!!f.__c});if(d.every(function(f){return!f.__N}))return!s||s.call(this,l,a,c);var h=r.__c.props!==l;return d.forEach(function(f){if(f.__N){var p=f.__[0];f.__=f.__N,f.__N=void 0,p!==f.__[0]&&(h=!0)}}),s&&s.call(this,l,a,c)||h};S.__f=!0;var s=S.shouldComponentUpdate,o=S.componentWillUpdate;S.componentWillUpdate=function(l,a,c){if(this.__e){var d=s;s=void 0,i(l,a,c),s=d}o&&o.call(this,l,a,c)},S.shouldComponentUpdate=i}return r.__N||r.__}function $(t,e){var n=Se(se++,3);!j.__s&&Vt(n.__H,e)&&(n.__=t,n.u=e,S.__H.__h.push(n))}function Be(t,e){var n=Se(se++,4);!j.__s&&Vt(n.__H,e)&&(n.__=t,n.u=e,S.__h.push(n))}function de(t){return ke=5,Q(function(){return{current:t}},[])}function or(t,e,n){ke=6,Be(function(){if(typeof t=="function"){var r=t(e());return function(){t(null),r&&typeof r=="function"&&r()}}if(t)return t.current=e(),function(){return t.current=null}},n==null?n:n.concat(t))}function Q(t,e){var n=Se(se++,7);return Vt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function je(t,e){return ke=8,Q(function(){return t},e)}function ct(t){var e=S.context[t.__c],n=Se(se++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(S)),e.props.value):t.__}function ar(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function lr(){var t=Se(se++,11);if(!t.__){for(var e=S.__v;e!==null&&!e.__m&&e.__!==null;)e=e.__;var n=e.__m||(e.__m=[0,0]);t.__="P"+n[0]+"-"+n[1]++}return t.__}function os(){for(var t;t=Xn.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(ut),t.__H.__h.forEach(Ut),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){S=null,er&&er(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),sr&&sr(t,e)},j.__r=function(t){tr&&tr(t),se=0;var e=(S=t.__c).__H;e&&(Ft===S?(e.__h=[],S.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(ut),e.__h.forEach(Ut),e.__h=[],se=0)),Ft=S},j.diffed=function(t){nr&&nr(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Xn.push(e)!==1&&Yn===j.requestAnimationFrame||((Yn=j.requestAnimationFrame)||as)(os)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ft=S=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(ut),n.__h=n.__h.filter(function(r){return!r.__||Ut(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),rr&&rr(t,e)},j.unmount=function(t){ir&&ir(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{ut(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var cr=typeof requestAnimationFrame=="function";function as(t){var e,n=function(){clearTimeout(r),cr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);cr&&(e=requestAnimationFrame(n))}function ut(t){var e=S,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),S=e}function Ut(t){var e=S;t.__c=t.__(),S=e}function Vt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function ur(t,e){return typeof e=="function"?e(t):e}function hr(t,e){for(var n in e)t[n]=e[n];return t}function Wt(t,e){for(var n in t)if(n!=="__source"&&!(n in e))return!0;for(var r in e)if(r!=="__source"&&t[r]!==e[r])return!0;return!1}function dr(t,e){var n=e(),r=C({t:{__:n,u:e}}),i=r[0].t,s=r[1];return Be(function(){i.__=n,i.u=e,Ht(i)&&s({t:i})},[t,n,e]),$(function(){return Ht(i)&&s({t:i}),t(function(){Ht(i)&&s({t:i})})},[t]),n}function Ht(t){var e,n,r=t.u,i=t.__;try{var s=r();return!((e=i)===(n=s)&&(e!==0||1/e==1/n)||e!=e&&n!=n)}catch{return!0}}function fr(t){t()}function pr(t){return t}function gr(){return[!1,fr]}var mr=Be;function Jt(t,e){this.props=t,this.context=e}function ls(t,e){function n(i){var s=this.props.ref,o=s==i.ref;return!o&&s&&(s.call?s(null):s.current=null),e?!e(this.props,i)||!o:Wt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,B(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Jt.prototype=new V).isPureReactComponent=!0,Jt.prototype.shouldComponentUpdate=function(t,e){return Wt(this.props,t)||Wt(this.state,e)};var xr=x.__b;x.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),xr&&xr(t)};var cs=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function us(t){function e(n){var r=hr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=cs,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var br=function(t,e){return t==null?null:Z(Z(t).map(e))},hs={map:br,forEach:br,count:function(t){return t?Z(t).length:0},only:function(t){var e=Z(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:Z},ds=x.__e;x.__e=function(t,e,n,r){if(t.then){for(var i,s=e;s=s.__;)if((i=s.__c)&&i.__c)return e.__e==null&&(e.__e=n.__e,e.__k=n.__k),i.__c(t,e)}ds(t,e,n,r)};var yr=x.unmount;function vr(t,e,n){return t&&(t.__c&&t.__c.__H&&(t.__c.__H.__.forEach(function(r){typeof r.__c=="function"&&r.__c()}),t.__c.__H=null),(t=hr({},t)).__c!=null&&(t.__c.__P===n&&(t.__c.__P=e),t.__c.__e=!0,t.__c=null),t.__k=t.__k&&t.__k.map(function(r){return vr(r,e,n)})),t}function _r(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return _r(r,e,n)}),t.__c&&t.__c.__P===e&&(t.__e&&n.appendChild(t.__e),t.__c.__e=!0,t.__c.__P=n)),t}function ht(){this.__u=0,this.o=null,this.__b=null}function wr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function fs(t){var e,n,r;function i(s){if(e||(e=t()).then(function(o){n=o.default||o},function(o){r=o}),r)throw r;if(!n)throw e;return B(n,s)}return i.displayName="Lazy",i.__f=!0,i}function Qe(){this.i=null,this.l=null}x.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),yr&&yr(t)},(ht.prototype=new V).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=wr(r.__v),s=!1,o=function(){s||(s=!0,n.__R=null,i?i(l):l())};n.__R=o;var l=function(){if(!--r.__u){if(r.state.__a){var a=r.state.__a;r.__v.__k[0]=_r(a,a.__c.__P,a.__c.__O)}var c;for(r.setState({__a:r.__b=null});c=r.o.pop();)c.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(o,o)},ht.prototype.componentWillUnmount=function(){this.o=[]},ht.prototype.render=function(t,e){if(this.__b){if(this.__v.__k){var n=document.createElement("div"),r=this.__v.__k[0].__c;this.__v.__k[0]=vr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&B(N,null,t.fallback);return i&&(i.__u&=-33),[B(N,null,e.__a?null:t.children),i]};var kr=function(t,e,n){if(++n[1]===n[0]&&t.l.delete(e),t.props.revealOrder&&(t.props.revealOrder[0]!=="t"||!t.l.size))for(n=t.i;n;){for(;n.length>3;)n.pop()();if(n[1]<n[0])break;t.i=n=n[2]}};function ps(t){return this.getChildContext=function(){return t.context},t.children}function gs(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){he(null,e.v),e.v=null,e.h=null},e.h&&e.h!==n&&e.componentWillUnmount(),!e.v){for(var r=e.__v;r!==null&&!r.__m&&r.__!==null;)r=r.__;e.h=n,e.v={nodeType:1,parentNode:n,childNodes:[],__k:{__m:r.__m},contains:function(){return!0},insertBefore:function(i,s){this.childNodes.push(i),e.h.insertBefore(i,s)},removeChild:function(i){this.childNodes.splice(this.childNodes.indexOf(i)>>>1,1),e.h.removeChild(i)}}}he(B(ps,{context:e.context},t.__v),e.v)}function ms(t,e){var n=B(gs,{__v:t,h:e});return n.containerInfo=e,n}(Qe.prototype=new V).__a=function(t){var e=this,n=wr(e.__v),r=e.l.get(t);return r[0]++,function(i){var s=function(){e.props.revealOrder?(r.push(i),kr(e,t,r)):i()};n?n(s):s()}},Qe.prototype.render=function(t){this.i=null,this.l=new Map;var e=Z(t.children);t.revealOrder&&t.revealOrder[0]==="b"&&e.reverse();for(var n=e.length;n--;)this.l.set(e[n],this.i=[1,0,this.i]);return t.children},Qe.prototype.componentDidUpdate=Qe.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){kr(t,n,e)})};var Sr=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,xs=/^(?: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]/,bs=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ys=/[A-Z0-9]/g,vs=typeof document<"u",_s=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function ws(t,e,n){return e.__k==null&&(e.textContent=""),he(t,e),typeof n=="function"&&n(),t?t.__c:null}function ks(t,e,n){return Zn(t,e),typeof n=="function"&&n(),t?t.__c:null}V.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(V.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var jr=x.event;function Ss(){}function js(){return this.cancelBubble}function Cs(){return this.defaultPrevented}x.event=function(t){return jr&&(t=jr(t)),t.persist=Ss,t.isPropagationStopped=js,t.isDefaultPrevented=Cs,t.nativeEvent=t};var Gt,Ts={enumerable:!1,configurable:!0,get:function(){return this.class}},Cr=x.vnode;x.vnode=function(t){typeof t.type=="string"&&(function(e){var n=e.props,r=e.type,i={},s=r.indexOf("-")===-1;for(var o in n){var l=n[o];if(!(o==="value"&&"defaultValue"in n&&l==null||vs&&o==="children"&&r==="noscript"||o==="class"||o==="className")){var a=o.toLowerCase();o==="defaultValue"&&"value"in n&&n.value==null?o="value":o==="download"&&l===!0?l="":a==="translate"&&l==="no"?l=!1:a[0]==="o"&&a[1]==="n"?a==="ondoubleclick"?o="ondblclick":a!=="onchange"||r!=="input"&&r!=="textarea"||_s(n.type)?a==="onfocus"?o="onfocusin":a==="onblur"?o="onfocusout":bs.test(o)&&(o=a):a=o="oninput":s&&xs.test(o)?o=o.replace(ys,"-$&").toLowerCase():l===null&&(l=void 0),a==="oninput"&&i[o=a]&&(o="oninputCapture"),i[o]=l}}r=="select"&&i.multiple&&Array.isArray(i.value)&&(i.value=Z(n.children).forEach(function(c){c.props.selected=i.value.indexOf(c.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=Z(n.children).forEach(function(c){c.props.selected=i.multiple?i.defaultValue.indexOf(c.props.value)!=-1:i.defaultValue==c.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",Ts)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=Sr,Cr&&Cr(t)};var Tr=x.__r;x.__r=function(t){Tr&&Tr(t),Gt=t.__c};var Rr=x.diffed;x.diffed=function(t){Rr&&Rr(t);var e=t.props,n=t.__e;n!=null&&t.type==="textarea"&&"value"in e&&e.value!==n.value&&(n.value=e.value==null?"":e.value),Gt=null};var Rs={ReactCurrentDispatcher:{current:{readContext:function(t){return Gt.__n[t.__c].props.value},useCallback:je,useContext:ct,useDebugValue:ar,useDeferredValue:pr,useEffect:$,useId:lr,useImperativeHandle:or,useInsertionEffect:mr,useLayoutEffect:Be,useMemo:Q,useReducer:Dt,useRef:de,useState:C,useSyncExternalStore:dr,useTransition:gr}}};function $s(t){return B.bind(null,t)}function dt(t){return!!t&&t.$$typeof===Sr}function As(t){return dt(t)&&t.type===N}function Es(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function Is(t){return dt(t)?rs.apply(null,arguments):t}function Ps(t){return!!t.__k&&(he(null,t),!0)}function qs(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var Ms=function(t,e){return t(e)},Ls=function(t,e){return t(e)},Os=N,Ns=dt,Kt={useState:C,useId:lr,useReducer:Dt,useEffect:$,useLayoutEffect:Be,useInsertionEffect:mr,useTransition:gr,useDeferredValue:pr,useSyncExternalStore:dr,startTransition:fr,useRef:de,useImperativeHandle:or,useMemo:Q,useCallback:je,useContext:ct,useDebugValue:ar,version:"18.3.1",Children:hs,render:ws,hydrate:ks,unmountComponentAtNode:Ps,createPortal:ms,createElement:B,createContext:is,createFactory:$s,cloneElement:Is,createRef:Yi,Fragment:N,isValidElement:dt,isElement:Ns,isFragment:As,isMemo:Es,findDOMNode:qs,Component:V,PureComponent:Jt,memo:ls,forwardRef:us,flushSync:Ls,unstable_batchedUpdates:Ms,StrictMode:Os,Suspense:ht,SuspenseList:Qe,lazy:fs,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:Rs},Y=[],F=[],zs=Uint8Array,Zt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ce=0,Bs=Zt.length;Ce<Bs;++Ce)Y[Ce]=Zt[Ce],F[Zt.charCodeAt(Ce)]=Ce;F[45]=62,F[95]=63;function Qs(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Fs(t,e,n){return(e+n)*3/4-n}function Fe(t){var e,n=Qs(t),r=n[0],i=n[1],s=new zs(Fs(t,r,i)),o=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=F[t.charCodeAt(a)]<<18|F[t.charCodeAt(a+1)]<<12|F[t.charCodeAt(a+2)]<<6|F[t.charCodeAt(a+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=F[t.charCodeAt(a)]<<2|F[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=F[t.charCodeAt(a)]<<10|F[t.charCodeAt(a+1)]<<4|F[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ds(t){return Y[t>>18&63]+Y[t>>12&63]+Y[t>>6&63]+Y[t&63]}function Us(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(Ds(r));return i.join("")}function De(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,l=n-r;o<l;o+=s)i.push(Us(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(Y[e>>2]+Y[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(Y[e>>10]+Y[e>>4&63]+Y[e<<2&63]+"=")),i.join("")}function re(t){if(t===void 0)return{};if(!$r(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function Vs(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function $r(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const Ar=!0,Te=BigInt("-9223372036854775808"),Yt=BigInt("9223372036854775807"),Xt=BigInt("0"),Ws=BigInt("8"),Hs=BigInt("256");function Er(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Js(t){t<Xt&&(t-=Te+Te);let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new Uint8Array(new ArrayBuffer(8));let r=0;for(const i of e.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),t>>=Ws;return De(n)}function Gs(t){const e=Fe(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Xt,r=Xt;for(const i of e)n+=BigInt(i)*Hs**r,r++;return n>Yt&&(n+=Te+Te),n}function Ks(t){if(t<Te||Yt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);const e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),De(new Uint8Array(e))}function Zs(t){const e=Fe(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}const Ys=DataView.prototype.setBigInt64?Ks:Js,Xs=DataView.prototype.getBigInt64?Zs:Gs,Ir=1024;function Pr(t){if(t.length>Ir)throw new Error(`Field name ${t} exceeds maximum field name length ${Ir}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){const n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}function Re(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>Re(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);const e=Object.entries(t);if(e.length===1){const r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return Fe(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return Xs(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=Fe(t.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const o=new DataView(i.buffer).getFloat64(0,Ar);if(!Er(o))throw new Error(`Float ${o} should be encoded as a number`);return o}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,i]of Object.entries(t))Pr(r),n[r]=Re(i);return n}const qr=16384;function Ue(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>qr){const n="[...truncated]";let r=qr-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function en(t,e,n,r){if(t===void 0){const o=n&&` (present at path ${n} in original object ${Ue(e)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<Te||Yt<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Ys(t)}}if(typeof t=="number")if(Er(t)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,t,Ar),{$float:De(new Uint8Array(o))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:De(new Uint8Array(t))};if(Array.isArray(t))return t.map((o,l)=>en(o,e,n+`[${l}]`));if(t instanceof Set)throw new Error(tn(n,"Set",[...t],e));if(t instanceof Map)throw new Error(tn(n,"Map",[...t],e));if(!$r(t)){const o=t?.constructor?.name,l=o?`${o} `:"";throw new Error(tn(n,l,t,e))}const i={},s=Object.entries(t);s.sort(([o,l],[a,c])=>o===a?0:o<a?-1:1);for(const[o,l]of s)l!==void 0&&(Pr(o),i[o]=en(l,e,n+`.${o}`));return i}function tn(t,e,n,r){return t?`${e}${Ue(n)} is not a supported Convex type (present at path ${t} in original object ${Ue(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${Ue(n)} is not a supported Convex type.`}function X(t){return en(t,t,"")}var eo=Object.defineProperty,to=(t,e,n)=>e in t?eo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nn=(t,e,n)=>to(t,typeof e!="symbol"?e+"":e,n),Mr,Lr;const no=Symbol.for("ConvexError");class rn extends(Lr=Error,Mr=no,Lr){constructor(e){super(typeof e=="string"?e:Ue(e)),nn(this,"name","ConvexError"),nn(this,"data"),nn(this,Mr,!0),this.data=e}}const Or=()=>Array.from({length:4},()=>0);Or(),Or();const Nr="1.39.1";var ro=Object.defineProperty,io=(t,e,n)=>e in t?ro(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zr=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);const so="color:rgb(0, 145, 255)";function Br(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Qr{constructor(e){zr(this,"_onLogLineFuncs"),zr(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(const n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(const n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(const n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(const n of Object.values(this._onLogLineFuncs))n("error",...e)}}function Fr(t){const e=new Qr(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}function Dr(t){return new Qr(t)}function ft(t,e,n,r,i){const s=Br(n);if(typeof i=="object"&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),e==="info"){const o=i.match(/^\[.*?\] /);if(o===null){t.error(`[CONVEX ${s}(${r})] Could not parse console.log`);return}const l=i.slice(1,o[0].length-2),a=i.slice(o[0].length);t.log(`%c[CONVEX ${s}(${r})] [${l}]`,so,a)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}function oo(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function $e(t,e,n){return`[CONVEX ${Br(t)}(${e})] ${n.errorMessage}
2
+ Called by client`}function sn(t,e){return e.data=t.errorData,e}function fe(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function pe(t,e){return JSON.stringify({udfPath:fe(t),args:X(e)})}function Ur(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:fe(t),args:X(e),options:X({initialNumItems:r,id:i})})}var ao=Object.defineProperty,lo=(t,e,n)=>e in t?ao(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ee=(t,e,n)=>lo(t,typeof e!="symbol"?e+"":e,n);class co{constructor(){ee(this,"nextQueryId"),ee(this,"querySetVersion"),ee(this,"querySet"),ee(this,"queryIdToToken"),ee(this,"identityVersion"),ee(this,"auth"),ee(this,"outstandingQueriesOlderThanRestart"),ee(this,"outstandingAuthOlderThanRestart"),ee(this,"paused"),ee(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,i){const s=fe(e),o=pe(s,n),l=this.querySet.get(o);if(l!==void 0)return l.numSubscribers+=1,{queryToken:o,modification:null,unsubscribe:()=>this.removeSubscriber(o)};{const a=this.nextQueryId++,c={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,c),this.queryIdToToken.set(a,o);const d=this.querySetVersion,h=this.querySetVersion+1,f={type:"Add",queryId:a,udfPath:s,args:[X(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,f):this.querySetVersion=h,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:h,modifications:[f]},unsubscribe:()=>this.removeSubscriber(o)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const i=this.queryIdToToken.get(n.queryId);i!==void 0&&(this.querySet.get(i).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=fe(e),i=pe(r,n),s=this.querySet.get(i);return s!==void 0?s.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const e=[];for(const i of this.querySet.values()){const s={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[X(i.args)],journal:i.journal,componentPath:i.componentPath};e.push(s),this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const n={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[n,void 0];this.outstandingAuthOlderThanRestart=!0;const r={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[n,r]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,i=this.querySetVersion+1,s={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,s):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:r,newVersion:i,modifications:[s]}}}}var uo=Object.defineProperty,ho=(t,e,n)=>e in t?uo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pt=(t,e,n)=>ho(t,typeof e!="symbol"?e+"":e,n);class fo{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,pt(this,"inflightRequests"),pt(this,"requestsOlderThanRestart"),pt(this,"inflightMutationsCount",0),pt(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(i=>{const s=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:s,requestedAt:new Date,onResult:i}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",i=n.message.udfPath;for(const a of e.logLines)ft(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:Re(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:c}=e;ft(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:c!==void 0?Re(c):void 0,logLines:e.logLines},l=()=>s.onResult(o)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:o}):(n.status={status:"Completed",result:o,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,i]of this.inflightRequests.entries()){const s=i.status;s.status==="Completed"&&s.ts.lessThanOrEqual(e)&&(s.onResolve(),n.set(r,s.result),i.message.type==="Mutation"?this.inflightMutationsCount--:i.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Ve=Symbol.for("functionName"),Vr=Symbol.for("toReferencePath");function po(t){return t[Vr]??null}function go(t){return t.startsWith("function://")}function mo(t){let e;if(typeof t=="string")go(t)?e={functionHandle:t}:e={name:t};else if(t[Ve])e={name:t[Ve]};else{const n=po(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function M(t){const e=mo(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Ve];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Wr(t){return{[Ve]:t}}function Hr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Hr(i)}else if(r===Ve){if(t.length<2){const o=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${o}\``)}const i=t.slice(0,-1).join("/"),s=t[t.length-1];return s==="default"?i:i+":"+s}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}const xo=Hr();var bo=Object.defineProperty,yo=(t,e,n)=>e in t?bo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gt=(t,e,n)=>yo(t,typeof e!="symbol"?e+"":e,n);class We{constructor(e){gt(this,"queryResults"),gt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=re(n[0]),i=M(e),s=this.queryResults.get(pe(i,r));if(s!==void 0)return We.queryValue(s.result)}getAllQueries(e){const n=[],r=M(e);for(const i of this.queryResults.values())i.udfPath===fe(r)&&n.push({args:i.args,value:We.queryValue(i.result)});return n}setQuery(e,n,r){const i=re(n),s=M(e),o=pe(s,i);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const a={udfPath:s,args:i,result:l};this.queryResults.set(o,a),this.modifiedQueries.push(o)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class vo{constructor(){gt(this,"queryResults"),gt(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(o=>!n.has(o.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const i=new We(this.queryResults);for(const o of this.optimisticUpdates)o.update(i);const s=[];for(const[o,l]of this.queryResults){const a=r.get(o);(a===void 0||a.result!==l.result)&&s.push(o)}return s}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new We(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){const n=this.queryResults.get(e);if(n!==void 0)return n.result}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?sn(r,new rn($e("query",n.udfPath,r))):new Error($e("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var _o=Object.defineProperty,wo=(t,e,n)=>e in t?_o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,on=(t,e,n)=>wo(t,typeof e!="symbol"?e+"":e,n);class L{constructor(e,n){on(this,"low"),on(this,"high"),on(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new L(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?Jr:e>=ko?So:new L(e%He|0,e/He|0)}toString(){return(BigInt(this.high)*BigInt(He)+BigInt(this.low)).toString()}equals(e){return L.isLong(e)||(e=L.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return L.isLong(e)||(e=L.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?L.fromNumber(e):new L(e.low,e.high)}}const Jr=new L(0,0),Gr=65536,He=Gr*Gr,ko=He*He,So=new L(-1,-1);var jo=Object.defineProperty,Co=(t,e,n)=>e in t?jo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mt=(t,e,n)=>Co(t,typeof e!="symbol"?e+"":e,n);class Kr{constructor(e,n){mt(this,"version"),mt(this,"remoteQuerySet"),mt(this,"queryPath"),mt(this,"logger"),this.version={querySet:0,ts:L.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ft(this.logger,"info","query",i,o);const s=Re(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:s,logLines:r.logLines});break}case"QueryFailed":{const i=this.queryPath(r.queryId);if(i)for(const o of r.logLines)ft(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?Re(s):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function an(t){const e=Fe(t);return L.fromBytesLE(Array.from(e))}function To(t){const e=new Uint8Array(t.toBytesLE());return De(e)}function Zr(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:an(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:an(t.startVersion.ts)},endVersion:{...t.endVersion,ts:an(t.endVersion.ts)}}}}function Ro(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:To(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var $o=Object.defineProperty,Ao=(t,e,n)=>e in t?$o(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,T=(t,e,n)=>Ao(t,typeof e!="symbol"?e+"":e,n);const Eo=1e3,Io=1001,Po=1005,qo=4040;let xt;function Ae(){return xt===void 0&&(xt=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(xt+performance.now())}function Yr(){return`t=${Math.round((Ae()-xt)/100)/10}s`}const Xr={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Mo(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Xr))if(t.startsWith(e))return e;return"Unknown"}class Lo{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,T(this,"socket"),T(this,"connectionCount"),T(this,"_hasEverConnected",!1),T(this,"lastCloseReason"),T(this,"transitionChunkBuffer",null),T(this,"defaultInitialBackoff"),T(this,"maxBackoff"),T(this,"retries"),T(this,"serverInactivityThreshold"),T(this,"reconnectDueToServerInactivityTimeout"),T(this,"scheduledReconnect",null),T(this,"networkOnlineHandler",null),T(this,"pendingNetworkRecoveryInfo",null),T(this,"uri"),T(this,"onOpen"),T(this,"onResume"),T(this,"onMessage"),T(this,"webSocketConstructor"),T(this,"logger"),T(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window>"u"||typeof window.addEventListener!="function"||this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<"u"&&typeof window.removeEventListener=="function"&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=Zr(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Ae()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Yr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Yr())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){const{timeSavedMs:n}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:n}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(n/1e3)}s of waiting`)}},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let i=Zr(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${i.type}`),i.type==="Ping")return;if(i.type==="TransitionChunk"){const o=this.assembleTransition(i);if(!o)return;i=o,this._logVerbose(`assembled full ws message of type ${i.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${i.type} while buffering TransitionChunks`)),i.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:i}),this.onMessage(i).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==Eo&&n.code!==Io&&n.code!==Po&&n.code!==qo){let i=`WebSocket closed with code ${n.code}`;n.reason&&(i+=`: ${n.reason}`),this.logger.log(i),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(i)}const r=Mo(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=Ro(e),i=JSON.stringify(r);let s=!1;try{this.socket.ws.send(i),s=!0}catch(o){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${o}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${s?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`);const r=Ae(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},n);this.scheduledReconnect={timeout:i,scheduledAt:r,backoffMs:n}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),this.socket.state!=="disconnected"){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){const n=Ae()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-n),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(n)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=e!==null?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:Ae()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:Xr[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const i=Math.min(r,this.maxBackoff),s=i*(Math.random()-.5);return i+s}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=Ae()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(r)}ms`,s=`${Math.round(n/1e4)/100}MB`,o=n/(r/1e3),l=`${Math.round(o/1e4)/100}MB per second`;this._logVerbose(`received ${s} transition in ${i} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${s}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${s} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function Oo(){return No()}function No(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class Je extends Error{}Je.prototype.name="InvalidTokenError";function zo(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function Bo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return zo(e)}catch{return atob(e)}}function ei(t,e){if(typeof t!="string")throw new Je("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new Je(`Invalid token specified: missing part #${n+1}`);let i;try{i=Bo(r)}catch(s){throw new Je(`Invalid token specified: invalid base64 for part #${n+1} (${s.message})`)}try{return JSON.parse(i)}catch(s){throw new Je(`Invalid token specified: invalid json for part #${n+1} (${s.message})`)}}var Qo=Object.defineProperty,Fo=(t,e,n)=>e in t?Qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e,n)=>Fo(t,typeof e!="symbol"?e+"":e,n);const Do=480*60*60*1e3,ti=2;class Uo{constructor(e,n,r){D(this,"authState",{state:"noAuth"}),D(this,"configVersion",0),D(this,"syncState"),D(this,"authenticate"),D(this,"stopSocket"),D(this,"tryRestartSocket"),D(this,"pauseSocket"),D(this,"resumeSocket"),D(this,"clearAuth"),D(this,"logger"),D(this,"refreshTokenLeewaySeconds"),D(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=ti){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${ti-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:i}=n;if(!r||!i){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const s=i-r;if(s<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let o=Math.min(Do,(s-this.refreshTokenLeewaySeconds)*1e3);o<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${s}s`),o=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},o);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${o}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const i=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return ei(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const Vo=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Wo(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function Ho(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Jo(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of Vo){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(Ho)}var Go=Object.defineProperty,Ko=(t,e,n)=>e in t?Go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,R=(t,e,n)=>Ko(t,typeof e!="symbol"?e+"":e,n);class Zo{constructor(e,n,r){if(R(this,"address"),R(this,"state"),R(this,"requestManager"),R(this,"webSocketManager"),R(this,"authenticationManager"),R(this,"remoteQuerySet"),R(this,"optimisticQueryResults"),R(this,"_transitionHandlerCounter",0),R(this,"_nextRequestId"),R(this,"_onTransitionFns",new Map),R(this,"_sessionId"),R(this,"firstMessageReceived",!1),R(this,"debug"),R(this,"logger"),R(this,"maxObservedTimestamp"),R(this,"connectionStateSubscribers",new Map),R(this,"nextConnectionStateSubscriberId",0),R(this,"_lastPublishedConnectionState"),R(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const p=this.connectionState();if(JSON.stringify(p)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=p;for(const g of this.connectionStateSubscribers.values())g(p)}})}),R(this,"mark",p=>{this.debug&&Wo(p,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&Vs(e),r={...r};const i=r.authRefreshTokenLeewaySeconds??10;let s=r.webSocketConstructor;if(!s&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");s=s||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?Dr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Fr({verbose:r.verbose??!1});const o=e.search("://");if(o===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(o+3),a=e.substring(0,o);let c;if(a==="http")c="ws";else if(a==="https")c="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${c}://${l}/api/${Nr}/sync`;this.state=new co,this.remoteQuerySet=new Kr(p=>this.state.queryPath(p),this.logger),this.requestManager=new fo(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Uo(this.state,{authenticate:p=>{const g=this.state.setAuth(p);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new vo,this.addOnTransitionHandler(p=>{n(p.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=Oo();const{unsavedChangesWarning:f}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(f===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else f!==!1&&window.addEventListener("beforeunload",p=>{if(this.requestManager.hasIncompleteRequests()){p.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(p||window.event).returnValue=g,g}});this.webSocketManager=new Lo(d,{onOpen:p=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...p,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Kr(b=>this.state.queryPath(b),this.logger);const[g,m]=this.state.restart();m&&this.webSocketManager.sendMessage(m),this.webSocketManager.sendMessage(g);for(const b of this.requestManager.restart())this.webSocketManager.sendMessage(b)},onResume:()=>{const[p,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),p&&this.webSocketManager.sendMessage(p);for(const m of this.requestManager.resume())this.webSocketManager.sendMessage(m)},onMessage:p=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),p.type){case"Transition":{this.observedTimestamp(p.endVersion.ts),this.authenticationManager.onTransition(p),this.remoteQuerySet.transition(p),this.state.transition(p);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{p.success&&this.observedTimestamp(p.ts);const g=this.requestManager.onResponse(p);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(p);break}case"AuthError":{this.authenticationManager.onAuthError(p);break}case"FatalError":{const g=oo(this.logger,p.error);throw this.webSocketManager.terminate(),g}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},s,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[s,o]of n){const l=this.state.queryToken(s);if(l!==null){const a={result:o,udfPath:this.state.queryPath(s),args:this.state.queryArgs(s)};r.set(l,a)}}const i=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:i.map(s=>{const o=this.optimisticQueryResults.rawQueryResult(s);return{token:s,modification:{kind:"Updated",result:o}}}),reflectedMutations:Array.from(e).map(([s,o])=>({requestId:s,result:o})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?ei(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const i=re(n),{modification:s,queryToken:o,unsubscribe:l}=this.state.subscribe(e,i,r?.journal,r?.componentPath);return s!==null&&this.webSocketManager.sendMessage(s),{queryToken:o,unsubscribe:()=>{const a=l();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(e,n){const r=re(n),i=pe(e,r);return this.optimisticQueryResults.queryResult(i)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=re(n),i=pe(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=re(n),i=pe(e,r);return this.state.queryJournal(i)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const i=await this.mutationInternal(e,n,r);if(!i.success)throw i.errorData!==void 0?sn(i,new rn($e("mutation",e,i))):new Error($e("mutation",e,i));return i.value}async mutationInternal(e,n,r,i){const{mutationPromise:s}=this.enqueueMutation(e,n,r,i);return s}enqueueMutation(e,n,r,i){const s=re(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const h=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},p=this.optimisticQueryResults.applyOptimisticUpdate(h,o).map(g=>{const m=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:m===void 0?void 0:{success:!0,value:m,logLines:[]}}}});this.handleTransition({queries:p,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[X(s)]},a=this.webSocketManager.sendMessage(l),c=this.requestManager.request(l,a);return{requestId:o,mutationPromise:c}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?sn(r,new rn($e("action",e,r))):new Error($e("action",e,r));return r.value}async actionInternal(e,n,r){const i=re(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[X(i)]},l=this.webSocketManager.sendMessage(o);return this.requestManager.request(o,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=Jo(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${Nr}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function ln(t){if(typeof t!="object"||t===null||!Array.isArray(t.page)||typeof t.isDone!="boolean"||typeof t.continueCursor!="string")throw new Error(`Not a valid paginated query result: ${t?.toString()}`);return t}var Yo=Object.defineProperty,Xo=(t,e,n)=>e in t?Yo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ni=(t,e,n)=>Xo(t,typeof e!="symbol"?e+"":e,n);class ea{constructor(e,n){this.client=e,this.onTransition=n,ni(this,"paginatedQuerySet",new Map),ni(this,"lastTransitionTs"),this.lastTransitionTs=L.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=fe(e),s=Ur(i,n,r),o=()=>this.removePaginatedQuerySubscriber(s),l=this.paginatedQuerySet.get(s);return l?(l.numSubscribers+=1,{paginatedQueryToken:s,unsubscribe:o}):(this.paginatedQuerySet.set(s,{token:s,canonicalizedUdfPath:i,args:n,numSubscribers:1,options:{initialNumItems:r.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:r.id}),this.addPageToPaginatedQuery(s,null,r.initialNumItems),{paginatedQueryToken:s,unsubscribe:o})}localQueryResult(e,n,r){const i=fe(e),s=Ur(i,n,r);return this.localQueryResultByToken(s)}localQueryResultByToken(e){const n=this.paginatedQuerySet.get(e);if(!n)return;const r=this.activePageQueryTokens(n);if(r.length===0)return{results:[],status:"LoadingFirstPage",loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)};let i=[],s=!1,o=!1;for(const a of r){const c=this.client.localQueryResultByToken(a);if(c===void 0){s=!0,o=!1;continue}const d=ln(c);i=i.concat(d.page),o=!!d.isDone}let l;return s?l=i.length===0?"LoadingFirstPage":"LoadingMore":o?l="Exhausted":l="CanLoadMore",{results:i,status:l,loadMore:a=>this.loadMoreOfPaginatedQuery(e,a)}}onBaseTransition(e){const n=e.queries.map(o=>o.token),r=this.queriesContainingTokens(n);let i=[];r.length>0&&(this.processPaginatedQuerySplits(r,o=>this.client.localQueryResultByToken(o)),i=r.map(o=>({token:o,modification:{kind:"Updated",result:this.localQueryResultByToken(o)}})));const s={...e,paginatedQueries:i};this.onTransition(s)}loadMoreOfPaginatedQuery(e,n){this.mustGetPaginatedQuery(e);const r=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(r);if(!i)return!1;const s=ln(i);if(s.isDone)return!1;this.addPageToPaginatedQuery(e,s.continueCursor,n);const o={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(o),!0}queriesContainingTokens(e){if(e.length===0)return[];const n=[],r=new Set(e);for(const[i,s]of this.paginatedQuerySet)for(const o of this.allQueryTokens(s))if(r.has(o)){n.push(i);break}return n}processPaginatedQuerySplits(e,n){for(const r of e){const i=this.mustGetPaginatedQuery(r),{ongoingSplits:s,pageKeyToQuery:o,pageKeys:l}=i;for(const[a,[c,d]]of s)n(o.get(c).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,c,d);for(const a of l){if(s.has(a))continue;const c=o.get(a).queryToken,d=n(c);if(!d)continue;const h=ln(d);h.splitCursor&&(h.pageStatus==="SplitRecommended"||h.pageStatus==="SplitRequired"||h.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(e,n,r,i){const s=e.nextPageKey++,o=e.nextPageKey++,l={cursor:i,numItems:e.options.initialNumItems,id:e.id},a=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:null,endCursor:r}});e.pageKeyToQuery.set(s,a);const c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,c),e.ongoingSplits.set(n,[s,o])}addPageToPaginatedQuery(e,n,r){const i=this.mustGetPaginatedQuery(e),s=i.nextPageKey++,o={cursor:n,numItems:r,id:i.id},l={...i.args,paginationOpts:o},a=this.client.subscribe(i.canonicalizedUdfPath,l);return i.pageKeys.push(s),i.pageKeyToQuery.set(s,a),a}removePaginatedQuerySubscriber(e){const n=this.paginatedQuerySet.get(e);if(n&&(n.numSubscribers-=1,!(n.numSubscribers>0))){for(const r of n.pageKeyToQuery.values())r.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,n,r,i){const s=e.pageKeyToQuery.get(n);e.pageKeyToQuery.delete(n);const o=e.pageKeys.indexOf(n);e.pageKeys.splice(o,1,r,i),e.ongoingSplits.delete(n),s.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(n=>e.pageKeyToQuery.get(n).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(n=>n.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){const n=this.mustGetPaginatedQuery(e),r=n.pageKeys[n.pageKeys.length-1];if(r===void 0)throw new Error(`No pages for paginated query ${e}`);return n.pageKeyToQuery.get(r).queryToken}mustGetPaginatedQuery(e){const n=this.paginatedQuerySet.get(e);if(!n)throw new Error("paginated query no longer exists for token "+e);return n}}function ta({getCurrentValue:t,subscribe:e}){const[n,r]=C(()=>({getCurrentValue:t,subscribe:e,value:t()}));let i=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(i=t(),r({getCurrentValue:t,subscribe:e,value:i})),$(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const c=t();return a.value===c?a:{...a,value:c}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var na=Object.defineProperty,ra=(t,e,n)=>e in t?na(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ie=(t,e,n)=>ra(t,typeof e!="symbol"?e+"":e,n);const ia=5e3;if(typeof Kt>"u")throw new Error("Required dependency 'react' not found");function ri(t,e,n){function r(i){return la(i),e.mutation(t,i,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(s){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${M(t)}`);return ri(t,e,s)},r}class sa{constructor(e,n){if(ie(this,"address"),ie(this,"cachedSync"),ie(this,"cachedPaginatedQueryClient"),ie(this,"listeners"),ie(this,"options"),ie(this,"closed",!1),ie(this,"_logger"),ie(this,"adminAuth"),ie(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?Dr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Fr({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new Zo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new ea(this.cachedSync,e=>this.handleTransition(e)),this.cachedSync)}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw new Error("Should already be instantiated")}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,i]=n,s=M(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),c=this.listeners.get(l);return c!==void 0?c.add(o):this.listeners.set(l,new Set([o])),()=>{if(this.closed)return;const d=this.listeners.get(l);d.delete(o),d.size===0&&this.listeners.delete(l),a()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(s,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(s,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(s,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??ia,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=M(e);return{onUpdate:s=>{const{paginatedQueryToken:o,unsubscribe:l}=this.paginatedQueryClient.subscribe(i,n||{},r),a=this.listeners.get(o);return a!==void 0?a.add(s):this.listeners.set(o,new Set([s])),()=>{if(this.closed)return;const c=this.listeners.get(o);c.delete(s),c.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=M(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=M(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),i=r.localQueryResult();return i!==void 0?Promise.resolve(i):new Promise((s,o)=>{const l=r.onUpdate(()=>{l();try{s(r.localQueryResult())}catch(a){o(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){const n=e.queries.map(i=>i.token),r=e.paginatedQueries.map(i=>i.token);this.transition([...n,...r])}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const i of r)i()}}}const cn=Kt.createContext(void 0);function oa(){return ct(cn)}const aa=({client:t,children:e})=>Kt.createElement(cn.Provider,{value:t},e);function ii(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:re(e[0]),i=typeof t=="string"?Wr(t):t,s=M(i),o=Q(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(X(r)),s,n]),a=da(o).query;if(a instanceof Error)throw a;return a}function Ge(t){const e=typeof t=="string"?Wr(t):t,n=ct(cn);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return Q(()=>ri(e,n),[n,M(e)])}function la(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var ca=Object.defineProperty,ua=(t,e,n)=>e in t?ca(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,un=(t,e,n)=>ua(t,typeof e!="symbol"?e+"":e,n);class ha{constructor(e){un(this,"createWatch"),un(this,"queries"),un(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:i,paginationOptions:s}=e[n];if(M(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(M(r)!==M(o.query)||JSON.stringify(X(i))!==JSON.stringify(X(o.args))||JSON.stringify(s)!==JSON.stringify(o.paginationOptions))&&(this.removeQuery(n),this.addQuery(n,r,i,s?{paginationOptions:s}:{}))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:i,args:s}=e[r],o=e[r].paginationOptions;M(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(c){if(c instanceof Error)a=c;else throw c}n[r]=a}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:i,watch:s,paginationOptions:o}=this.queries[n],l="journal"in s?s.journal():void 0;this.removeQuery(n),this.addQuery(n,r,i,{...l?{journal:l}:[],...o?{paginationOptions:o}:{}})}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,{paginationOptions:i,journal:s}){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const o=this.createWatch(n,r,{...s?{journal:s}:[],...i?{paginationOptions:i}:{}}),l=o.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:o,unsubscribe:l,...i?{paginationOptions:i}:{}}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function da(t){const e=oa();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=Q(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return fa(t,n)}function fa(t,e){const[n]=C(()=>new ha(e));n.createWatch!==e&&n.setCreateWatch(e),$(()=>()=>n.destroy(),[n]);const r=Q(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return ta(r)}var pa=Symbol.for("preact-signals");function bt(){if(oe>1)oe--;else{for(var t,e=!1;Ke!==void 0;){var n=Ke;for(Ke=void 0,hn++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&ai(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(hn=0,oe--,e)throw t}}function ga(t){if(oe>0)return t();oe++;try{return t()}finally{bt()}}var w=void 0;function si(t){var e=w;w=void 0;try{return t()}finally{w=e}}var Ke=void 0,oe=0,hn=0,yt=0;function oi(t){if(w!==void 0){var e=t.n;if(e===void 0||e.t!==w)return e={i:0,S:t,p:w.s,n:void 0,t:w,e:void 0,x:void 0,r:e},w.s!==void 0&&(w.s.n=e),w.s=e,t.n=e,32&w.f&&t.S(e),e;if(e.i===-1)return e.i=0,e.n!==void 0&&(e.n.p=e.p,e.p!==void 0&&(e.p.n=e.n),e.p=w.s,e.n=void 0,w.s.n=e,w.s=e),e}}function A(t,e){this.v=t,this.i=0,this.n=void 0,this.t=void 0,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}A.prototype.brand=pa,A.prototype.h=function(){return!0},A.prototype.S=function(t){var e=this,n=this.t;n!==t&&t.e===void 0&&(t.x=n,this.t=t,n!==void 0?n.e=t:si(function(){var r;(r=e.W)==null||r.call(e)}))},A.prototype.U=function(t){var e=this;if(this.t!==void 0){var n=t.e,r=t.x;n!==void 0&&(n.x=r,t.e=void 0),r!==void 0&&(r.e=n,t.x=void 0),t===this.t&&(this.t=r,r===void 0&&si(function(){var i;(i=e.Z)==null||i.call(e)}))}},A.prototype.subscribe=function(t){var e=this;return Ze(function(){var n=e.value,r=w;w=void 0;try{t(n)}finally{w=r}},{name:"sub"})},A.prototype.valueOf=function(){return this.value},A.prototype.toString=function(){return this.value+""},A.prototype.toJSON=function(){return this.value},A.prototype.peek=function(){var t=w;w=void 0;try{return this.value}finally{w=t}},Object.defineProperty(A.prototype,"value",{get:function(){var t=oi(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(hn>100)throw new Error("Cycle detected");this.v=t,this.i++,yt++,oe++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{bt()}}}});function O(t,e){return new A(t,e)}function ai(t){for(var e=t.s;e!==void 0;e=e.n)if(e.S.i!==e.i||!e.S.h()||e.S.i!==e.i)return!0;return!1}function li(t){for(var e=t.s;e!==void 0;e=e.n){var n=e.S.n;if(n!==void 0&&(e.r=n),e.S.n=e,e.i=-1,e.n===void 0){t.s=e;break}}}function ci(t){for(var e=t.s,n=void 0;e!==void 0;){var r=e.p;e.i===-1?(e.S.U(e),r!==void 0&&(r.n=e.n),e.n!==void 0&&(e.n.p=r)):n=e,e.S.n=e.r,e.r!==void 0&&(e.r=void 0),e=r}t.s=n}function ge(t,e){A.call(this,void 0),this.x=t,this.s=void 0,this.g=yt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}ge.prototype=new A,ge.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===yt))return!0;if(this.g=yt,this.f|=1,this.i>0&&!ai(this))return this.f&=-2,!0;var t=w;try{li(this),w=this;var e=this.x();(16&this.f||this.v!==e||this.i===0)&&(this.v=e,this.f&=-17,this.i++)}catch(n){this.v=n,this.f|=16,this.i++}return w=t,ci(this),this.f&=-2,!0},ge.prototype.S=function(t){if(this.t===void 0){this.f|=36;for(var e=this.s;e!==void 0;e=e.n)e.S.S(e)}A.prototype.S.call(this,t)},ge.prototype.U=function(t){if(this.t!==void 0&&(A.prototype.U.call(this,t),this.t===void 0)){this.f&=-33;for(var e=this.s;e!==void 0;e=e.n)e.S.U(e)}},ge.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var t=this.t;t!==void 0;t=t.x)t.t.N()}},Object.defineProperty(ge.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=oi(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function vt(t,e){return new ge(t,e)}function ui(t){var e=t.u;if(t.u=void 0,typeof e=="function"){oe++;var n=w;w=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,dn(t),r}finally{w=n,bt()}}}function dn(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ui(t)}function ma(t){if(w!==this)throw new Error("Out-of-order effect");ci(this),w=t,this.f&=-2,8&this.f&&dn(this),bt()}function Ee(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ee.prototype.c=function(){var t=this.S();try{if(8&this.f||this.x===void 0)return;var e=this.x();typeof e=="function"&&(this.u=e)}finally{t()}},Ee.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ui(this),li(this),oe++;var t=w;return w=this,ma.bind(this,t)},Ee.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ke,Ke=this)},Ee.prototype.d=function(){this.f|=8,1&this.f||dn(this)},Ee.prototype.dispose=function(){this.d()};function Ze(t,e){var n=new Ee(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var hi,_t,wt,xa=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,di=[];Ze(function(){hi=this.N})();function Ie(t,e){x[t]=e.bind(null,x[t]||function(){})}function kt(t){if(wt){var e=wt;wt=void 0,e()}wt=t&&t.S()}function fi(t){var e=this,n=t.data,r=Ye(n);r.value=n;var i=Q(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var c=vt(function(){var p=r.value.value;return p===0?0:p===!0?"":p||""}),d=vt(function(){return!Array.isArray(c.value)&&!Ln(c.value)}),h=Ze(function(){if(this.N=pi,d.value){var p=c.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=p)}}),f=e.__$u.d;return e.__$u.d=function(){h(),f.call(this)},[d,c]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}fi.displayName="ReactiveTextNode",Object.defineProperties(A.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:fi},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Ie("__b",function(t,e){if(typeof e.type=="string"){var n,r=e.props;for(var i in r)if(i!=="children"){var s=r[i];s instanceof A&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Ie("__r",function(t,e){if(t(e),e.type!==N){kt();var n,r=e.__c;r&&(r.__$f&=-2,(n=r.__$u)===void 0&&(r.__$u=n=(function(i,s){var o;return Ze(function(){o=this},{name:s}),o.c=i,o})(function(){var i;xa&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),_t=r,kt(n)}}),Ie("__e",function(t,e,n,r){kt(),_t=void 0,t(e,n,r)}),Ie("diffed",function(t,e){kt(),_t=void 0;var n;if(typeof e.type=="string"&&(n=e.__e)){var r=e.__np,i=e.props;if(r){var s=n.U;if(s)for(var o in s){var l=s[o];l!==void 0&&!(o in r)&&(l.d(),s[o]=void 0)}else s={},n.U=s;for(var a in r){var c=s[a],d=r[a];c===void 0?(c=ba(n,a,d,i),s[a]=c):c.o(d,i)}}}t(e)});function ba(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=O(n);return{o:function(o,l){s.value=o,r=l},d:Ze(function(){this.N=pi;var o=s.value.value;r[e]!==o&&(r[e]=o,i?t[e]=o:o!=null&&(o!==!1||e[4]==="-")?t.setAttribute(e,o):t.removeAttribute(e))})}}Ie("unmount",function(t,e){if(typeof e.type=="string"){var n=e.__e;if(n){var r=n.U;if(r){n.U=void 0;for(var i in r){var s=r[i];s&&s.d()}}}}else{var o=e.__c;if(o){var l=o.__$u;l&&(o.__$u=void 0,l.d())}}t(e)}),Ie("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),V.prototype.shouldComponentUpdate=function(t,e){if(this.__R)return!0;var n=this.__$u,r=n&&n.s!==void 0;for(var i in e)return!0;if(this.__f||typeof this.u=="boolean"&&this.u===!0){var s=2&this.__$f;if(!(r||s||4&this.__$f)||1&this.__$f)return!0}else if(!(r||4&this.__$f)||3&this.__$f)return!0;for(var o in t)if(o!=="__source"&&t[o]!==this.props[o])return!0;for(var l in this.props)if(!(l in t))return!0;return!1};function Ye(t,e){return Q(function(){return O(t,e)},[])}function ya(t,e){var n=de(t);return n.current=t,_t.__$f|=4,Q(function(){return vt(function(){return n.current()},e)},[])}var va=function(t){queueMicrotask(function(){queueMicrotask(t)})};function _a(){ga(function(){for(var t;t=di.shift();)hi.call(t)})}function pi(){di.push(this)===1&&(x.requestAnimationFrame||va)(_a)}const I=O(!1),St=O(void 0),me=O(void 0);function wa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function fn(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function ka(t,e){const n=t.title??e?.title??"Assistant";return{title:n,greeting:t.greeting??e?.welcomeMessage??`Hi! I'm ${n}. How can I help?`,locale:t.locale??e?.locale,position:t.position??e?.position,colorScheme:t.colorScheme??e?.colorScheme,hideBranding:t.hideBranding??e?.hideBranding??!1,triggerIcon:t.triggerIcon??e?.triggerIcon??"chat",triggerRadius:t.triggerRadius??e?.triggerRadius??"full",triggerLabel:t.triggerLabel??e?.triggerLabel??"Chatte mit uns",mode:t.mode??"floating",primaryColor:t.primaryColor??e?.primaryColor,accentColor:t.accentColor??e?.accentColor,fontFamily:t.fontFamily??e?.fontFamily,fontSize:t.fontSize??e?.fontSize,borderRadius:t.borderRadius??e?.borderRadius,windowWidth:t.windowWidth??e?.windowWidth,windowHeight:t.windowHeight??e?.windowHeight}}async function Sa(t,e,n,r){const i=new URL(`${t}/widget/config`);i.searchParams.set("orgSlug",e),r&&i.searchParams.set("projSlug",r);const s=await fetch(i.toString(),{signal:n});return s.ok?s.json():null}function ja(t,e,n){const[r,i]=C(null);return $(()=>{i(null);const s=n??"https://festive-mouse-978.eu-west-1.convex.cloud",o=s?fn(s):void 0;if(!o||!t)return;const l=new AbortController;async function a(c){try{const d=await Sa(c,t,l.signal,e);d&&i(d)}catch(d){if(d instanceof Error&&d.name==="AbortError")return}}return a(o),()=>{l.abort()}},[t,e,n]),r}async function gi(t,e,n){try{const r=await fetch(`${e}/widget/bootstrap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{orgSlug:t,projSlug:n}:{orgSlug:t}),credentials:"omit"});if(r.ok){const i=await r.json();return{ok:!0,token:i.token,excludePaths:i.excludePaths}}return r.status===403?{ok:!1,error:"unauthorized"}:r.status===404?{ok:!1,error:"not_found"}:r.status===429?{ok:!1,error:"rate_limited",retryAfterSec:Number(r.headers.get("Retry-After"))||60}:{ok:!1,error:"network"}}catch{return{ok:!1,error:"network"}}}function Ca(t,e,n,r){$(()=>{if(n)return;const i=r??"https://festive-mouse-978.eu-west-1.convex.cloud",s=i?fn(i):void 0;if(!s||!t)return;let o=!1;return(async()=>{const l=await gi(t,s,e);if(!o)if(l.ok)me.value=l.token;else{const a=e?`project '${t}/${e}'`:`org '${t}'`;l.error==="unauthorized"?console.error(`[JexityChat] This domain is not authorized for ${a}. Check the widget's domain rules.`):l.error==="not_found"?console.error(`[JexityChat] No active widget config found for ${a}.`):l.error==="rate_limited"?console.error(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${l.retryAfterSec??60}s.`):console.error(`[JexityChat] Bootstrap failed: ${l.error}`)}})(),()=>{o=!0}},[t,e,n,r])}const mi={title:"Assistant",statusOnline:"Online · Responds in seconds",inputPlaceholder:"Type a message…",aiThinking:"AI is responding…",sendAriaLabel:"Send message",openChatAriaLabel:"Open chat",closeChatAriaLabel:"Close chat",errorNetwork:"Network error. Please try again.",errorQuota:"Message limit reached. Please try again later.",errorRateLimited:"Too many messages. Try again in {seconds}s.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resuming conversation…",startingConversation:"Starting conversation…",sessionNotFound:"Your previous session was not found. Starting a new conversation.",startNewConversation:"Start new conversation",chatWith:"Chat with {title}",haveReferenceNumber:"Have a reference number?",referencePlaceholder:"e.g. JEX-A3B7C2",resume:"Resume",howCanWeHelp:"How can we help?",getInstantHelp:"Get instant help",submitTicket:"Submit a ticket",replyByEmail:"We'll reply by email",ticketSubmitted:"Ticket submitted",yourReferenceNumber:"Your reference number:",sentToEmailHint:"We've sent it to your email. Use this number to follow up.",done:"Done",submittingTicket:"Submitting your ticket…",yourName:"Your name",yourEmail:"Your email",submit:"Submit",back:"Go back",escalationFormTitle:"Leave your details",escalationSubtitle:"Our team will get back to you by email so you don’t have to wait here.",escalationNameLabel:"Your name",escalationEmailLabel:"Your email",escalationSubmit:"Send to team",escalationSubmitting:"Sending…",escalationSubmitted:"Request submitted",escalationConsent:"We’ll only use your email to respond to this conversation.",escalationSkip:"Skip, I’ll wait here",escalationPromptTitle:"Talk to our team",escalationPromptSubtitle:"We can notify you by email when our team replies.",escalationPromptSubmit:"Leave details",escalationSubmitFailed:"Failed to submit. Please try again.",sessionNotFoundPrompt:"Session not found. Would you like to start a new conversation?",sessionResolved:"This conversation has been resolved.",tryAgain:"Try again",goBack:"Go back",somethingWentWrong:"Something went wrong",fabLabel:"Chat with us",chatNoLongerAvailable:"This chat is no longer available.",talkToHuman:"Talk to human",talkToHumanAria:"Talk to a human agent",handoffPending:"Connecting you to a human agent…",handoffFailed:"Could not request a human agent. Try again.",handoffRateLimited:"You requested an agent recently. Please wait before trying again.",resumeListLabel:"Continue conversation",resumeListTimestamp:"{minutes}m ago"},Ta={title:"Assistent",statusOnline:"Online · Antwortet in Sekunden",inputPlaceholder:"Nachricht eingeben…",aiThinking:"KI antwortet…",sendAriaLabel:"Nachricht senden",openChatAriaLabel:"Chat öffnen",closeChatAriaLabel:"Chat schließen",errorNetwork:"Netzwerkfehler. Bitte versuche es erneut.",errorQuota:"Nachrichtenlimit erreicht. Bitte versuche es später erneut.",errorRateLimited:"Zu viele Nachrichten. Bitte in {seconds} Sek. erneut versuchen.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch wird fortgesetzt…",startingConversation:"Konversation wird gestartet…",sessionNotFound:"Ihre vorherige Sitzung wurde nicht gefunden. Ein neues Gespräch wird gestartet.",startNewConversation:"Neues Gespräch beginnen",chatWith:"Chatte mit {title}",haveReferenceNumber:"Hast du eine Referenznummer?",referencePlaceholder:"z.B. JEX-A3B7C2",resume:"Fortsetzen",howCanWeHelp:"Wie können wir helfen?",getInstantHelp:"Soforthilfe erhalten",submitTicket:"Ticket einreichen",replyByEmail:"Wir antworten per E-Mail",ticketSubmitted:"Ticket eingereicht",yourReferenceNumber:"Deine Referenznummer:",sentToEmailHint:"Wir haben sie an deine E-Mail gesendet. Verwende diese Nummer für Rückfragen.",done:"Fertig",submittingTicket:"Dein Ticket wird übermittelt…",yourName:"Dein Name",yourEmail:"Deine E-Mail",submit:"Absenden",back:"Zurück",escalationFormTitle:"Hinterlassen Sie Ihre Daten",escalationSubtitle:"Unser Team meldet sich per E-Mail bei Ihnen — Sie müssen nicht hier warten.",escalationNameLabel:"Ihr Name",escalationEmailLabel:"Ihre E-Mail",escalationSubmit:"An Team senden",escalationSubmitting:"Wird gesendet…",escalationSubmitted:"Anfrage gesendet",escalationConsent:"Wir verwenden Ihre E-Mail nur, um auf diese Unterhaltung zu antworten.",escalationSkip:"Überspringen, ich warte hier",escalationPromptTitle:"Sprechen Sie mit unserem Team",escalationPromptSubtitle:"Wir benachrichtigen Sie per E-Mail, wenn wir antworten.",escalationPromptSubmit:"Daten hinterlassen",escalationSubmitFailed:"Senden fehlgeschlagen. Bitte versuche es erneut.",sessionNotFoundPrompt:"Sitzung nicht gefunden. Möchten Sie ein neues Gespräch beginnen?",sessionResolved:"Diese Unterhaltung wurde abgeschlossen.",tryAgain:"Erneut versuchen",goBack:"Zurück",somethingWentWrong:"Etwas ist schiefgelaufen",fabLabel:"Chatte mit uns",chatNoLongerAvailable:"Dieser Chat ist nicht mehr verfügbar.",talkToHuman:"Mit Mitarbeiter sprechen",talkToHumanAria:"Mit einem menschlichen Mitarbeiter sprechen",handoffPending:"Sie werden mit einem Mitarbeiter verbunden…",handoffFailed:"Anfrage konnte nicht gesendet werden. Erneut versuchen.",handoffRateLimited:"Sie haben kürzlich einen Mitarbeiter angefragt. Bitte warten Sie.",resumeListLabel:"Unterhaltung fortsetzen",resumeListTimestamp:"vor {minutes} Min."},Ra=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],$a="de",Aa="jex-locale",pn=O("de"),Ea={en:mi,de:Ta};function P(){return Ea[pn.value]??mi}function gn(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return Ra.some(r=>r.value===e)?e:null}function xi(t){const e=gn(t);if(e)return e;try{const n=gn(localStorage.getItem(Aa));if(n)return n}catch{}if(typeof navigator<"u"){const n=gn(navigator.language);if(n)return n}return $a}function Ia(t){$(()=>{function e(n){const r=t??window.location.origin;if(n.origin!==r||n.data?.type!=="jexity:config")return;const{locale:i}=n.data.payload;i&&(pn.value=xi(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const bi="jex-session-history",Pa=900*1e3,W=O([]),Xe=O(null),yi=vt(()=>W.value.length>0),et=O(null);function qa(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function Ma(t){try{const e=sessionStorage.getItem(bi);if(!e)return[];const n=JSON.parse(e);return n.v!==1||!Array.isArray(n.entries)?[]:n.entries.filter(r=>t-r.lastActivityAt<=Pa)}catch{return[]}}function jt(t){try{const e={v:1,entries:t};sessionStorage.setItem(bi,JSON.stringify(e))}catch{}}function La(){const t=Date.now(),e=Ma(t);W.value=e,jt(e),Xe.value=e.length>0?e[e.length-1].ref:null}function vi(){const t=qa(),e=Date.now(),n=[...W.value,{ref:t,startedAt:e,lastActivityAt:e}];return W.value=n,Xe.value=t,jt(n),t}function _i(t){const e=Date.now(),n=W.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);W.value=n,Xe.value=t,jt(n)}function mn(t){if(!t)return;const e=Date.now(),n=W.value.map(r=>r.ref===t?{...r,lastActivityAt:e}:r);W.value=n,jt(n)}const z=O(wi());function wi(){return yi.value?[{id:"home"}]:[{id:"chat"}]}function Oa(){z.value=wi()}const Na=O("screen");function xe(t){z.value=[...z.value,t]}function Ct(){z.value.length>1&&(z.value=z.value.slice(0,-1))}function xn(t){z.value=[...z.value.slice(0,-1),t]}function za(t){const e={},{primaryColor:n,theme:r}=t;if(n&&(e["--jex-primary"]=n,e["--jex-bg-trigger"]=n,e["--jex-bg-header"]=n,e["--jex-bg-msg-user"]=n,e["--jex-bg-send-btn"]=n),t.accentColor&&(e["--jex-accent"]=t.accentColor),r?.bg){const i=r.bg;i.trigger&&(e["--jex-bg-trigger"]=i.trigger),i.header&&(e["--jex-bg-header"]=i.header),i.msgUser&&(e["--jex-bg-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-bg-msg-bot"]=i.msgBot),i.window&&(e["--jex-bg-window"]=i.window),i.sendBtn&&(e["--jex-bg-send-btn"]=i.sendBtn)}if(r?.text){const i=r.text;i.header&&(e["--jex-text-header"]=i.header),i.msgUser&&(e["--jex-text-msg-user"]=i.msgUser),i.msgBot&&(e["--jex-text-msg-bot"]=i.msgBot),i.main&&(e["--jex-text-main"]=i.main),i.muted&&(e["--jex-text-muted"]=i.muted)}if(r?.border){const i=r.border;i.window&&(e["--jex-border-window"]=i.window),i.input&&(e["--jex-border-input"]=i.input)}return t.fontFamily&&(e["--jex-font-family"]=t.fontFamily),t.fontSize&&(e["--jex-font-size"]=`${t.fontSize}px`),t.borderRadius&&(e["--jex-radius"]=t.borderRadius),t.windowWidth&&(e["--jex-window-width"]=`${t.windowWidth}px`),t.windowHeight&&(e["--jex-window-height"]=`${t.windowHeight}px`),Object.keys(e).length>0?e:void 0}function bn({size:t=24}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M12 8V4H8"}),u("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),u("path",{d:"M2 14h2"}),u("path",{d:"M20 14h2"}),u("path",{d:"M15 13v2"}),u("path",{d:"M9 13v2"})]})}function ki({title:t,rightAction:e}){const n=P(),r=z.value.length>1;return u("header",{class:"jex-chat-header",children:[r&&u("button",{class:"jex-header-back",onClick:Ct,"aria-label":n.back||"Go back",children:u("svg",{width:20,height:20,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"m15 18-6-6 6-6"})})}),!r&&u(bn,{size:24}),u("div",{class:"jex-header-info",children:[u("h3",{children:t}),u("p",{children:n.statusOnline})]}),e&&u("div",{class:"jex-header-right",children:e})]})}function Ba({size:t=14}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"})})}function Si(){return u("div",{class:"jex-widget-footer",children:u("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[u(Ba,{size:14}),u("span",{children:["Powered by ",u("strong",{children:"Jexity"})]})]})})}function ji({size:t=28}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:u("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Qa({size:t=28}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M18 6 6 18"}),u("path",{d:"m6 6 12 12"})]})}function Fa({size:t=24,...e}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",...e,children:u("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"})})}const Da={chat:u(ji,{size:28}),bot:u(bn,{size:28}),sparkles:u(Fa,{size:28})},Ua={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Va({radius:t="full",iconOption:e="chat",label:n}){const r=P(),i=n??r.fabLabel,s=i!=="";return u("button",{class:`jex-floating-button ${!I.value&&s?"jex-has-label":""}`,style:{borderRadius:Ua[t]??"9999px"},onClick:()=>{I.value=!I.value},"aria-label":I.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:I.value?u(Qa,{size:28}):u("div",{class:"jex-fab-inner",children:[Da[e],s&&u("span",{class:"jex-fab-label",children:i})]})})}function Wa({title:t,onStartFresh:e,onResetSession:n}){const r=P(),[i,s]=C("");function o(){et.value="fresh",e(),xe({id:"chat"})}function l(c){et.value="resume",n(),_i(c),xe({id:"chat"})}function a(c){c.preventDefault();const d=i.trim().toUpperCase();d&&(et.value="resume",n(),_i(d),xe({id:"chat"}))}return u("div",{class:"jex-home",children:[u("div",{class:"jex-home-hero",children:[u("div",{class:"jex-home-avatar",children:[u(ji,{size:24}),u("span",{class:"jex-home-status-dot"})]}),u("div",{class:"jex-home-hero-text",children:[u("h2",{class:"jex-home-title",children:t}),u("span",{class:"jex-home-status",children:r.statusOnline})]})]}),u("form",{class:"jex-home-lookup",onSubmit:a,children:[u("input",{class:"jex-home-lookup-input",type:"text",placeholder:r.referencePlaceholder,value:i,onInput:c=>{s(c.currentTarget.value)}}),u("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!i.trim(),children:r.resume})]}),u("div",{class:"jex-home-actions",children:[W.value.length>0&&u("div",{class:"jex-home-history",children:W.value.slice().reverse().map(c=>u("button",{class:"jex-home-resume-card",onClick:()=>{l(c.ref)},children:[u("div",{class:"jex-home-resume-top",children:[u("span",{class:"jex-home-resume-label",children:r.resumeListLabel}),u("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:u("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),u("span",{class:"jex-home-resume-ref",children:c.ref}),u("span",{class:"jex-home-resume-meta",children:r.resumeListTimestamp.replace("{minutes}",String(Math.max(1,Math.round((Date.now()-c.lastActivityAt)/6e4))))})]},c.ref))}),u("button",{class:"jex-home-new-btn",onClick:o,children:W.value.length>0?r.startNewConversation:r.chatWith.replace("{title}",t)})]})]})}function Ha({title:t}){const e=P();return u("div",{class:"jex-selection",children:[u("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),u("div",{class:"jex-selection-options",children:[u("button",{class:"jex-selection-option",onClick:()=>xe({id:"chat"}),children:[u("span",{class:"jex-selection-icon",children:"💬"}),u("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),u("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),u("button",{class:"jex-selection-option",onClick:()=>xe({id:"form"}),children:[u("span",{class:"jex-selection-icon",children:"📝"}),u("span",{class:"jex-selection-label",children:e.submitTicket}),u("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function Ci(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return Ci(t,s)}else if(i===Vr){if(e.length<1){const s=[t,...e].join(".");throw new Error(`API path is expected to be of the form \`${t}.childComponent.functionName\`. Found: \`${s}\``)}return"_reference/childComponent/"+e.join("/")}else return}};return new Proxy({},n)}const Ja=()=>Ci("components",[]),be=xo;Ja();const Ga=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim();const Ti=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();const Ka=t=>t.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,n,r)=>r?r.toUpperCase():n.toLowerCase());const Ri=t=>{const e=Ka(t);return e.charAt(0).toUpperCase()+e.slice(1)};var Za={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};const Ya=t=>{for(const e in t)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};const Xa=({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,children:i,iconNode:s,class:o="",...l})=>B("svg",{...Za,width:String(e),height:e,stroke:t,"stroke-width":r?Number(n)*24/Number(e):n,class:["lucide",o].join(" "),...!i&&!Ya(l)&&{"aria-hidden":"true"},...l},[...s.map(([a,c])=>B(a,c)),...Z(i)]);const el=(t,e)=>{const n=({class:r="",className:i="",children:s,...o})=>B(Xa,{...o,iconNode:e,class:Ga(`lucide-${Ti(Ri(t))}`,`lucide-${Ti(t)}`,r,i)},s);return n.displayName=Ri(t),n};const tl=el("corner-up-left",[["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}],["path",{d:"M9 14 4 9l5-5",key:"102s5s"}]]);function yn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ye=yn();function $i(t){ye=t}var ve={exec:()=>null};function y(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,s)=>{let o=typeof s=="string"?s:s.source;return o=o.replace(q.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var nl=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),q={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),htmlBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:t=>new RegExp(`^ {0,${Math.min(3,t-1)}}>`)},rl=/^(?:[ \t]*(?:\n|$))+/,il=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,sl=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,tt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ol=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,vn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ai=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ei=y(Ai).replace(/bull/g,vn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),al=y(Ai).replace(/bull/g,vn).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),_n=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ll=/^[^\n]+/,wn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,cl=y(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ul=y(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,vn).getRegex(),Tt="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",kn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,hl=y("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",kn).replace("tag",Tt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ii=y(_n).replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex(),dl=y(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ii).getRegex(),Sn={blockquote:dl,code:il,def:cl,fences:sl,heading:ol,hr:tt,html:hl,lheading:Ei,list:ul,newline:rl,paragraph:Ii,table:ve,text:ll},Pi=y("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex(),fl={...Sn,lheading:al,table:Pi,paragraph:y(_n).replace("hr",tt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pi).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Tt).getRegex()},pl={...Sn,html:y(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",kn).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ve,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:y(_n).replace("hr",tt).replace("heading",` *#{1,6} *[^
3
+ ]`).replace("lheading",Ei).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},gl=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ml=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,qi=/^( {2,}|\\)\n(?!\s*$)/,xl=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Pe=/[\p{P}\p{S}]/u,Rt=/[\s\p{P}\p{S}]/u,jn=/[^\s\p{P}\p{S}]/u,bl=y(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Rt).getRegex(),Mi=/(?!~)[\p{P}\p{S}]/u,yl=/(?!~)[\s\p{P}\p{S}]/u,vl=/(?:[^\s\p{P}\p{S}]|~)/u,_l=y(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",nl?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Li=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,wl=y(Li,"u").replace(/punct/g,Pe).getRegex(),kl=y(Li,"u").replace(/punct/g,Mi).getRegex(),Oi="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Sl=y(Oi,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Pe).getRegex(),jl=y(Oi,"gu").replace(/notPunctSpace/g,vl).replace(/punctSpace/g,yl).replace(/punct/g,Mi).getRegex(),Cl=y("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Pe).getRegex(),Tl=y(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Pe).getRegex(),Rl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$l=y(Rl,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,Rt).replace(/punct/g,Pe).getRegex(),Al=y(/\\(punct)/,"gu").replace(/punct/g,Pe).getRegex(),El=y(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Il=y(kn).replace("(?:-->|$)","-->").getRegex(),Pl=y("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Il).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),$t=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ql=y(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",$t).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ni=y(/^!?\[(label)\]\[(ref)\]/).replace("label",$t).replace("ref",wn).getRegex(),zi=y(/^!?\[(ref)\](?:\[\])?/).replace("ref",wn).getRegex(),Ml=y("reflink|nolink(?!\\()","g").replace("reflink",Ni).replace("nolink",zi).getRegex(),Bi=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Cn={_backpedal:ve,anyPunctuation:Al,autolink:El,blockSkip:_l,br:qi,code:ml,del:ve,delLDelim:ve,delRDelim:ve,emStrongLDelim:wl,emStrongRDelimAst:Sl,emStrongRDelimUnd:Cl,escape:gl,link:ql,nolink:zi,punctuation:bl,reflink:Ni,reflinkSearch:Ml,tag:Pl,text:xl,url:ve},Ll={...Cn,link:y(/^!?\[(label)\]\((.*?)\)/).replace("label",$t).getRegex(),reflink:y(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",$t).getRegex()},Tn={...Cn,emStrongRDelimAst:jl,emStrongLDelim:kl,delLDelim:Tl,delRDelim:$l,url:y(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Bi).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:y(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Bi).getRegex()},Ol={...Tn,br:y(qi).replace("{2,}","*").getRegex(),text:y(Tn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},At={normal:Sn,gfm:fl,pedantic:pl},nt={normal:Cn,gfm:Tn,breaks:Ol,pedantic:Ll},Nl={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Qi=t=>Nl[t];function te(t,e){if(e){if(q.escapeTest.test(t))return t.replace(q.escapeReplace,Qi)}else if(q.escapeTestNoEncode.test(t))return t.replace(q.escapeReplaceNoEncode,Qi);return t}function Fi(t){try{t=encodeURI(t).replace(q.percentDecode,"%")}catch{return null}return t}function Di(t,e){let n=t.replace(q.findPipe,(s,o,l)=>{let a=!1,c=o;for(;--c>=0&&l[c]==="\\";)a=!a;return a?"|":" |"}),r=n.split(q.splitPipe),i=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;i<r.length;i++)r[i]=r[i].trim().replace(q.slashPipe,"|");return r}function rt(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r&&t.charAt(r-i-1)===e;)i++;return t.slice(0,r-i)}function zl(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function Bl(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=i,n++;return r}function Ui(t,e,n,r,i){let s=e.href,o=e.title||null,l=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let a={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:o,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,a}function Ql(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
4
4
  `).map(s=>{let o=s.match(n.other.beginningSpace);if(o===null)return s;let[l]=o;return l.length>=i.length?s.slice(i.length):s}).join(`
5
- `)}var Et=class{options;rules;lexer;constructor(t){this.options=t||be}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:rt(n,`
5
+ `)}var Et=class{options;rules;lexer;constructor(t){this.options=t||ye}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?n:rt(n,`
6
6
  `)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Ql(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=rt(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:rt(e[0],`
7
7
  `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=rt(e[0],`
8
8
  `).split(`
@@ -24,7 +24,7 @@ ${d}`:d;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
24
24
  `+f}p=!f.trim(),c+=ce+`
25
25
  `,t=t.substring(ce.length+1),h=G.slice(g)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),i.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),i.raw+=c}let l=i.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let a of i.items){if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),a.task){if(a.text=a.text.replace(this.rules.other.listReplaceTask,""),a.tokens[0]?.type==="text"||a.tokens[0]?.type==="paragraph"){a.tokens[0].raw=a.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),a.tokens[0].text=a.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let d={type:"checkbox",raw:c[0]+" ",checked:c[0]!=="[ ]"};a.checked=d.checked,i.loose?a.tokens[0]&&["paragraph","text"].includes(a.tokens[0].type)&&"tokens"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}if(!i.loose){let c=a.tokens.filter(h=>h.type==="space"),d=c.length>0&&c.some(h=>this.rules.other.anyLine.test(h.raw));i.loose=d}}if(i.loose)for(let a of i.items){a.loose=!0;for(let c of a.tokens)c.type==="text"&&(c.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:e[0],href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Di(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
26
26
  `):[],s={type:"table",raw:e[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?s.align.push("right"):this.rules.other.tableAlignCenter.test(o)?s.align.push("center"):this.rules.other.tableAlignLeft.test(o)?s.align.push("left"):s.align.push(null);for(let o=0;o<n.length;o++)s.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:s.align[o]});for(let o of i)s.rows.push(Di(o,s.header.length).map((l,a)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:s.align[a]})));return s}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
27
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=rt(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=zl(e[2],"()");if(s===-2)return;if(s>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+s;e[2]=e[2].substring(0,s),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ui(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Ui(n,i,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,l=i,a=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+i);(r=c.exec(e))!=null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(o=[...s].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&i%3&&!((i+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let d=[...r[0]][0].length,h=t.slice(0,i+r.index+d+o);if(Math.min(i,o)%2){let p=h.slice(1,-1);return{type:"em",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,l=i,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+i);(r=a.exec(e))!=null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(o=[...s].length,o!==i))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...r[0]][0].length,d=t.slice(0,i+r.index+c+o),h=d.slice(i,-i);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},H=class Pn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||be,this.options.tokenizer=this.options.tokenizer||new Et,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:q,block:At.normal,inline:nt.normal};this.options.pedantic?(n.block=At.pedantic,n.inline=nt.pedantic):this.options.gfm&&(n.block=At.gfm,this.options.breaks?n.inline=nt.breaks:n.inline=nt.gfm),this.tokenizer.rules=n}static get rules(){return{block:At,inline:nt}}static lex(e,n){return new Pn(n).lex(e)}static lexInline(e,n){return new Pn(n).inlineTokens(e)}lex(e){e=e.replace(q.carriageReturn,`
27
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=rt(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=zl(e[2],"()");if(s===-2)return;if(s>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+s;e[2]=e[2].substring(0,s),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Ui(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=e[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Ui(n,i,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,l=i,a=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+i);(r=c.exec(e))!=null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(o=[...s].length,r[3]||r[4]){l+=o;continue}else if((r[5]||r[6])&&i%3&&!((i+o)%3)){a+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l+a);let d=[...r[0]][0].length,h=t.slice(0,i+r.index+d+o);if(Math.min(i,o)%2){let p=h.slice(1,-1);return{type:"em",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,s,o,l=i,a=this.rules.inline.delRDelim;for(a.lastIndex=0,e=e.slice(-1*t.length+i);(r=a.exec(e))!=null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(o=[...s].length,o!==i))continue;if(r[3]||r[4]){l+=o;continue}if(l-=o,l>0)continue;o=Math.min(o,o+l);let c=[...r[0]][0].length,d=t.slice(0,i+r.index+c+o),h=d.slice(i,-i);return{type:"del",raw:d,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},H=class Pn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ye,this.options.tokenizer=this.options.tokenizer||new Et,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:q,block:At.normal,inline:nt.normal};this.options.pedantic?(n.block=At.pedantic,n.inline=nt.pedantic):this.options.gfm&&(n.block=At.gfm,this.options.breaks?n.inline=nt.breaks:n.inline=nt.gfm),this.tokenizer.rules=n}static get rules(){return{block:At,inline:nt}}static lex(e,n){return new Pn(n).lex(e)}static lexInline(e,n){return new Pn(n).inlineTokens(e)}lex(e){e=e.replace(q.carriageReturn,`
28
28
  `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){for(this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(q.tabCharGlobal," ").replace(q.spaceLine,""));e;){let i;if(this.options.extensions?.block?.some(o=>(i=o.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let o=n.at(-1);i.raw.length===1&&o!==void 0?o.raw+=`
29
29
  `:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
30
30
  `)?"":`
@@ -38,7 +38,7 @@ ${d}`:d;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
38
38
  `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i),r=s.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
39
39
  `)?"":`
40
40
  `)+i.raw,o.text+=`
41
- `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i);continue}if(e){let o="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,i=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)a.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)s=i[2]?i[2].length:0,r=r.slice(0,i.index+s)+"["+"a".repeat(i[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="";for(;e;){o||(l=""),o=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=n.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let c=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(c=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),o=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},It=class{options;parser;constructor(t){this.options=t||be}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(q.notSpaceStart)?.[0],i=t.replace(q.endingNewline,"")+`
41
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(i);continue}if(e){let o="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,i=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)a.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)s=i[2]?i[2].length:0,r=r.slice(0,i.index+s)+"["+"a".repeat(i[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,l="";for(;e;){o||(l=""),o=!1;let a;if(this.options.extensions?.inline?.some(d=>(a=d.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let d=n.at(-1);a.type==="text"&&d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,l)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let c=e;if(this.options.extensions?.startInline){let d=1/0,h=e.slice(1),f;this.options.extensions.startInline.forEach(p=>{f=p.call({lexer:this},h),typeof f=="number"&&f>=0&&(d=Math.min(d,f))}),d<1/0&&d>=0&&(c=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(l=a.raw.slice(-1)),o=!0;let d=n.at(-1);d?.type==="text"?(d.raw+=a.raw,d.text+=a.text):n.push(a);continue}if(e){let d="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(d);break}else throw new Error(d)}}return n}},It=class{options;parser;constructor(t){this.options=t||ye}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(q.notSpaceStart)?.[0],i=t.replace(q.endingNewline,"")+`
42
42
  `;return r?'<pre><code class="language-'+te(r)+'">'+(n?i:te(i,!0))+`</code></pre>
43
43
  `:"<pre><code>"+(n?i:te(i,!0))+`</code></pre>
44
44
  `}blockquote({tokens:t}){return`<blockquote>
@@ -56,7 +56,7 @@ ${this.parser.parse(t)}</blockquote>
56
56
  `}tablerow({text:t}){return`<tr>
57
57
  ${t}</tr>
58
58
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
59
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${te(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),i=Fi(t);if(i===null)return r;t=i;let s='<a href="'+t+'"';return e&&(s+=' title="'+te(e)+'"'),s+=">"+r+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Fi(t);if(i===null)return te(n);t=i;let s=`<img src="${t}" alt="${te(n)}"`;return e&&(s+=` title="${te(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:te(t.text)}},Rn=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},J=class qn{options;renderer;textRenderer;constructor(e){this.options=e||be,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Rn}static parse(e,n){return new qn(n).parse(e)}static parseInline(e,n){return new qn(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let o=i,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let s=i;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let o='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let s=e[i];if(this.options.extensions?.renderers?.[s.type]){let l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=l||"";continue}}let o=s;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},it=class{options;block;constructor(t){this.options=t||be}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?H.lex:H.lexInline}provideParser(){return this.block?J.parse:J.parseInline}},Fl=class{defaults=yn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=J;Renderer=It;TextRenderer=Rn;Lexer=H;Tokenizer=Et;Hooks=it;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let i=r;for(let s of i.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of i.rows)for(let o of s)n=n.concat(this.walkTokens(o.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(s=>{let o=i[s].flat(1/0);n=n.concat(this.walkTokens(o,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=e.renderers[i.name];s?e.renderers[i.name]=function(...o){let l=i.renderer.apply(this,o);return l===!1&&(l=s.apply(this,o)),l}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=e[i.level];s?s.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new It(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,l=n.renderer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Et(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,l=n.tokenizer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new it;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,l=n.hooks[o],a=i[o];it.passThroughHooks.has(s)?i[o]=c=>{if(this.defaults.async&&it.passThroughHooksRespectAsync.has(s))return(async()=>{let h=await l.call(i,c);return a.call(i,h)})();let d=l.call(i,c);return a.call(i,d)}:i[o]=(...c)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(i,c);return h===!1&&(h=await a.apply(i,c)),h})();let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(o){let l=[];return l.push(s.call(this,o)),i&&(l=l.concat(i.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return H.lex(t,e??this.defaults)}parser(t,e){return J.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(e):e,l=await(i.hooks?await i.hooks.provideLexer():t?H.lex:H.lexInline)(o,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser():t?J.parse:J.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(s);try{i.hooks&&(e=i.hooks.preprocess(e));let o=(i.hooks?i.hooks.provideLexer():t?H.lex:H.lexInline)(e,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():t?J.parse:J.parseInline)(o,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(o){return s(o)}}}onError(t,e){return n=>{if(n.message+=`
60
- Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+te(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},ve=new Fl;function k(t,e){return ve.parse(t,e)}k.options=k.setOptions=function(t){return ve.setOptions(t),k.defaults=ve.defaults,$i(k.defaults),k},k.getDefaults=yn,k.defaults=be,k.use=function(...t){return ve.use(...t),k.defaults=ve.defaults,$i(k.defaults),k},k.walkTokens=function(t,e){return ve.walkTokens(t,e)},k.parseInline=ve.parseInline,k.Parser=J,k.parser=J.parse,k.Renderer=It,k.TextRenderer=Rn,k.Lexer=H,k.lexer=H.lex,k.Tokenizer=Et,k.Hooks=it,k.parse=k,k.options,k.setOptions,k.use,k.walkTokens,k.parseInline,J.parse,H.lex,k.setOptions({breaks:!0,gfm:!0});function Dl({text:t}){const e=Q(()=>{if(!t)return"";const n=k.parse(t);return typeof n=="string"?n:""},[t]);return u("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}const $n=O(""),ae=O(null),Vi=O(Date.now());function Ul(t){if(!t)return;const e=t.trim().split(/\s+/)[0];if(!e)return;const n=`@${e} `,r=$n.value;r.includes(n)||r.includes(`@${e}`)||($n.value=r.trimStart()?`${n}${r.trimStart()}`:n)}function Vl(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function Pe({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:s,botAvatarUrl:o}){const l=!!r,[a,c]=C(!1),d=Se(()=>c(!0),[]),h=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return u("div",{class:"jex-message-row bot",children:[u("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?u("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?u("span",{class:"jex-avatar-initials",children:Vl(i??"")}):o&&!a?u("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):u(bn,{size:14})}),u("div",{class:"jex-message-content",children:[u("div",{class:h,children:[u(Dl,{text:t}),e&&u("span",{class:"jex-streaming-cursor"})]}),l&&i&&u("div",{class:"jex-message-author-row",children:[u("span",{class:"jex-message-author",children:i}),u("button",{type:"button",class:"jex-reply-tag-btn","aria-label":`Reply to ${i}`,title:`Reply to ${i}`,onClick:()=>{Ul(i)},children:u(tl,{size:12})})]})]})]})}function Wl({text:t}){return u("div",{class:"jex-message user",children:t})}function Hl({message:t,sessionId:e,visitorId:n}){const r=P();return t.formData?u("div",{class:"jex-inline-form-submitted",children:[u("span",{class:"jex-inline-form-check",children:"✓"}),u("div",{children:[u("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),u("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):u("div",{class:"jex-message-row bot",children:u(Jl,{messageId:t._id,sessionId:e,visitorId:n})})}function Jl({messageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=C(""),[o,l]=C(""),[a,c]=C(!1),d=Je(xe.functions.chat.public.helpdesk.submitEscalation);async function h(f){if(f.preventDefault(),!a){c(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()})}catch(p){console.error("[FormMessage] Submit failed:",p),c(!1)}}}return u("div",{class:"jex-inline-form",children:[u("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),u("form",{class:"jex-form",onSubmit:f=>{h(f)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:f=>{s(f.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,disabled:a,onInput:f=>{l(f.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),u("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}const Gl={crawl:"🌐",file:"📄",snippet:"💡",qa:"❓"};function Kl({sources:t}){const[e,n]=C(!1);return t.length===0?null:u("div",{class:"jex-sources-row",children:[u("button",{type:"button",class:"jex-sources-toggle",onClick:()=>{n(r=>!r)},"aria-expanded":e,children:[u("span",{class:"jex-sources-icon",children:"📖"}),u("span",{children:[t.length," ",t.length===1?"source":"sources"]}),u("span",{class:`jex-sources-chevron${e?" jex-sources-chevron--open":""}`,children:"▾"})]}),e?u("div",{class:"jex-sources-pills",children:t.map((r,i)=>{const s=r.sourceType==="crawl",o=Zl(r),l=s&&r.url?`${r.title}
61
- ${r.url}`:r.title,a=u(N,{children:[typeof r.id=="number"?u("span",{class:"jex-source-id",children:r.id}):null,u("span",{class:"jex-source-type",children:Gl[r.sourceType]}),u("span",{class:"jex-source-label",children:o}),u("span",{class:"jex-source-score",children:["· ",r.score.toFixed(2)]})]});return s&&r.url?u("a",{class:"jex-source-pill",href:r.url,target:"_blank",rel:"noopener noreferrer",title:l,children:a},i):u("span",{class:"jex-source-pill",title:l,children:a},i)})}):null]})}function Zl(t){if(t.sourceType==="crawl"&&t.url)try{const e=new URL(t.url);return!e.pathname||e.pathname==="/"?e.hostname:e.pathname}catch{}return t.title}function Yl(){return u("div",{class:"jex-typing",children:[u("span",{}),u("span",{}),u("span",{})]})}const Xl=/\s?\[\d+\]/g;function Wi(t){return t.replace(Xl,"")}function ec({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:s,visitorId:o}){const l=P(),a=de(null),[c,d]=C(null),h=de(null);return $(()=>{if(!o||!t||t.length===0)return;const f=t[t.length-1];f.role==="assistant"&&f.status!=="streaming"&&f._id!==h.current&&(h.current=f._id,mn(o))},[t,o]),$(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),u("div",{class:"jex-chat-messages",children:[u(Pe,{text:e}),n&&r&&i?u("div",{class:"jex-session-prompt",children:[u("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),u("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?u("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(f=>{if(f.contentType==="human-notice")return u(Pe,{text:f.content},f._id);if(f.contentType==="escalation-form"&&s&&o)return Na.value==="screen"&&!f.formData?c===f._id?null:u("div",{class:"jex-inline-form jex-inline-form-card",children:[u("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),u("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),u("button",{class:"jex-form-submit",type:"button",onClick:()=>{me({id:"escalation-form",formMessageId:f._id,sessionId:s,visitorId:o})},children:l.escalationPromptSubmit}),u("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(f._id)},children:l.escalationSkip})]},f._id):u(Hl,{message:f,sessionId:s,visitorId:o},f._id);if(f.contentType==="escalation-confirm")return u(Pe,{text:f.content},f._id);if(f.role==="user")return u(Wl,{text:f.content},f._id);const p={authorId:f.authorId,authorName:f.authorName,authorImage:f.authorImage};return f.status==="streaming"&&f.content===""?u(Yl,{},f._id):f.status==="streaming"?u(Pe,{text:Wi(f.content),streaming:!0,...p},f._id):f.status==="error"?u(Pe,{text:f.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},f._id):u("div",{children:[u(Pe,{text:Wi(f.content),...p}),f.sources&&f.sources.length>0?u(Kl,{sources:f.sources}):null]},f._id)}),u("div",{ref:a})]})}function tc({size:t=18}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M22 2 11 13"}),u("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function nc(){const t=P(),e=ya(()=>{const n=ae.value;return n===null?0:Math.max(0,Math.ceil((n-Vi.value)/1e3))});return $(()=>{const n=ae.value;if(n===null)return;const r=setInterval(()=>{Vi.value=Date.now()},1e3),i=setTimeout(()=>{ae.value=null},Math.max(0,n-Date.now()));return()=>{clearInterval(r),clearTimeout(i)}},[ae.value]),ae.value===null?null:u("div",{class:"jex-rate-limit-notice",role:"status","aria-live":"polite",children:t.errorRateLimited.replace("{seconds}",String(e.value))})}function rc({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:s,onStartFresh:o}){const l=P(),a=$n,c=Je(xe.functions.chat.public.conversations.send),d=ae.value!==null&&ae.value>Date.now(),h=n||r||d;if(i==="resolved")return u("div",{class:"jex-chat-input-resolved",children:[u("div",{class:"jex-resolved-notice",children:l.sessionResolved}),u("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{o()},children:l.startNewConversation})]});async function f(){const p=a.value.trim();if(!p||h)return;const g=t&&e?{sessionId:t,visitorId:e}:await s();if(g){a.value="";try{const m=await c({sessionId:g.sessionId,visitorId:g.visitorId,content:p});!m.ok&&m.reason==="rate_limited"?ae.value=Date.now()+m.retryAfterMs:mn(g.visitorId)}catch(m){console.error("[jexity] Failed to send message:",m)}}}return u("div",{class:"jex-chat-input",children:[u(nc,{}),u("input",{type:"text","aria-label":l.inputPlaceholder,placeholder:r?l.aiThinking:l.inputPlaceholder,value:a.value,onInput:p=>{a.value=p.currentTarget.value},onKeyDown:p=>{p.key==="Enter"&&f()},disabled:n||r}),u("button",{class:"jex-send-btn",onClick:f,"aria-label":l.sendAriaLabel,disabled:h,children:u(tc,{size:18})})]})}function An({message:t}){const[e,n]=C(!1);return $(()=>{const r=setTimeout(()=>{n(!0)},80);return()=>{clearTimeout(r)}},[]),e?u("div",{class:"jex-overlay jex-loading",children:[u("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&u("p",{class:"jex-loading-message",children:t})]}):null}function ic({greeting:t,orgSlug:e,projSlug:n,sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,resumeFailed:l,isOrgDeleted:a,ensureSession:c,startFresh:d}){const h=P(),f=ii(xe.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),p=ii(xe.functions.chat.public.sessions.getSessionStatus,r&&i?{sessionId:r,visitorId:i}:"skip"),g=r!==null&&f===void 0,m=f?.some(E=>E.status==="streaming")??!1,b=de((()=>{const E=et.peek();return E!==null?E:yi.peek()?"resume":"fresh"})()).current;if($(()=>{et.value=null},[]),$(()=>{c()},[c]),$(()=>{i&&mn(i)},[i]),a)return u("div",{class:"jex-chat-messages",children:u("div",{class:"jex-session-notice",children:h.chatNoLongerAvailable})});const _=b==="fresh"&&!r,v=b==="resume"&&(!r||g);return _?u(An,{message:h.startingConversation}):v?u(An,{message:h.resumeConversation}):u(N,{children:[u(ec,{conversations:f,greeting:t,sessionNotFound:o,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),u(rc,{sessionId:r,visitorId:i,isLoading:s,isStreaming:m,sessionStatus:p??null,ensureSession:c,onStartFresh:d})]})}function sc({formMessageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=C(""),[o,l]=C(""),a=Je(xe.functions.chat.public.helpdesk.submitEscalation),[c,d]=C(!1),[h,f]=C(null);async function p(g){g.preventDefault(),d(!0),f(null);try{await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()}),Ct()}catch(m){console.error("[EscalationFormScreen] Submit failed:",m),f(r.escalationSubmitFailed)}finally{d(!1)}}return u("div",{class:"jex-form-screen",children:[u("h2",{class:"jex-form-title",children:r.escalationFormTitle}),u("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h&&u("div",{class:"jex-form-error",role:"alert",children:h}),u("form",{class:"jex-form",onSubmit:g=>{p(g)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:g=>{s(g.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,onInput:g=>{l(g.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",disabled:c,children:r.escalationSubmit})]}),u("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),u("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{Ct()},children:r.escalationSkip})]})}function oc(){const t=P(),[e,n]=C(""),[r,i]=C(""),[s,o]=C("");async function l(a){a.preventDefault(),xn({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const c="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();xn({id:"confirmation",ref:c})}return u("div",{class:"jex-form-screen",children:[u("h2",{class:"jex-form-title",children:t.submitTicket}),u("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),u("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function ac({ticketRef:t}){const e=P();return u("div",{class:"jex-confirmation",children:[u("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),u("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),u("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),u("div",{class:"jex-confirmation-ref",children:t}),u("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),u("button",{class:"jex-confirmation-done",onClick:()=>{I.value=!1},children:e.done})]})}function lc({message:t,onRetry:e,onBack:n}){const r=P();return u("div",{class:"jex-overlay jex-error",children:[u("p",{class:"jex-error-message",children:t}),u("div",{class:"jex-error-actions",children:[e&&u("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&u("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function Hi({greeting:t,title:e,orgSlug:n,projSlug:r,sessionId:i,visitorId:s,isLoading:o,sessionNotFound:l,resumeFailed:a,isOrgDeleted:c,ensureSession:d,startFresh:h,resetSession:f}){const p=z.value,g=p[p.length-1],m=[...p].reverse().find(b=>b.id==="confirmation");return u("div",{class:"jex-screen-container",children:[g.id==="home"&&u(Wa,{greeting:t,title:e,onStartFresh:h,onResetSession:f}),g.id==="selection"&&u(Ha,{title:e}),g.id==="form"&&u(oc,{}),g.id==="escalation-form"&&u(sc,{formMessageId:g.formMessageId,sessionId:g.sessionId,visitorId:g.visitorId}),g.id==="confirmation"&&m&&u(ac,{ticketRef:m.ref}),g.id==="chat"&&u(ic,{greeting:t,orgSlug:n,projSlug:r,sessionId:i,visitorId:s,isLoading:o,sessionNotFound:l,resumeFailed:a,isOrgDeleted:c,ensureSession:d,startFresh:h}),g.id==="loading"&&u(An,{message:g.message}),g.id==="error"&&u(lc,{message:g.message,onRetry:()=>xn({id:"loading"}),onBack:Ct})]})}function cc(t,e){const n=de(null),r=Ze(!1),i=Ze(!1),s=Ze(!1),o=Ze(null),l=Je(xe.functions.chat.public.sessions.createOrResume),a=async p=>{const g=Ye.value;if(!g)return console.warn("[JexityChat] No bootstrap token — session creation blocked."),null;const m=await l({orgSlug:t,...e?{projSlug:e}:{},visitorId:p,bootstrapToken:g,...St.value?{source:St.value}:{}});o.value=m.status;const b={sessionId:m.sessionId,visitorId:p};return n.current=b,{session:b,result:m}},c=Se(async()=>{if(n.current)return n.current;if(s.value)return null;r.value=!0;const p=Xe.value!==null,g=Xe.value??vi();try{const m=await a(g);return m?(p&&m.result.isNew&&(i.value=!0,s.value=!0),m.session):null}catch(m){return console.error("[JexityChat] Failed to create session:",m),null}finally{r.value=!1}},[t,e,l,r,i,s]),d=Se(()=>{n.current=null,i.value=!1,s.value=!1},[i,s]),h=Se(async()=>{n.current=null,s.value=!1,i.value=!1;const p=vi();r.value=!0;try{return(await a(p))?.session??null}catch(g){return console.error("[JexityChat] Failed to create fresh session:",g),null}finally{r.value=!1}},[t,e,l,r,i,s,o]),f=n.current;return{sessionId:f?.sessionId??null,visitorId:f?.visitorId??null,isLoading:r.value,sessionNotFound:i.value,resumeFailed:s.value,sessionStatus:o.value,isOrgDeleted:o.value==="org_deleted",ensureSession:c,startFresh:h,resetSession:d}}function Ji({sessionId:t,visitorId:e}){const n=P(),[r,i]=C(!1),[s,o]=C(null),l=Je(xe.functions.chat.public.helpdesk.createEscalationRequest);async function a(){if(!t||!e)return;const c=Ye.value;if(c){i(!0),o(null);try{const d=await l({sessionId:t,visitorId:e,bootstrapToken:c});if(d.skipForm)return;me({id:"escalation-form",formMessageId:d.formMessageId,sessionId:t,visitorId:e})}catch(d){const h=d instanceof Error?d.message:String(d);o(/RATE_LIMITED|Too many/.test(h)?n.handoffRateLimited:n.handoffFailed)}finally{i(!1)}}}return u(N,{children:[u("button",{class:"jex-header-handoff",type:"button",onClick:()=>{a()},disabled:r||!t||!e,"aria-label":n.talkToHumanAria,title:n.talkToHuman,children:n.talkToHuman}),s&&u("div",{class:"jex-handoff-error",role:"alert",children:s})]})}function uc({options:t}){Ca(t.orgSlug,t.projSlug,t.bootstrapToken,t.convexUrl);const e=ja(t.orgSlug,t.projSlug,t.convexUrl);Ia(t.parentOrigin),$(()=>{La(),Oa()},[]);const{sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}=cc(t.orgSlug,t.projSlug),h=ka(t,e);$(()=>{pn.value=xi(h.locale)},[h.locale]);const f=h.position==="bottom-left",p=h.colorScheme==="dark"||h.colorScheme==="light"?h.colorScheme:"",g=za({...t,primaryColor:h.primaryColor,accentColor:h.accentColor,fontFamily:h.fontFamily,fontSize:h.fontSize,borderRadius:h.borderRadius,windowWidth:h.windowWidth,windowHeight:h.windowHeight}),m=h.mode==="embedded",b=z.value,v=b[b.length-1]?.id==="chat",U=e!==null||m||!!t.parentOrigin?g:{...g,visibility:"hidden"};return u("div",{class:`jex-widget ${p}`.trim(),style:U,children:m?u("div",{class:"jex-embedded",children:[u(ki,{title:h.title,rightAction:v?u(Ji,{sessionId:n,visitorId:r}):null}),u(Hi,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}),!h.hideBranding&&u(Si,{})]}):u("div",{class:`jex-container${f?" jex-pos-left":""}`,children:[I.value&&u("div",{class:"jex-chat-window",children:[u(ki,{title:h.title,rightAction:v?u(Ji,{sessionId:n,visitorId:r}):null}),u(Hi,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}),!h.hideBranding&&u(Si,{})]}),u(Va,{iconOption:h.triggerIcon,radius:h.triggerRadius,label:h.triggerLabel})]})})}const hc='.jex-widget{--jex-primary: #115A62;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-radius: .75rem;--jex-font-family: "Inter", system-ui, -apple-system, sans-serif;--jex-font-size: 14px;--jex-window-width: 380px;--jex-window-height: 600px;--jex-shadow: 0 16px 48px -12px rgba(13, 127, 138, .25), 0 4px 16px rgba(0, 0, 0, .08);pointer-events:auto;--jex-bg-trigger: var(--jex-primary);--jex-bg-header: var(--jex-primary);--jex-bg-msg-user: var(--jex-primary);--jex-bg-send-btn: var(--jex-primary);--jex-bg-window: rgba(255, 255, 255, .95);--jex-bg-msg-bot: #f1f5f9;--jex-bg-input: rgba(247, 253, 253, .6);--jex-text-header: #ffffff;--jex-text-msg-user: #ffffff;--jex-text-msg-bot: #0f172a;--jex-text-main: #0f172a;--jex-text-muted: #64748b;--jex-bg-avatar-agent: #d1fae5;--jex-text-avatar-agent: #065f46;--jex-border-window: rgba(226, 232, 240, .8);--jex-border-input: rgba(203, 213, 225, .8);--jex-bg-glass: var(--jex-bg-window);--jex-border-glass: var(--jex-border-window);font-family:var(--jex-font-family);-webkit-font-smoothing:antialiased}.dark .jex-widget,.jex-widget.dark{--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-avatar-agent: #064e3b;--jex-text-avatar-agent: #6ee7b7;--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light){--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}}.jex-widget *{box-sizing:border-box;margin:0;padding:0}.jex-container{position:fixed;bottom:24px;right:24px;display:flex;flex-direction:column;align-items:flex-end;gap:16px;z-index:9999}.jex-container.jex-pos-left{right:auto;left:24px;align-items:flex-start}:host(.jex-mode-embedded){display:block;width:100%;height:100%}:host(.jex-mode-embedded) .jex-widget{width:100%;height:100%}.jex-embedded{display:flex;flex-direction:column;width:100%;height:100%;background:var(--jex-bg-window);border:1px solid var(--jex-border-window);overflow:hidden}.jex-embedded .jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-floating-button{height:56px;min-width:56px;padding:0;background:var(--jex-bg-trigger);color:var(--jex-text-header);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:var(--jex-shadow);transition:transform .3s cubic-bezier(.175,.885,.32,1.275),background .2s,width .3s ease,border-radius .3s ease}.jex-floating-button.jex-has-label{min-width:110px;padding:0 20px}.jex-fab-inner{display:flex;align-items:center;gap:12px}.jex-fab-label{font-size:15px;font-weight:600;white-space:nowrap}.jex-floating-button:hover{transform:scale(1.1);background:var(--jex-primary-hover)}.jex-floating-button:active{transform:scale(.95)}.jex-chat-window{width:var(--jex-window-width);height:var(--jex-window-height);max-height:calc(100vh - 120px);background:var(--jex-bg-window);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border:1px solid var(--jex-border-window);border-radius:calc(var(--jex-radius) * 2);box-shadow:var(--jex-shadow);display:flex;flex-direction:column;overflow:hidden;animation:jexSlideUp .4s cubic-bezier(.16,1,.3,1);transform-origin:bottom right}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) translateY(0)}}.jex-chat-header{padding:20px;background:var(--jex-bg-header);color:var(--jex-text-header);display:flex;align-items:center;gap:12px;flex-shrink:0}.jex-header-info h3{font-size:16px;font-weight:600;color:var(--jex-text-header);margin:0}.jex-header-info p{font-size:12px;opacity:.8;color:var(--jex-text-header);margin:0}.jex-header-right{margin-left:auto;display:flex;align-items:center}.jex-header-handoff{background:transparent;border:1px solid currentColor;border-radius:999px;padding:4px 10px;font-size:12px;color:inherit;cursor:pointer}.jex-header-handoff:disabled{opacity:.5;cursor:not-allowed}.jex-handoff-error{position:absolute;top:100%;right:8px;background:#fee;color:#b00;padding:4px 8px;font-size:12px;border-radius:4px}.jex-header-back{background:none;border:none;color:var(--jex-text-header);cursor:pointer;padding:4px;display:flex;align-items:center;opacity:.8;transition:opacity .2s;flex-shrink:0}.jex-header-back:hover{opacity:1}.jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-home{flex:1;display:flex;flex-direction:column;padding:24px;gap:20px;overflow-y:auto}.jex-home-hero{display:flex;align-items:center;gap:14px;animation:jexFadeIn .4s ease both}.jex-home-avatar{position:relative;width:48px;height:48px;border-radius:14px;background:var(--jex-primary);color:var(--jex-text-header);display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 4px 12px color-mix(in srgb,var(--jex-primary) 30%,transparent)}.jex-home-status-dot{position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;border-radius:50%;background:#22c55e;border:2.5px solid var(--jex-bg-window);animation:jexPulse 2s ease-in-out infinite}@keyframes jexPulse{0%,to{box-shadow:0 0 #22c55e66}50%{box-shadow:0 0 0 6px #22c55e00}}.jex-home-hero-text{display:flex;flex-direction:column;gap:2px;min-width:0}.jex-home-title{font-size:17px;font-weight:700;color:var(--jex-text-main);margin:0;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.jex-home-status{font-size:12px;font-weight:500;color:#22c55e;letter-spacing:.02em}.jex-home-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:4px 16px 16px;padding:16px 18px;font-size:14px;line-height:1.55;color:var(--jex-text-main);animation:jexFadeIn .4s .1s ease both}.jex-home-greeting p{margin:0}@keyframes jexFadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.jex-home-actions{display:flex;flex-direction:column;gap:10px;animation:jexFadeIn .4s .2s ease both}.jex-home-start-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;padding:14px 20px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,transform .15s,box-shadow .2s;width:100%;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 25%,transparent)}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 35%,transparent)}.jex-home-start-btn:active{transform:translateY(0);box-shadow:0 1px 4px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card{display:flex;flex-direction:column;gap:8px;width:100%;text-align:left;padding:16px 18px;border-radius:14px;border:1.5px solid var(--jex-primary);background:color-mix(in srgb,var(--jex-primary) 6%,var(--jex-bg-window));cursor:pointer;font-family:inherit;transition:background .2s,border-color .2s,transform .15s,box-shadow .2s;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 12%,transparent)}.jex-home-resume-card:hover{background:color-mix(in srgb,var(--jex-primary) 10%,var(--jex-bg-window));transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card:active{transform:translateY(0)}.jex-home-resume-top{display:flex;align-items:center;justify-content:space-between}.jex-home-resume-label{font-size:14px;font-weight:600;color:var(--jex-primary)}.jex-home-resume-arrow{color:var(--jex-primary);opacity:.6;transition:opacity .2s,transform .2s}.jex-home-resume-card:hover .jex-home-resume-arrow{opacity:1;transform:translate(2px)}.jex-home-resume-ref{font-family:ui-monospace,Cascadia Code,Fira Code,monospace;font-size:13px;font-weight:600;letter-spacing:.06em;color:var(--jex-text-muted)}.jex-home-history{display:flex;flex-direction:column;gap:8px}.jex-home-resume-meta{font-size:11px;opacity:.7;margin-top:4px}.jex-home-new-btn{background:transparent;color:var(--jex-text-muted);border:1px solid var(--jex-border-input);border-radius:12px;padding:12px 20px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;transition:color .2s,border-color .2s,background .2s;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted);background:color-mix(in srgb,var(--jex-primary) 3%,transparent)}.jex-session-ref{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:8px;font-size:12px}.jex-session-ref-label{color:var(--jex-text-muted);font-weight:500}.jex-session-ref-code{color:var(--jex-primary);font-weight:700;font-family:ui-monospace,Cascadia Code,monospace;letter-spacing:.05em}.jex-chat-messages{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}.jex-message-row{display:flex;align-items:flex-end;gap:8px;max-width:85%}.jex-message-row.bot{align-self:flex-start}.jex-message-content{flex:1;min-width:0}.jex-avatar{width:24px;height:24px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:2px}.jex-avatar-bot{background:var(--jex-bg-msg-bot);color:var(--jex-primary)}.jex-avatar-agent{background:var(--jex-bg-avatar-agent)}.jex-avatar-img{width:100%;height:100%;border-radius:50%;object-fit:cover}.jex-avatar-initials{font-size:9px;font-weight:700;color:var(--jex-text-avatar-agent)}.jex-message-author-row{display:flex;align-items:center;gap:6px;margin-top:2px;padding-left:4px}.jex-message-author{font-size:10px;color:var(--jex-text-muted)}.jex-reply-tag-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;border-radius:4px;background:transparent;color:var(--jex-text-muted, #6b7280);cursor:pointer;transition:background .15s,color .15s}.jex-reply-tag-btn:hover{background:#0000000f;color:var(--jex-primary, #115A62)}.jex-reply-tag-btn:focus-visible{outline:2px solid var(--jex-primary, #115A62);outline-offset:1px}.jex-message{padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);color:var(--jex-text-msg-bot);border-bottom-left-radius:4px}.jex-message.user{align-self:flex-end;max-width:80%;background:var(--jex-bg-msg-user);color:var(--jex-text-msg-user);border-bottom-right-radius:4px}.jex-typing{align-self:flex-start;display:flex;gap:4px;padding:12px 16px}.jex-typing span{width:8px;height:8px;border-radius:50%;background:var(--jex-text-muted);animation:jexTypingDot 1.2s infinite ease-in-out}.jex-typing span:nth-child(2){animation-delay:.2s}.jex-typing span:nth-child(3){animation-delay:.4s}@keyframes jexTypingDot{0%,80%,to{transform:scale(.8);opacity:.4}40%{transform:scale(1);opacity:1}}.jex-md{word-break:break-word;overflow-wrap:anywhere}.jex-md p{margin:0 0 8px}.jex-md p:last-child{margin-bottom:0}.jex-md strong{font-weight:600}.jex-md em{font-style:italic}.jex-md ul,.jex-md ol{margin:0 0 8px;padding-left:20px}.jex-md ul:last-child,.jex-md ol:last-child{margin-bottom:0}.jex-md ul{list-style-type:disc}.jex-md ol{list-style-type:decimal}.jex-md li{margin-bottom:2px}.jex-md li:last-child{margin-bottom:0}.jex-md a{color:var(--jex-primary);text-decoration:underline;text-underline-offset:2px}.jex-md a:hover{opacity:.8}.jex-md code{background:#00000014;padding:1px 5px;border-radius:4px;font-size:.9em;font-family:ui-monospace,Cascadia Code,Fira Code,monospace}.jex-md pre{background:#0000000f;border-radius:8px;padding:10px 12px;margin:0 0 8px;overflow-x:auto;font-size:.85em}.jex-md pre:last-child{margin-bottom:0}.jex-md pre code{background:none;padding:0;border-radius:0;font-size:inherit}.jex-md h1,.jex-md h2,.jex-md h3,.jex-md h4{font-weight:600;margin:8px 0 4px}.jex-md h1:first-child,.jex-md h2:first-child,.jex-md h3:first-child,.jex-md h4:first-child{margin-top:0}.jex-md h3{font-size:1em}.jex-md h4{font-size:.95em}.jex-md hr{border:none;border-top:1px solid var(--jex-border-window);margin:8px 0}.jex-md blockquote{border-left:3px solid var(--jex-primary);margin:0 0 8px;padding:4px 12px;color:var(--jex-text-muted)}.jex-md blockquote:last-child{margin-bottom:0}.dark .jex-md code,.jex-widget.dark .jex-md code{background:#ffffff1a}.dark .jex-md pre,.jex-widget.dark .jex-md pre{background:#ffffff14}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-md code{background:#ffffff1a}:host:not(.light) .jex-widget:not(.light) .jex-md pre{background:#ffffff14}}.jex-streaming-cursor:after{content:"◊";margin-left:2px;animation:jexBlinkCursor .8s ease-in-out infinite}@keyframes jexBlinkCursor{0%,to{opacity:1}50%{opacity:0}}.jex-session-notice{align-self:center;text-align:center;padding:8px 16px;margin:8px 0;font-size:12px;color:var(--jex-text-muted);background:var(--jex-bg-input, #f1f5f9);border-radius:8px;line-height:1.4}.jex-message-error{background:var(--jex-bg-error, #fef2f2)!important;border-color:var(--jex-border-error, #fecaca)!important;color:var(--jex-text-error, #991b1b)!important}.jex-chat-input{padding:16px;border-top:1px solid var(--jex-border-window);display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}.jex-rate-limit-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-muted, #64748b);font-size:12px;line-height:1.4;text-align:center}.jex-chat-input input{flex:1;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:12px;padding:10px 14px;color:var(--jex-text-main);outline:none;font-family:inherit;font-size:14px}.jex-chat-input input:focus{border-color:var(--jex-primary)}.jex-send-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s cubic-bezier(.175,.885,.32,1.275);flex-shrink:0}.jex-send-btn:hover{transform:scale(1.05);background:var(--jex-primary-hover)}.jex-send-btn:active{transform:scale(.95)}.jex-widget-footer{display:flex;align-items:center;justify-content:center;padding:8px 16px;border-top:1px solid var(--jex-border-glass);background:#00000005;flex-shrink:0}.jex-widget.dark .jex-widget-footer{background:#ffffff05}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-widget-footer{background:#ffffff05}}.jex-branding{display:flex;align-items:center;gap:6px;text-decoration:none;color:var(--jex-text-muted);font-size:11px;font-weight:500;transition:color .2s}.jex-branding:hover{color:var(--jex-text-main)}.jex-branding-icon{color:var(--jex-primary)}.jex-branding span strong{font-weight:700;color:var(--jex-text-main)}.jex-locale-select-wrapper{position:relative;display:flex;align-items:center}.jex-locale-select{appearance:none;-webkit-appearance:none;background:transparent;border:1px solid transparent;padding:4px 20px 4px 6px;border-radius:6px;font-family:inherit;font-size:11px;font-weight:600;color:var(--jex-text-muted);background-color:transparent;cursor:pointer;outline:none;transition:all .2s ease}.jex-locale-select option{background-color:#fff;color:#0f172a}.jex-locale-select:hover,.jex-locale-select:focus-visible{color:var(--jex-text-main);background:#0000000a}.jex-widget.dark .jex-locale-select:hover,.jex-widget.dark .jex-locale-select:focus-visible{background:#ffffff0d}.jex-widget.dark .jex-locale-select option{background-color:#0f172a;color:#f8fafc}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-locale-select:hover,:host:not(.light) .jex-widget:not(.light) .jex-locale-select:focus-visible{background:#ffffff0d}:host:not(.light) .jex-widget:not(.light) .jex-locale-select option{background-color:#0f172a;color:#f8fafc}}.jex-locale-select:focus-visible{border-color:var(--jex-primary)}.jex-locale-chevron{position:absolute;right:4px;pointer-events:none;color:var(--jex-text-muted);transition:color .2s ease}.jex-locale-select-wrapper:hover .jex-locale-chevron{color:var(--jex-text-main)}.jex-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:var(--jex-bg-window, #fff);z-index:10;padding:24px;text-align:center}.jex-loading-spinner{width:32px;height:32px;border:3px solid var(--jex-border-input, #e2e8f0);border-top-color:var(--jex-primary, #115A62);border-radius:50%;animation:jex-spin .7s linear infinite}@keyframes jex-spin{to{transform:rotate(360deg)}}.jex-loading-message{font-size:14px;color:var(--jex-text-muted, #64748b)}.jex-error-message{font-size:14px;color:var(--jex-text-main, #334155)}.jex-error-actions{display:flex;gap:8px}.jex-error-retry,.jex-error-back{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:none}.jex-error-retry{background:var(--jex-primary, #115A62);color:#fff}.jex-error-back{background:transparent;color:var(--jex-text-muted, #64748b);border:1px solid var(--jex-border-input, #e2e8f0)}.jex-selection{display:flex;flex-direction:column;gap:12px;padding:24px 16px;height:100%}.jex-selection-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 8px}.jex-selection-options{display:flex;flex-direction:column;gap:10px}.jex-selection-option{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:16px;border-radius:12px;border:1px solid var(--jex-border-window, #e2e8f0);background:transparent;cursor:pointer;text-align:left;transition:border-color .15s ease,background .15s ease}.jex-selection-option:hover{border-color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 5%,transparent)}.jex-selection-icon{font-size:20px}.jex-selection-label{font-size:14px;font-weight:600;color:var(--jex-text-main, #0f172a)}.jex-selection-sub{font-size:12px;color:var(--jex-text-muted, #64748b)}.jex-form-screen{display:flex;flex-direction:column;padding:20px 16px;height:100%;overflow-y:auto}.jex-form-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 16px}.jex-form{display:flex;flex-direction:column;gap:10px}.jex-form-input,.jex-form-textarea{padding:10px 12px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:14px;background:transparent;color:var(--jex-text-main, #0f172a);outline:none}.jex-form-input:focus,.jex-form-textarea:focus{border-color:var(--jex-primary, #115A62)}.jex-form-textarea{min-height:80px;resize:vertical}.jex-form-submit{padding:10px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer;margin-top:4px}.jex-inline-form{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-title{font-weight:600;font-size:15px;color:var(--jex-text-main, #0f172a);margin:0}.jex-inline-form-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.4;margin:0 0 4px}.jex-inline-form-consent{font-size:11px;color:var(--jex-text-muted, #64748b);line-height:1.3;margin-top:4px;text-align:center}.jex-inline-form .jex-form-submit:disabled{opacity:.7;cursor:not-allowed}.jex-escalation-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.45;margin:0 0 8px}.jex-escalation-skip{padding:8px 12px;border:none;background:transparent;color:var(--jex-text-muted, #64748b);font-size:13px;cursor:pointer;text-decoration:underline;text-underline-offset:2px;text-align:center}.jex-escalation-skip:hover{color:var(--jex-text-main, #0f172a)}.jex-inline-form-card{position:relative;padding:14px;gap:8px}.jex-inline-form-dismiss{position:absolute;top:10px;right:10px;width:24px;height:24px;border-radius:50%;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-window, #fff);color:var(--jex-text-muted, #64748b);font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}.jex-inline-form-dismiss:hover{background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-check{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary) 15%,transparent);color:var(--jex-primary, #115A62);font-size:14px;font-weight:700;flex-shrink:0}.jex-inline-form-submitted-title{font-weight:600;font-size:var(--jex-font-size, 14px);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted-detail{font-size:12px;color:var(--jex-text-muted, #64748b);margin-top:2px}.jex-escalation-confirm{border-left:3px solid var(--jex-primary, #115A62);padding-left:8px}.jex-session-prompt{display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px 16px;margin:8px 0;text-align:center}.jex-session-prompt-text{font-size:13px;color:var(--jex-text-muted, #64748b)}.jex-session-prompt-btn{padding:8px 16px;border-radius:8px;border:1px solid var(--jex-primary, #115A62);background:transparent;color:var(--jex-primary, #115A62);font-size:13px;font-weight:600;cursor:pointer}.jex-session-prompt-btn:hover{background:color-mix(in srgb,var(--jex-primary) 10%,transparent)}.jex-chat-input-resolved{display:flex;flex-direction:column;align-items:center;gap:10px;padding:14px 16px;border-top:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-msg-bot, #f1f5f9);text-align:center}.jex-resolved-notice{font-size:13px;font-weight:500;color:var(--jex-text-muted, #64748b)}.jex-resolved-new-btn{padding:10px 20px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;width:100%}.jex-resolved-new-btn:hover{opacity:.9}.jex-confirmation{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 24px;height:100%;text-align:center}.jex-confirmation-icon{width:48px;height:48px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary, #115A62) 15%,transparent);color:var(--jex-primary, #115A62);font-size:22px;display:flex;align-items:center;justify-content:center}.jex-confirmation-title{font-size:18px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0}.jex-confirmation-body{font-size:13px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-ref{font-size:20px;font-weight:700;letter-spacing:.05em;color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 10%,transparent);padding:10px 20px;border-radius:10px}.jex-confirmation-hint{font-size:12px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-done{margin-top:8px;padding:10px 28px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer}.jex-home-lookup-link{background:none;border:none;font-size:12px;color:var(--jex-text-muted, #64748b);cursor:pointer;text-decoration:underline;padding:0;align-self:center}.jex-home-lookup{display:flex;gap:8px;width:100%;animation:jexFadeIn .4s .1s ease both}.jex-home-lookup-input{flex:1;padding:10px 14px;border-radius:10px;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-input);color:var(--jex-text-main);font-size:13px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}.jex-home-lookup-input::placeholder{font-family:inherit;letter-spacing:.04em;color:var(--jex-text-muted);opacity:.7}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:10px 16px;border-radius:10px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,opacity .2s;flex-shrink:0}.jex-home-lookup-submit:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-home-lookup-submit:disabled{opacity:.4;cursor:default}.jex-sources-row{margin-top:6px;margin-left:32px;display:flex;flex-direction:column;gap:6px}.jex-sources-toggle{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;background:transparent;border:none;border-radius:6px;cursor:pointer;font-size:11px;color:var(--jex-text-muted, #6b7280);font-family:inherit;align-self:flex-start;transition:background .15s,color .15s}.jex-sources-toggle:hover{background:#0000000a;color:inherit}.jex-sources-icon{font-size:12px;line-height:1}.jex-sources-chevron{display:inline-block;font-size:10px;transition:transform .15s}.jex-sources-chevron--open{transform:rotate(180deg)}.jex-sources-pills{display:flex;flex-wrap:wrap;align-items:center;gap:6px}.jex-source-pill{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:2px 8px;border-radius:999px;border:1px solid rgba(0,0,0,.1);background:#0000000a;color:var(--jex-text-muted, #6b7280);font-size:11px;text-decoration:none;cursor:pointer;transition:background .15s,color .15s}.jex-source-pill:hover{background:#00000014;color:inherit}.jex-source-id{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 4px;border-radius:4px;background:var(--jex-primary, #115A62);color:#fff;font-size:10px;font-weight:600;line-height:1;flex-shrink:0;font-variant-numeric:tabular-nums}.jex-source-type{font-size:10px;flex-shrink:0}.jex-source-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}.jex-source-score{opacity:.6;flex-shrink:0;font-variant-numeric:tabular-nums}';function dc(t){const e=document.createElement("style");e.textContent=hc,t.appendChild(e)}const fc="https://festive-mouse-978.eu-west-1.convex.cloud";let En=null;function pc(t){const e=t??fc;if(!e)throw new Error("[jexity] No Convex URL — set VITE_CONVEX_URL at build time or data-convex-url on the script tag");return En||(En=new sa(wa(e))),En}function gc(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);dc(n),St.value=e.source,Ye.value=e.bootstrapToken,z.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),I.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),he(u(aa,{client:pc(e.convexUrl),children:u(uc,{options:e})}),r),function(){he(null,r),I.value=!1,St.value=void 0,Ye.value=void 0,z.value=[{id:"home"}]}}function mc(t,e,n){const r=gc(t,e),i=new Set,s=I.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){I.value=!0},close(){I.value=!1},toggle(){I.value=!I.value},get isOpen(){return I.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let st=null;function xc(t){st&&st.shutdown();let e;t.container?e=typeof t.container=="string"?document.querySelector(t.container):t.container:(e=document.createElement("div"),e.id="jexity-chat-widget",document.body.appendChild(e));const n=mc(e,t,()=>{t.container||e.remove(),st===n&&(st=null)});return st=n,n}function le(t,e){return t.getAttribute(e)??void 0}async function Gi(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const e=t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",n=t.getAttribute("data-proj-slug")??void 0,r=le(t,"data-convex-url")??"https://festive-mouse-978.eu-west-1.convex.cloud"??"",i=fn(r),s=await gi(e,i,n);if(!s.ok){const l=window.location.origin,a=n?`project '${e}/${n}'`:`org '${e}'`;s.error==="unauthorized"?console.warn(`[JexityChat] This domain is not authorized for ${a}. Add '${l}' under Allowed Domains in your Jexity dashboard.`):s.error==="not_found"?console.warn(`[JexityChat] No active widget config found for ${a}. Check that the org slug is correct and the widget is enabled.`):s.error==="rate_limited"?console.warn(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${s.retryAfterSec??60}s.`):console.warn(`[JexityChat] Bootstrap failed (network error). Check that the Convex deployment is reachable at ${i}.`);return}const o={orgSlug:e,projSlug:n,bootstrapToken:s.token,position:le(t,"data-position")??void 0,theme:le(t,"data-theme")??void 0,greeting:le(t,"data-greeting"),title:le(t,"data-title"),primaryColor:le(t,"data-primary-color"),locale:le(t,"data-locale"),convexUrl:le(t,"data-convex-url")};window.JexityChat=xc(o)}document.readyState==="complete"?Gi():window.addEventListener("load",Gi)})();
59
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${te(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),i=Fi(t);if(i===null)return r;t=i;let s='<a href="'+t+'"';return e&&(s+=' title="'+te(e)+'"'),s+=">"+r+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Fi(t);if(i===null)return te(n);t=i;let s=`<img src="${t}" alt="${te(n)}"`;return e&&(s+=` title="${te(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:te(t.text)}},Rn=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},J=class qn{options;renderer;textRenderer;constructor(e){this.options=e||ye,this.options.renderer=this.options.renderer||new It,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Rn}static parse(e,n){return new qn(n).parse(e)}static parseInline(e,n){return new qn(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let o=i,l=this.options.extensions.renderers[o.type].call({parser:this},o);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=l||"";continue}}let s=i;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let o='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let s=e[i];if(this.options.extensions?.renderers?.[s.type]){let l=this.options.extensions.renderers[s.type].call({parser:this},s);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=l||"";continue}}let o=s;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let l='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return r}},it=class{options;block;constructor(t){this.options=t||ye}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(){return this.block?H.lex:H.lexInline}provideParser(){return this.block?J.parse:J.parseInline}},Fl=class{defaults=yn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=J;Renderer=It;TextRenderer=Rn;Lexer=H;Tokenizer=Et;Hooks=it;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let i=r;for(let s of i.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of i.rows)for(let o of s)n=n.concat(this.walkTokens(o.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(s=>{let o=i[s].flat(1/0);n=n.concat(this.walkTokens(o,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=e.renderers[i.name];s?e.renderers[i.name]=function(...o){let l=i.renderer.apply(this,o);return l===!1&&(l=s.apply(this,o)),l}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=e[i.level];s?s.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new It(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let o=s,l=n.renderer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Et(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let o=s,l=n.tokenizer[o],a=i[o];i[o]=(...c)=>{let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new it;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let o=s,l=n.hooks[o],a=i[o];it.passThroughHooks.has(s)?i[o]=c=>{if(this.defaults.async&&it.passThroughHooksRespectAsync.has(s))return(async()=>{let h=await l.call(i,c);return a.call(i,h)})();let d=l.call(i,c);return a.call(i,d)}:i[o]=(...c)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(i,c);return h===!1&&(h=await a.apply(i,c)),h})();let d=l.apply(i,c);return d===!1&&(d=a.apply(i,c)),d}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(o){let l=[];return l.push(s.call(this,o)),i&&(l=l.concat(i.call(this,o))),l}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return H.lex(t,e??this.defaults)}parser(t,e){return J.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},s=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(e):e,l=await(i.hooks?await i.hooks.provideLexer():t?H.lex:H.lexInline)(o,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser():t?J.parse:J.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(s);try{i.hooks&&(e=i.hooks.preprocess(e));let o=(i.hooks?i.hooks.provideLexer():t?H.lex:H.lexInline)(e,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let l=(i.hooks?i.hooks.provideParser():t?J.parse:J.parseInline)(o,i);return i.hooks&&(l=i.hooks.postprocess(l)),l}catch(o){return s(o)}}}onError(t,e){return n=>{if(n.message+=`
60
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+te(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},_e=new Fl;function k(t,e){return _e.parse(t,e)}k.options=k.setOptions=function(t){return _e.setOptions(t),k.defaults=_e.defaults,$i(k.defaults),k},k.getDefaults=yn,k.defaults=ye,k.use=function(...t){return _e.use(...t),k.defaults=_e.defaults,$i(k.defaults),k},k.walkTokens=function(t,e){return _e.walkTokens(t,e)},k.parseInline=_e.parseInline,k.Parser=J,k.parser=J.parse,k.Renderer=It,k.TextRenderer=Rn,k.Lexer=H,k.lexer=H.lex,k.Tokenizer=Et,k.Hooks=it,k.parse=k,k.options,k.setOptions,k.use,k.walkTokens,k.parseInline,J.parse,H.lex,k.setOptions({breaks:!0,gfm:!0});function Dl({text:t}){const e=Q(()=>{if(!t)return"";const n=k.parse(t);return typeof n=="string"?n:""},[t]);return u("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}const $n=O(""),ae=O(null),Vi=O(Date.now());function Ul(t){if(!t)return;const e=t.trim().split(/\s+/)[0];if(!e)return;const n=`@${e} `,r=$n.value;r.includes(n)||r.includes(`@${e}`)||($n.value=r.trimStart()?`${n}${r.trimStart()}`:n)}function Vl(t){const e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.map(n=>n[0]).join("").slice(0,2).toUpperCase()}function qe({text:t,streaming:e,error:n,authorId:r,authorName:i,authorImage:s,botAvatarUrl:o}){const l=!!r,[a,c]=C(!1),d=je(()=>c(!0),[]),h=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return u("div",{class:"jex-message-row bot",children:[u("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?u("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?u("span",{class:"jex-avatar-initials",children:Vl(i??"")}):o&&!a?u("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):u(bn,{size:14})}),u("div",{class:"jex-message-content",children:[u("div",{class:h,children:[u(Dl,{text:t}),e&&u("span",{class:"jex-streaming-cursor"})]}),l&&i&&u("div",{class:"jex-message-author-row",children:[u("span",{class:"jex-message-author",children:i}),u("button",{type:"button",class:"jex-reply-tag-btn","aria-label":`Reply to ${i}`,title:`Reply to ${i}`,onClick:()=>{Ul(i)},children:u(tl,{size:12})})]})]})]})}function Wl({text:t}){return u("div",{class:"jex-message user",children:t})}function Hl({message:t,sessionId:e,visitorId:n}){const r=P();return t.formData?u("div",{class:"jex-inline-form-submitted",children:[u("span",{class:"jex-inline-form-check",children:"✓"}),u("div",{children:[u("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),u("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):u("div",{class:"jex-message-row bot",children:u(Jl,{messageId:t._id,sessionId:e,visitorId:n})})}function Jl({messageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=C(""),[o,l]=C(""),[a,c]=C(!1),d=Ge(be.functions.chat.public.helpdesk.submitEscalation);async function h(f){if(f.preventDefault(),!a){c(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()})}catch(p){console.error("[FormMessage] Submit failed:",p),c(!1)}}}return u("div",{class:"jex-inline-form",children:[u("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),u("form",{class:"jex-form",onSubmit:f=>{h(f)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:f=>{s(f.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,disabled:a,onInput:f=>{l(f.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),u("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}const Gl={crawl:"🌐",file:"📄",snippet:"💡",qa:"❓"};function Kl({sources:t}){const[e,n]=C(!1);return t.length===0?null:u("div",{class:"jex-sources-row",children:[u("button",{type:"button",class:"jex-sources-toggle",onClick:()=>{n(r=>!r)},"aria-expanded":e,children:[u("span",{class:"jex-sources-icon",children:"📖"}),u("span",{children:[t.length," ",t.length===1?"source":"sources"]}),u("span",{class:`jex-sources-chevron${e?" jex-sources-chevron--open":""}`,children:"▾"})]}),e?u("div",{class:"jex-sources-pills",children:t.map((r,i)=>{const s=r.sourceType==="crawl",o=Zl(r),l=s&&r.url?`${r.title}
61
+ ${r.url}`:r.title,a=u(N,{children:[typeof r.id=="number"?u("span",{class:"jex-source-id",children:r.id}):null,u("span",{class:"jex-source-type",children:Gl[r.sourceType]}),u("span",{class:"jex-source-label",children:o}),u("span",{class:"jex-source-score",children:["· ",r.score.toFixed(2)]})]});return s&&r.url?u("a",{class:"jex-source-pill",href:r.url,target:"_blank",rel:"noopener noreferrer",title:l,children:a},i):u("span",{class:"jex-source-pill",title:l,children:a},i)})}):null]})}function Zl(t){if(t.sourceType==="crawl"&&t.url)try{const e=new URL(t.url);return!e.pathname||e.pathname==="/"?e.hostname:e.pathname}catch{}return t.title}function Yl(){return u("div",{class:"jex-typing",children:[u("span",{}),u("span",{}),u("span",{})]})}const Xl=/\s?\[\d+\]/g;function Wi(t){return t.replace(Xl,"")}function ec({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:s,visitorId:o}){const l=P(),a=de(null),[c,d]=C(null),h=de(null);return $(()=>{if(!o||!t||t.length===0)return;const f=t[t.length-1];f.role==="assistant"&&f.status!=="streaming"&&f._id!==h.current&&(h.current=f._id,mn(o))},[t,o]),$(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),u("div",{class:"jex-chat-messages",children:[u(qe,{text:e}),n&&r&&i?u("div",{class:"jex-session-prompt",children:[u("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),u("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?u("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(f=>{if(f.contentType==="human-notice")return u(qe,{text:f.content},f._id);if(f.contentType==="escalation-form"&&s&&o)return Na.value==="screen"&&!f.formData?c===f._id?null:u("div",{class:"jex-inline-form jex-inline-form-card",children:[u("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),u("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),u("button",{class:"jex-form-submit",type:"button",onClick:()=>{xe({id:"escalation-form",formMessageId:f._id,sessionId:s,visitorId:o})},children:l.escalationPromptSubmit}),u("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(f._id)},children:l.escalationSkip})]},f._id):u(Hl,{message:f,sessionId:s,visitorId:o},f._id);if(f.contentType==="escalation-confirm")return u(qe,{text:f.content},f._id);if(f.role==="user")return u(Wl,{text:f.content},f._id);const p={authorId:f.authorId,authorName:f.authorName,authorImage:f.authorImage};return f.status==="streaming"&&f.content===""?u(Yl,{},f._id):f.status==="streaming"?u(qe,{text:Wi(f.content),streaming:!0,...p},f._id):f.status==="error"?u(qe,{text:f.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},f._id):u("div",{children:[u(qe,{text:Wi(f.content),...p}),f.sources&&f.sources.length>0?u(Kl,{sources:f.sources}):null]},f._id)}),u("div",{ref:a})]})}function tc({size:t=18}){return u("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true",children:[u("path",{d:"M22 2 11 13"}),u("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function nc(){const t=P(),e=ya(()=>{const n=ae.value;return n===null?0:Math.max(0,Math.ceil((n-Vi.value)/1e3))});return $(()=>{const n=ae.value;if(n===null)return;const r=setInterval(()=>{Vi.value=Date.now()},1e3),i=setTimeout(()=>{ae.value=null},Math.max(0,n-Date.now()));return()=>{clearInterval(r),clearTimeout(i)}},[ae.value]),ae.value===null?null:u("div",{class:"jex-rate-limit-notice",role:"status","aria-live":"polite",children:t.errorRateLimited.replace("{seconds}",String(e.value))})}function rc({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:s,onStartFresh:o}){const l=P(),a=$n,c=Ge(be.functions.chat.public.conversations.send),d=ae.value!==null&&ae.value>Date.now(),h=n||r||d;if(i==="resolved")return u("div",{class:"jex-chat-input-resolved",children:[u("div",{class:"jex-resolved-notice",children:l.sessionResolved}),u("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{o()},children:l.startNewConversation})]});async function f(){const p=a.value.trim();if(!p||h)return;const g=t&&e?{sessionId:t,visitorId:e}:await s();if(g){a.value="";try{const m=await c({sessionId:g.sessionId,visitorId:g.visitorId,content:p});!m.ok&&m.reason==="rate_limited"?ae.value=Date.now()+m.retryAfterMs:mn(g.visitorId)}catch(m){console.error("[jexity] Failed to send message:",m)}}}return u("div",{class:"jex-chat-input",children:[u(nc,{}),u("input",{type:"text","aria-label":l.inputPlaceholder,placeholder:r?l.aiThinking:l.inputPlaceholder,value:a.value,onInput:p=>{a.value=p.currentTarget.value},onKeyDown:p=>{p.key==="Enter"&&f()},disabled:n||r}),u("button",{class:"jex-send-btn",onClick:f,"aria-label":l.sendAriaLabel,disabled:h,children:u(tc,{size:18})})]})}function An({message:t}){const[e,n]=C(!1);return $(()=>{const r=setTimeout(()=>{n(!0)},80);return()=>{clearTimeout(r)}},[]),e?u("div",{class:"jex-overlay jex-loading",children:[u("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&u("p",{class:"jex-loading-message",children:t})]}):null}function ic({greeting:t,orgSlug:e,projSlug:n,sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,resumeFailed:l,isOrgDeleted:a,ensureSession:c,startFresh:d}){const h=P(),f=ii(be.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),p=ii(be.functions.chat.public.sessions.getSessionStatus,r&&i?{sessionId:r,visitorId:i}:"skip"),g=r!==null&&f===void 0,m=f?.some(E=>E.status==="streaming")??!1,b=de((()=>{const E=et.peek();return E!==null?E:yi.peek()?"resume":"fresh"})()).current;if($(()=>{et.value=null},[]),$(()=>{c()},[c]),$(()=>{i&&mn(i)},[i]),a)return u("div",{class:"jex-chat-messages",children:u("div",{class:"jex-session-notice",children:h.chatNoLongerAvailable})});const _=b==="fresh"&&!r,v=b==="resume"&&(!r||g);return _?u(An,{message:h.startingConversation}):v?u(An,{message:h.resumeConversation}):u(N,{children:[u(ec,{conversations:f,greeting:t,sessionNotFound:o,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),u(rc,{sessionId:r,visitorId:i,isLoading:s,isStreaming:m,sessionStatus:p??null,ensureSession:c,onStartFresh:d})]})}function sc({formMessageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=C(""),[o,l]=C(""),a=Ge(be.functions.chat.public.helpdesk.submitEscalation),[c,d]=C(!1),[h,f]=C(null);async function p(g){g.preventDefault(),d(!0),f(null);try{await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()}),Ct()}catch(m){console.error("[EscalationFormScreen] Submit failed:",m),f(r.escalationSubmitFailed)}finally{d(!1)}}return u("div",{class:"jex-form-screen",children:[u("h2",{class:"jex-form-title",children:r.escalationFormTitle}),u("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h&&u("div",{class:"jex-form-error",role:"alert",children:h}),u("form",{class:"jex-form",onSubmit:g=>{p(g)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:g=>{s(g.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,onInput:g=>{l(g.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",disabled:c,children:r.escalationSubmit})]}),u("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),u("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{Ct()},children:r.escalationSkip})]})}function oc(){const t=P(),[e,n]=C(""),[r,i]=C(""),[s,o]=C("");async function l(a){a.preventDefault(),xn({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const c="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();xn({id:"confirmation",ref:c})}return u("div",{class:"jex-form-screen",children:[u("h2",{class:"jex-form-title",children:t.submitTicket}),u("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[u("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),u("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),u("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),u("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function ac({ticketRef:t}){const e=P();return u("div",{class:"jex-confirmation",children:[u("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),u("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),u("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),u("div",{class:"jex-confirmation-ref",children:t}),u("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),u("button",{class:"jex-confirmation-done",onClick:()=>{I.value=!1},children:e.done})]})}function lc({message:t,onRetry:e,onBack:n}){const r=P();return u("div",{class:"jex-overlay jex-error",children:[u("p",{class:"jex-error-message",children:t}),u("div",{class:"jex-error-actions",children:[e&&u("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&u("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function Hi({greeting:t,title:e,orgSlug:n,projSlug:r,sessionId:i,visitorId:s,isLoading:o,sessionNotFound:l,resumeFailed:a,isOrgDeleted:c,ensureSession:d,startFresh:h,resetSession:f}){const p=z.value,g=p[p.length-1],m=[...p].reverse().find(b=>b.id==="confirmation");return u("div",{class:"jex-screen-container",children:[g.id==="home"&&u(Wa,{greeting:t,title:e,onStartFresh:h,onResetSession:f}),g.id==="selection"&&u(Ha,{title:e}),g.id==="form"&&u(oc,{}),g.id==="escalation-form"&&u(sc,{formMessageId:g.formMessageId,sessionId:g.sessionId,visitorId:g.visitorId}),g.id==="confirmation"&&m&&u(ac,{ticketRef:m.ref}),g.id==="chat"&&u(ic,{greeting:t,orgSlug:n,projSlug:r,sessionId:i,visitorId:s,isLoading:o,sessionNotFound:l,resumeFailed:a,isOrgDeleted:c,ensureSession:d,startFresh:h}),g.id==="loading"&&u(An,{message:g.message}),g.id==="error"&&u(lc,{message:g.message,onRetry:()=>xn({id:"loading"}),onBack:Ct})]})}function cc(t=1e4){return me.value?Promise.resolve(me.value):new Promise(e=>{let n=!1;const r=o=>{n||(n=!0,clearTimeout(i),s(),e(o))},i=setTimeout(()=>{r(null)},t),s=me.subscribe(o=>{o&&r(o)})})}function uc(t,e){const n=de(null),r=Ye(!1),i=Ye(!1),s=Ye(!1),o=Ye(null),l=Ge(be.functions.chat.public.sessions.createOrResume),a=async p=>{const g=await cc();if(!g)return console.warn("[JexityChat] No bootstrap token after 10s — session creation blocked."),null;const m=await l({orgSlug:t,...e?{projSlug:e}:{},visitorId:p,bootstrapToken:g,...St.value?{source:St.value}:{}});o.value=m.status;const b={sessionId:m.sessionId,visitorId:p};return n.current=b,{session:b,result:m}},c=je(async()=>{if(n.current)return n.current;if(s.value)return null;r.value=!0;const p=Xe.value!==null,g=Xe.value??vi();try{const m=await a(g);return m?(p&&m.result.isNew&&(i.value=!0,s.value=!0),m.session):null}catch(m){return console.error("[JexityChat] Failed to create session:",m),null}finally{r.value=!1}},[t,e,l,r,i,s]),d=je(()=>{n.current=null,i.value=!1,s.value=!1},[i,s]),h=je(async()=>{n.current=null,s.value=!1,i.value=!1;const p=vi();r.value=!0;try{return(await a(p))?.session??null}catch(g){return console.error("[JexityChat] Failed to create fresh session:",g),null}finally{r.value=!1}},[t,e,l,r,i,s,o]),f=n.current;return{sessionId:f?.sessionId??null,visitorId:f?.visitorId??null,isLoading:r.value,sessionNotFound:i.value,resumeFailed:s.value,sessionStatus:o.value,isOrgDeleted:o.value==="org_deleted",ensureSession:c,startFresh:h,resetSession:d}}function Ji({sessionId:t,visitorId:e}){const n=P(),[r,i]=C(!1),[s,o]=C(null),l=Ge(be.functions.chat.public.helpdesk.createEscalationRequest);async function a(){if(!t||!e)return;const c=me.value;if(c){i(!0),o(null);try{const d=await l({sessionId:t,visitorId:e,bootstrapToken:c});if(d.skipForm)return;xe({id:"escalation-form",formMessageId:d.formMessageId,sessionId:t,visitorId:e})}catch(d){const h=d instanceof Error?d.message:String(d);o(/RATE_LIMITED|Too many/.test(h)?n.handoffRateLimited:n.handoffFailed)}finally{i(!1)}}}return u(N,{children:[u("button",{class:"jex-header-handoff",type:"button",onClick:()=>{a()},disabled:r||!t||!e,"aria-label":n.talkToHumanAria,title:n.talkToHuman,children:n.talkToHuman}),s&&u("div",{class:"jex-handoff-error",role:"alert",children:s})]})}function hc({options:t}){Ca(t.orgSlug,t.projSlug,t.bootstrapToken,t.convexUrl);const e=ja(t.orgSlug,t.projSlug,t.convexUrl);Ia(t.parentOrigin),$(()=>{La(),Oa()},[]);const{sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}=uc(t.orgSlug,t.projSlug),h=ka(t,e);$(()=>{pn.value=xi(h.locale)},[h.locale]);const f=h.position==="bottom-left",p=h.colorScheme==="dark"||h.colorScheme==="light"?h.colorScheme:"",g=za({...t,primaryColor:h.primaryColor,accentColor:h.accentColor,fontFamily:h.fontFamily,fontSize:h.fontSize,borderRadius:h.borderRadius,windowWidth:h.windowWidth,windowHeight:h.windowHeight}),m=h.mode==="embedded",b=z.value,v=b[b.length-1]?.id==="chat",U=e!==null||m||!!t.parentOrigin?g:{...g,visibility:"hidden"};return u("div",{class:`jex-widget ${p}`.trim(),style:U,children:m?u("div",{class:"jex-embedded",children:[u(ki,{title:h.title,rightAction:v?u(Ji,{sessionId:n,visitorId:r}):null}),u(Hi,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}),!h.hideBranding&&u(Si,{})]}):u("div",{class:`jex-container${f?" jex-pos-left":""}`,children:[I.value&&u("div",{class:"jex-chat-window",children:[u(ki,{title:h.title,rightAction:v?u(Ji,{sessionId:n,visitorId:r}):null}),u(Hi,{greeting:h.greeting,title:h.title,orgSlug:t.orgSlug,projSlug:t.projSlug,sessionId:n,visitorId:r,isLoading:i,sessionNotFound:s,resumeFailed:o,isOrgDeleted:l,ensureSession:a,startFresh:c,resetSession:d}),!h.hideBranding&&u(Si,{})]}),u(Va,{iconOption:h.triggerIcon,radius:h.triggerRadius,label:h.triggerLabel})]})})}const dc='.jex-widget{--jex-primary: #115A62;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-radius: .75rem;--jex-font-family: "Inter", system-ui, -apple-system, sans-serif;--jex-font-size: 14px;--jex-window-width: 380px;--jex-window-height: 600px;--jex-shadow: 0 16px 48px -12px rgba(13, 127, 138, .25), 0 4px 16px rgba(0, 0, 0, .08);pointer-events:auto;--jex-bg-trigger: var(--jex-primary);--jex-bg-header: var(--jex-primary);--jex-bg-msg-user: var(--jex-primary);--jex-bg-send-btn: var(--jex-primary);--jex-bg-window: rgba(255, 255, 255, .95);--jex-bg-msg-bot: #f1f5f9;--jex-bg-input: rgba(247, 253, 253, .6);--jex-text-header: #ffffff;--jex-text-msg-user: #ffffff;--jex-text-msg-bot: #0f172a;--jex-text-main: #0f172a;--jex-text-muted: #64748b;--jex-bg-avatar-agent: #d1fae5;--jex-text-avatar-agent: #065f46;--jex-border-window: rgba(226, 232, 240, .8);--jex-border-input: rgba(203, 213, 225, .8);--jex-bg-glass: var(--jex-bg-window);--jex-border-glass: var(--jex-border-window);font-family:var(--jex-font-family);-webkit-font-smoothing:antialiased}.dark .jex-widget,.jex-widget.dark{--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-avatar-agent: #064e3b;--jex-text-avatar-agent: #6ee7b7;--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light){--jex-primary: #1cb0bf;--jex-primary-hover: var(--jex-accent, color-mix(in srgb, var(--jex-primary) 85%, #000));--jex-bg-window: rgba(10, 15, 26, .95);--jex-bg-msg-bot: #233146;--jex-bg-input: rgba(10, 15, 26, .6);--jex-text-msg-bot: #f8fafc;--jex-text-main: #f8fafc;--jex-text-muted: #94a3b8;--jex-border-window: rgba(30, 41, 59, .8);--jex-border-input: rgba(51, 65, 85, .9);--jex-bg-error: #3b1318;--jex-border-error: #5c1d24;--jex-text-error: #fca5a5}}.jex-widget *{box-sizing:border-box;margin:0;padding:0}.jex-container{position:fixed;bottom:24px;right:24px;display:flex;flex-direction:column;align-items:flex-end;gap:16px;z-index:9999}.jex-container.jex-pos-left{right:auto;left:24px;align-items:flex-start}:host(.jex-mode-embedded){display:block;width:100%;height:100%}:host(.jex-mode-embedded) .jex-widget{width:100%;height:100%}.jex-embedded{display:flex;flex-direction:column;width:100%;height:100%;background:var(--jex-bg-window);border:1px solid var(--jex-border-window);overflow:hidden}.jex-embedded .jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-floating-button{height:56px;min-width:56px;padding:0;background:var(--jex-bg-trigger);color:var(--jex-text-header);border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:var(--jex-shadow);transition:transform .3s cubic-bezier(.175,.885,.32,1.275),background .2s,width .3s ease,border-radius .3s ease}.jex-floating-button.jex-has-label{min-width:110px;padding:0 20px}.jex-fab-inner{display:flex;align-items:center;gap:12px}.jex-fab-label{font-size:15px;font-weight:600;white-space:nowrap}.jex-floating-button:hover{transform:scale(1.1);background:var(--jex-primary-hover)}.jex-floating-button:active{transform:scale(.95)}.jex-chat-window{width:var(--jex-window-width);height:var(--jex-window-height);max-height:calc(100vh - 120px);background:var(--jex-bg-window);backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);border:1px solid var(--jex-border-window);border-radius:calc(var(--jex-radius) * 2);box-shadow:var(--jex-shadow);display:flex;flex-direction:column;overflow:hidden;animation:jexSlideUp .4s cubic-bezier(.16,1,.3,1);transform-origin:bottom right}@keyframes jexSlideUp{0%{opacity:0;transform:scale(.8) translateY(20px)}to{opacity:1;transform:scale(1) translateY(0)}}.jex-chat-header{padding:20px;background:var(--jex-bg-header);color:var(--jex-text-header);display:flex;align-items:center;gap:12px;flex-shrink:0}.jex-header-info h3{font-size:16px;font-weight:600;color:var(--jex-text-header);margin:0}.jex-header-info p{font-size:12px;opacity:.8;color:var(--jex-text-header);margin:0}.jex-header-right{margin-left:auto;display:flex;align-items:center}.jex-header-handoff{background:transparent;border:1px solid currentColor;border-radius:999px;padding:4px 10px;font-size:12px;color:inherit;cursor:pointer}.jex-header-handoff:disabled{opacity:.5;cursor:not-allowed}.jex-handoff-error{position:absolute;top:100%;right:8px;background:#fee;color:#b00;padding:4px 8px;font-size:12px;border-radius:4px}.jex-header-back{background:none;border:none;color:var(--jex-text-header);cursor:pointer;padding:4px;display:flex;align-items:center;opacity:.8;transition:opacity .2s;flex-shrink:0}.jex-header-back:hover{opacity:1}.jex-screen-container{flex:1;overflow:hidden;display:flex;flex-direction:column}.jex-home{flex:1;display:flex;flex-direction:column;padding:24px;gap:20px;overflow-y:auto}.jex-home-hero{display:flex;align-items:center;gap:14px;animation:jexFadeIn .4s ease both}.jex-home-avatar{position:relative;width:48px;height:48px;border-radius:14px;background:var(--jex-primary);color:var(--jex-text-header);display:flex;align-items:center;justify-content:center;flex-shrink:0;box-shadow:0 4px 12px color-mix(in srgb,var(--jex-primary) 30%,transparent)}.jex-home-status-dot{position:absolute;bottom:-2px;right:-2px;width:14px;height:14px;border-radius:50%;background:#22c55e;border:2.5px solid var(--jex-bg-window);animation:jexPulse 2s ease-in-out infinite}@keyframes jexPulse{0%,to{box-shadow:0 0 #22c55e66}50%{box-shadow:0 0 0 6px #22c55e00}}.jex-home-hero-text{display:flex;flex-direction:column;gap:2px;min-width:0}.jex-home-title{font-size:17px;font-weight:700;color:var(--jex-text-main);margin:0;line-height:1.2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.jex-home-status{font-size:12px;font-weight:500;color:#22c55e;letter-spacing:.02em}.jex-home-greeting{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:4px 16px 16px;padding:16px 18px;font-size:14px;line-height:1.55;color:var(--jex-text-main);animation:jexFadeIn .4s .1s ease both}.jex-home-greeting p{margin:0}@keyframes jexFadeIn{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.jex-home-actions{display:flex;flex-direction:column;gap:10px;animation:jexFadeIn .4s .2s ease both}.jex-home-start-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;padding:14px 20px;font-size:15px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,transform .15s,box-shadow .2s;width:100%;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 25%,transparent)}.jex-home-start-btn:hover{background:var(--jex-primary-hover);transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 35%,transparent)}.jex-home-start-btn:active{transform:translateY(0);box-shadow:0 1px 4px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card{display:flex;flex-direction:column;gap:8px;width:100%;text-align:left;padding:16px 18px;border-radius:14px;border:1.5px solid var(--jex-primary);background:color-mix(in srgb,var(--jex-primary) 6%,var(--jex-bg-window));cursor:pointer;font-family:inherit;transition:background .2s,border-color .2s,transform .15s,box-shadow .2s;box-shadow:0 2px 8px color-mix(in srgb,var(--jex-primary) 12%,transparent)}.jex-home-resume-card:hover{background:color-mix(in srgb,var(--jex-primary) 10%,var(--jex-bg-window));transform:translateY(-1px);box-shadow:0 4px 16px color-mix(in srgb,var(--jex-primary) 20%,transparent)}.jex-home-resume-card:active{transform:translateY(0)}.jex-home-resume-top{display:flex;align-items:center;justify-content:space-between}.jex-home-resume-label{font-size:14px;font-weight:600;color:var(--jex-primary)}.jex-home-resume-arrow{color:var(--jex-primary);opacity:.6;transition:opacity .2s,transform .2s}.jex-home-resume-card:hover .jex-home-resume-arrow{opacity:1;transform:translate(2px)}.jex-home-resume-ref{font-family:ui-monospace,Cascadia Code,Fira Code,monospace;font-size:13px;font-weight:600;letter-spacing:.06em;color:var(--jex-text-muted)}.jex-home-history{display:flex;flex-direction:column;gap:8px}.jex-home-resume-meta{font-size:11px;opacity:.7;margin-top:4px}.jex-home-new-btn{background:transparent;color:var(--jex-text-muted);border:1px solid var(--jex-border-input);border-radius:12px;padding:12px 20px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;transition:color .2s,border-color .2s,background .2s;width:100%}.jex-home-new-btn:hover{color:var(--jex-text-main);border-color:var(--jex-text-muted);background:color-mix(in srgb,var(--jex-primary) 3%,transparent)}.jex-session-ref{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);border-radius:8px;font-size:12px}.jex-session-ref-label{color:var(--jex-text-muted);font-weight:500}.jex-session-ref-code{color:var(--jex-primary);font-weight:700;font-family:ui-monospace,Cascadia Code,monospace;letter-spacing:.05em}.jex-chat-messages{flex:1;padding:20px;overflow-y:auto;display:flex;flex-direction:column;gap:12px}.jex-message-row{display:flex;align-items:flex-end;gap:8px;max-width:85%}.jex-message-row.bot{align-self:flex-start}.jex-message-content{flex:1;min-width:0}.jex-avatar{width:24px;height:24px;border-radius:50%;flex-shrink:0;display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:2px}.jex-avatar-bot{background:var(--jex-bg-msg-bot);color:var(--jex-primary)}.jex-avatar-agent{background:var(--jex-bg-avatar-agent)}.jex-avatar-img{width:100%;height:100%;border-radius:50%;object-fit:cover}.jex-avatar-initials{font-size:9px;font-weight:700;color:var(--jex-text-avatar-agent)}.jex-message-author-row{display:flex;align-items:center;gap:6px;margin-top:2px;padding-left:4px}.jex-message-author{font-size:10px;color:var(--jex-text-muted)}.jex-reply-tag-btn{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;padding:0;border:none;border-radius:4px;background:transparent;color:var(--jex-text-muted, #6b7280);cursor:pointer;transition:background .15s,color .15s}.jex-reply-tag-btn:hover{background:#0000000f;color:var(--jex-primary, #115A62)}.jex-reply-tag-btn:focus-visible{outline:2px solid var(--jex-primary, #115A62);outline-offset:1px}.jex-message{padding:12px 16px;border-radius:18px;font-size:14px;line-height:1.4}.jex-message.bot{background:var(--jex-bg-msg-bot);border:1px solid var(--jex-border-window);color:var(--jex-text-msg-bot);border-bottom-left-radius:4px}.jex-message.user{align-self:flex-end;max-width:80%;background:var(--jex-bg-msg-user);color:var(--jex-text-msg-user);border-bottom-right-radius:4px}.jex-typing{align-self:flex-start;display:flex;gap:4px;padding:12px 16px}.jex-typing span{width:8px;height:8px;border-radius:50%;background:var(--jex-text-muted);animation:jexTypingDot 1.2s infinite ease-in-out}.jex-typing span:nth-child(2){animation-delay:.2s}.jex-typing span:nth-child(3){animation-delay:.4s}@keyframes jexTypingDot{0%,80%,to{transform:scale(.8);opacity:.4}40%{transform:scale(1);opacity:1}}.jex-md{word-break:break-word;overflow-wrap:anywhere}.jex-md p{margin:0 0 8px}.jex-md p:last-child{margin-bottom:0}.jex-md strong{font-weight:600}.jex-md em{font-style:italic}.jex-md ul,.jex-md ol{margin:0 0 8px;padding-left:20px}.jex-md ul:last-child,.jex-md ol:last-child{margin-bottom:0}.jex-md ul{list-style-type:disc}.jex-md ol{list-style-type:decimal}.jex-md li{margin-bottom:2px}.jex-md li:last-child{margin-bottom:0}.jex-md a{color:var(--jex-primary);text-decoration:underline;text-underline-offset:2px}.jex-md a:hover{opacity:.8}.jex-md code{background:#00000014;padding:1px 5px;border-radius:4px;font-size:.9em;font-family:ui-monospace,Cascadia Code,Fira Code,monospace}.jex-md pre{background:#0000000f;border-radius:8px;padding:10px 12px;margin:0 0 8px;overflow-x:auto;font-size:.85em}.jex-md pre:last-child{margin-bottom:0}.jex-md pre code{background:none;padding:0;border-radius:0;font-size:inherit}.jex-md h1,.jex-md h2,.jex-md h3,.jex-md h4{font-weight:600;margin:8px 0 4px}.jex-md h1:first-child,.jex-md h2:first-child,.jex-md h3:first-child,.jex-md h4:first-child{margin-top:0}.jex-md h3{font-size:1em}.jex-md h4{font-size:.95em}.jex-md hr{border:none;border-top:1px solid var(--jex-border-window);margin:8px 0}.jex-md blockquote{border-left:3px solid var(--jex-primary);margin:0 0 8px;padding:4px 12px;color:var(--jex-text-muted)}.jex-md blockquote:last-child{margin-bottom:0}.dark .jex-md code,.jex-widget.dark .jex-md code{background:#ffffff1a}.dark .jex-md pre,.jex-widget.dark .jex-md pre{background:#ffffff14}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-md code{background:#ffffff1a}:host:not(.light) .jex-widget:not(.light) .jex-md pre{background:#ffffff14}}.jex-streaming-cursor:after{content:"◊";margin-left:2px;animation:jexBlinkCursor .8s ease-in-out infinite}@keyframes jexBlinkCursor{0%,to{opacity:1}50%{opacity:0}}.jex-session-notice{align-self:center;text-align:center;padding:8px 16px;margin:8px 0;font-size:12px;color:var(--jex-text-muted);background:var(--jex-bg-input, #f1f5f9);border-radius:8px;line-height:1.4}.jex-message-error{background:var(--jex-bg-error, #fef2f2)!important;border-color:var(--jex-border-error, #fecaca)!important;color:var(--jex-text-error, #991b1b)!important}.jex-chat-input{padding:16px;border-top:1px solid var(--jex-border-window);display:flex;gap:8px;flex-shrink:0;flex-wrap:wrap}.jex-rate-limit-notice{flex:1 0 100%;order:-1;margin-bottom:8px;padding:8px 12px;border-radius:10px;background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-muted, #64748b);font-size:12px;line-height:1.4;text-align:center}.jex-chat-input input{flex:1;background:var(--jex-bg-input);border:1px solid var(--jex-border-input);border-radius:12px;padding:10px 14px;color:var(--jex-text-main);outline:none;font-family:inherit;font-size:14px}.jex-chat-input input:focus{border-color:var(--jex-primary)}.jex-send-btn{background:var(--jex-bg-send-btn);color:var(--jex-text-header);border:none;border-radius:12px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s cubic-bezier(.175,.885,.32,1.275);flex-shrink:0}.jex-send-btn:hover{transform:scale(1.05);background:var(--jex-primary-hover)}.jex-send-btn:active{transform:scale(.95)}.jex-widget-footer{display:flex;align-items:center;justify-content:center;padding:8px 16px;border-top:1px solid var(--jex-border-glass);background:#00000005;flex-shrink:0}.jex-widget.dark .jex-widget-footer{background:#ffffff05}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-widget-footer{background:#ffffff05}}.jex-branding{display:flex;align-items:center;gap:6px;text-decoration:none;color:var(--jex-text-muted);font-size:11px;font-weight:500;transition:color .2s}.jex-branding:hover{color:var(--jex-text-main)}.jex-branding-icon{color:var(--jex-primary)}.jex-branding span strong{font-weight:700;color:var(--jex-text-main)}.jex-locale-select-wrapper{position:relative;display:flex;align-items:center}.jex-locale-select{appearance:none;-webkit-appearance:none;background:transparent;border:1px solid transparent;padding:4px 20px 4px 6px;border-radius:6px;font-family:inherit;font-size:11px;font-weight:600;color:var(--jex-text-muted);background-color:transparent;cursor:pointer;outline:none;transition:all .2s ease}.jex-locale-select option{background-color:#fff;color:#0f172a}.jex-locale-select:hover,.jex-locale-select:focus-visible{color:var(--jex-text-main);background:#0000000a}.jex-widget.dark .jex-locale-select:hover,.jex-widget.dark .jex-locale-select:focus-visible{background:#ffffff0d}.jex-widget.dark .jex-locale-select option{background-color:#0f172a;color:#f8fafc}@media(prefers-color-scheme:dark){:host:not(.light) .jex-widget:not(.light) .jex-locale-select:hover,:host:not(.light) .jex-widget:not(.light) .jex-locale-select:focus-visible{background:#ffffff0d}:host:not(.light) .jex-widget:not(.light) .jex-locale-select option{background-color:#0f172a;color:#f8fafc}}.jex-locale-select:focus-visible{border-color:var(--jex-primary)}.jex-locale-chevron{position:absolute;right:4px;pointer-events:none;color:var(--jex-text-muted);transition:color .2s ease}.jex-locale-select-wrapper:hover .jex-locale-chevron{color:var(--jex-text-main)}.jex-overlay{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:var(--jex-bg-window, #fff);z-index:10;padding:24px;text-align:center}.jex-loading-spinner{width:32px;height:32px;border:3px solid var(--jex-border-input, #e2e8f0);border-top-color:var(--jex-primary, #115A62);border-radius:50%;animation:jex-spin .7s linear infinite}@keyframes jex-spin{to{transform:rotate(360deg)}}.jex-loading-message{font-size:14px;color:var(--jex-text-muted, #64748b)}.jex-error-message{font-size:14px;color:var(--jex-text-main, #334155)}.jex-error-actions{display:flex;gap:8px}.jex-error-retry,.jex-error-back{padding:8px 16px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;border:none}.jex-error-retry{background:var(--jex-primary, #115A62);color:#fff}.jex-error-back{background:transparent;color:var(--jex-text-muted, #64748b);border:1px solid var(--jex-border-input, #e2e8f0)}.jex-selection{display:flex;flex-direction:column;gap:12px;padding:24px 16px;height:100%}.jex-selection-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 8px}.jex-selection-options{display:flex;flex-direction:column;gap:10px}.jex-selection-option{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:16px;border-radius:12px;border:1px solid var(--jex-border-window, #e2e8f0);background:transparent;cursor:pointer;text-align:left;transition:border-color .15s ease,background .15s ease}.jex-selection-option:hover{border-color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 5%,transparent)}.jex-selection-icon{font-size:20px}.jex-selection-label{font-size:14px;font-weight:600;color:var(--jex-text-main, #0f172a)}.jex-selection-sub{font-size:12px;color:var(--jex-text-muted, #64748b)}.jex-form-screen{display:flex;flex-direction:column;padding:20px 16px;height:100%;overflow-y:auto}.jex-form-title{font-size:16px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0 0 16px}.jex-form{display:flex;flex-direction:column;gap:10px}.jex-form-input,.jex-form-textarea{padding:10px 12px;border-radius:8px;border:1px solid var(--jex-border-input, #e2e8f0);font-size:14px;background:transparent;color:var(--jex-text-main, #0f172a);outline:none}.jex-form-input:focus,.jex-form-textarea:focus{border-color:var(--jex-primary, #115A62)}.jex-form-textarea{min-height:80px;resize:vertical}.jex-form-submit{padding:10px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer;margin-top:4px}.jex-inline-form{display:flex;flex-direction:column;gap:8px;padding:12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-title{font-weight:600;font-size:15px;color:var(--jex-text-main, #0f172a);margin:0}.jex-inline-form-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.4;margin:0 0 4px}.jex-inline-form-consent{font-size:11px;color:var(--jex-text-muted, #64748b);line-height:1.3;margin-top:4px;text-align:center}.jex-inline-form .jex-form-submit:disabled{opacity:.7;cursor:not-allowed}.jex-escalation-subtitle{font-size:13px;color:var(--jex-text-muted, #64748b);line-height:1.45;margin:0 0 8px}.jex-escalation-skip{padding:8px 12px;border:none;background:transparent;color:var(--jex-text-muted, #64748b);font-size:13px;cursor:pointer;text-decoration:underline;text-underline-offset:2px;text-align:center}.jex-escalation-skip:hover{color:var(--jex-text-main, #0f172a)}.jex-inline-form-card{position:relative;padding:14px;gap:8px}.jex-inline-form-dismiss{position:absolute;top:10px;right:10px;width:24px;height:24px;border-radius:50%;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-window, #fff);color:var(--jex-text-muted, #64748b);font-size:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}.jex-inline-form-dismiss:hover{background:var(--jex-bg-msg-bot, #f1f5f9);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted{display:flex;align-items:center;gap:10px;padding:10px 12px;background:var(--jex-bg-msg-bot, #f1f5f9);border:1px solid var(--jex-border-input, #e2e8f0);border-radius:var(--jex-radius, .75rem);width:100%}.jex-inline-form-check{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary) 15%,transparent);color:var(--jex-primary, #115A62);font-size:14px;font-weight:700;flex-shrink:0}.jex-inline-form-submitted-title{font-weight:600;font-size:var(--jex-font-size, 14px);color:var(--jex-text-main, #0f172a)}.jex-inline-form-submitted-detail{font-size:12px;color:var(--jex-text-muted, #64748b);margin-top:2px}.jex-escalation-confirm{border-left:3px solid var(--jex-primary, #115A62);padding-left:8px}.jex-session-prompt{display:flex;flex-direction:column;align-items:center;gap:8px;padding:12px 16px;margin:8px 0;text-align:center}.jex-session-prompt-text{font-size:13px;color:var(--jex-text-muted, #64748b)}.jex-session-prompt-btn{padding:8px 16px;border-radius:8px;border:1px solid var(--jex-primary, #115A62);background:transparent;color:var(--jex-primary, #115A62);font-size:13px;font-weight:600;cursor:pointer}.jex-session-prompt-btn:hover{background:color-mix(in srgb,var(--jex-primary) 10%,transparent)}.jex-chat-input-resolved{display:flex;flex-direction:column;align-items:center;gap:10px;padding:14px 16px;border-top:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-msg-bot, #f1f5f9);text-align:center}.jex-resolved-notice{font-size:13px;font-weight:500;color:var(--jex-text-muted, #64748b)}.jex-resolved-new-btn{padding:10px 20px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;width:100%}.jex-resolved-new-btn:hover{opacity:.9}.jex-confirmation{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:32px 24px;height:100%;text-align:center}.jex-confirmation-icon{width:48px;height:48px;border-radius:50%;background:color-mix(in srgb,var(--jex-primary, #115A62) 15%,transparent);color:var(--jex-primary, #115A62);font-size:22px;display:flex;align-items:center;justify-content:center}.jex-confirmation-title{font-size:18px;font-weight:700;color:var(--jex-text-main, #0f172a);margin:0}.jex-confirmation-body{font-size:13px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-ref{font-size:20px;font-weight:700;letter-spacing:.05em;color:var(--jex-primary, #115A62);background:color-mix(in srgb,var(--jex-primary, #115A62) 10%,transparent);padding:10px 20px;border-radius:10px}.jex-confirmation-hint{font-size:12px;color:var(--jex-text-muted, #64748b);margin:0}.jex-confirmation-done{margin-top:8px;padding:10px 28px;border-radius:8px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:14px;font-weight:600;cursor:pointer}.jex-home-lookup-link{background:none;border:none;font-size:12px;color:var(--jex-text-muted, #64748b);cursor:pointer;text-decoration:underline;padding:0;align-self:center}.jex-home-lookup{display:flex;gap:8px;width:100%;animation:jexFadeIn .4s .1s ease both}.jex-home-lookup-input{flex:1;padding:10px 14px;border-radius:10px;border:1px solid var(--jex-border-input, #e2e8f0);background:var(--jex-bg-input);color:var(--jex-text-main);font-size:13px;font-family:ui-monospace,Cascadia Code,Fira Code,monospace;letter-spacing:.04em;outline:none;transition:border-color .2s}.jex-home-lookup-input::placeholder{font-family:inherit;letter-spacing:.04em;color:var(--jex-text-muted);opacity:.7}.jex-home-lookup-input:focus{border-color:var(--jex-primary, #115A62)}.jex-home-lookup-submit{padding:10px 16px;border-radius:10px;border:none;background:var(--jex-primary, #115A62);color:#fff;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;transition:background .2s,opacity .2s;flex-shrink:0}.jex-home-lookup-submit:hover:not(:disabled){background:var(--jex-primary-hover)}.jex-home-lookup-submit:disabled{opacity:.4;cursor:default}.jex-sources-row{margin-top:6px;margin-left:32px;display:flex;flex-direction:column;gap:6px}.jex-sources-toggle{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;background:transparent;border:none;border-radius:6px;cursor:pointer;font-size:11px;color:var(--jex-text-muted, #6b7280);font-family:inherit;align-self:flex-start;transition:background .15s,color .15s}.jex-sources-toggle:hover{background:#0000000a;color:inherit}.jex-sources-icon{font-size:12px;line-height:1}.jex-sources-chevron{display:inline-block;font-size:10px;transition:transform .15s}.jex-sources-chevron--open{transform:rotate(180deg)}.jex-sources-pills{display:flex;flex-wrap:wrap;align-items:center;gap:6px}.jex-source-pill{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:2px 8px;border-radius:999px;border:1px solid rgba(0,0,0,.1);background:#0000000a;color:var(--jex-text-muted, #6b7280);font-size:11px;text-decoration:none;cursor:pointer;transition:background .15s,color .15s}.jex-source-pill:hover{background:#00000014;color:inherit}.jex-source-id{display:inline-flex;align-items:center;justify-content:center;min-width:16px;height:16px;padding:0 4px;border-radius:4px;background:var(--jex-primary, #115A62);color:#fff;font-size:10px;font-weight:600;line-height:1;flex-shrink:0;font-variant-numeric:tabular-nums}.jex-source-type{font-size:10px;flex-shrink:0}.jex-source-label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500}.jex-source-score{opacity:.6;flex-shrink:0;font-variant-numeric:tabular-nums}';function fc(t){const e=document.createElement("style");e.textContent=dc,t.appendChild(e)}const pc="https://festive-mouse-978.eu-west-1.convex.cloud";let En=null;function gc(t){const e=t??pc;if(!e)throw new Error("[jexity] No Convex URL — set VITE_CONVEX_URL at build time or data-convex-url on the script tag");return En||(En=new sa(wa(e))),En}function mc(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);fc(n),St.value=e.source,me.value=e.bootstrapToken,z.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),I.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),he(u(aa,{client:gc(e.convexUrl),children:u(hc,{options:e})}),r),function(){he(null,r),I.value=!1,St.value=void 0,me.value=void 0,z.value=[{id:"home"}]}}function xc(t,e,n){const r=mc(t,e),i=new Set,s=I.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){I.value=!0},close(){I.value=!1},toggle(){I.value=!I.value},get isOpen(){return I.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let st=null;function bc(t){st&&st.shutdown();let e;t.container?e=typeof t.container=="string"?document.querySelector(t.container):t.container:(e=document.createElement("div"),e.id="jexity-chat-widget",document.body.appendChild(e));const n=xc(e,t,()=>{t.container||e.remove(),st===n&&(st=null)});return st=n,n}function le(t,e){return t.getAttribute(e)??void 0}async function Gi(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const e=t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",n=t.getAttribute("data-proj-slug")??void 0,r=le(t,"data-convex-url")??"https://festive-mouse-978.eu-west-1.convex.cloud"??"",i=fn(r),s=await gi(e,i,n);if(!s.ok){const l=window.location.origin,a=n?`project '${e}/${n}'`:`org '${e}'`;s.error==="unauthorized"?console.warn(`[JexityChat] This domain is not authorized for ${a}. Add '${l}' under Allowed Domains in your Jexity dashboard.`):s.error==="not_found"?console.warn(`[JexityChat] No active widget config found for ${a}. Check that the org slug is correct and the widget is enabled.`):s.error==="rate_limited"?console.warn(`[JexityChat] Bootstrap rate-limited for ${a}. Retry after ${s.retryAfterSec??60}s.`):console.warn(`[JexityChat] Bootstrap failed (network error). Check that the Convex deployment is reachable at ${i}.`);return}const o={orgSlug:e,projSlug:n,bootstrapToken:s.token,position:le(t,"data-position")??void 0,theme:le(t,"data-theme")??void 0,greeting:le(t,"data-greeting"),title:le(t,"data-title"),primaryColor:le(t,"data-primary-color"),locale:le(t,"data-locale"),convexUrl:le(t,"data-convex-url")};window.JexityChat=bc(o)}document.readyState==="complete"?Gi():window.addEventListener("load",Gi)})();
62
62
  //# sourceMappingURL=widget.js.map