@evelan/jexity-widget 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +775 -779
- package/dist/index.mjs.map +1 -1
- package/dist/react.mjs +787 -791
- package/dist/react.mjs.map +1 -1
- package/dist/types/features/chat/hooks/useConvexSession.d.ts +0 -1
- package/dist/types/features/chat/hooks/useConvexSession.d.ts.map +1 -1
- package/dist/types/module/shell/mount.d.ts.map +1 -1
- package/dist/types/module/shell/shell.state.d.ts +3 -0
- package/dist/types/module/shell/shell.state.d.ts.map +1 -1
- package/dist/types/types.d.ts +2 -0
- package/dist/types/types.d.ts.map +1 -1
- package/dist/widget.js +19 -19
- package/dist/widget.js.map +1 -1
- package/package.json +1 -1
package/dist/widget.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(){"use strict";var Le,m,Rn,$n,le,An,In,En,qn,$t,At,It,Pn,Oe={},Mn=[],Mi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Ne=Array.isArray;function V(t,e){for(var n in e)t[n]=e[n];return t}function Et(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function Y(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 Qe(t,o,r,i,null)}function Qe(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??++Rn,__i:-1,__u:0};return i==null&&m.vnode!=null&&m.vnode(s),s}function Li(){return{current:null}}function O(t){return t.children}function N(t,e){this.props=t,this.context=e}function be(t,e){if(e==null)return t.__?be(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"?be(t):null}function Ln(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 Ln(t)}}function qt(t){(!t.__d&&(t.__d=!0)&&le.push(t)&&!it.__r++||An!=m.debounceRendering)&&((An=m.debounceRendering)||In)(it)}function it(){for(var t,e,n,r,i,s,o,l=1;le.length;)le.length>l&&le.sort(En),t=le.shift(),l=le.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,s=[],o=[],e.__P&&((n=V({},r)).__v=r.__v+1,m.vnode&&m.vnode(n),Pt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,s,i??be(r),!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Bn(s,n,o),r.__e=r.__=null,n.__e!=i&&Ln(n)));it.__r=0}function On(t,e,n,r,i,s,o,l,a,u,d){var c,p,f,g,b,S,_,w=r&&r.__k||Mn,K=e.length;for(a=Oi(n,e,w,a,K),c=0;c<K;c++)(f=n.__k[c])!=null&&(p=f.__i==-1?Oe:w[f.__i]||Oe,f.__i=c,S=Pt(t,f,p,i,s,o,l,a,u,d),g=f.__e,f.ref&&p.ref!=f.ref&&(p.ref&&Lt(p.ref,null,f),d.push(f.ref,f.__c||g,f)),b==null&&g!=null&&(b=g),(_=!!(4&f.__u))||p.__k===f.__k?a=Nn(f,a,t,_):typeof f.type=="function"&&S!==void 0?a=S:g&&(a=g.nextSibling),f.__u&=-7);return n.__e=b,a}function Oi(t,e,n,r,i){var s,o,l,a,u,d=n.length,c=d,p=0;for(t.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(a=s+p,(o=t.__k[s]=typeof o=="string"||typeof o=="number"||typeof o=="bigint"||o.constructor==String?Qe(null,o,null,null,null):Ne(o)?Qe(O,{children:o},null,null,null):o.constructor==null&&o.__b>0?Qe(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):o).__=t,o.__b=t.__b+1,l=null,(u=o.__i=Ni(o,n,a,c))!=-1&&(c--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?p--:i<d&&p++),typeof o.type!="function"&&(o.__u|=4)):u!=a&&(u==a-1?p--:u==a+1?p++:(u>a?p--:p++,o.__u|=4))):t.__k[s]=null;if(c)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=be(l)),Dn(l,l));return r}function Nn(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=Nn(i[s],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=be(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ee(t,e){return e=e||[],t==null||typeof t=="boolean"||(Ne(t)?t.some(function(n){ee(n,e)}):e.push(t)),e}function Ni(t,e,n,r){var i,s,o,l=t.key,a=t.type,u=e[n],d=u!=null&&(2&u.__u)==0;if(u===null&&t.key==null||d&&l==u.key&&a==u.type)return n;if(r>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<e.length;)if((u=e[o=i>=0?i--:s++])!=null&&(2&u.__u)==0&&l==u.key&&a==u.type)return o}return-1}function Qn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Mi.test(e)?n:n+"px"}function st(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||Qn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||Qn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(qn,"$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=$t,t.addEventListener(e,s?It:At,s)):t.removeEventListener(e,s?It:At,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 zn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=$t++;else if(e.t<n.u)return;return n(m.event?m.event(e):e)}}}function Pt(t,e,n,r,i,s,o,l,a,u){var d,c,p,f,g,b,S,_,w,K,Z,ae,U,Pi,Rt,rt,jn,X=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),s=[l=e.__e=n.__e]),(d=m.__b)&&d(e);e:if(typeof X=="function")try{if(_=e.props,w="prototype"in X&&X.prototype.render,K=(d=X.contextType)&&r[d.__c],Z=d?K?K.props.value:d.__:r,n.__c?S=(c=e.__c=n.__c).__=c.__E:(w?e.__c=c=new X(_,Z):(e.__c=c=new N(_,Z),c.constructor=X,c.render=zi),K&&K.sub(c),c.props=_,c.state||(c.state={}),c.context=Z,c.__n=r,p=c.__d=!0,c.__h=[],c._sb=[]),w&&c.__s==null&&(c.__s=c.state),w&&X.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=V({},c.__s)),V(c.__s,X.getDerivedStateFromProps(_,c.__s))),f=c.props,g=c.state,c.__v=e,p)w&&X.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),w&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(w&&X.getDerivedStateFromProps==null&&_!==f&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(_,Z),!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(_,c.__s,Z)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(c.props=_,c.state=c.__s,c.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Me){Me&&(Me.__=e)}),ae=0;ae<c._sb.length;ae++)c.__h.push(c._sb[ae]);c._sb=[],c.__h.length&&o.push(c);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(_,c.__s,Z),w&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(f,g,b)})}if(c.context=Z,c.props=_,c.__P=t,c.__e=!1,U=m.__r,Pi=0,w){for(c.state=c.__s,c.__d=!1,U&&U(e),d=c.render(c.props,c.state,c.context),Rt=0;Rt<c._sb.length;Rt++)c.__h.push(c._sb[Rt]);c._sb=[]}else do c.__d=!1,U&&U(e),d=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++Pi<25);c.state=c.__s,c.getChildContext!=null&&(r=V(V({},r),c.getChildContext())),w&&!p&&c.getSnapshotBeforeUpdate!=null&&(b=c.getSnapshotBeforeUpdate(f,g)),rt=d,d!=null&&d.type===O&&d.key==null&&(rt=Fn(d.props.children)),l=On(t,Ne(rt)?rt:[rt],e,n,r,i,s,o,l,a,u),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),S&&(c.__E=c.__=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(jn=s.length;jn--;)Et(s[jn]);Mt(e)}else e.__e=n.__e,e.__k=n.__k,Me.then||Mt(e);m.__e(Me,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Qi(n.__e,e,n,r,i,s,o,a,u);return(d=m.diffed)&&d(e),128&e.__u?void 0:l}function Mt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Mt)}function Bn(t,e,n){for(var r=0;r<n.length;r++)Lt(n[r],n[++r],n[++r]);m.__c&&m.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(s){s.call(i)})}catch(s){m.__e(s,i.__v)}})}function Fn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Ne(t)?t.map(Fn):V({},t)}function Qi(t,e,n,r,i,s,o,l,a){var u,d,c,p,f,g,b,S=n.props,_=e.props,w=e.type;if(w=="svg"?i="http://www.w3.org/2000/svg":w=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((f=s[u])&&"setAttribute"in f==!!w&&(w?f.localName==w:f.nodeType==3)){t=f,s[u]=null;break}}if(t==null){if(w==null)return document.createTextNode(_);t=document.createElementNS(i,w,_.is&&_),l&&(m.__m&&m.__m(e,s),l=!1),s=null}if(w==null)S===_||l&&t.data==_||(t.data=_);else{if(s=s&&Le.call(t.childNodes),S=n.props||Oe,!l&&s!=null)for(S={},u=0;u<t.attributes.length;u++)S[(f=t.attributes[u]).name]=f.value;for(u in S)if(f=S[u],u!="children"){if(u=="dangerouslySetInnerHTML")c=f;else if(!(u in _)){if(u=="value"&&"defaultValue"in _||u=="checked"&&"defaultChecked"in _)continue;st(t,u,null,f,i)}}for(u in _)f=_[u],u=="children"?p=f:u=="dangerouslySetInnerHTML"?d=f:u=="value"?g=f:u=="checked"?b=f:l&&typeof f!="function"||S[u]===f||st(t,u,f,S[u],i);if(d)l||c&&(d.__html==c.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(c&&(t.innerHTML=""),On(e.type=="template"?t.content:t,Ne(p)?p:[p],e,n,r,w=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:n.__k&&be(n,0),l,a),s!=null)for(u=s.length;u--;)Et(s[u]);l||(u="value",w=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[u]||w=="progress"&&!g||w=="option"&&g!=S[u])&&st(t,u,g,S[u],i),u="checked",b!=null&&b!=t[u]&&st(t,u,b,S[u],i))}return t}function Lt(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){m.__e(i,n)}}function Dn(t,e,n){var r,i;if(m.unmount&&m.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Lt(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(s){m.__e(s,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&Dn(r[i],e,n||typeof t.type!="function");n||Et(t.__e),t.__c=t.__=t.__e=void 0}function zi(t,e,n){return this.constructor(t,n)}function ce(t,e,n){var r,i,s,o;e==document&&(e=document.documentElement),m.__&&m.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],Pt(e,t=(!r&&n||e).__k=Y(O,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),Bn(s,t,o)}function Un(t,e){ce(t,e,Un)}function Bi(t,e,n){var r,i,s,o,l=V({},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),Qe(t.type,l,r||t.key,i||t.ref,null)}function Fi(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,qt(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"+Pn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}Le=Mn.slice,m={__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}},Rn=0,$n=function(t){return t!=null&&t.constructor==null},N.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=V({},this.state),typeof t=="function"&&(t=t(V({},n),this.props)),t&&V(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),qt(this))},N.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),qt(this))},N.prototype.render=O,le=[],In=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,En=function(t,e){return t.__v.__b-e.__v.__b},it.__r=0,qn=/(PointerCapture)$|Capture$/i,$t=0,At=zn(!1),It=zn(!0),Pn=0;var Di=0;function h(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 u={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Di,__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 m.vnode&&m.vnode(u),u}var ie,k,Ot,Vn,ye=0,Wn=[],j=m,Hn=j.__b,Gn=j.__r,Jn=j.diffed,Kn=j.__c,Zn=j.unmount,Xn=j.__;function ve(t,e){j.__h&&j.__h(k,t,ye||e),ye=0;var n=k.__H||(k.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function R(t){return ye=1,Nt(rr,t)}function Nt(t,e,n){var r=ve(ie++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):rr(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],u=r.t(a,l);a!==u&&(r.__N=[u,r.__[1]],r.__c.setState({}))}],r.__c=k,!k.__f)){var i=function(l,a,u){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(p){return!!p.__c});if(d.every(function(p){return!p.__N}))return!s||s.call(this,l,a,u);var c=r.__c.props!==l;return d.forEach(function(p){if(p.__N){var f=p.__[0];p.__=p.__N,p.__N=void 0,f!==p.__[0]&&(c=!0)}}),s&&s.call(this,l,a,u)||c};k.__f=!0;var s=k.shouldComponentUpdate,o=k.componentWillUpdate;k.componentWillUpdate=function(l,a,u){if(this.__e){var d=s;s=void 0,i(l,a,u),s=d}o&&o.call(this,l,a,u)},k.shouldComponentUpdate=i}return r.__N||r.__}function Q(t,e){var n=ve(ie++,3);!j.__s&&zt(n.__H,e)&&(n.__=t,n.u=e,k.__H.__h.push(n))}function ze(t,e){var n=ve(ie++,4);!j.__s&&zt(n.__H,e)&&(n.__=t,n.u=e,k.__h.push(n))}function ot(t){return ye=5,z(function(){return{current:t}},[])}function Yn(t,e,n){ye=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 z(t,e){var n=ve(ie++,7);return zt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function Be(t,e){return ye=8,z(function(){return t},e)}function at(t){var e=k.context[t.__c],n=ve(ie++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(k)),e.props.value):t.__}function er(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function tr(){var t=ve(ie++,11);if(!t.__){for(var e=k.__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 Ui(){for(var t;t=Wn.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(lt),t.__H.__h.forEach(Qt),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){k=null,Hn&&Hn(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Xn&&Xn(t,e)},j.__r=function(t){Gn&&Gn(t),ie=0;var e=(k=t.__c).__H;e&&(Ot===k?(e.__h=[],k.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(lt),e.__h.forEach(Qt),e.__h=[],ie=0)),Ot=k},j.diffed=function(t){Jn&&Jn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Wn.push(e)!==1&&Vn===j.requestAnimationFrame||((Vn=j.requestAnimationFrame)||Vi)(Ui)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ot=k=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(lt),n.__h=n.__h.filter(function(r){return!r.__||Qt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),Kn&&Kn(t,e)},j.unmount=function(t){Zn&&Zn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{lt(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var nr=typeof requestAnimationFrame=="function";function Vi(t){var e,n=function(){clearTimeout(r),nr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);nr&&(e=requestAnimationFrame(n))}function lt(t){var e=k,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),k=e}function Qt(t){var e=k;t.__c=t.__(),k=e}function zt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function rr(t,e){return typeof e=="function"?e(t):e}function ir(t,e){for(var n in e)t[n]=e[n];return t}function Bt(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 sr(t,e){var n=e(),r=R({t:{__:n,u:e}}),i=r[0].t,s=r[1];return ze(function(){i.__=n,i.u=e,Ft(i)&&s({t:i})},[t,n,e]),Q(function(){return Ft(i)&&s({t:i}),t(function(){Ft(i)&&s({t:i})})},[t]),n}function Ft(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 or(t){t()}function ar(t){return t}function lr(){return[!1,or]}var cr=ze;function Dt(t,e){this.props=t,this.context=e}function Wi(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:Bt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,Y(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Dt.prototype=new N).isPureReactComponent=!0,Dt.prototype.shouldComponentUpdate=function(t,e){return Bt(this.props,t)||Bt(this.state,e)};var ur=m.__b;m.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),ur&&ur(t)};var Hi=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Gi(t){function e(n){var r=ir({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=Hi,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var hr=function(t,e){return t==null?null:ee(ee(t).map(e))},Ji={map:hr,forEach:hr,count:function(t){return t?ee(t).length:0},only:function(t){var e=ee(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:ee},Ki=m.__e;m.__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)}Ki(t,e,n,r)};var dr=m.unmount;function fr(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=ir({},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 fr(r,e,n)})),t}function pr(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return pr(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 ct(){this.__u=0,this.o=null,this.__b=null}function gr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Zi(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 Y(n,s)}return i.displayName="Lazy",i.__f=!0,i}function Fe(){this.i=null,this.l=null}m.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),dr&&dr(t)},(ct.prototype=new N).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=gr(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]=pr(a,a.__c.__P,a.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(o,o)},ct.prototype.componentWillUnmount=function(){this.o=[]},ct.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]=fr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&Y(O,null,t.fallback);return i&&(i.__u&=-33),[Y(O,null,e.__a?null:t.children),i]};var mr=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 Xi(t){return this.getChildContext=function(){return t.context},t.children}function Yi(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){ce(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)}}}ce(Y(Xi,{context:e.context},t.__v),e.v)}function es(t,e){var n=Y(Yi,{__v:t,h:e});return n.containerInfo=e,n}(Fe.prototype=new N).__a=function(t){var e=this,n=gr(e.__v),r=e.l.get(t);return r[0]++,function(i){var s=function(){e.props.revealOrder?(r.push(i),mr(e,t,r)):i()};n?n(s):s()}},Fe.prototype.render=function(t){this.i=null,this.l=new Map;var e=ee(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},Fe.prototype.componentDidUpdate=Fe.prototype.componentDidMount=function(){var t=this;this.l.forEach(function(e,n){mr(t,n,e)})};var xr=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,ts=/^(?: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]/,ns=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,rs=/[A-Z0-9]/g,is=typeof document<"u",ss=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function os(t,e,n){return e.__k==null&&(e.textContent=""),ce(t,e),typeof n=="function"&&n(),t?t.__c:null}function as(t,e,n){return Un(t,e),typeof n=="function"&&n(),t?t.__c:null}N.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(N.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var br=m.event;function ls(){}function cs(){return this.cancelBubble}function us(){return this.defaultPrevented}m.event=function(t){return br&&(t=br(t)),t.persist=ls,t.isPropagationStopped=cs,t.isDefaultPrevented=us,t.nativeEvent=t};var Ut,hs={enumerable:!1,configurable:!0,get:function(){return this.class}},yr=m.vnode;m.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||is&&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"||ss(n.type)?a==="onfocus"?o="onfocusin":a==="onblur"?o="onfocusout":ns.test(o)&&(o=a):a=o="oninput":s&&ts.test(o)?o=o.replace(rs,"-$&").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=ee(n.children).forEach(function(u){u.props.selected=i.value.indexOf(u.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=ee(n.children).forEach(function(u){u.props.selected=i.multiple?i.defaultValue.indexOf(u.props.value)!=-1:i.defaultValue==u.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",hs)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=xr,yr&&yr(t)};var vr=m.__r;m.__r=function(t){vr&&vr(t),Ut=t.__c};var _r=m.diffed;m.diffed=function(t){_r&&_r(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),Ut=null};var ds={ReactCurrentDispatcher:{current:{readContext:function(t){return Ut.__n[t.__c].props.value},useCallback:Be,useContext:at,useDebugValue:er,useDeferredValue:ar,useEffect:Q,useId:tr,useImperativeHandle:Yn,useInsertionEffect:cr,useLayoutEffect:ze,useMemo:z,useReducer:Nt,useRef:ot,useState:R,useSyncExternalStore:sr,useTransition:lr}}};function fs(t){return Y.bind(null,t)}function ut(t){return!!t&&t.$$typeof===xr}function ps(t){return ut(t)&&t.type===O}function gs(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function ms(t){return ut(t)?Bi.apply(null,arguments):t}function xs(t){return!!t.__k&&(ce(null,t),!0)}function bs(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var ys=function(t,e){return t(e)},vs=function(t,e){return t(e)},_s=O,ws=ut,Vt={useState:R,useId:tr,useReducer:Nt,useEffect:Q,useLayoutEffect:ze,useInsertionEffect:cr,useTransition:lr,useDeferredValue:ar,useSyncExternalStore:sr,startTransition:or,useRef:ot,useImperativeHandle:Yn,useMemo:z,useCallback:Be,useContext:at,useDebugValue:er,version:"18.3.1",Children:Ji,render:os,hydrate:as,unmountComponentAtNode:xs,createPortal:es,createElement:Y,createContext:Fi,createFactory:fs,cloneElement:ms,createRef:Li,Fragment:O,isValidElement:ut,isElement:ws,isFragment:ps,isMemo:gs,findDOMNode:bs,Component:N,PureComponent:Dt,memo:Wi,forwardRef:Gi,flushSync:vs,unstable_batchedUpdates:ys,StrictMode:_s,Suspense:ct,SuspenseList:Fe,lazy:Zi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ds},W=[],M=[],ks=Uint8Array,Wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_e=0,Ss=Wt.length;_e<Ss;++_e)W[_e]=Wt[_e],M[Wt.charCodeAt(_e)]=_e;M[45]=62,M[95]=63;function js(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 Cs(t,e,n){return(e+n)*3/4-n}function De(t){var e,n=js(t),r=n[0],i=n[1],s=new ks(Cs(t,r,i)),o=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=M[t.charCodeAt(a)]<<18|M[t.charCodeAt(a+1)]<<12|M[t.charCodeAt(a+2)]<<6|M[t.charCodeAt(a+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=M[t.charCodeAt(a)]<<2|M[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=M[t.charCodeAt(a)]<<10|M[t.charCodeAt(a+1)]<<4|M[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function Ts(t){return W[t>>18&63]+W[t>>12&63]+W[t>>6&63]+W[t&63]}function Rs(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(Ts(r));return i.join("")}function Ue(t){for(var e,n=t.length,r=n%3,i=[],s=16383,o=0,l=n-r;o<l;o+=s)i.push(Rs(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(W[e>>2]+W[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(W[e>>10]+W[e>>4&63]+W[e<<2&63]+"=")),i.join("")}function te(t){if(t===void 0)return{};if(!wr(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function $s(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 wr(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const kr=!0,we=BigInt("-9223372036854775808"),Ht=BigInt("9223372036854775807"),Gt=BigInt("0"),As=BigInt("8"),Is=BigInt("256");function Sr(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Es(t){t<Gt&&(t-=we+we);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>>=As;return Ue(n)}function qs(t){const e=De(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Gt,r=Gt;for(const i of e)n+=BigInt(i)*Is**r,r++;return n>Ht&&(n+=we+we),n}function Ps(t){if(t<we||Ht<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),Ue(new Uint8Array(e))}function Ms(t){const e=De(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 Ls=DataView.prototype.setBigInt64?Ps:Es,Os=DataView.prototype.getBigInt64?Ms:qs,jr=1024;function Cr(t){if(t.length>jr)throw new Error(`Field name ${t} exceeds maximum field name length ${jr}.`);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 ke(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>ke(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 De(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return Os(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const i=De(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,kr);if(!Sr(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))Cr(r),n[r]=ke(i);return n}const Tr=16384;function Ve(t){const e=JSON.stringify(t,(n,r)=>r===void 0?"undefined":typeof r=="bigint"?`${r.toString()}n`:r);if(e.length>Tr){const n="[...truncated]";let r=Tr-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function Jt(t,e,n,r){if(t===void 0){const o=n&&` (present at path ${n} in original object ${Ve(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<we||Ht<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Ls(t)}}if(typeof t=="number")if(Sr(t)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,t,kr),{$float:Ue(new Uint8Array(o))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:Ue(new Uint8Array(t))};if(Array.isArray(t))return t.map((o,l)=>Jt(o,e,n+`[${l}]`));if(t instanceof Set)throw new Error(Kt(n,"Set",[...t],e));if(t instanceof Map)throw new Error(Kt(n,"Map",[...t],e));if(!wr(t)){const o=t?.constructor?.name,l=o?`${o} `:"";throw new Error(Kt(n,l,t,e))}const i={},s=Object.entries(t);s.sort(([o,l],[a,u])=>o===a?0:o<a?-1:1);for(const[o,l]of s)l!==void 0&&(Cr(o),i[o]=Jt(l,e,n+`.${o}`));return i}function Kt(t,e,n,r){return t?`${e}${Ve(n)} is not a supported Convex type (present at path ${t} in original object ${Ve(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${Ve(n)} is not a supported Convex type.`}function H(t){return Jt(t,t,"")}var Ns=Object.defineProperty,Qs=(t,e,n)=>e in t?Ns(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zt=(t,e,n)=>Qs(t,typeof e!="symbol"?e+"":e,n),Rr,$r;const zs=Symbol.for("ConvexError");class Xt extends($r=Error,Rr=zs,$r){constructor(e){super(typeof e=="string"?e:Ve(e)),Zt(this,"name","ConvexError"),Zt(this,"data"),Zt(this,Rr,!0),this.data=e}}const Ar=()=>Array.from({length:4},()=>0);Ar(),Ar();const Ir="1.35.1";var Bs=Object.defineProperty,Fs=(t,e,n)=>e in t?Bs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Er=(t,e,n)=>Fs(t,typeof e!="symbol"?e+"":e,n);const Ds="color:rgb(0, 145, 255)";function qr(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Pr{constructor(e){Er(this,"_onLogLineFuncs"),Er(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 Mr(t){const e=new Pr(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 Lr(t){return new Pr(t)}function ht(t,e,n,r,i){const s=qr(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}]`,Ds,a)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}function Us(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Se(t,e,n){return`[CONVEX ${qr(t)}(${e})] ${n.errorMessage}
|
|
2
|
-
Called by client`}function Yt(t,e){return e.data=t.errorData,e}function ue(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 he(t,e){return JSON.stringify({udfPath:ue(t),args:H(e)})}function Or(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:ue(t),args:H(e),options:H({initialNumItems:r,id:i})})}var Vs=Object.defineProperty,Ws=(t,e,n)=>e in t?Vs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G=(t,e,n)=>Ws(t,typeof e!="symbol"?e+"":e,n);class Hs{constructor(){G(this,"nextQueryId"),G(this,"querySetVersion"),G(this,"querySet"),G(this,"queryIdToToken"),G(this,"identityVersion"),G(this,"auth"),G(this,"outstandingQueriesOlderThanRestart"),G(this,"outstandingAuthOlderThanRestart"),G(this,"paused"),G(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=ue(e),o=he(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++,u={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,u),this.queryIdToToken.set(a,o);const d=this.querySetVersion,c=this.querySetVersion+1,p={type:"Add",queryId:a,udfPath:s,args:[H(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,p):this.querySetVersion=c,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:c,modifications:[p]},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=ue(e),i=he(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:[H(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 Gs=Object.defineProperty,Js=(t,e,n)=>e in t?Gs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dt=(t,e,n)=>Js(t,typeof e!="symbol"?e+"":e,n);class Ks{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,dt(this,"inflightRequests"),dt(this,"requestsOlderThanRestart"),dt(this,"inflightMutationsCount",0),dt(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)ht(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:ke(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:u}=e;ht(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:u!==void 0?ke(u):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 We=Symbol.for("functionName"),Nr=Symbol.for("toReferencePath");function Zs(t){return t[Nr]??null}function Xs(t){return t.startsWith("function://")}function Ys(t){let e;if(typeof t=="string")Xs(t)?e={functionHandle:t}:e={name:t};else if(t[We])e={name:t[We]};else{const n=Zs(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function E(t){const e=Ys(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[We];if(!n)throw new Error(`${t} is not a functionReference`);return n}function Qr(t){return{[We]:t}}function zr(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return zr(i)}else if(r===We){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 eo=zr();var to=Object.defineProperty,no=(t,e,n)=>e in t?to(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ft=(t,e,n)=>no(t,typeof e!="symbol"?e+"":e,n);class He{constructor(e){ft(this,"queryResults"),ft(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=te(n[0]),i=E(e),s=this.queryResults.get(he(i,r));if(s!==void 0)return He.queryValue(s.result)}getAllQueries(e){const n=[],r=E(e);for(const i of this.queryResults.values())i.udfPath===ue(r)&&n.push({args:i.args,value:He.queryValue(i.result)});return n}setQuery(e,n,r){const i=te(n),s=E(e),o=he(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 ro{constructor(){ft(this,"queryResults"),ft(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 He(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 He(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?Yt(r,new Xt(Se("query",n.udfPath,r))):new Error(Se("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var io=Object.defineProperty,so=(t,e,n)=>e in t?io(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,en=(t,e,n)=>so(t,typeof e!="symbol"?e+"":e,n);class q{constructor(e,n){en(this,"low"),en(this,"high"),en(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 q(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?Br:e>=oo?ao:new q(e%Ge|0,e/Ge|0)}toString(){return(BigInt(this.high)*BigInt(Ge)+BigInt(this.low)).toString()}equals(e){return q.isLong(e)||(e=q.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 q.isLong(e)||(e=q.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"?q.fromNumber(e):new q(e.low,e.high)}}const Br=new q(0,0),Fr=65536,Ge=Fr*Fr,oo=Ge*Ge,ao=new q(-1,-1);var lo=Object.defineProperty,co=(t,e,n)=>e in t?lo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pt=(t,e,n)=>co(t,typeof e!="symbol"?e+"":e,n);class Dr{constructor(e,n){pt(this,"version"),pt(this,"remoteQuerySet"),pt(this,"queryPath"),pt(this,"logger"),this.version={querySet:0,ts:q.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)ht(this.logger,"info","query",i,o);const s=ke(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)ht(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?ke(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 tn(t){const e=De(t);return q.fromBytesLE(Array.from(e))}function uo(t){const e=new Uint8Array(t.toBytesLE());return Ue(e)}function Ur(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:tn(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:tn(t.startVersion.ts)},endVersion:{...t.endVersion,ts:tn(t.endVersion.ts)}}}}function ho(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:uo(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var fo=Object.defineProperty,po=(t,e,n)=>e in t?fo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C=(t,e,n)=>po(t,typeof e!="symbol"?e+"":e,n);const go=1e3,mo=1001,xo=1005,bo=4040;let gt;function je(){return gt===void 0&&(gt=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(gt+performance.now())}function Vr(){return`t=${Math.round((je()-gt)/100)/10}s`}const Wr={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 yo(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Wr))if(t.startsWith(e))return e;return"Unknown"}class vo{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,C(this,"socket"),C(this,"connectionCount"),C(this,"_hasEverConnected",!1),C(this,"lastCloseReason"),C(this,"transitionChunkBuffer",null),C(this,"defaultInitialBackoff"),C(this,"maxBackoff"),C(this,"retries"),C(this,"serverInactivityThreshold"),C(this,"reconnectDueToServerInactivityTimeout"),C(this,"scheduledReconnect",null),C(this,"networkOnlineHandler",null),C(this,"pendingNetworkRecoveryInfo",null),C(this,"uri"),C(this,"onOpen"),C(this,"onResume"),C(this,"onMessage"),C(this,"webSocketConstructor"),C(this,"logger"),C(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=Ur(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:je()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Vr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Vr())),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=Ur(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!==go&&n.code!==mo&&n.code!==xo&&n.code!==bo){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=yo(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=ho(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=je(),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=je()-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.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:je()})):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:Wr[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=je()-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 _o(){return wo()}function wo(){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 ko(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 So(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 ko(e)}catch{return atob(e)}}function Hr(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=So(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 jo=Object.defineProperty,Co=(t,e,n)=>e in t?jo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,L=(t,e,n)=>Co(t,typeof e!="symbol"?e+"":e,n);const To=480*60*60*1e3,Gr=2;class Ro{constructor(e,n,r){L(this,"authState",{state:"noAuth"}),L(this,"configVersion",0),L(this,"syncState"),L(this,"authenticate"),L(this,"stopSocket"),L(this,"tryRestartSocket"),L(this,"pauseSocket"),L(this,"resumeSocket"),L(this,"clearAuth"),L(this,"logger"),L(this,"refreshTokenLeewaySeconds"),L(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>=Gr){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, ${Gr-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(To,(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 Hr(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 $o=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Ao(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function Io(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Eo(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of $o){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(Io)}var qo=Object.defineProperty,Po=(t,e,n)=>e in t?qo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,T=(t,e,n)=>Po(t,typeof e!="symbol"?e+"":e,n);class Mo{constructor(e,n,r){if(T(this,"address"),T(this,"state"),T(this,"requestManager"),T(this,"webSocketManager"),T(this,"authenticationManager"),T(this,"remoteQuerySet"),T(this,"optimisticQueryResults"),T(this,"_transitionHandlerCounter",0),T(this,"_nextRequestId"),T(this,"_onTransitionFns",new Map),T(this,"_sessionId"),T(this,"firstMessageReceived",!1),T(this,"debug"),T(this,"logger"),T(this,"maxObservedTimestamp"),T(this,"connectionStateSubscribers",new Map),T(this,"nextConnectionStateSubscriberId",0),T(this,"_lastPublishedConnectionState"),T(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const f=this.connectionState();if(JSON.stringify(f)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=f;for(const g of this.connectionStateSubscribers.values())g(f)}})}),T(this,"mark",f=>{this.debug&&Ao(f,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&&$s(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?Lr({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Mr({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 u;if(a==="http")u="ws";else if(a==="https")u="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${u}://${l}/api/${Ir}/sync`;this.state=new Hs,this.remoteQuerySet=new Dr(f=>this.state.queryPath(f),this.logger),this.requestManager=new Ks(this.logger,this.markConnectionStateDirty);const c=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ro(this.state,{authenticate:f=>{const g=this.state.setAuth(f);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:c,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new ro,this.addOnTransitionHandler(f=>{n(f.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=_o();const{unsavedChangesWarning:p}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(p===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else p!==!1&&window.addEventListener("beforeunload",f=>{if(this.requestManager.hasIncompleteRequests()){f.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(f||window.event).returnValue=g,g}});this.webSocketManager=new vo(d,{onOpen:f=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...f,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Dr(S=>this.state.queryPath(S),this.logger);const[g,b]=this.state.restart();b&&this.webSocketManager.sendMessage(b),this.webSocketManager.sendMessage(g);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[f,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),f&&this.webSocketManager.sendMessage(f);for(const b of this.requestManager.resume())this.webSocketManager.sendMessage(b)},onMessage:f=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),f.type){case"Transition":{this.observedTimestamp(f.endVersion.ts),this.authenticationManager.onTransition(f),this.remoteQuerySet.transition(f),this.state.transition(f);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{f.success&&this.observedTimestamp(f.ts);const g=this.requestManager.onResponse(f);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(f);break}case"AuthError":{this.authenticationManager.onAuthError(f);break}case"FatalError":{const g=Us(this.logger,f.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&&c()}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?Hr(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=te(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=te(n),i=he(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=te(n),i=he(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=te(n),i=he(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?Yt(i,new Xt(Se("mutation",e,i))):new Error(Se("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=te(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const c=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},f=this.optimisticQueryResults.applyOptimisticUpdate(c,o).map(g=>{const b=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:b===void 0?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:f,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[H(s)]},a=this.webSocketManager.sendMessage(l),u=this.requestManager.request(l,a);return{requestId:o,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?Yt(r,new Xt(Se("action",e,r))):new Error(Se("action",e,r));return r.value}async actionInternal(e,n,r){const i=te(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[H(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=Eo(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-${Ir}`},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 nn(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 Lo=Object.defineProperty,Oo=(t,e,n)=>e in t?Lo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Jr=(t,e,n)=>Oo(t,typeof e!="symbol"?e+"":e,n);class No{constructor(e,n){this.client=e,this.onTransition=n,Jr(this,"paginatedQuerySet",new Map),Jr(this,"lastTransitionTs"),this.lastTransitionTs=q.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=ue(e),s=Or(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=ue(e),s=Or(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 u=this.client.localQueryResultByToken(a);if(u===void 0){s=!0,o=!1;continue}const d=nn(u);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=nn(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,[u,d]]of s)n(o.get(u).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,u,d);for(const a of l){if(s.has(a))continue;const u=o.get(a).queryToken,d=n(u);if(!d)continue;const c=nn(d);c.splitCursor&&(c.pageStatus==="SplitRecommended"||c.pageStatus==="SplitRequired"||c.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,c.splitCursor,c.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 u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,u),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 Qo({getCurrentValue:t,subscribe:e}){const[n,r]=R(()=>({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})),Q(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const u=t();return a.value===u?a:{...a,value:u}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var zo=Object.defineProperty,Bo=(t,e,n)=>e in t?zo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ne=(t,e,n)=>Bo(t,typeof e!="symbol"?e+"":e,n);const Fo=5e3;if(typeof Vt>"u")throw new Error("Required dependency 'react' not found");function Kr(t,e,n){function r(i){return Wo(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 ${E(t)}`);return Kr(t,e,s)},r}class Do{constructor(e,n){if(ne(this,"address"),ne(this,"cachedSync"),ne(this,"cachedPaginatedQueryClient"),ne(this,"listeners"),ne(this,"options"),ne(this,"closed",!1),ne(this,"_logger"),ne(this,"adminAuth"),ne(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?Lr({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Mr({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 Mo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new No(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=E(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),u=this.listeners.get(l);return u!==void 0?u.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??Fo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=E(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 u=this.listeners.get(o);u.delete(s),u.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=E(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=E(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 rn=Vt.createContext(void 0);function Uo(){return at(rn)}const Vo=({client:t,children:e})=>Vt.createElement(rn.Provider,{value:t},e);function Zr(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:te(e[0]),i=typeof t=="string"?Qr(t):t,s=E(i),o=z(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(H(r)),s,n]),a=Ko(o).query;if(a instanceof Error)throw a;return a}function mt(t){const e=typeof t=="string"?Qr(t):t,n=at(rn);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 z(()=>Kr(e,n),[n,E(e)])}function Wo(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 Ho=Object.defineProperty,Go=(t,e,n)=>e in t?Ho(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sn=(t,e,n)=>Go(t,typeof e!="symbol"?e+"":e,n);class Jo{constructor(e){sn(this,"createWatch"),sn(this,"queries"),sn(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(E(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(E(r)!==E(o.query)||JSON.stringify(H(i))!==JSON.stringify(H(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;E(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(u){if(u instanceof Error)a=u;else throw u}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 Ko(t){const e=Uo();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=z(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return Zo(t,n)}function Zo(t,e){const[n]=R(()=>new Jo(e));n.createWatch!==e&&n.setCreateWatch(e),Q(()=>()=>n.destroy(),[n]);const r=z(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return Qo(r)}var Xo=Symbol.for("preact-signals");function xt(){if(se>1)se--;else{for(var t,e=!1;Ke!==void 0;){var n=Ke;for(Ke=void 0,on++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&ei(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(on=0,se--,e)throw t}}function Yo(t){if(se>0)return t();se++;try{return t()}finally{xt()}}var y=void 0;function Xr(t){var e=y;y=void 0;try{return t()}finally{y=e}}var Ke=void 0,se=0,on=0,bt=0;function Yr(t){if(y!==void 0){var e=t.n;if(e===void 0||e.t!==y)return e={i:0,S:t,p:y.s,n:void 0,t:y,e:void 0,x:void 0,r:e},y.s!==void 0&&(y.s.n=e),y.s=e,t.n=e,32&y.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=y.s,e.n=void 0,y.s.n=e,y.s=e),e}}function $(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}$.prototype.brand=Xo,$.prototype.h=function(){return!0},$.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:Xr(function(){var r;(r=e.W)==null||r.call(e)}))},$.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&&Xr(function(){var i;(i=e.Z)==null||i.call(e)}))}},$.prototype.subscribe=function(t){var e=this;return Ze(function(){var n=e.value,r=y;y=void 0;try{t(n)}finally{y=r}},{name:"sub"})},$.prototype.valueOf=function(){return this.value},$.prototype.toString=function(){return this.value+""},$.prototype.toJSON=function(){return this.value},$.prototype.peek=function(){var t=y;y=void 0;try{return this.value}finally{y=t}},Object.defineProperty($.prototype,"value",{get:function(){var t=Yr(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(on>100)throw new Error("Cycle detected");this.v=t,this.i++,bt++,se++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{xt()}}}});function re(t,e){return new $(t,e)}function ei(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 ti(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 ni(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 de(t,e){$.call(this,void 0),this.x=t,this.s=void 0,this.g=bt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}de.prototype=new $,de.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===bt))return!0;if(this.g=bt,this.f|=1,this.i>0&&!ei(this))return this.f&=-2,!0;var t=y;try{ti(this),y=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 y=t,ni(this),this.f&=-2,!0},de.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)}$.prototype.S.call(this,t)},de.prototype.U=function(t){if(this.t!==void 0&&($.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)}},de.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(de.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=Yr(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ri(t,e){return new de(t,e)}function ii(t){var e=t.u;if(t.u=void 0,typeof e=="function"){se++;var n=y;y=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,an(t),r}finally{y=n,xt()}}}function an(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,ii(t)}function ea(t){if(y!==this)throw new Error("Out-of-order effect");ni(this),y=t,this.f&=-2,8&this.f&&an(this),xt()}function Ce(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ce.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()}},Ce.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ii(this),ti(this),se++;var t=y;return y=this,ea.bind(this,t)},Ce.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ke,Ke=this)},Ce.prototype.d=function(){this.f|=8,1&this.f||an(this)},Ce.prototype.dispose=function(){this.d()};function Ze(t,e){var n=new Ce(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var si,yt,ta=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,oi=[];Ze(function(){si=this.N})();function Te(t,e){m[t]=e.bind(null,m[t]||function(){})}function vt(t){if(yt){var e=yt;yt=void 0,e()}yt=t&&t.S()}function ai(t){var e=this,n=t.data,r=Re(n);r.value=n;var i=z(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var u=ri(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),d=ri(function(){return!Array.isArray(u.value)&&!$n(u.value)}),c=Ze(function(){if(this.N=li,d.value){var f=u.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=f)}}),p=e.__$u.d;return e.__$u.d=function(){c(),p.call(this)},[d,u]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}ai.displayName="ReactiveTextNode",Object.defineProperties($.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:ai},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Te("__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 $&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Te("__r",function(t,e){if(t(e),e.type!==O){vt();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;ta&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),vt(n)}}),Te("__e",function(t,e,n,r){vt(),t(e,n,r)}),Te("diffed",function(t,e){vt();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 u=s[a],d=r[a];u===void 0?(u=na(n,a,d,i),s[a]=u):u.o(d,i)}}}t(e)});function na(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=re(n);return{o:function(o,l){s.value=o,r=l},d:Ze(function(){this.N=li;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))})}}Te("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)}),Te("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),N.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 Re(t,e){return z(function(){return re(t,e)},[])}var ra=function(t){queueMicrotask(function(){queueMicrotask(t)})};function ia(){Yo(function(){for(var t;t=oi.shift();)si.call(t)})}function li(){oi.push(this)===1&&(m.requestAnimationFrame||ra)(ia)}const A=re(!1),$e=re(void 0);function sa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function oa(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function aa(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 la(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function ca(t,e){const[n,r]=R(null);return Q(()=>{r(null);const i=e??"https://festive-mouse-978.eu-west-1.convex.cloud",s=i?oa(i):void 0;if(!s||!t)return;const o=new AbortController;async function l(a){try{const u=await la(a,t,o.signal);u&&r(u)}catch(u){if(u instanceof Error&&u.name==="AbortError")return}}return l(s),()=>{o.abort()}},[t,e]),n}const ci={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.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resume 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."},ua={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.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch fortsetzen",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."},ha=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],da="de",fa="jex-locale",ln=re("de"),pa={en:ci,de:ua};function P(){return pa[ln.value]??ci}function cn(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return ha.some(r=>r.value===e)?e:null}function ui(t){const e=cn(t);if(e)return e;try{const n=cn(localStorage.getItem(fa));if(n)return n}catch{}if(typeof navigator<"u"){const n=cn(navigator.language);if(n)return n}return da}function ga(t){Q(()=>{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&&(ln.value=ui(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const un="jex-session-ref",_t="jex-session-active",oe=re(null),fe=re(!1);function ma(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function xa(){try{const t=sessionStorage.getItem(un),e=sessionStorage.getItem(_t);oe.value=t??null,fe.value=t!==null&&e==="true"}catch{oe.value=null,fe.value=!1}}function hn(){const t=ma();oe.value=t,fe.value=!1;try{sessionStorage.setItem(un,t),sessionStorage.removeItem(_t)}catch{}return t}function ba(t){oe.value=t,fe.value=!0;try{sessionStorage.setItem(un,t),sessionStorage.setItem(_t,"true")}catch{}}function ya(){if(oe.value){fe.value=!0;try{sessionStorage.setItem(_t,"true")}catch{}}}function va(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}const B=re([{id:"home"}]),_a=re("screen");function Ae(t){B.value=[...B.value,t]}function dn(){B.value.length>1&&(B.value=B.value.slice(0,-1))}function Ie(t){B.value=[...B.value.slice(0,-1),t]}function fn({size:t=24}){return h("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:[h("path",{d:"M12 8V4H8"}),h("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),h("path",{d:"M2 14h2"}),h("path",{d:"M20 14h2"}),h("path",{d:"M15 13v2"}),h("path",{d:"M9 13v2"})]})}function hi({title:t}){const e=P(),n=B.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:dn,"aria-label":e.back||"Go back",children:h("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:h("path",{d:"m15 18-6-6 6-6"})})}),!n&&h(fn,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function wa({size:t=14}){return h("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:h("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 di(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(wa,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function fi({size:t=28}){return h("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:h("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 ka({size:t=28}){return h("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:[h("path",{d:"M18 6 6 18"}),h("path",{d:"m6 6 12 12"})]})}function Sa({size:t=24,...e}){return h("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:h("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 ja={chat:h(fi,{size:28}),bot:h(fn,{size:28}),sparkles:h(Sa,{size:28})},Ca={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Ta({radius:t="full",iconOption:e="chat",label:n}){const r=P(),i=n??r.fabLabel,s=i!=="";return h("button",{class:`jex-floating-button ${!A.value&&s?"jex-has-label":""}`,style:{borderRadius:Ca[t]??"9999px"},onClick:()=>{A.value=!A.value},"aria-label":A.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:A.value?h(ka,{size:28}):h("div",{class:"jex-fab-inner",children:[ja[e],s&&h("span",{class:"jex-fab-label",children:i})]})})}function Ra({title:t}){const e=P(),n=oe.value,[r,i]=R("");function s(){hn(),Ae({id:"chat"})}function o(){Ae({id:"chat"})}function l(a){a.preventDefault();const u=r.trim().toUpperCase();u&&(ba(u),Ae({id:"chat"}))}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-hero",children:[h("div",{class:"jex-home-avatar",children:[h(fi,{size:24}),h("span",{class:"jex-home-status-dot"})]}),h("div",{class:"jex-home-hero-text",children:[h("h2",{class:"jex-home-title",children:t}),h("span",{class:"jex-home-status",children:e.statusOnline})]})]}),h("form",{class:"jex-home-lookup",onSubmit:l,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:e.referencePlaceholder,value:r,onInput:a=>{i(a.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!r.trim(),children:e.resume})]}),h("div",{class:"jex-home-actions",children:[n&&h("button",{class:"jex-home-resume-card",onClick:o,children:[h("div",{class:"jex-home-resume-top",children:[h("span",{class:"jex-home-resume-label",children:e.resumeConversation}),h("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:h("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),h("span",{class:"jex-home-resume-ref",children:n})]}),h("button",{class:"jex-home-new-btn",onClick:s,children:n?e.startNewConversation:e.chatWith.replace("{title}",t)})]})]})}function $a({title:t}){const e=P();return h("div",{class:"jex-selection",children:[h("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),h("div",{class:"jex-selection-options",children:[h("button",{class:"jex-selection-option",onClick:()=>Ae({id:"chat"}),children:[h("span",{class:"jex-selection-icon",children:"💬"}),h("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),h("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),h("button",{class:"jex-selection-option",onClick:()=>Ae({id:"form"}),children:[h("span",{class:"jex-selection-icon",children:"📝"}),h("span",{class:"jex-selection-label",children:e.submitTicket}),h("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function pi(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return pi(t,s)}else if(i===Nr){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 Aa=()=>pi("components",[]),Ee=eo;Aa();function Ia(t){const e=ot(null),n=Re(!1),r=Re(!1),i=Re(!1),s=Re(null),o=mt(Ee.functions.chat.public.sessions.createOrResume),l=Be(async()=>{if(e.current)return e.current;if(i.value)return null;n.value=!0;const d=oe.value!==null,c=oe.value??hn();try{const p=await o({orgSlug:t,visitorId:c,...$e.value?{source:$e.value}:{}});if(s.value=p.status,d&&p.isNew){r.value=!0,i.value=!0;const g={sessionId:p.sessionId,visitorId:c};return e.current=g,g}const f={sessionId:p.sessionId,visitorId:c};return e.current=f,f}catch(p){return console.error("[jexity] Failed to create session:",p),null}finally{n.value=!1}},[t,o,n,r,i]),a=Be(async()=>{e.current=null,i.value=!1,r.value=!1;const d=hn();n.value=!0;try{const c=await o({orgSlug:t,visitorId:d,...$e.value?{source:$e.value}:{}});s.value=c.status;const p={sessionId:c.sessionId,visitorId:d};return e.current=p,p}catch(c){return console.error("[jexity] Failed to create fresh session:",c),null}finally{n.value=!1}},[t,o,n,r,i,s]),u=e.current;return{sessionId:u?.sessionId??null,visitorId:u?.visitorId??null,isLoading:n.value,sessionNotFound:r.value,resumeFailed:i.value,sessionStatus:s.value,isOrgDeleted:s.value==="org_deleted",ensureSession:l,startFresh:a}}function pn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var pe=pn();function gi(t){pe=t}var ge={exec:()=>null};function x(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(I.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var Ea=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),I={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)}}>`)},qa=/^(?:[ \t]*(?:\n|$))+/,Pa=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ma=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Xe=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,La=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,gn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,mi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,xi=x(mi).replace(/bull/g,gn).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(),Oa=x(mi).replace(/bull/g,gn).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(),mn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Na=/^[^\n]+/,xn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Qa=x(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",xn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),za=x(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,gn).getRegex(),wt="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",bn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ba=x("^ {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",bn).replace("tag",wt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),bi=x(mn).replace("hr",Xe).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",wt).getRegex(),Fa=x(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",bi).getRegex(),yn={blockquote:Fa,code:Pa,def:Qa,fences:Ma,heading:La,hr:Xe,html:Ba,lheading:xi,list:za,newline:qa,paragraph:bi,table:ge,text:Na},yi=x("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Xe).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",wt).getRegex(),Da={...yn,lheading:Oa,table:yi,paragraph:x(mn).replace("hr",Xe).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",yi).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",wt).getRegex()},Ua={...yn,html:x(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",bn).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:ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:x(mn).replace("hr",Xe).replace("heading",` *#{1,6} *[^
|
|
3
|
-
]`).replace("lheading",
|
|
1
|
+
(function(){"use strict";var Me,m,$n,An,ce,In,En,qn,Pn,$t,At,It,Mn,Le={},Ln=[],Oi=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,Oe=Array.isArray;function V(t,e){for(var n in e)t[n]=e[n];return t}function Et(t){t&&t.parentNode&&t.parentNode.removeChild(t)}function ee(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??++$n,__i:-1,__u:0};return i==null&&m.vnode!=null&&m.vnode(s),s}function Ni(){return{current:null}}function O(t){return t.children}function N(t,e){this.props=t,this.context=e}function be(t,e){if(e==null)return t.__?be(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"?be(t):null}function On(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 On(t)}}function qt(t){(!t.__d&&(t.__d=!0)&&ce.push(t)&&!rt.__r++||In!=m.debounceRendering)&&((In=m.debounceRendering)||En)(rt)}function rt(){for(var t,e,n,r,i,s,o,l=1;ce.length;)ce.length>l&&ce.sort(qn),t=ce.shift(),l=ce.length,t.__d&&(n=void 0,r=void 0,i=(r=(e=t).__v).__e,s=[],o=[],e.__P&&((n=V({},r)).__v=r.__v+1,m.vnode&&m.vnode(n),Pt(e.__P,n,r,e.__n,e.__P.namespaceURI,32&r.__u?[i]:null,s,i??be(r),!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Fn(s,n,o),r.__e=r.__=null,n.__e!=i&&On(n)));rt.__r=0}function Nn(t,e,n,r,i,s,o,l,a,u,d){var c,p,f,g,b,S,_,k=r&&r.__k||Ln,Z=e.length;for(a=Qi(n,e,k,a,Z),c=0;c<Z;c++)(f=n.__k[c])!=null&&(p=f.__i==-1?Le:k[f.__i]||Le,f.__i=c,S=Pt(t,f,p,i,s,o,l,a,u,d),g=f.__e,f.ref&&p.ref!=f.ref&&(p.ref&&Lt(p.ref,null,f),d.push(f.ref,f.__c||g,f)),b==null&&g!=null&&(b=g),(_=!!(4&f.__u))||p.__k===f.__k?a=Qn(f,a,t,_):typeof f.type=="function"&&S!==void 0?a=S:g&&(a=g.nextSibling),f.__u&=-7);return n.__e=b,a}function Qi(t,e,n,r,i){var s,o,l,a,u,d=n.length,c=d,p=0;for(t.__k=new Array(i),s=0;s<i;s++)(o=e[s])!=null&&typeof o!="boolean"&&typeof o!="function"?(a=s+p,(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(O,{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,(u=o.__i=zi(o,n,a,c))!=-1&&(c--,(l=n[u])&&(l.__u|=2)),l==null||l.__v==null?(u==-1&&(i>d?p--:i<d&&p++),typeof o.type!="function"&&(o.__u|=4)):u!=a&&(u==a-1?p--:u==a+1?p++:(u>a?p--:p++,o.__u|=4))):t.__k[s]=null;if(c)for(s=0;s<d;s++)(l=n[s])!=null&&(2&l.__u)==0&&(l.__e==r&&(r=be(l)),Un(l,l));return r}function Qn(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=Qn(i[s],e,n,r));return e}t.__e!=e&&(r&&(e&&t.type&&!e.parentNode&&(e=be(t)),n.insertBefore(t.__e,e||null)),e=t.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function te(t,e){return e=e||[],t==null||typeof t=="boolean"||(Oe(t)?t.some(function(n){te(n,e)}):e.push(t)),e}function zi(t,e,n,r){var i,s,o,l=t.key,a=t.type,u=e[n],d=u!=null&&(2&u.__u)==0;if(u===null&&t.key==null||d&&l==u.key&&a==u.type)return n;if(r>(d?1:0)){for(i=n-1,s=n+1;i>=0||s<e.length;)if((u=e[o=i>=0?i--:s++])!=null&&(2&u.__u)==0&&l==u.key&&a==u.type)return o}return-1}function zn(t,e,n){e[0]=="-"?t.setProperty(e,n??""):t[e]=n==null?"":typeof n!="number"||Oi.test(e)?n:n+"px"}function it(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||zn(t.style,e,"");if(n)for(e in n)r&&n[e]==r[e]||zn(t.style,e,n[e])}else if(e[0]=="o"&&e[1]=="n")s=e!=(e=e.replace(Pn,"$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=$t,t.addEventListener(e,s?It:At,s)):t.removeEventListener(e,s?It:At,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 Bn(t){return function(e){if(this.l){var n=this.l[e.type+t];if(e.t==null)e.t=$t++;else if(e.t<n.u)return;return n(m.event?m.event(e):e)}}}function Pt(t,e,n,r,i,s,o,l,a,u){var d,c,p,f,g,b,S,_,k,Z,X,le,U,Li,Rt,nt,Cn,Y=e.type;if(e.constructor!=null)return null;128&n.__u&&(a=!!(32&n.__u),s=[l=e.__e=n.__e]),(d=m.__b)&&d(e);e:if(typeof Y=="function")try{if(_=e.props,k="prototype"in Y&&Y.prototype.render,Z=(d=Y.contextType)&&r[d.__c],X=d?Z?Z.props.value:d.__:r,n.__c?S=(c=e.__c=n.__c).__=c.__E:(k?e.__c=c=new Y(_,X):(e.__c=c=new N(_,X),c.constructor=Y,c.render=Fi),Z&&Z.sub(c),c.props=_,c.state||(c.state={}),c.context=X,c.__n=r,p=c.__d=!0,c.__h=[],c._sb=[]),k&&c.__s==null&&(c.__s=c.state),k&&Y.getDerivedStateFromProps!=null&&(c.__s==c.state&&(c.__s=V({},c.__s)),V(c.__s,Y.getDerivedStateFromProps(_,c.__s))),f=c.props,g=c.state,c.__v=e,p)k&&Y.getDerivedStateFromProps==null&&c.componentWillMount!=null&&c.componentWillMount(),k&&c.componentDidMount!=null&&c.__h.push(c.componentDidMount);else{if(k&&Y.getDerivedStateFromProps==null&&_!==f&&c.componentWillReceiveProps!=null&&c.componentWillReceiveProps(_,X),!c.__e&&c.shouldComponentUpdate!=null&&c.shouldComponentUpdate(_,c.__s,X)===!1||e.__v==n.__v){for(e.__v!=n.__v&&(c.props=_,c.state=c.__s,c.__d=!1),e.__e=n.__e,e.__k=n.__k,e.__k.some(function(Pe){Pe&&(Pe.__=e)}),le=0;le<c._sb.length;le++)c.__h.push(c._sb[le]);c._sb=[],c.__h.length&&o.push(c);break e}c.componentWillUpdate!=null&&c.componentWillUpdate(_,c.__s,X),k&&c.componentDidUpdate!=null&&c.__h.push(function(){c.componentDidUpdate(f,g,b)})}if(c.context=X,c.props=_,c.__P=t,c.__e=!1,U=m.__r,Li=0,k){for(c.state=c.__s,c.__d=!1,U&&U(e),d=c.render(c.props,c.state,c.context),Rt=0;Rt<c._sb.length;Rt++)c.__h.push(c._sb[Rt]);c._sb=[]}else do c.__d=!1,U&&U(e),d=c.render(c.props,c.state,c.context),c.state=c.__s;while(c.__d&&++Li<25);c.state=c.__s,c.getChildContext!=null&&(r=V(V({},r),c.getChildContext())),k&&!p&&c.getSnapshotBeforeUpdate!=null&&(b=c.getSnapshotBeforeUpdate(f,g)),nt=d,d!=null&&d.type===O&&d.key==null&&(nt=Dn(d.props.children)),l=Nn(t,Oe(nt)?nt:[nt],e,n,r,i,s,o,l,a,u),c.base=e.__e,e.__u&=-161,c.__h.length&&o.push(c),S&&(c.__E=c.__=null)}catch(Pe){if(e.__v=null,a||s!=null)if(Pe.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(Cn=s.length;Cn--;)Et(s[Cn]);Mt(e)}else e.__e=n.__e,e.__k=n.__k,Pe.then||Mt(e);m.__e(Pe,e,n)}else s==null&&e.__v==n.__v?(e.__k=n.__k,e.__e=n.__e):l=e.__e=Bi(n.__e,e,n,r,i,s,o,a,u);return(d=m.diffed)&&d(e),128&e.__u?void 0:l}function Mt(t){t&&t.__c&&(t.__c.__e=!0),t&&t.__k&&t.__k.forEach(Mt)}function Fn(t,e,n){for(var r=0;r<n.length;r++)Lt(n[r],n[++r],n[++r]);m.__c&&m.__c(e,t),t.some(function(i){try{t=i.__h,i.__h=[],t.some(function(s){s.call(i)})}catch(s){m.__e(s,i.__v)}})}function Dn(t){return typeof t!="object"||t==null||t.__b&&t.__b>0?t:Oe(t)?t.map(Dn):V({},t)}function Bi(t,e,n,r,i,s,o,l,a){var u,d,c,p,f,g,b,S=n.props,_=e.props,k=e.type;if(k=="svg"?i="http://www.w3.org/2000/svg":k=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),s!=null){for(u=0;u<s.length;u++)if((f=s[u])&&"setAttribute"in f==!!k&&(k?f.localName==k:f.nodeType==3)){t=f,s[u]=null;break}}if(t==null){if(k==null)return document.createTextNode(_);t=document.createElementNS(i,k,_.is&&_),l&&(m.__m&&m.__m(e,s),l=!1),s=null}if(k==null)S===_||l&&t.data==_||(t.data=_);else{if(s=s&&Me.call(t.childNodes),S=n.props||Le,!l&&s!=null)for(S={},u=0;u<t.attributes.length;u++)S[(f=t.attributes[u]).name]=f.value;for(u in S)if(f=S[u],u!="children"){if(u=="dangerouslySetInnerHTML")c=f;else if(!(u in _)){if(u=="value"&&"defaultValue"in _||u=="checked"&&"defaultChecked"in _)continue;it(t,u,null,f,i)}}for(u in _)f=_[u],u=="children"?p=f:u=="dangerouslySetInnerHTML"?d=f:u=="value"?g=f:u=="checked"?b=f:l&&typeof f!="function"||S[u]===f||it(t,u,f,S[u],i);if(d)l||c&&(d.__html==c.__html||d.__html==t.innerHTML)||(t.innerHTML=d.__html),e.__k=[];else if(c&&(t.innerHTML=""),Nn(e.type=="template"?t.content:t,Oe(p)?p:[p],e,n,r,k=="foreignObject"?"http://www.w3.org/1999/xhtml":i,s,o,s?s[0]:n.__k&&be(n,0),l,a),s!=null)for(u=s.length;u--;)Et(s[u]);l||(u="value",k=="progress"&&g==null?t.removeAttribute("value"):g!=null&&(g!==t[u]||k=="progress"&&!g||k=="option"&&g!=S[u])&&it(t,u,g,S[u],i),u="checked",b!=null&&b!=t[u]&&it(t,u,b,S[u],i))}return t}function Lt(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){m.__e(i,n)}}function Un(t,e,n){var r,i;if(m.unmount&&m.unmount(t),(r=t.ref)&&(r.current&&r.current!=t.__e||Lt(r,null,e)),(r=t.__c)!=null){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(s){m.__e(s,e)}r.base=r.__P=null}if(r=t.__k)for(i=0;i<r.length;i++)r[i]&&Un(r[i],e,n||typeof t.type!="function");n||Et(t.__e),t.__c=t.__=t.__e=void 0}function Fi(t,e,n){return this.constructor(t,n)}function ue(t,e,n){var r,i,s,o;e==document&&(e=document.documentElement),m.__&&m.__(t,e),i=(r=typeof n=="function")?null:n&&n.__k||e.__k,s=[],o=[],Pt(e,t=(!r&&n||e).__k=ee(O,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),Fn(s,t,o)}function Vn(t,e){ue(t,e,Vn)}function Di(t,e,n){var r,i,s,o,l=V({},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 Ui(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,qt(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"+Mn++,e.__=t,e.Provider=e.__l=(e.Consumer=function(n,r){return n.children(r)}).contextType=e,e}Me=Ln.slice,m={__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}},$n=0,An=function(t){return t!=null&&t.constructor==null},N.prototype.setState=function(t,e){var n;n=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=V({},this.state),typeof t=="function"&&(t=t(V({},n),this.props)),t&&V(n,t),t!=null&&this.__v&&(e&&this._sb.push(e),qt(this))},N.prototype.forceUpdate=function(t){this.__v&&(this.__e=!0,t&&this.__h.push(t),qt(this))},N.prototype.render=O,ce=[],En=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,qn=function(t,e){return t.__v.__b-e.__v.__b},rt.__r=0,Pn=/(PointerCapture)$|Capture$/i,$t=0,At=Bn(!1),It=Bn(!0),Mn=0;var Vi=0;function h(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 u={type:t,props:a,key:n,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--Vi,__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 m.vnode&&m.vnode(u),u}var ie,w,Ot,Wn,ye=0,Hn=[],j=m,Jn=j.__b,Gn=j.__r,Kn=j.diffed,Zn=j.__c,Xn=j.unmount,Yn=j.__;function ve(t,e){j.__h&&j.__h(w,t,ye||e),ye=0;var n=w.__H||(w.__H={__:[],__h:[]});return t>=n.__.length&&n.__.push({}),n.__[t]}function R(t){return ye=1,Nt(ir,t)}function Nt(t,e,n){var r=ve(ie++,2);if(r.t=t,!r.__c&&(r.__=[n?n(e):ir(void 0,e),function(l){var a=r.__N?r.__N[0]:r.__[0],u=r.t(a,l);a!==u&&(r.__N=[u,r.__[1]],r.__c.setState({}))}],r.__c=w,!w.__f)){var i=function(l,a,u){if(!r.__c.__H)return!0;var d=r.__c.__H.__.filter(function(p){return!!p.__c});if(d.every(function(p){return!p.__N}))return!s||s.call(this,l,a,u);var c=r.__c.props!==l;return d.forEach(function(p){if(p.__N){var f=p.__[0];p.__=p.__N,p.__N=void 0,f!==p.__[0]&&(c=!0)}}),s&&s.call(this,l,a,u)||c};w.__f=!0;var s=w.shouldComponentUpdate,o=w.componentWillUpdate;w.componentWillUpdate=function(l,a,u){if(this.__e){var d=s;s=void 0,i(l,a,u),s=d}o&&o.call(this,l,a,u)},w.shouldComponentUpdate=i}return r.__N||r.__}function Q(t,e){var n=ve(ie++,3);!j.__s&&zt(n.__H,e)&&(n.__=t,n.u=e,w.__H.__h.push(n))}function Qe(t,e){var n=ve(ie++,4);!j.__s&&zt(n.__H,e)&&(n.__=t,n.u=e,w.__h.push(n))}function st(t){return ye=5,z(function(){return{current:t}},[])}function er(t,e,n){ye=6,Qe(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 z(t,e){var n=ve(ie++,7);return zt(n.__H,e)&&(n.__=t(),n.__H=e,n.__h=t),n.__}function ze(t,e){return ye=8,z(function(){return t},e)}function ot(t){var e=w.context[t.__c],n=ve(ie++,9);return n.c=t,e?(n.__==null&&(n.__=!0,e.sub(w)),e.props.value):t.__}function tr(t,e){j.useDebugValue&&j.useDebugValue(e?e(t):t)}function nr(){var t=ve(ie++,11);if(!t.__){for(var e=w.__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 Wi(){for(var t;t=Hn.shift();)if(t.__P&&t.__H)try{t.__H.__h.forEach(at),t.__H.__h.forEach(Qt),t.__H.__h=[]}catch(e){t.__H.__h=[],j.__e(e,t.__v)}}j.__b=function(t){w=null,Jn&&Jn(t)},j.__=function(t,e){t&&e.__k&&e.__k.__m&&(t.__m=e.__k.__m),Yn&&Yn(t,e)},j.__r=function(t){Gn&&Gn(t),ie=0;var e=(w=t.__c).__H;e&&(Ot===w?(e.__h=[],w.__h=[],e.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})):(e.__h.forEach(at),e.__h.forEach(Qt),e.__h=[],ie=0)),Ot=w},j.diffed=function(t){Kn&&Kn(t);var e=t.__c;e&&e.__H&&(e.__H.__h.length&&(Hn.push(e)!==1&&Wn===j.requestAnimationFrame||((Wn=j.requestAnimationFrame)||Hi)(Wi)),e.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0})),Ot=w=null},j.__c=function(t,e){e.some(function(n){try{n.__h.forEach(at),n.__h=n.__h.filter(function(r){return!r.__||Qt(r)})}catch(r){e.some(function(i){i.__h&&(i.__h=[])}),e=[],j.__e(r,n.__v)}}),Zn&&Zn(t,e)},j.unmount=function(t){Xn&&Xn(t);var e,n=t.__c;n&&n.__H&&(n.__H.__.forEach(function(r){try{at(r)}catch(i){e=i}}),n.__H=void 0,e&&j.__e(e,n.__v))};var rr=typeof requestAnimationFrame=="function";function Hi(t){var e,n=function(){clearTimeout(r),rr&&cancelAnimationFrame(e),setTimeout(t)},r=setTimeout(n,35);rr&&(e=requestAnimationFrame(n))}function at(t){var e=w,n=t.__c;typeof n=="function"&&(t.__c=void 0,n()),w=e}function Qt(t){var e=w;t.__c=t.__(),w=e}function zt(t,e){return!t||t.length!==e.length||e.some(function(n,r){return n!==t[r]})}function ir(t,e){return typeof e=="function"?e(t):e}function sr(t,e){for(var n in e)t[n]=e[n];return t}function Bt(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 or(t,e){var n=e(),r=R({t:{__:n,u:e}}),i=r[0].t,s=r[1];return Qe(function(){i.__=n,i.u=e,Ft(i)&&s({t:i})},[t,n,e]),Q(function(){return Ft(i)&&s({t:i}),t(function(){Ft(i)&&s({t:i})})},[t]),n}function Ft(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 ar(t){t()}function lr(t){return t}function cr(){return[!1,ar]}var ur=Qe;function Dt(t,e){this.props=t,this.context=e}function Ji(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:Bt(this.props,i)}function r(i){return this.shouldComponentUpdate=n,ee(t,i)}return r.displayName="Memo("+(t.displayName||t.name)+")",r.prototype.isReactComponent=!0,r.__f=!0,r.type=t,r}(Dt.prototype=new N).isPureReactComponent=!0,Dt.prototype.shouldComponentUpdate=function(t,e){return Bt(this.props,t)||Bt(this.state,e)};var hr=m.__b;m.__b=function(t){t.type&&t.type.__f&&t.ref&&(t.props.ref=t.ref,t.ref=null),hr&&hr(t)};var Gi=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.forward_ref")||3911;function Ki(t){function e(n){var r=sr({},n);return delete r.ref,t(r,n.ref||null)}return e.$$typeof=Gi,e.render=t,e.prototype.isReactComponent=e.__f=!0,e.displayName="ForwardRef("+(t.displayName||t.name)+")",e}var dr=function(t,e){return t==null?null:te(te(t).map(e))},Zi={map:dr,forEach:dr,count:function(t){return t?te(t).length:0},only:function(t){var e=te(t);if(e.length!==1)throw"Children.only";return e[0]},toArray:te},Xi=m.__e;m.__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)}Xi(t,e,n,r)};var fr=m.unmount;function pr(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=sr({},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 pr(r,e,n)})),t}function gr(t,e,n){return t&&n&&(t.__v=null,t.__k=t.__k&&t.__k.map(function(r){return gr(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 lt(){this.__u=0,this.o=null,this.__b=null}function mr(t){var e=t.__.__c;return e&&e.__a&&e.__a(t)}function Yi(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 ee(n,s)}return i.displayName="Lazy",i.__f=!0,i}function Be(){this.i=null,this.l=null}m.unmount=function(t){var e=t.__c;e&&e.__R&&e.__R(),e&&32&t.__u&&(t.type=null),fr&&fr(t)},(lt.prototype=new N).__c=function(t,e){var n=e.__c,r=this;r.o==null&&(r.o=[]),r.o.push(n);var i=mr(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]=gr(a,a.__c.__P,a.__c.__O)}var u;for(r.setState({__a:r.__b=null});u=r.o.pop();)u.forceUpdate()}};r.__u++||32&e.__u||r.setState({__a:r.__b=r.__v.__k[0]}),t.then(o,o)},lt.prototype.componentWillUnmount=function(){this.o=[]},lt.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]=pr(this.__b,n,r.__O=r.__P)}this.__b=null}var i=e.__a&&ee(O,null,t.fallback);return i&&(i.__u&=-33),[ee(O,null,e.__a?null:t.children),i]};var xr=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 es(t){return this.getChildContext=function(){return t.context},t.children}function ts(t){var e=this,n=t.h;if(e.componentWillUnmount=function(){ue(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)}}}ue(ee(es,{context:e.context},t.__v),e.v)}function ns(t,e){var n=ee(ts,{__v:t,h:e});return n.containerInfo=e,n}(Be.prototype=new N).__a=function(t){var e=this,n=mr(e.__v),r=e.l.get(t);return r[0]++,function(i){var s=function(){e.props.revealOrder?(r.push(i),xr(e,t,r)):i()};n?n(s):s()}},Be.prototype.render=function(t){this.i=null,this.l=new Map;var e=te(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){xr(t,n,e)})};var br=typeof Symbol<"u"&&Symbol.for&&Symbol.for("react.element")||60103,rs=/^(?: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]/,is=/^on(Ani|Tra|Tou|BeforeInp|Compo)/,ss=/[A-Z0-9]/g,os=typeof document<"u",as=function(t){return(typeof Symbol<"u"&&typeof Symbol()=="symbol"?/fil|che|rad/:/fil|che|ra/).test(t)};function ls(t,e,n){return e.__k==null&&(e.textContent=""),ue(t,e),typeof n=="function"&&n(),t?t.__c:null}function cs(t,e,n){return Vn(t,e),typeof n=="function"&&n(),t?t.__c:null}N.prototype.isReactComponent={},["componentWillMount","componentWillReceiveProps","componentWillUpdate"].forEach(function(t){Object.defineProperty(N.prototype,t,{configurable:!0,get:function(){return this["UNSAFE_"+t]},set:function(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})});var yr=m.event;function us(){}function hs(){return this.cancelBubble}function ds(){return this.defaultPrevented}m.event=function(t){return yr&&(t=yr(t)),t.persist=us,t.isPropagationStopped=hs,t.isDefaultPrevented=ds,t.nativeEvent=t};var Ut,fs={enumerable:!1,configurable:!0,get:function(){return this.class}},vr=m.vnode;m.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||os&&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"||as(n.type)?a==="onfocus"?o="onfocusin":a==="onblur"?o="onfocusout":is.test(o)&&(o=a):a=o="oninput":s&&rs.test(o)?o=o.replace(ss,"-$&").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=te(n.children).forEach(function(u){u.props.selected=i.value.indexOf(u.props.value)!=-1})),r=="select"&&i.defaultValue!=null&&(i.value=te(n.children).forEach(function(u){u.props.selected=i.multiple?i.defaultValue.indexOf(u.props.value)!=-1:i.defaultValue==u.props.value})),n.class&&!n.className?(i.class=n.class,Object.defineProperty(i,"className",fs)):(n.className&&!n.class||n.class&&n.className)&&(i.class=i.className=n.className),e.props=i})(t),t.$$typeof=br,vr&&vr(t)};var _r=m.__r;m.__r=function(t){_r&&_r(t),Ut=t.__c};var kr=m.diffed;m.diffed=function(t){kr&&kr(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),Ut=null};var ps={ReactCurrentDispatcher:{current:{readContext:function(t){return Ut.__n[t.__c].props.value},useCallback:ze,useContext:ot,useDebugValue:tr,useDeferredValue:lr,useEffect:Q,useId:nr,useImperativeHandle:er,useInsertionEffect:ur,useLayoutEffect:Qe,useMemo:z,useReducer:Nt,useRef:st,useState:R,useSyncExternalStore:or,useTransition:cr}}};function gs(t){return ee.bind(null,t)}function ct(t){return!!t&&t.$$typeof===br}function ms(t){return ct(t)&&t.type===O}function xs(t){return!!t&&!!t.displayName&&(typeof t.displayName=="string"||t.displayName instanceof String)&&t.displayName.startsWith("Memo(")}function bs(t){return ct(t)?Di.apply(null,arguments):t}function ys(t){return!!t.__k&&(ue(null,t),!0)}function vs(t){return t&&(t.base||t.nodeType===1&&t)||null}for(var _s=function(t,e){return t(e)},ks=function(t,e){return t(e)},ws=O,Ss=ct,Vt={useState:R,useId:nr,useReducer:Nt,useEffect:Q,useLayoutEffect:Qe,useInsertionEffect:ur,useTransition:cr,useDeferredValue:lr,useSyncExternalStore:or,startTransition:ar,useRef:st,useImperativeHandle:er,useMemo:z,useCallback:ze,useContext:ot,useDebugValue:tr,version:"18.3.1",Children:Zi,render:ls,hydrate:cs,unmountComponentAtNode:ys,createPortal:ns,createElement:ee,createContext:Ui,createFactory:gs,cloneElement:bs,createRef:Ni,Fragment:O,isValidElement:ct,isElement:Ss,isFragment:ms,isMemo:xs,findDOMNode:vs,Component:N,PureComponent:Dt,memo:Ji,forwardRef:Ki,flushSync:ks,unstable_batchedUpdates:_s,StrictMode:ws,Suspense:lt,SuspenseList:Be,lazy:Yi,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:ps},W=[],M=[],js=Uint8Array,Wt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_e=0,Cs=Wt.length;_e<Cs;++_e)W[_e]=Wt[_e],M[Wt.charCodeAt(_e)]=_e;M[45]=62,M[95]=63;function Ts(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 Rs(t,e,n){return(e+n)*3/4-n}function Fe(t){var e,n=Ts(t),r=n[0],i=n[1],s=new js(Rs(t,r,i)),o=0,l=i>0?r-4:r,a;for(a=0;a<l;a+=4)e=M[t.charCodeAt(a)]<<18|M[t.charCodeAt(a+1)]<<12|M[t.charCodeAt(a+2)]<<6|M[t.charCodeAt(a+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=M[t.charCodeAt(a)]<<2|M[t.charCodeAt(a+1)]>>4,s[o++]=e&255),i===1&&(e=M[t.charCodeAt(a)]<<10|M[t.charCodeAt(a+1)]<<4|M[t.charCodeAt(a+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}function $s(t){return W[t>>18&63]+W[t>>12&63]+W[t>>6&63]+W[t&63]}function As(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($s(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(As(t,o,o+s>l?l:o+s));return r===1?(e=t[n-1],i.push(W[e>>2]+W[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(W[e>>10]+W[e>>4&63]+W[e<<2&63]+"=")),i.join("")}function ne(t){if(t===void 0)return{};if(!wr(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function Is(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 wr(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const Sr=!0,ke=BigInt("-9223372036854775808"),Ht=BigInt("9223372036854775807"),Jt=BigInt("0"),Es=BigInt("8"),qs=BigInt("256");function jr(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function Ps(t){t<Jt&&(t-=ke+ke);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>>=Es;return De(n)}function Ms(t){const e=Fe(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=Jt,r=Jt;for(const i of e)n+=BigInt(i)*qs**r,r++;return n>Ht&&(n+=ke+ke),n}function Ls(t){if(t<ke||Ht<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 Os(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 Ns=DataView.prototype.setBigInt64?Ls:Ps,Qs=DataView.prototype.getBigInt64?Os:Ms,Cr=1024;function Tr(t){if(t.length>Cr)throw new Error(`Field name ${t} exceeds maximum field name length ${Cr}.`);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 we(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>we(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 Qs(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,Sr);if(!jr(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))Tr(r),n[r]=we(i);return n}const Rr=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>Rr){const n="[...truncated]";let r=Rr-n.length;const i=e.codePointAt(r-1);return i!==void 0&&i>65535&&(r-=1),e.substring(0,r)+n}return e}function Gt(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<ke||Ht<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:Ns(t)}}if(typeof t=="number")if(jr(t)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,t,Sr),{$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)=>Gt(o,e,n+`[${l}]`));if(t instanceof Set)throw new Error(Kt(n,"Set",[...t],e));if(t instanceof Map)throw new Error(Kt(n,"Map",[...t],e));if(!wr(t)){const o=t?.constructor?.name,l=o?`${o} `:"";throw new Error(Kt(n,l,t,e))}const i={},s=Object.entries(t);s.sort(([o,l],[a,u])=>o===a?0:o<a?-1:1);for(const[o,l]of s)l!==void 0&&(Tr(o),i[o]=Gt(l,e,n+`.${o}`));return i}function Kt(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 H(t){return Gt(t,t,"")}var zs=Object.defineProperty,Bs=(t,e,n)=>e in t?zs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zt=(t,e,n)=>Bs(t,typeof e!="symbol"?e+"":e,n),$r,Ar;const Fs=Symbol.for("ConvexError");class Xt extends(Ar=Error,$r=Fs,Ar){constructor(e){super(typeof e=="string"?e:Ue(e)),Zt(this,"name","ConvexError"),Zt(this,"data"),Zt(this,$r,!0),this.data=e}}const Ir=()=>Array.from({length:4},()=>0);Ir(),Ir();const Er="1.35.1";var Ds=Object.defineProperty,Us=(t,e,n)=>e in t?Ds(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qr=(t,e,n)=>Us(t,typeof e!="symbol"?e+"":e,n);const Vs="color:rgb(0, 145, 255)";function Pr(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Mr{constructor(e){qr(this,"_onLogLineFuncs"),qr(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 Lr(t){const e=new Mr(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 Or(t){return new Mr(t)}function ut(t,e,n,r,i){const s=Pr(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}]`,Vs,a)}else t.error(`[CONVEX ${s}(${r})] ${i}`)}function Ws(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Se(t,e,n){return`[CONVEX ${Pr(t)}(${e})] ${n.errorMessage}
|
|
2
|
+
Called by client`}function Yt(t,e){return e.data=t.errorData,e}function he(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 de(t,e){return JSON.stringify({udfPath:he(t),args:H(e)})}function Nr(t,e,n){const{initialNumItems:r,id:i}=n;return JSON.stringify({type:"paginated",udfPath:he(t),args:H(e),options:H({initialNumItems:r,id:i})})}var Hs=Object.defineProperty,Js=(t,e,n)=>e in t?Hs(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,J=(t,e,n)=>Js(t,typeof e!="symbol"?e+"":e,n);class Gs{constructor(){J(this,"nextQueryId"),J(this,"querySetVersion"),J(this,"querySet"),J(this,"queryIdToToken"),J(this,"identityVersion"),J(this,"auth"),J(this,"outstandingQueriesOlderThanRestart"),J(this,"outstandingAuthOlderThanRestart"),J(this,"paused"),J(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=he(e),o=de(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++,u={id:a,canonicalizedUdfPath:s,args:n,numSubscribers:1,journal:r,componentPath:i};this.querySet.set(o,u),this.queryIdToToken.set(a,o);const d=this.querySetVersion,c=this.querySetVersion+1,p={type:"Add",queryId:a,udfPath:s,args:[H(n)],journal:r,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(a,p):this.querySetVersion=c,{queryToken:o,modification:{type:"ModifyQuerySet",baseVersion:d,newVersion:c,modifications:[p]},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=he(e),i=de(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:[H(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 Ks=Object.defineProperty,Zs=(t,e,n)=>e in t?Ks(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ht=(t,e,n)=>Zs(t,typeof e!="symbol"?e+"":e,n);class Xs{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,ht(this,"inflightRequests"),ht(this,"requestsOlderThanRestart"),ht(this,"inflightMutationsCount",0),ht(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)ut(this.logger,"info",r,i,a);const s=n.status;let o,l;if(e.success)o={success:!0,logLines:e.logLines,value:we(e.result)},l=()=>s.onResult(o);else{const a=e.result,{errorData:u}=e;ut(this.logger,"error",r,i,a),o={success:!1,errorMessage:a,errorData:u!==void 0?we(u):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"),Qr=Symbol.for("toReferencePath");function Ys(t){return t[Qr]??null}function eo(t){return t.startsWith("function://")}function to(t){let e;if(typeof t=="string")eo(t)?e={functionHandle:t}:e={name:t};else if(t[Ve])e={name:t[Ve]};else{const n=Ys(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function E(t){const e=to(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 zr(t){return{[Ve]:t}}function Br(t=[]){const e={get(n,r){if(typeof r=="string"){const i=[...t,r];return Br(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 no=Br();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,dt=(t,e,n)=>io(t,typeof e!="symbol"?e+"":e,n);class We{constructor(e){dt(this,"queryResults"),dt(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=ne(n[0]),i=E(e),s=this.queryResults.get(de(i,r));if(s!==void 0)return We.queryValue(s.result)}getAllQueries(e){const n=[],r=E(e);for(const i of this.queryResults.values())i.udfPath===he(r)&&n.push({args:i.args,value:We.queryValue(i.result)});return n}setQuery(e,n,r){const i=ne(n),s=E(e),o=de(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 so{constructor(){dt(this,"queryResults"),dt(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?Yt(r,new Xt(Se("query",n.udfPath,r))):new Error(Se("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var oo=Object.defineProperty,ao=(t,e,n)=>e in t?oo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,en=(t,e,n)=>ao(t,typeof e!="symbol"?e+"":e,n);class q{constructor(e,n){en(this,"low"),en(this,"high"),en(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 q(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?Fr:e>=lo?co:new q(e%He|0,e/He|0)}toString(){return(BigInt(this.high)*BigInt(He)+BigInt(this.low)).toString()}equals(e){return q.isLong(e)||(e=q.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 q.isLong(e)||(e=q.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"?q.fromNumber(e):new q(e.low,e.high)}}const Fr=new q(0,0),Dr=65536,He=Dr*Dr,lo=He*He,co=new q(-1,-1);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,ft=(t,e,n)=>ho(t,typeof e!="symbol"?e+"":e,n);class Ur{constructor(e,n){ft(this,"version"),ft(this,"remoteQuerySet"),ft(this,"queryPath"),ft(this,"logger"),this.version={querySet:0,ts:q.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)ut(this.logger,"info","query",i,o);const s=we(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)ut(this.logger,"info","query",i,o);const{errorData:s}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:s!==void 0?we(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 tn(t){const e=Fe(t);return q.fromBytesLE(Array.from(e))}function fo(t){const e=new Uint8Array(t.toBytesLE());return De(e)}function Vr(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:tn(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:tn(t.startVersion.ts)},endVersion:{...t.endVersion,ts:tn(t.endVersion.ts)}}}}function po(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:fo(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var go=Object.defineProperty,mo=(t,e,n)=>e in t?go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C=(t,e,n)=>mo(t,typeof e!="symbol"?e+"":e,n);const xo=1e3,bo=1001,yo=1005,vo=4040;let pt;function je(){return pt===void 0&&(pt=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(pt+performance.now())}function Wr(){return`t=${Math.round((je()-pt)/100)/10}s`}const Hr={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 _o(t){if(t===void 0)return"Unknown";for(const e of Object.keys(Hr))if(t.startsWith(e))return e;return"Unknown"}class ko{constructor(e,n,r,i,s,o){this.markConnectionStateDirty=s,this.debug=o,C(this,"socket"),C(this,"connectionCount"),C(this,"_hasEverConnected",!1),C(this,"lastCloseReason"),C(this,"transitionChunkBuffer",null),C(this,"defaultInitialBackoff"),C(this,"maxBackoff"),C(this,"retries"),C(this,"serverInactivityThreshold"),C(this,"reconnectDueToServerInactivityTimeout"),C(this,"scheduledReconnect",null),C(this,"networkOnlineHandler",null),C(this,"pendingNetworkRecoveryInfo",null),C(this,"uri"),C(this,"onOpen"),C(this,"onResume"),C(this,"onMessage"),C(this,"webSocketConstructor"),C(this,"logger"),C(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=Vr(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:je()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Wr(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Wr())),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=Vr(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!==xo&&n.code!==bo&&n.code!==yo&&n.code!==vo){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=_o(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=po(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=je(),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=je()-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.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:je()})):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:Hr[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=je()-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 wo(){return So()}function So(){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 jo(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 Co(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 jo(e)}catch{return atob(e)}}function Jr(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=Co(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 To=Object.defineProperty,Ro=(t,e,n)=>e in t?To(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,L=(t,e,n)=>Ro(t,typeof e!="symbol"?e+"":e,n);const $o=480*60*60*1e3,Gr=2;class Ao{constructor(e,n,r){L(this,"authState",{state:"noAuth"}),L(this,"configVersion",0),L(this,"syncState"),L(this,"authenticate"),L(this,"stopSocket"),L(this,"tryRestartSocket"),L(this,"pauseSocket"),L(this,"resumeSocket"),L(this,"clearAuth"),L(this,"logger"),L(this,"refreshTokenLeewaySeconds"),L(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>=Gr){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, ${Gr-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($o,(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 Jr(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 Io=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function Eo(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function qo(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function Po(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of Io){const r=performance.getEntriesByName(n).filter(i=>i.entryType==="mark").filter(i=>i.detail.sessionId===t);e.push(...r)}return e.map(qo)}var Mo=Object.defineProperty,Lo=(t,e,n)=>e in t?Mo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,T=(t,e,n)=>Lo(t,typeof e!="symbol"?e+"":e,n);class Oo{constructor(e,n,r){if(T(this,"address"),T(this,"state"),T(this,"requestManager"),T(this,"webSocketManager"),T(this,"authenticationManager"),T(this,"remoteQuerySet"),T(this,"optimisticQueryResults"),T(this,"_transitionHandlerCounter",0),T(this,"_nextRequestId"),T(this,"_onTransitionFns",new Map),T(this,"_sessionId"),T(this,"firstMessageReceived",!1),T(this,"debug"),T(this,"logger"),T(this,"maxObservedTimestamp"),T(this,"connectionStateSubscribers",new Map),T(this,"nextConnectionStateSubscriberId",0),T(this,"_lastPublishedConnectionState"),T(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const f=this.connectionState();if(JSON.stringify(f)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=f;for(const g of this.connectionStateSubscribers.values())g(f)}})}),T(this,"mark",f=>{this.debug&&Eo(f,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&&Is(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?Or({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:Lr({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 u;if(a==="http")u="ws";else if(a==="https")u="wss";else throw new Error(`Unknown parent protocol ${a}`);const d=`${u}://${l}/api/${Er}/sync`;this.state=new Gs,this.remoteQuerySet=new Ur(f=>this.state.queryPath(f),this.logger),this.requestManager=new Xs(this.logger,this.markConnectionStateDirty);const c=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Ao(this.state,{authenticate:f=>{const g=this.state.setAuth(f);return this.webSocketManager.sendMessage(g),g.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:c,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:i}),this.optimisticQueryResults=new so,this.addOnTransitionHandler(f=>{n(f.queries.map(g=>g.token))}),this._nextRequestId=0,this._sessionId=wo();const{unsavedChangesWarning:p}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(p===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else p!==!1&&window.addEventListener("beforeunload",f=>{if(this.requestManager.hasIncompleteRequests()){f.preventDefault();const g="Are you sure you want to leave? Your changes may not be saved.";return(f||window.event).returnValue=g,g}});this.webSocketManager=new ko(d,{onOpen:f=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...f,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Ur(S=>this.state.queryPath(S),this.logger);const[g,b]=this.state.restart();b&&this.webSocketManager.sendMessage(b),this.webSocketManager.sendMessage(g);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[f,g]=this.state.resume();g&&this.webSocketManager.sendMessage(g),f&&this.webSocketManager.sendMessage(f);for(const b of this.requestManager.resume())this.webSocketManager.sendMessage(b)},onMessage:f=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),f.type){case"Transition":{this.observedTimestamp(f.endVersion.ts),this.authenticationManager.onTransition(f),this.remoteQuerySet.transition(f),this.state.transition(f);const g=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(g);break}case"MutationResponse":{f.success&&this.observedTimestamp(f.ts);const g=this.requestManager.onResponse(f);g!==null&&this.notifyOnQueryResultChanges(new Map([[g.requestId,g.result]]));break}case"ActionResponse":{this.requestManager.onResponse(f);break}case"AuthError":{this.authenticationManager.onAuthError(f);break}case"FatalError":{const g=Ws(this.logger,f.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&&c()}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?Jr(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=ne(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=ne(n),i=de(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=ne(n),i=de(e,r);return this.optimisticQueryResults.queryLogs(i)}queryJournal(e,n){const r=ne(n),i=de(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?Yt(i,new Xt(Se("mutation",e,i))):new Error(Se("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=ne(n);this.tryReportLongDisconnect();const o=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const d=r.optimisticUpdate;if(d!==void 0){const c=g=>{d(g,s)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},f=this.optimisticQueryResults.applyOptimisticUpdate(c,o).map(g=>{const b=this.localQueryResultByToken(g);return{token:g,modification:{kind:"Updated",result:b===void 0?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:f,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:o,udfPath:e,componentPath:i,args:[H(s)]},a=this.webSocketManager.sendMessage(l),u=this.requestManager.request(l,a);return{requestId:o,mutationPromise:u}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?Yt(r,new Xt(Se("action",e,r))):new Error(Se("action",e,r));return r.value}async actionInternal(e,n,r){const i=ne(n),s=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const o={type:"Action",requestId:s,udfPath:e,componentPath:r,args:[H(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=Po(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-${Er}`},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 nn(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 No=Object.defineProperty,Qo=(t,e,n)=>e in t?No(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kr=(t,e,n)=>Qo(t,typeof e!="symbol"?e+"":e,n);class zo{constructor(e,n){this.client=e,this.onTransition=n,Kr(this,"paginatedQuerySet",new Map),Kr(this,"lastTransitionTs"),this.lastTransitionTs=q.fromNumber(0),this.client.addOnTransitionHandler(r=>this.onBaseTransition(r))}subscribe(e,n,r){const i=he(e),s=Nr(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=he(e),s=Nr(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 u=this.client.localQueryResultByToken(a);if(u===void 0){s=!0,o=!1;continue}const d=nn(u);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=nn(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,[u,d]]of s)n(o.get(u).queryToken)!==void 0&&n(o.get(d).queryToken)!==void 0&&this.completePaginatedQuerySplit(i,a,u,d);for(const a of l){if(s.has(a))continue;const u=o.get(a).queryToken,d=n(u);if(!d)continue;const c=nn(d);c.splitCursor&&(c.pageStatus==="SplitRecommended"||c.pageStatus==="SplitRequired"||c.page.length>i.options.initialNumItems*2)&&this.splitPaginatedQueryPage(i,a,c.splitCursor,c.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 u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...l,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,u),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 Bo({getCurrentValue:t,subscribe:e}){const[n,r]=R(()=>({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})),Q(()=>{let s=!1;const o=()=>{s||r(a=>{if(a.getCurrentValue!==t||a.subscribe!==e)return a;const u=t();return a.value===u?a:{...a,value:u}})},l=e(o);return o(),()=>{s=!0,l()}},[t,e]),i}var Fo=Object.defineProperty,Do=(t,e,n)=>e in t?Fo(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,re=(t,e,n)=>Do(t,typeof e!="symbol"?e+"":e,n);const Uo=5e3;if(typeof Vt>"u")throw new Error("Required dependency 'react' not found");function Zr(t,e,n){function r(i){return Jo(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 ${E(t)}`);return Zr(t,e,s)},r}class Vo{constructor(e,n){if(re(this,"address"),re(this,"cachedSync"),re(this,"cachedPaginatedQueryClient"),re(this,"listeners"),re(this,"options"),re(this,"closed",!1),re(this,"_logger"),re(this,"adminAuth"),re(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?Or({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:Lr({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 Oo(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new zo(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=E(e);return{onUpdate:o=>{const{queryToken:l,unsubscribe:a}=this.sync.subscribe(s,r,i),u=this.listeners.get(l);return u!==void 0?u.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??Uo,i=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(i,n)}watchPaginatedQuery(e,n,r){const i=E(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 u=this.listeners.get(o);u.delete(s),u.size===0&&this.listeners.delete(o),l()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,n,r)}}mutation(e,...n){const[r,i]=n,s=E(e);return this.sync.mutation(s,r,i)}action(e,...n){const r=E(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 rn=Vt.createContext(void 0);function Wo(){return ot(rn)}const Ho=({client:t,children:e})=>Vt.createElement(rn.Provider,{value:t},e);function Xr(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:ne(e[0]),i=typeof t=="string"?zr(t):t,s=E(i),o=z(()=>n?{}:{query:{query:i,args:r}},[JSON.stringify(H(r)),s,n]),a=Xo(o).query;if(a instanceof Error)throw a;return a}function gt(t){const e=typeof t=="string"?zr(t):t,n=ot(rn);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 z(()=>Zr(e,n),[n,E(e)])}function Jo(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 Go=Object.defineProperty,Ko=(t,e,n)=>e in t?Go(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sn=(t,e,n)=>Ko(t,typeof e!="symbol"?e+"":e,n);class Zo{constructor(e){sn(this,"createWatch"),sn(this,"queries"),sn(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(E(r),this.queries[n]===void 0)this.addQuery(n,r,i,s?{paginationOptions:s}:{});else{const o=this.queries[n];(E(r)!==E(o.query)||JSON.stringify(H(i))!==JSON.stringify(H(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;E(i);const l=this.createWatch(i,s,o?{paginationOptions:o}:{});let a;try{a=l.localQueryResult()}catch(u){if(u instanceof Error)a=u;else throw u}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 Xo(t){const e=Wo();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=z(()=>(r,i,{journal:s,paginationOptions:o})=>o?e.watchPaginatedQuery(r,i,o):e.watchQuery(r,i,s?{journal:s}:{}),[e]);return Yo(t,n)}function Yo(t,e){const[n]=R(()=>new Zo(e));n.createWatch!==e&&n.setCreateWatch(e),Q(()=>()=>n.destroy(),[n]);const r=z(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:i=>(n.setQueries(t),n.subscribe(i))}),[n,t]);return Bo(r)}var ea=Symbol.for("preact-signals");function mt(){if(se>1)se--;else{for(var t,e=!1;Ge!==void 0;){var n=Ge;for(Ge=void 0,on++;n!==void 0;){var r=n.o;if(n.o=void 0,n.f&=-3,!(8&n.f)&&ti(n))try{n.c()}catch(i){e||(t=i,e=!0)}n=r}}if(on=0,se--,e)throw t}}function ta(t){if(se>0)return t();se++;try{return t()}finally{mt()}}var y=void 0;function Yr(t){var e=y;y=void 0;try{return t()}finally{y=e}}var Ge=void 0,se=0,on=0,xt=0;function ei(t){if(y!==void 0){var e=t.n;if(e===void 0||e.t!==y)return e={i:0,S:t,p:y.s,n:void 0,t:y,e:void 0,x:void 0,r:e},y.s!==void 0&&(y.s.n=e),y.s=e,t.n=e,32&y.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=y.s,e.n=void 0,y.s.n=e,y.s=e),e}}function $(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}$.prototype.brand=ea,$.prototype.h=function(){return!0},$.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:Yr(function(){var r;(r=e.W)==null||r.call(e)}))},$.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&&Yr(function(){var i;(i=e.Z)==null||i.call(e)}))}},$.prototype.subscribe=function(t){var e=this;return Ke(function(){var n=e.value,r=y;y=void 0;try{t(n)}finally{y=r}},{name:"sub"})},$.prototype.valueOf=function(){return this.value},$.prototype.toString=function(){return this.value+""},$.prototype.toJSON=function(){return this.value},$.prototype.peek=function(){var t=y;y=void 0;try{return this.value}finally{y=t}},Object.defineProperty($.prototype,"value",{get:function(){var t=ei(this);return t!==void 0&&(t.i=this.i),this.v},set:function(t){if(t!==this.v){if(on>100)throw new Error("Cycle detected");this.v=t,this.i++,xt++,se++;try{for(var e=this.t;e!==void 0;e=e.x)e.t.N()}finally{mt()}}}});function G(t,e){return new $(t,e)}function ti(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 ni(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 ri(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 fe(t,e){$.call(this,void 0),this.x=t,this.s=void 0,this.g=xt-1,this.f=4,this.W=e?.watched,this.Z=e?.unwatched,this.name=e?.name}fe.prototype=new $,fe.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===xt))return!0;if(this.g=xt,this.f|=1,this.i>0&&!ti(this))return this.f&=-2,!0;var t=y;try{ni(this),y=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 y=t,ri(this),this.f&=-2,!0},fe.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)}$.prototype.S.call(this,t)},fe.prototype.U=function(t){if(this.t!==void 0&&($.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)}},fe.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(fe.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var t=ei(this);if(this.h(),t!==void 0&&(t.i=this.i),16&this.f)throw this.v;return this.v}});function ii(t,e){return new fe(t,e)}function si(t){var e=t.u;if(t.u=void 0,typeof e=="function"){se++;var n=y;y=void 0;try{e()}catch(r){throw t.f&=-2,t.f|=8,an(t),r}finally{y=n,mt()}}}function an(t){for(var e=t.s;e!==void 0;e=e.n)e.S.U(e);t.x=void 0,t.s=void 0,si(t)}function na(t){if(y!==this)throw new Error("Out-of-order effect");ri(this),y=t,this.f&=-2,8&this.f&&an(this),mt()}function Ce(t,e){this.x=t,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32,this.name=e?.name}Ce.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()}},Ce.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,si(this),ni(this),se++;var t=y;return y=this,na.bind(this,t)},Ce.prototype.N=function(){2&this.f||(this.f|=2,this.o=Ge,Ge=this)},Ce.prototype.d=function(){this.f|=8,1&this.f||an(this)},Ce.prototype.dispose=function(){this.d()};function Ke(t,e){var n=new Ce(t,e);try{n.c()}catch(i){throw n.d(),i}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}var oi,bt,ra=typeof window<"u"&&!!window.__PREACT_SIGNALS_DEVTOOLS__,ai=[];Ke(function(){oi=this.N})();function Te(t,e){m[t]=e.bind(null,m[t]||function(){})}function yt(t){if(bt){var e=bt;bt=void 0,e()}bt=t&&t.S()}function li(t){var e=this,n=t.data,r=Re(n);r.value=n;var i=z(function(){for(var l=e,a=e.__v;a=a.__;)if(a.__c){a.__c.__$f|=4;break}var u=ii(function(){var f=r.value.value;return f===0?0:f===!0?"":f||""}),d=ii(function(){return!Array.isArray(u.value)&&!An(u.value)}),c=Ke(function(){if(this.N=ci,d.value){var f=u.value;l.__v&&l.__v.__e&&l.__v.__e.nodeType===3&&(l.__v.__e.data=f)}}),p=e.__$u.d;return e.__$u.d=function(){c(),p.call(this)},[d,u]},[]),s=i[0],o=i[1];return s.value?o.peek():o.value}li.displayName="ReactiveTextNode",Object.defineProperties($.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:li},props:{configurable:!0,get:function(){return{data:this}}},__b:{configurable:!0,value:1}}),Te("__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 $&&(n||(e.__np=n={}),n[i]=s,r[i]=s.peek())}}t(e)}),Te("__r",function(t,e){if(t(e),e.type!==O){yt();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;ra&&((i=n.y)==null||i.call(n)),r.__$f|=1,r.setState({})},typeof e.type=="function"?e.type.displayName||e.type.name:""))),yt(n)}}),Te("__e",function(t,e,n,r){yt(),t(e,n,r)}),Te("diffed",function(t,e){yt();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 u=s[a],d=r[a];u===void 0?(u=ia(n,a,d,i),s[a]=u):u.o(d,i)}}}t(e)});function ia(t,e,n,r){var i=e in t&&t.ownerSVGElement===void 0,s=G(n);return{o:function(o,l){s.value=o,r=l},d:Ke(function(){this.N=ci;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))})}}Te("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)}),Te("__h",function(t,e,n,r){(r<3||r===9)&&(e.__$f|=2),t(e,n,r)}),N.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 Re(t,e){return z(function(){return G(t,e)},[])}var sa=function(t){queueMicrotask(function(){queueMicrotask(t)})};function oa(){ta(function(){for(var t;t=ai.shift();)oi.call(t)})}function ci(){ai.push(this)===1&&(m.requestAnimationFrame||sa)(oa)}const A=G(!1),vt=G(void 0),ln=G(void 0);function aa(t){return t.replace(/\.convex\.site\b/,".convex.cloud")}function ui(t){return t.replace(/\.convex\.cloud\b/,".convex.site")}function la(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 ca(t,e,n){const r=`${t}/widget/config?orgSlug=${encodeURIComponent(e)}`,i=await fetch(r,{signal:n});return i.ok?i.json():null}function ua(t,e){const[n,r]=R(null);return Q(()=>{r(null);const i=e??"https://festive-mouse-978.eu-west-1.convex.cloud",s=i?ui(i):void 0;if(!s||!t)return;const o=new AbortController;async function l(a){try{const u=await ca(a,t,o.signal);u&&r(u)}catch(u){if(u instanceof Error&&u.name==="AbortError")return}}return l(s),()=>{o.abort()}},[t,e]),n}const hi={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.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Resume 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."},ha={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.",localeLabelDe:"DE",localeLabelEn:"EN",resumeConversation:"Gespräch fortsetzen",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."},da=[{value:"de",label:"Deutsch",flag:"🇩🇪"},{value:"en",label:"English",flag:"🇬🇧"}],fa="de",pa="jex-locale",cn=G("de"),ga={en:hi,de:ha};function P(){return ga[cn.value]??hi}function un(t){if(!t)return null;const e=(t.split("-")[0]??"").toLowerCase();return da.some(r=>r.value===e)?e:null}function di(t){const e=un(t);if(e)return e;try{const n=un(localStorage.getItem(pa));if(n)return n}catch{}if(typeof navigator<"u"){const n=un(navigator.language);if(n)return n}return fa}function ma(t){Q(()=>{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&&(cn.value=di(i))}return window.addEventListener("message",e),()=>{window.removeEventListener("message",e)}},[t])}const hn="jex-session-ref",_t="jex-session-active",oe=G(null),pe=G(!1);function xa(){return"JEX-"+Math.random().toString(36).slice(2,8).toUpperCase()}function ba(){try{const t=sessionStorage.getItem(hn),e=sessionStorage.getItem(_t);oe.value=t??null,pe.value=t!==null&&e==="true"}catch{oe.value=null,pe.value=!1}}function dn(){const t=xa();oe.value=t,pe.value=!1;try{sessionStorage.setItem(hn,t),sessionStorage.removeItem(_t)}catch{}return t}function ya(t){oe.value=t,pe.value=!0;try{sessionStorage.setItem(hn,t),sessionStorage.setItem(_t,"true")}catch{}}function va(){if(oe.value){pe.value=!0;try{sessionStorage.setItem(_t,"true")}catch{}}}function _a(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}const B=G([{id:"home"}]),ka=G("screen");function $e(t){B.value=[...B.value,t]}function fn(){B.value.length>1&&(B.value=B.value.slice(0,-1))}function Ae(t){B.value=[...B.value.slice(0,-1),t]}function pn({size:t=24}){return h("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:[h("path",{d:"M12 8V4H8"}),h("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),h("path",{d:"M2 14h2"}),h("path",{d:"M20 14h2"}),h("path",{d:"M15 13v2"}),h("path",{d:"M9 13v2"})]})}function fi({title:t}){const e=P(),n=B.value.length>1;return h("header",{class:"jex-chat-header",children:[n&&h("button",{class:"jex-header-back",onClick:fn,"aria-label":e.back||"Go back",children:h("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:h("path",{d:"m15 18-6-6 6-6"})})}),!n&&h(pn,{size:24}),h("div",{class:"jex-header-info",children:[h("h3",{children:t}),h("p",{children:e.statusOnline})]})]})}function wa({size:t=14}){return h("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:h("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 pi(){return h("div",{class:"jex-widget-footer",children:h("a",{href:"https://jexitychat.de",target:"_blank",rel:"noopener noreferrer",class:"jex-branding",children:[h(wa,{size:14}),h("span",{children:["Powered by ",h("strong",{children:"Jexity"})]})]})})}function gi({size:t=28}){return h("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:h("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 Sa({size:t=28}){return h("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:[h("path",{d:"M18 6 6 18"}),h("path",{d:"m6 6 12 12"})]})}function ja({size:t=24,...e}){return h("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:h("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 Ca={chat:h(gi,{size:28}),bot:h(pn,{size:28}),sparkles:h(ja,{size:28})},Ta={none:"0px",sm:"0.5rem",md:"0.75rem",lg:"1.25rem",full:"9999px"};function Ra({radius:t="full",iconOption:e="chat",label:n}){const r=P(),i=n??r.fabLabel,s=i!=="";return h("button",{class:`jex-floating-button ${!A.value&&s?"jex-has-label":""}`,style:{borderRadius:Ta[t]??"9999px"},onClick:()=>{A.value=!A.value},"aria-label":A.value?r.closeChatAriaLabel:r.openChatAriaLabel,children:A.value?h(Sa,{size:28}):h("div",{class:"jex-fab-inner",children:[Ca[e],s&&h("span",{class:"jex-fab-label",children:i})]})})}function $a({title:t}){const e=P(),n=oe.value,[r,i]=R("");function s(){dn(),$e({id:"chat"})}function o(){$e({id:"chat"})}function l(a){a.preventDefault();const u=r.trim().toUpperCase();u&&(ya(u),$e({id:"chat"}))}return h("div",{class:"jex-home",children:[h("div",{class:"jex-home-hero",children:[h("div",{class:"jex-home-avatar",children:[h(gi,{size:24}),h("span",{class:"jex-home-status-dot"})]}),h("div",{class:"jex-home-hero-text",children:[h("h2",{class:"jex-home-title",children:t}),h("span",{class:"jex-home-status",children:e.statusOnline})]})]}),h("form",{class:"jex-home-lookup",onSubmit:l,children:[h("input",{class:"jex-home-lookup-input",type:"text",placeholder:e.referencePlaceholder,value:r,onInput:a=>{i(a.currentTarget.value)}}),h("button",{class:"jex-home-lookup-submit",type:"submit",disabled:!r.trim(),children:e.resume})]}),h("div",{class:"jex-home-actions",children:[n&&h("button",{class:"jex-home-resume-card",onClick:o,children:[h("div",{class:"jex-home-resume-top",children:[h("span",{class:"jex-home-resume-label",children:e.resumeConversation}),h("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",class:"jex-home-resume-arrow",children:h("path",{d:"M6 3l5 5-5 5",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"})})]}),h("span",{class:"jex-home-resume-ref",children:n})]}),h("button",{class:"jex-home-new-btn",onClick:s,children:n?e.startNewConversation:e.chatWith.replace("{title}",t)})]})]})}function Aa({title:t}){const e=P();return h("div",{class:"jex-selection",children:[h("h2",{class:"jex-selection-title",children:e.howCanWeHelp}),h("div",{class:"jex-selection-options",children:[h("button",{class:"jex-selection-option",onClick:()=>$e({id:"chat"}),children:[h("span",{class:"jex-selection-icon",children:"💬"}),h("span",{class:"jex-selection-label",children:e.chatWith.replace("{title}",t)}),h("span",{class:"jex-selection-sub",children:e.getInstantHelp})]}),h("button",{class:"jex-selection-option",onClick:()=>$e({id:"form"}),children:[h("span",{class:"jex-selection-icon",children:"📝"}),h("span",{class:"jex-selection-label",children:e.submitTicket}),h("span",{class:"jex-selection-sub",children:e.replyByEmail})]})]})]})}function mi(t,e){const n={get(r,i){if(typeof i=="string"){const s=[...e,i];return mi(t,s)}else if(i===Qr){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 Ia=()=>mi("components",[]),Ie=no;Ia();function Ea(t){const e=st(null),n=Re(!1),r=Re(!1),i=Re(!1),s=Re(null),o=gt(Ie.functions.chat.public.sessions.createOrResume),l=async c=>{const p=ln.value;if(!p)return console.warn("[JexityChat] No bootstrap token — session creation blocked."),null;const f=await o({orgSlug:t,visitorId:c,bootstrapToken:p,...vt.value?{source:vt.value}:{}});s.value=f.status;const g={sessionId:f.sessionId,visitorId:c};return e.current=g,{session:g,result:f}},a=ze(async()=>{if(e.current)return e.current;if(i.value)return null;n.value=!0;const c=oe.value!==null,p=oe.value??dn();try{const f=await l(p);return f?(c&&f.result.isNew&&(r.value=!0,i.value=!0),f.session):null}catch(f){return console.error("[JexityChat] Failed to create session:",f),null}finally{n.value=!1}},[t,o,n,r,i]),u=ze(async()=>{e.current=null,i.value=!1,r.value=!1;const c=dn();n.value=!0;try{return(await l(c))?.session??null}catch(p){return console.error("[JexityChat] Failed to create fresh session:",p),null}finally{n.value=!1}},[t,o,n,r,i,s]),d=e.current;return{sessionId:d?.sessionId??null,visitorId:d?.visitorId??null,isLoading:n.value,sessionNotFound:r.value,resumeFailed:i.value,sessionStatus:s.value,isOrgDeleted:s.value==="org_deleted",ensureSession:a,startFresh:u}}function gn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ge=gn();function xi(t){ge=t}var me={exec:()=>null};function x(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(I.caret,"$1"),n=n.replace(i,o),r},getRegex:()=>new RegExp(n,e)};return r}var qa=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),I={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)}}>`)},Pa=/^(?:[ \t]*(?:\n|$))+/,Ma=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,La=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ze=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Oa=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,mn=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,bi=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,yi=x(bi).replace(/bull/g,mn).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(),Na=x(bi).replace(/bull/g,mn).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(),xn=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Qa=/^[^\n]+/,bn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,za=x(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",bn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ba=x(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,mn).getRegex(),kt="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",yn=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Fa=x("^ {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",yn).replace("tag",kt).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),vi=x(xn).replace("hr",Ze).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",kt).getRegex(),Da=x(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",vi).getRegex(),vn={blockquote:Da,code:Ma,def:za,fences:La,heading:Oa,hr:Ze,html:Fa,lheading:yi,list:Ba,newline:Pa,paragraph:vi,table:me,text:Qa},_i=x("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ze).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",kt).getRegex(),Ua={...vn,lheading:Na,table:_i,paragraph:x(xn).replace("hr",Ze).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",_i).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",kt).getRegex()},Va={...vn,html:x(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",yn).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:me,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:x(xn).replace("hr",Ze).replace("heading",` *#{1,6} *[^
|
|
3
|
+
]`).replace("lheading",yi).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Wa=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ha=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ki=/^( {2,}|\\)\n(?!\s*$)/,Ja=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ee=/[\p{P}\p{S}]/u,wt=/[\s\p{P}\p{S}]/u,_n=/[^\s\p{P}\p{S}]/u,Ga=x(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,wt).getRegex(),wi=/(?!~)[\p{P}\p{S}]/u,Ka=/(?!~)[\s\p{P}\p{S}]/u,Za=/(?:[^\s\p{P}\p{S}]|~)/u,Xa=x(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",qa?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Si=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ya=x(Si,"u").replace(/punct/g,Ee).getRegex(),el=x(Si,"u").replace(/punct/g,wi).getRegex(),ji="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",tl=x(ji,"gu").replace(/notPunctSpace/g,_n).replace(/punctSpace/g,wt).replace(/punct/g,Ee).getRegex(),nl=x(ji,"gu").replace(/notPunctSpace/g,Za).replace(/punctSpace/g,Ka).replace(/punct/g,wi).getRegex(),rl=x("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,_n).replace(/punctSpace/g,wt).replace(/punct/g,Ee).getRegex(),il=x(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Ee).getRegex(),sl="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ol=x(sl,"gu").replace(/notPunctSpace/g,_n).replace(/punctSpace/g,wt).replace(/punct/g,Ee).getRegex(),al=x(/\\(punct)/,"gu").replace(/punct/g,Ee).getRegex(),ll=x(/^<(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(),cl=x(yn).replace("(?:-->|$)","-->").getRegex(),ul=x("^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",cl).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),St=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,hl=x(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",St).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Ci=x(/^!?\[(label)\]\[(ref)\]/).replace("label",St).replace("ref",bn).getRegex(),Ti=x(/^!?\[(ref)\](?:\[\])?/).replace("ref",bn).getRegex(),dl=x("reflink|nolink(?!\\()","g").replace("reflink",Ci).replace("nolink",Ti).getRegex(),Ri=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,kn={_backpedal:me,anyPunctuation:al,autolink:ll,blockSkip:Xa,br:ki,code:Ha,del:me,delLDelim:me,delRDelim:me,emStrongLDelim:Ya,emStrongRDelimAst:tl,emStrongRDelimUnd:rl,escape:Wa,link:hl,nolink:Ti,punctuation:Ga,reflink:Ci,reflinkSearch:dl,tag:ul,text:Ja,url:me},fl={...kn,link:x(/^!?\[(label)\]\((.*?)\)/).replace("label",St).getRegex(),reflink:x(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",St).getRegex()},wn={...kn,emStrongRDelimAst:nl,emStrongLDelim:el,delLDelim:il,delRDelim:ol,url:x(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Ri).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:x(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Ri).getRegex()},pl={...wn,br:x(ki).replace("{2,}","*").getRegex(),text:x(wn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},jt={normal:vn,gfm:Ua,pedantic:Va},Xe={normal:kn,gfm:wn,breaks:pl,pedantic:fl},gl={"&":"&","<":"<",">":">",'"':""","'":"'"},$i=t=>gl[t];function K(t,e){if(e){if(I.escapeTest.test(t))return t.replace(I.escapeReplace,$i)}else if(I.escapeTestNoEncode.test(t))return t.replace(I.escapeReplaceNoEncode,$i);return t}function Ai(t){try{t=encodeURI(t).replace(I.percentDecode,"%")}catch{return null}return t}function Ii(t,e){let n=t.replace(I.findPipe,(s,o,l)=>{let a=!1,u=o;for(;--u>=0&&l[u]==="\\";)a=!a;return a?"|":" |"}),r=n.split(I.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(I.slashPipe,"|");return r}function Ye(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 ml(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 xl(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 Ei(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 bl(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 Ct=class{options;rules;lexer;constructor(t){this.options=t||
|
|
6
|
-
`)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=
|
|
7
|
-
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=
|
|
5
|
+
`)}var Ct=class{options;rules;lexer;constructor(t){this.options=t||ge}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:Ye(n,`
|
|
6
|
+
`)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=bl(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=Ye(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:Ye(e[0],`
|
|
7
|
+
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=Ye(e[0],`
|
|
8
8
|
`).split(`
|
|
9
9
|
`),r="",i="",s=[];for(;n.length>0;){let o=!1,l=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))l.push(n[a]),o=!0;else if(!o)l.push(n[a]);else break;n=n.slice(a);let u=l.join(`
|
|
10
10
|
`),d=u.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -15,16 +15,16 @@ ${d}`:d;let c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
15
15
|
`),b=this.blockquote(g);s[s.length-1]=b,r=r.substring(0,r.length-f.raw.length)+b.raw,i=i.substring(0,i.length-f.text.length)+b.text;break}else if(p?.type==="list"){let f=p,g=f.raw+`
|
|
16
16
|
`+n.join(`
|
|
17
17
|
`),b=this.list(g);s[s.length-1]=b,r=r.substring(0,r.length-p.raw.length)+b.raw,i=i.substring(0,i.length-f.raw.length)+b.raw,n=g.substring(s.at(-1).raw.length).split(`
|
|
18
|
-
`);continue}}return{type:"blockquote",raw:r,tokens:s,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),o=!1;for(;t;){let a=!1,u="",d="";if(!(e=s.exec(t))||this.rules.block.hr.test(t))break;u=e[0],t=t.substring(u.length);let c=
|
|
18
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:s,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),o=!1;for(;t;){let a=!1,u="",d="";if(!(e=s.exec(t))||this.rules.block.hr.test(t))break;u=e[0],t=t.substring(u.length);let c=xl(e[2].split(`
|
|
19
19
|
`,1)[0],e[1].length),p=t.split(`
|
|
20
20
|
`,1)[0],f=!c.trim(),g=0;if(this.options.pedantic?(g=2,d=c.trimStart()):f?g=e[1].length+1:(g=c.search(this.rules.other.nonSpaceChar),g=g>4?1:g,d=c.slice(g),g+=e[1].length),f&&this.rules.other.blankLine.test(p)&&(u+=p+`
|
|
21
|
-
`,t=t.substring(p.length+1),a=!0),!a){let b=this.rules.other.nextBulletRegex(g),S=this.rules.other.hrRegex(g),_=this.rules.other.fencesBeginRegex(g),
|
|
22
|
-
`,1)[0],U;if(p=
|
|
23
|
-
`+U.slice(g);else{if(f||c.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(c)||
|
|
24
|
-
`+p}f=!p.trim(),u+=
|
|
25
|
-
`,t=t.substring(
|
|
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(
|
|
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=
|
|
21
|
+
`,t=t.substring(p.length+1),a=!0),!a){let b=this.rules.other.nextBulletRegex(g),S=this.rules.other.hrRegex(g),_=this.rules.other.fencesBeginRegex(g),k=this.rules.other.headingBeginRegex(g),Z=this.rules.other.htmlBeginRegex(g),X=this.rules.other.blockquoteBeginRegex(g);for(;t;){let le=t.split(`
|
|
22
|
+
`,1)[0],U;if(p=le,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),U=p):U=p.replace(this.rules.other.tabCharGlobal," "),_.test(p)||k.test(p)||Z.test(p)||X.test(p)||b.test(p)||S.test(p))break;if(U.search(this.rules.other.nonSpaceChar)>=g||!p.trim())d+=`
|
|
23
|
+
`+U.slice(g);else{if(f||c.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(c)||k.test(c)||S.test(c))break;d+=`
|
|
24
|
+
`+p}f=!p.trim(),u+=le+`
|
|
25
|
+
`,t=t.substring(le.length+1),c=U.slice(g)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(o=!0)),i.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]}),i.raw+=u}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 u=this.rules.other.listTaskCheckbox.exec(a.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[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 u=a.tokens.filter(c=>c.type==="space"),d=u.length>0&&u.some(c=>this.rules.other.anyLine.test(c.raw));i.loose=d}}if(i.loose)for(let a of i.items){a.loose=!0;for(let u of a.tokens)u.type==="text"&&(u.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=Ii(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
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(Ii(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=Ye(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=ml(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)),Ei(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 Ei(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,u=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,e=e.slice(-1*t.length+i);(r=u.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,c=t.slice(0,i+r.index+d+o);if(Math.min(i,o)%2){let f=c.slice(1,-1);return{type:"em",raw:c,text:f,tokens:this.lexer.inlineTokens(f)}}let p=c.slice(2,-2);return{type:"strong",raw:c,text:p,tokens:this.lexer.inlineTokens(p)}}}}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 u=[...r[0]][0].length,d=t.slice(0,i+r.index+u+o),c=d.slice(i,-i);return{type:"del",raw:d,text:c,tokens:this.lexer.inlineTokens(c)}}}}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}}}},F=class Tn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ge,this.options.tokenizer=this.options.tokenizer||new Ct,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:I,block:jt.normal,inline:Xe.normal};this.options.pedantic?(n.block=jt.pedantic,n.inline=Xe.pedantic):this.options.gfm&&(n.block=jt.gfm,this.options.breaks?n.inline=Xe.breaks:n.inline=Xe.gfm),this.tokenizer.rules=n}static get rules(){return{block:jt,inline:Xe}}static lex(e,n){return new Tn(n).lex(e)}static lexInline(e,n){return new Tn(n).inlineTokens(e)}lex(e){e=e.replace(I.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(I.tabCharGlobal," ").replace(I.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,9 +38,9 @@ ${d}`:d;let c=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 u=e;if(this.options.extensions?.startInline){let d=1/0,c=e.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},c),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(u)){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}},Tt=class{options;parser;constructor(t){this.options=t||
|
|
42
|
-
`;return r?'<pre><code class="language-'+
|
|
43
|
-
`:"<pre><code>"+(n?i:
|
|
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 u=e;if(this.options.extensions?.startInline){let d=1/0,c=e.slice(1),p;this.options.extensions.startInline.forEach(f=>{p=f.call({lexer:this},c),typeof p=="number"&&p>=0&&(d=Math.min(d,p))}),d<1/0&&d>=0&&(u=e.substring(0,d+1))}if(a=this.tokenizer.inlineText(u)){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}},Tt=class{options;parser;constructor(t){this.options=t||ge}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(I.notSpaceStart)?.[0],i=t.replace(I.endingNewline,"")+`
|
|
42
|
+
`;return r?'<pre><code class="language-'+K(r)+'">'+(n?i:K(i,!0))+`</code></pre>
|
|
43
|
+
`:"<pre><code>"+(n?i:K(i,!0))+`</code></pre>
|
|
44
44
|
`}blockquote({tokens:t}){return`<blockquote>
|
|
45
45
|
${this.parser.parse(t)}</blockquote>
|
|
46
46
|
`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
|
|
@@ -56,6 +56,6 @@ ${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>${
|
|
60
|
-
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+J(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},me=new bl;function v(t,e){return me.parse(t,e)}v.options=v.setOptions=function(t){return me.setOptions(t),v.defaults=me.defaults,gi(v.defaults),v},v.getDefaults=pn,v.defaults=pe,v.use=function(...t){return me.use(...t),v.defaults=me.defaults,gi(v.defaults),v},v.walkTokens=function(t,e){return me.walkTokens(t,e)},v.parseInline=me.parseInline,v.Parser=D,v.parser=D.parse,v.Renderer=Tt,v.TextRenderer=kn,v.Lexer=F,v.lexer=F.lex,v.Tokenizer=Ct,v.Hooks=tt,v.parse=v,v.options,v.setOptions,v.use,v.walkTokens,v.parseInline,D.parse,F.lex,v.setOptions({breaks:!0,gfm:!0});function yl({text:t}){const e=z(()=>{if(!t)return"";const n=v.parse(t);return typeof n=="string"?n:""},[t]);return h("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}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,u]=R(!1),d=Be(()=>u(!0),[]),c=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return h("div",{class:"jex-message-row bot",children:[h("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?h("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?h("span",{class:"jex-avatar-initials",children:vl(i??"")}):o&&!a?h("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):h(fn,{size:14})}),h("div",{class:"jex-message-content",children:[h("div",{class:c,children:[h(yl,{text:t}),e&&h("span",{class:"jex-streaming-cursor"})]}),l&&i&&h("span",{class:"jex-message-author",children:i})]})]})}function _l({text:t}){return h("div",{class:"jex-message user",children:t})}function wl({message:t,sessionId:e,visitorId:n}){const r=P();return t.formData?h("div",{class:"jex-inline-form-submitted",children:[h("span",{class:"jex-inline-form-check",children:"✓"}),h("div",{children:[h("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),h("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):h("div",{class:"jex-message-row bot",children:h(kl,{messageId:t._id,sessionId:e,visitorId:n})})}function kl({messageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=R(""),[o,l]=R(""),[a,u]=R(!1),d=mt(Ee.functions.chat.public.helpdesk.submitEscalation);async function c(p){if(p.preventDefault(),!a){u(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()})}catch(f){console.error("[FormMessage] Submit failed:",f),u(!1)}}}return h("div",{class:"jex-inline-form",children:[h("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),h("form",{class:"jex-form",onSubmit:p=>{c(p)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:p=>{s(p.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,disabled:a,onInput:p=>{l(p.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),h("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}function Sl(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function jl({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:s,visitorId:o}){const l=P(),a=ot(null),[u,d]=R(null);return Q(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),h("div",{class:"jex-chat-messages",children:[h(Pe,{text:e}),n&&r&&i?h("div",{class:"jex-session-prompt",children:[h("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),h("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?h("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(c=>{if(c.contentType==="human-notice")return h(Pe,{text:c.content},c._id);if(c.contentType==="escalation-form"&&s&&o)return _a.value==="screen"&&!c.formData?u===c._id?null:h("div",{class:"jex-inline-form jex-inline-form-card",children:[h("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),h("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),h("button",{class:"jex-form-submit",type:"button",onClick:()=>{Ae({id:"escalation-form",formMessageId:c._id,sessionId:s,visitorId:o})},children:l.escalationPromptSubmit}),h("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(c._id)},children:l.escalationSkip})]},c._id):h(wl,{message:c,sessionId:s,visitorId:o},c._id);if(c.contentType==="escalation-confirm")return h(Pe,{text:c.content},c._id);if(c.role==="user")return h(_l,{text:c.content},c._id);const p={authorId:c.authorId,authorName:c.authorName,authorImage:c.authorImage};return c.status==="streaming"&&c.content===""?h(Sl,{},c._id):c.status==="streaming"?h(Pe,{text:c.content,streaming:!0,...p},c._id):c.status==="error"?h(Pe,{text:c.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},c._id):h(Pe,{text:c.content,...p},c._id)}),h("div",{ref:a})]})}function Cl({size:t=18}){return h("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:[h("path",{d:"M22 2 11 13"}),h("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function Tl({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:s,onStartFresh:o}){const l=P(),a=Re(""),u=mt(Ee.functions.chat.public.conversations.send),d=n||r;if(i==="resolved")return h("div",{class:"jex-chat-input-resolved",children:[h("div",{class:"jex-resolved-notice",children:l.sessionResolved}),h("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{o()},children:l.startNewConversation})]});async function c(){const p=a.value.trim();if(!p||d)return;const f=t&&e?{sessionId:t,visitorId:e}:await s();f&&(ya(),a.value="",u({sessionId:f.sessionId,visitorId:f.visitorId,content:p}).catch(g=>{console.error("[jexity] Failed to send message:",g)}))}return h("div",{class:"jex-chat-input",children:[h("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"&&c()},disabled:d}),h("button",{class:"jex-send-btn",onClick:c,"aria-label":l.sendAriaLabel,disabled:d,children:h(Cl,{size:18})})]})}function Ii({message:t}){return h("div",{class:"jex-overlay jex-loading",children:[h("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&h("p",{class:"jex-loading-message",children:t})]})}function Rl({greeting:t,orgSlug:e}){const n=P(),{sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,resumeFailed:l,isOrgDeleted:a,ensureSession:u,startFresh:d}=Ia(e),c=Zr(Ee.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),p=Zr(Ee.functions.chat.public.sessions.getSessionStatus,r&&i?{sessionId:r,visitorId:i}:"skip"),f=r!==null&&c===void 0,g=c?.some(b=>b.status==="streaming")??!1;return Q(()=>{fe.value&&!r&&u()},[u,r]),a?h("div",{class:"jex-chat-messages",children:h("div",{class:"jex-session-notice",children:n.chatNoLongerAvailable})}):s||f&&fe.value?h(Ii,{message:n.resumeConversation}):h(O,{children:[h(jl,{conversations:c,greeting:t,sessionNotFound:o,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),h(Tl,{sessionId:r,visitorId:i,isLoading:s,isStreaming:g,sessionStatus:p??null,ensureSession:u,onStartFresh:d})]})}function $l({formMessageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=R(""),[o,l]=R(""),a=mt(Ee.functions.chat.public.helpdesk.submitEscalation);async function u(d){d.preventDefault(),Ie({id:"loading",message:r.escalationSubmitting});try{const c=await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()});Ie({id:"confirmation",ref:c.ticketRef})}catch(c){console.error("[EscalationFormScreen] Submit failed:",c),Ie({id:"error",message:r.escalationSubmitFailed})}}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:r.escalationFormTitle}),h("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h("form",{class:"jex-form",onSubmit:d=>{u(d)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:d=>{s(d.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,onInput:d=>{l(d.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:r.escalationSubmit})]}),h("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),h("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{dn()},children:r.escalationSkip})]})}function Al(){const t=P(),[e,n]=R(""),[r,i]=R(""),[s,o]=R("");async function l(a){a.preventDefault(),Ie({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();Ie({id:"confirmation",ref:u})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function Il({ticketRef:t}){const e=P();return h("div",{class:"jex-confirmation",children:[h("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),h("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),h("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),h("div",{class:"jex-confirmation-ref",children:t}),h("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),h("button",{class:"jex-confirmation-done",onClick:()=>{A.value=!1},children:e.done})]})}function El({message:t,onRetry:e,onBack:n}){const r=P();return h("div",{class:"jex-overlay jex-error",children:[h("p",{class:"jex-error-message",children:t}),h("div",{class:"jex-error-actions",children:[e&&h("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&h("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function Ei({greeting:t,title:e,orgSlug:n}){const r=B.value,i=r[r.length-1],s=r.findLast(o=>o.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h(Ra,{greeting:t,title:e}),i.id==="selection"&&h($a,{title:e}),i.id==="form"&&h(Al,{}),i.id==="escalation-form"&&h($l,{formMessageId:i.formMessageId,sessionId:i.sessionId,visitorId:i.visitorId}),i.id==="confirmation"&&s&&h(Il,{ticketRef:s.ref}),i.id==="chat"&&h(Rl,{greeting:t,orgSlug:n}),i.id==="loading"&&h(Ii,{message:i.message}),i.id==="error"&&h(El,{message:i.message,onRetry:()=>Ie({id:"loading"}),onBack:dn})]})}function ql({options:t}){const e=ca(t.orgSlug,t.convexUrl);ga(t.parentOrigin),Q(()=>{xa()},[]);const n=aa(t,e);Q(()=>{ln.value=ui(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",s=va({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight}),o=n.mode==="embedded",a=e!==null||o||!!t.parentOrigin?s:{...s,visibility:"hidden"};return h("div",{class:`jex-widget ${i}`.trim(),style:a,children:o?h("div",{class:"jex-embedded",children:[h(hi,{title:n.title}),h(Ei,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(di,{})]}):h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[A.value&&h("div",{class:"jex-chat-window",children:[h(hi,{title:n.title}),h(Ei,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(di,{})]}),h(Ta,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Pl='.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-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-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{display:block;font-size:10px;color:var(--jex-text-muted);margin-top:2px;padding-left:4px}.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}.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}';function Ml(t){const e=document.createElement("style");e.textContent=Pl,t.appendChild(e)}const Ll="https://festive-mouse-978.eu-west-1.convex.cloud";let Sn=null;function Ol(t){const e=t??Ll;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 Sn||(Sn=new Do(sa(e))),Sn}function Nl(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Ml(n),$e.value=e.source,B.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),A.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),ce(h(Vo,{client:Ol(e.convexUrl),children:h(ql,{options:e})}),r),function(){ce(null,r),A.value=!1,$e.value=void 0,B.value=[{id:"home"}]}}function Ql(t,e,n){const r=Nl(t,e),i=new Set,s=A.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){A.value=!0},close(){A.value=!1},toggle(){A.value=!A.value},get isOpen(){return A.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let nt=null;function zl(t){nt&&nt.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=Ql(e,t,()=>{t.container||e.remove(),nt===n&&(nt=null)});return nt=n,n}function xe(t,e){return t.getAttribute(e)??void 0}function qi(){const t=document.currentScript??document.querySelector("script[data-org-slug]")??document.querySelector("script[data-org-id]");if(!t)return;const n={orgSlug:t.getAttribute("data-org-slug")??t.getAttribute("data-org-id")??"default-org",position:xe(t,"data-position")??void 0,theme:xe(t,"data-theme")??void 0,greeting:xe(t,"data-greeting"),title:xe(t,"data-title"),primaryColor:xe(t,"data-primary-color"),locale:xe(t,"data-locale"),convexUrl:xe(t,"data-convex-url")};window.JexityChat=zl(n)}document.readyState==="complete"?qi():window.addEventListener("load",qi)})();
|
|
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>${K(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=Ai(t);if(i===null)return r;t=i;let s='<a href="'+t+'"';return e&&(s+=' title="'+K(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=Ai(t);if(i===null)return K(n);t=i;let s=`<img src="${t}" alt="${K(n)}"`;return e&&(s+=` title="${K(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:K(t.text)}},Sn=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}},D=class Rn{options;renderer;textRenderer;constructor(e){this.options=e||ge,this.options.renderer=this.options.renderer||new Tt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Sn}static parse(e,n){return new Rn(n).parse(e)}static parseInline(e,n){return new Rn(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}},et=class{options;block;constructor(t){this.options=t||ge}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?F.lex:F.lexInline}provideParser(){return this.block?D.parse:D.parseInline}},yl=class{defaults=gn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=D;Renderer=Tt;TextRenderer=Sn;Lexer=F;Tokenizer=Ct;Hooks=et;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 Tt(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]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new Ct(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]=(...u)=>{let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),d}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new et;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];et.passThroughHooks.has(s)?i[o]=u=>{if(this.defaults.async&&et.passThroughHooksRespectAsync.has(s))return(async()=>{let c=await l.call(i,u);return a.call(i,c)})();let d=l.call(i,u);return a.call(i,d)}:i[o]=(...u)=>{if(this.defaults.async)return(async()=>{let c=await l.apply(i,u);return c===!1&&(c=await a.apply(i,u)),c})();let d=l.apply(i,u);return d===!1&&(d=a.apply(i,u)),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 F.lex(t,e??this.defaults)}parser(t,e){return D.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?F.lex:F.lexInline)(o,i),a=i.hooks?await i.hooks.processAllTokens(l):l;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let u=await(i.hooks?await i.hooks.provideParser():t?D.parse:D.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(u):u})().catch(s);try{i.hooks&&(e=i.hooks.preprocess(e));let o=(i.hooks?i.hooks.provideLexer():t?F.lex:F.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?D.parse:D.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>"+K(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},xe=new yl;function v(t,e){return xe.parse(t,e)}v.options=v.setOptions=function(t){return xe.setOptions(t),v.defaults=xe.defaults,xi(v.defaults),v},v.getDefaults=gn,v.defaults=ge,v.use=function(...t){return xe.use(...t),v.defaults=xe.defaults,xi(v.defaults),v},v.walkTokens=function(t,e){return xe.walkTokens(t,e)},v.parseInline=xe.parseInline,v.Parser=D,v.parser=D.parse,v.Renderer=Tt,v.TextRenderer=Sn,v.Lexer=F,v.lexer=F.lex,v.Tokenizer=Ct,v.Hooks=et,v.parse=v,v.options,v.setOptions,v.use,v.walkTokens,v.parseInline,D.parse,F.lex,v.setOptions({breaks:!0,gfm:!0});function vl({text:t}){const e=z(()=>{if(!t)return"";const n=v.parse(t);return typeof n=="string"?n:""},[t]);return h("div",{class:"jex-md",dangerouslySetInnerHTML:{__html:e}})}function _l(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,u]=R(!1),d=ze(()=>u(!0),[]),c=["jex-message bot",n?"jex-message-error":""].filter(Boolean).join(" ");return h("div",{class:"jex-message-row bot",children:[h("div",{class:`jex-avatar ${l?"jex-avatar-agent":"jex-avatar-bot"}`,children:l&&s&&!a?h("img",{src:s,alt:i??"",class:"jex-avatar-img",onError:d}):l?h("span",{class:"jex-avatar-initials",children:_l(i??"")}):o&&!a?h("img",{src:o,alt:"",class:"jex-avatar-img",onError:d}):h(pn,{size:14})}),h("div",{class:"jex-message-content",children:[h("div",{class:c,children:[h(vl,{text:t}),e&&h("span",{class:"jex-streaming-cursor"})]}),l&&i&&h("span",{class:"jex-message-author",children:i})]})]})}function kl({text:t}){return h("div",{class:"jex-message user",children:t})}function wl({message:t,sessionId:e,visitorId:n}){const r=P();return t.formData?h("div",{class:"jex-inline-form-submitted",children:[h("span",{class:"jex-inline-form-check",children:"✓"}),h("div",{children:[h("div",{class:"jex-inline-form-submitted-title",children:r.escalationSubmitted}),h("div",{class:"jex-inline-form-submitted-detail",children:[t.formData.visitorName," · ",t.formData.visitorEmail]})]})]}):h("div",{class:"jex-message-row bot",children:h(Sl,{messageId:t._id,sessionId:e,visitorId:n})})}function Sl({messageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=R(""),[o,l]=R(""),[a,u]=R(!1),d=gt(Ie.functions.chat.public.helpdesk.submitEscalation);async function c(p){if(p.preventDefault(),!a){u(!0);try{await d({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()})}catch(f){console.error("[FormMessage] Submit failed:",f),u(!1)}}}return h("div",{class:"jex-inline-form",children:[h("div",{class:"jex-inline-form-title",children:r.escalationFormTitle}),h("form",{class:"jex-form",onSubmit:p=>{c(p)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,disabled:a,onInput:p=>{s(p.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,disabled:a,onInput:p=>{l(p.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",disabled:a,children:a?r.escalationSubmitting:r.escalationSubmit})]}),h("div",{class:"jex-inline-form-consent",children:r.escalationConsent})]})}function jl(){return h("div",{class:"jex-typing",children:[h("span",{}),h("span",{}),h("span",{})]})}function Cl({conversations:t,greeting:e,sessionNotFound:n,resumeFailed:r,onStartFresh:i,sessionId:s,visitorId:o}){const l=P(),a=st(null),[u,d]=R(null);return Q(()=>{a.current?.scrollIntoView({behavior:"smooth"})},[t?.length,t?.at(-1)?.content]),h("div",{class:"jex-chat-messages",children:[h(qe,{text:e}),n&&r&&i?h("div",{class:"jex-session-prompt",children:[h("div",{class:"jex-session-prompt-text",children:l.sessionNotFoundPrompt}),h("button",{class:"jex-session-prompt-btn",type:"button",onClick:()=>{i()},children:l.startNewConversation})]}):n?h("div",{class:"jex-session-notice",children:l.sessionNotFound}):null,t?.map(c=>{if(c.contentType==="human-notice")return h(qe,{text:c.content},c._id);if(c.contentType==="escalation-form"&&s&&o)return ka.value==="screen"&&!c.formData?u===c._id?null:h("div",{class:"jex-inline-form jex-inline-form-card",children:[h("div",{class:"jex-inline-form-title",children:l.escalationPromptTitle}),h("div",{class:"jex-inline-form-subtitle",children:l.escalationPromptSubtitle}),h("button",{class:"jex-form-submit",type:"button",onClick:()=>{$e({id:"escalation-form",formMessageId:c._id,sessionId:s,visitorId:o})},children:l.escalationPromptSubmit}),h("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{d(c._id)},children:l.escalationSkip})]},c._id):h(wl,{message:c,sessionId:s,visitorId:o},c._id);if(c.contentType==="escalation-confirm")return h(qe,{text:c.content},c._id);if(c.role==="user")return h(kl,{text:c.content},c._id);const p={authorId:c.authorId,authorName:c.authorName,authorImage:c.authorImage};return c.status==="streaming"&&c.content===""?h(jl,{},c._id):c.status==="streaming"?h(qe,{text:c.content,streaming:!0,...p},c._id):c.status==="error"?h(qe,{text:c.errorMessage??`${l.somethingWentWrong}. ${l.tryAgain}.`,error:!0,...p},c._id):h(qe,{text:c.content,...p},c._id)}),h("div",{ref:a})]})}function Tl({size:t=18}){return h("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:[h("path",{d:"M22 2 11 13"}),h("path",{d:"M22 2 15 22 11 13 2 9l20-7z"})]})}function Rl({sessionId:t,visitorId:e,isLoading:n,isStreaming:r,sessionStatus:i,ensureSession:s,onStartFresh:o}){const l=P(),a=Re(""),u=gt(Ie.functions.chat.public.conversations.send),d=n||r;if(i==="resolved")return h("div",{class:"jex-chat-input-resolved",children:[h("div",{class:"jex-resolved-notice",children:l.sessionResolved}),h("button",{class:"jex-resolved-new-btn",type:"button",onClick:()=>{o()},children:l.startNewConversation})]});async function c(){const p=a.value.trim();if(!p||d)return;const f=t&&e?{sessionId:t,visitorId:e}:await s();f&&(va(),a.value="",u({sessionId:f.sessionId,visitorId:f.visitorId,content:p}).catch(g=>{console.error("[jexity] Failed to send message:",g)}))}return h("div",{class:"jex-chat-input",children:[h("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"&&c()},disabled:d}),h("button",{class:"jex-send-btn",onClick:c,"aria-label":l.sendAriaLabel,disabled:d,children:h(Tl,{size:18})})]})}function qi({message:t}){return h("div",{class:"jex-overlay jex-loading",children:[h("div",{class:"jex-loading-spinner","aria-hidden":"true"}),t&&h("p",{class:"jex-loading-message",children:t})]})}function $l({greeting:t,orgSlug:e}){const n=P(),{sessionId:r,visitorId:i,isLoading:s,sessionNotFound:o,resumeFailed:l,isOrgDeleted:a,ensureSession:u,startFresh:d}=Ea(e),c=Xr(Ie.functions.chat.public.conversations.listBySession,r&&i?{sessionId:r,visitorId:i}:"skip"),p=Xr(Ie.functions.chat.public.sessions.getSessionStatus,r&&i?{sessionId:r,visitorId:i}:"skip"),f=r!==null&&c===void 0,g=c?.some(b=>b.status==="streaming")??!1;return Q(()=>{pe.value&&!r&&u()},[u,r]),a?h("div",{class:"jex-chat-messages",children:h("div",{class:"jex-session-notice",children:n.chatNoLongerAvailable})}):s||f&&pe.value?h(qi,{message:n.resumeConversation}):h(O,{children:[h(Cl,{conversations:c,greeting:t,sessionNotFound:o,resumeFailed:l,onStartFresh:d,sessionId:r,visitorId:i}),h(Rl,{sessionId:r,visitorId:i,isLoading:s,isStreaming:g,sessionStatus:p??null,ensureSession:u,onStartFresh:d})]})}function Al({formMessageId:t,sessionId:e,visitorId:n}){const r=P(),[i,s]=R(""),[o,l]=R(""),a=gt(Ie.functions.chat.public.helpdesk.submitEscalation);async function u(d){d.preventDefault(),Ae({id:"loading",message:r.escalationSubmitting});try{const c=await a({sessionId:e,visitorId:n,formMessageId:t,visitorName:i.trim(),visitorEmail:o.trim()});Ae({id:"confirmation",ref:c.ticketRef})}catch(c){console.error("[EscalationFormScreen] Submit failed:",c),Ae({id:"error",message:r.escalationSubmitFailed})}}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:r.escalationFormTitle}),h("p",{class:"jex-escalation-subtitle",children:r.escalationSubtitle}),h("form",{class:"jex-form",onSubmit:d=>{u(d)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:r.escalationNameLabel,value:i,required:!0,onInput:d=>{s(d.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:r.escalationEmailLabel,value:o,required:!0,onInput:d=>{l(d.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:r.escalationSubmit})]}),h("div",{class:"jex-inline-form-consent",style:{textAlign:"center",margin:"16px 0 8px 0"},children:r.escalationConsent}),h("button",{class:"jex-escalation-skip",type:"button",onClick:()=>{fn()},children:r.escalationSkip})]})}function Il(){const t=P(),[e,n]=R(""),[r,i]=R(""),[s,o]=R("");async function l(a){a.preventDefault(),Ae({id:"loading",message:t.submittingTicket}),await new Promise(d=>{setTimeout(d,1200)});const u="JEX-"+Math.random().toString(36).slice(2,8).toUpperCase();Ae({id:"confirmation",ref:u})}return h("div",{class:"jex-form-screen",children:[h("h2",{class:"jex-form-title",children:t.submitTicket}),h("form",{class:"jex-form",onSubmit:a=>{l(a)},children:[h("input",{class:"jex-form-input",type:"text",placeholder:t.yourName,value:e,required:!0,onInput:a=>{n(a.currentTarget.value)}}),h("input",{class:"jex-form-input",type:"email",placeholder:t.yourEmail,value:r,required:!0,onInput:a=>{i(a.currentTarget.value)}}),h("textarea",{class:"jex-form-textarea",placeholder:t.howCanWeHelp,value:s,required:!0,onInput:a=>{o(a.currentTarget.value)}}),h("button",{class:"jex-form-submit",type:"submit",children:t.submit})]})]})}function El({ticketRef:t}){const e=P();return h("div",{class:"jex-confirmation",children:[h("div",{class:"jex-confirmation-icon","aria-hidden":"true",children:"✓"}),h("h2",{class:"jex-confirmation-title",children:e.ticketSubmitted}),h("p",{class:"jex-confirmation-body",children:e.yourReferenceNumber}),h("div",{class:"jex-confirmation-ref",children:t}),h("p",{class:"jex-confirmation-hint",children:e.sentToEmailHint}),h("button",{class:"jex-confirmation-done",onClick:()=>{A.value=!1},children:e.done})]})}function ql({message:t,onRetry:e,onBack:n}){const r=P();return h("div",{class:"jex-overlay jex-error",children:[h("p",{class:"jex-error-message",children:t}),h("div",{class:"jex-error-actions",children:[e&&h("button",{class:"jex-error-retry",onClick:e,children:r.tryAgain}),n&&h("button",{class:"jex-error-back",onClick:n,children:r.goBack})]})]})}function Pi({greeting:t,title:e,orgSlug:n}){const r=B.value,i=r[r.length-1],s=r.findLast(o=>o.id==="confirmation");return h("div",{class:"jex-screen-container",children:[i.id==="home"&&h($a,{greeting:t,title:e}),i.id==="selection"&&h(Aa,{title:e}),i.id==="form"&&h(Il,{}),i.id==="escalation-form"&&h(Al,{formMessageId:i.formMessageId,sessionId:i.sessionId,visitorId:i.visitorId}),i.id==="confirmation"&&s&&h(El,{ticketRef:s.ref}),i.id==="chat"&&h($l,{greeting:t,orgSlug:n}),i.id==="loading"&&h(qi,{message:i.message}),i.id==="error"&&h(ql,{message:i.message,onRetry:()=>Ae({id:"loading"}),onBack:fn})]})}function Pl({options:t}){const e=ua(t.orgSlug,t.convexUrl);ma(t.parentOrigin),Q(()=>{ba()},[]);const n=la(t,e);Q(()=>{cn.value=di(n.locale)},[n.locale]);const r=n.position==="bottom-left",i=n.colorScheme==="dark"||n.colorScheme==="light"?n.colorScheme:"",s=_a({...t,primaryColor:n.primaryColor,accentColor:n.accentColor,fontFamily:n.fontFamily,fontSize:n.fontSize,borderRadius:n.borderRadius,windowWidth:n.windowWidth,windowHeight:n.windowHeight}),o=n.mode==="embedded",a=e!==null||o||!!t.parentOrigin?s:{...s,visibility:"hidden"};return h("div",{class:`jex-widget ${i}`.trim(),style:a,children:o?h("div",{class:"jex-embedded",children:[h(fi,{title:n.title}),h(Pi,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(pi,{})]}):h("div",{class:`jex-container${r?" jex-pos-left":""}`,children:[A.value&&h("div",{class:"jex-chat-window",children:[h(fi,{title:n.title}),h(Pi,{greeting:n.greeting,title:n.title,orgSlug:t.orgSlug}),!n.hideBranding&&h(pi,{})]}),h(Ra,{iconOption:n.triggerIcon,radius:n.triggerRadius,label:n.triggerLabel})]})})}const Ml='.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-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-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{display:block;font-size:10px;color:var(--jex-text-muted);margin-top:2px;padding-left:4px}.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}.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}';function Ll(t){const e=document.createElement("style");e.textContent=Ml,t.appendChild(e)}const Ol="https://festive-mouse-978.eu-west-1.convex.cloud";let jn=null;function Nl(t){const e=t??Ol;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 jn||(jn=new Vo(aa(e))),jn}function Ql(t,e){const n=t.shadowRoot??t.attachShadow({mode:"open"});for(;n.firstChild;)n.removeChild(n.firstChild);Ll(n),vt.value=e.source,ln.value=e.bootstrapToken,B.value=[{id:"home"}],e.mode==="embedded"&&(t.classList.add("jex-mode-embedded"),A.value=!0);const r=document.createElement("div");return e.mode==="embedded"&&(r.style.cssText="width:100%;height:100%"),n.appendChild(r),ue(h(Ho,{client:Nl(e.convexUrl),children:h(Pl,{options:e})}),r),function(){ue(null,r),A.value=!1,vt.value=void 0,ln.value=void 0,B.value=[{id:"home"}]}}function zl(t,e,n){const r=Ql(t,e),i=new Set,s=A.subscribe(l=>{for(const a of i)a(l)});return{shutdown(){s(),i.clear(),r(),n&&n()},open(){A.value=!0},close(){A.value=!1},toggle(){A.value=!A.value},get isOpen(){return A.value},subscribe(l){return i.add(l),()=>{i.delete(l)}}}}let tt=null;function Bl(t){tt&&tt.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=zl(e,t,()=>{t.container||e.remove(),tt===n&&(tt=null)});return tt=n,n}async function Fl(t,e){try{const n=await fetch(`${e}/widget/bootstrap`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({orgSlug:t}),credentials:"omit"});if(n.ok){const r=await n.json();return{ok:!0,token:r.token,excludePaths:r.excludePaths}}return n.status===403?{ok:!1,error:"unauthorized"}:n.status===404?{ok:!1,error:"not_found"}:{ok:!1,error:"network"}}catch{return{ok:!1,error:"network"}}}function ae(t,e){return t.getAttribute(e)??void 0}async function Mi(){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=ae(t,"data-convex-url")??"https://festive-mouse-978.eu-west-1.convex.cloud"??"",r=ui(n),i=await Fl(e,r);if(!i.ok){const o=window.location.origin;i.error==="unauthorized"?console.warn(`[JexityChat] This domain is not authorized for org '${e}'. Add '${o}' under Allowed Domains in your Jexity dashboard.`):i.error==="not_found"?console.warn(`[JexityChat] No active widget config found for org '${e}'. Check that the org slug is correct and the widget is enabled.`):console.warn(`[JexityChat] Bootstrap failed (network error). Check that the Convex deployment is reachable at ${r}.`);return}const s={orgSlug:e,bootstrapToken:i.token,position:ae(t,"data-position")??void 0,theme:ae(t,"data-theme")??void 0,greeting:ae(t,"data-greeting"),title:ae(t,"data-title"),primaryColor:ae(t,"data-primary-color"),locale:ae(t,"data-locale"),convexUrl:ae(t,"data-convex-url")};window.JexityChat=Bl(s)}document.readyState==="complete"?Mi():window.addEventListener("load",Mi)})();
|
|
61
61
|
//# sourceMappingURL=widget.js.map
|