z)for(;S<=O;)pe(p[S],T,k,!0),S++;else{const G=S,re=S,me=new Map;for(S=re;S<=z;S++){const Ye=d[S]=E?Yt(d[S]):Tt(d[S]);Ye.key!=null&&me.set(Ye.key,S)}let ce,Ne=0;const Re=z-re+1;let Qe=!1,et=0;const tn=new Array(Re);for(S=0;S=Re){pe(Ye,T,k,!0);continue}let rt;if(Ye.key!=null)rt=me.get(Ye.key);else for(ce=re;ce<=z;ce++)if(tn[ce-re]===0&&fn(Ye,d[ce])){rt=ce;break}rt===void 0?pe(Ye,T,k,!0):(tn[rt-re]=S+1,rt>=et?et=rt:Qe=!0,_(Ye,d[rt],x,null,T,k,P,I,E),Ne++)}const os=Qe?mu(tn):pt;for(ce=os.length-1,S=Re-1;S>=0;S--){const Ye=re+S,rt=d[Ye],In=d[Ye+1],Ht=Ye+1 {const{el:k,type:P,transition:I,children:E,shapeFlag:S}=p;if(S&6){M(p.component.subTree,d,x,y);return}if(S&128){p.suspense.move(d,x,y);return}if(S&64){P.move(p,d,x,j);return}if(P===Be){s(k,d,x);for(let O=0;OI.enter(k),T);else{const{leave:O,delayLeave:z,afterLeave:G}=I,re=()=>{p.ctx.isUnmounted?r(k):s(k,d,x)},me=()=>{O(k,()=>{re(),G&&G()})};z?z(k,re,me):me()}else s(k,d,x)},pe=(p,d,x,y=!1,T=!1)=>{const{type:k,props:P,ref:I,children:E,dynamicChildren:S,shapeFlag:q,patchFlag:O,dirs:z,cacheIndex:G}=p;if(O===-2&&(T=!1),I!=null&&(It(),Vn(I,null,x,p,!0),Ot()),G!=null&&(d.renderCache[G]=void 0),q&256){d.ctx.deactivate(p);return}const re=q&1&&z,me=!qn(p);let ce;if(me&&(ce=P&&P.onVnodeBeforeUnmount)&&kt(ce,d,p),q&6)bt(p.component,x,y);else{if(q&128){p.suspense.unmount(x,y);return}re&&an(p,null,d,"beforeUnmount"),q&64?p.type.remove(p,d,x,j,y):S&&!S.hasOnce&&(k!==Be||O>0&&O&64)?Me(S,d,x,!1,!0):(k===Be&&O&384||!T&&q&16)&&Me(E,d,x),y&&Ve(p)}(me&&(ce=P&&P.onVnodeUnmounted)||re)&&it(()=>{ce&&kt(ce,d,p),re&&an(p,null,d,"unmounted")},x)},Ve=p=>{const{type:d,el:x,anchor:y,transition:T}=p;if(d===Be){Te(x,y);return}if(d===Ar){$(p);return}const k=()=>{r(x),T&&!T.persisted&&T.afterLeave&&T.afterLeave()};if(p.shapeFlag&1&&T&&!T.persisted){const{leave:P,delayLeave:I}=T,E=()=>P(x,k);I?I(p.el,k,E):E()}else k()},Te=(p,d)=>{let x;for(;p!==d;)x=g(p),r(p),p=x;r(d)},bt=(p,d,x)=>{const{bum:y,scope:T,job:k,subTree:P,um:I,m:E,a:S,parent:q,slots:{__:O}}=p;go(E),go(S),y&&ps(y),q&&Q(O)&&O.forEach(z=>{q.renderCache[z]=void 0}),T.stop(),k&&(k.flags|=8,pe(P,p,d,x)),I&&it(I,d),it(()=>{p.isUnmounted=!0},d),d&&d.pendingBranch&&!d.isUnmounted&&p.asyncDep&&!p.asyncResolved&&p.suspenseId===d.pendingId&&(d.deps--,d.deps===0&&d.resolve())},Me=(p,d,x,y=!1,T=!1,k=0)=>{for(let P=k;P {if(p.shapeFlag&6)return Ft(p.component.subTree);if(p.shapeFlag&128)return p.suspense.next();const d=g(p.anchor||p.el),x=d&&d[Za];return x?g(x):d};let Bt=!1;const xn=(p,d,x)=>{p==null?d._vnode&&pe(d._vnode,null,null,!0):_(d._vnode||null,p,d,null,null,null,x),d._vnode=p,Bt||(Bt=!0,Vi(),qi(),Bt=!1)},j={p:_,um:pe,m:M,r:Ve,mt:Ae,mc:te,pc:ye,pbc:X,n:Ft,o:e};return{render:xn,hydrate:void 0,createApp:iu(xn)}}function Er({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function un({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function gu(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function po(e,t,n=!1){const s=e.children,r=t.children;if(Q(s)&&Q(r))for(let i=0;i >1,e[n[a]] 0&&(t[s]=n[i-1]),n[i]=s)}}for(i=n.length,o=n[i-1];i-- >0;)n[i]=o,o=t[o];return n}function ho(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:ho(t)}function go(e){if(e)for(let t=0;t ou(bu);function cn(e,t,n){return yu(e,t,n)}function yu(e,t,n=ie){const{immediate:s,deep:r,flush:i,once:o}=n,a=dt({},n),l=t&&s||!t&&i!=="post";let f;if(Zn){if(i==="sync"){const w=xu();f=w.__watcherHandles||(w.__watcherHandles=[])}else if(!l){const w=()=>{};return w.stop=sn,w.resume=sn,w.pause=sn,w}}const u=Zt;a.call=(w,A,_)=>yt(w,u,A,_);let h=!1;i==="post"?a.scheduler=w=>{it(w,u&&u.suspense)}:i!=="sync"&&(h=!0,a.scheduler=(w,A)=>{A?w():br(w)}),a.augmentJob=w=>{t&&(w.flags|=4),h&&(w.flags|=2,u&&(w.id=u.uid,w.i=u))};const g=za(e,t,a);return Zn&&(f?f.push(g):l&&g()),g}const wu=(e,t)=>t==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${jt(t)}Modifiers`]||e[`${rn(t)}Modifiers`];function vu(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||ie;let r=n;const i=t.startsWith("update:"),o=i&&wu(s,t.slice(7));o&&(o.trim&&(r=n.map(u=>Ce(u)?u.trim():u)),o.number&&(r=n.map(tr)));let a,l=s[a=Qs(t)]||s[a=Qs(jt(t))];!l&&i&&(l=s[a=Qs(rn(t))]),l&&yt(l,e,6,r);const f=s[a+"Once"];if(f){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,yt(f,e,6,r)}}function _u(e,t,n=!1){const s=t.emitsCache,r=s.get(e);if(r!==void 0)return r;const i=e.emits;let o={};return i?(Q(i)?i.forEach(a=>o[a]=null):dt(o,i),Ee(e)&&s.set(e,o),o):(Ee(e)&&s.set(e,null),null)}function Cs(e,t){return!e||!us(t)?!1:(t=t.slice(2).replace(/Once$/,""),he(e,t[0].toLowerCase()+t.slice(1))||he(e,rn(t))||he(e,t))}function ih(){}function mo(e){const{type:t,vnode:n,proxy:s,withProxy:r,propsOptions:[i],slots:o,attrs:a,emit:l,render:f,renderCache:u,props:h,data:g,setupState:w,ctx:A,inheritAttrs:_}=e,F=Ss(e);let b,U;try{if(n.shapeFlag&4){const $=r||s,Y=$;b=Tt(f.call(Y,$,u,h,w,g,A)),U=a}else{const $=t;b=Tt($.length>1?$(h,{attrs:a,slots:o,emit:l}):$(h,null)),U=t.props?a:Tu(a)}}catch($){Kn.length=0,Ts($,e,1),b=Oe(Xe)}let Z=b;if(U&&_!==!1){const $=Object.keys(U),{shapeFlag:Y}=Z;$.length&&Y&7&&(i&&$.some(Xs)&&(U=ku(U,i)),Z=Kt(Z,U,!1,!0))}return n.dirs&&(Z=Kt(Z,null,!1,!0),Z.dirs=Z.dirs?Z.dirs.concat(n.dirs):n.dirs),n.transition&&jn(Z,n.transition),b=Z,Ss(F),b}const Tu=e=>{let t;for(const n in e)(n==="class"||n==="style"||us(n))&&((t||(t={}))[n]=e[n]);return t},ku=(e,t)=>{const n={};for(const s in e)(!Xs(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function Su(e,t,n){const{props:s,children:r,component:i}=e,{props:o,children:a,patchFlag:l}=t,f=i.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&l>=0){if(l&1024)return!0;if(l&16)return s?bo(s,o,f):!!o;if(l&8){const u=t.dynamicProps;for(let h=0;h e.__isSuspense;function Au(e,t){t&&t.pendingBranch?Q(e)?t.effects.push(...e):t.effects.push(e):Ka(e)}const Be=Symbol.for("v-fgt"),Ps=Symbol.for("v-txt"),Xe=Symbol.for("v-cmt"),Ar=Symbol.for("v-stc"),Kn=[];let ot=null;function H(e=!1){Kn.push(ot=e?null:[])}function Ru(){Kn.pop(),ot=Kn[Kn.length-1]||null}let Yn=1;function yo(e,t=!1){Yn+=e,e<0&&ot&&t&&(ot.hasOnce=!0)}function wo(e){return e.dynamicChildren=Yn>0?ot||pt:null,Ru(),Yn>0&&ot&&ot.push(e),e}function K(e,t,n,s,r,i){return wo(v(e,t,n,s,r,i,!0))}function _t(e,t,n,s,r){return wo(Oe(e,t,n,s,r,!0))}function Is(e){return e?e.__v_isVNode===!0:!1}function fn(e,t){return e.type===t.type&&e.key===t.key}const vo=({key:e})=>e!=null?e:null,Os=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?Ce(e)||We(e)||be(e)?{i:at,r:e,k:t,f:!!n}:e:null);function v(e,t=null,n=null,s=0,r=null,i=e===Be?0:1,o=!1,a=!1){const l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&vo(t),ref:t&&Os(t),scopeId:Gi,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:i,patchFlag:s,dynamicProps:r,dynamicChildren:null,appContext:null,ctx:at};return a?(Rr(l,n),i&128&&e.normalize(l)):n&&(l.shapeFlag|=Ce(n)?8:16),Yn>0&&!o&&ot&&(l.patchFlag>0||i&6)&&l.patchFlag!==32&&ot.push(l),l}const Oe=Cu;function Cu(e,t=null,n=null,s=0,r=null,i=!1){if((!e||e===nu)&&(e=Xe),Is(e)){const a=Kt(e,t,!0);return n&&Rr(a,n),Yn>0&&!i&&ot&&(a.shapeFlag&6?ot[ot.indexOf(e)]=a:ot.push(a)),a.patchFlag=-2,a}if(Uu(e)&&(e=e.__vccOpts),t){t=Pu(t);let{class:a,style:l}=t;a&&!Ce(a)&&(t.class=we(a)),Ee(l)&&(gr(l)&&!Q(l)&&(l=dt({},l)),t.style=nr(l))}const o=Ce(e)?1:xo(e)?128:Yi(e)?64:Ee(e)?4:be(e)?2:0;return v(e,t,n,s,r,o,i,!0)}function Pu(e){return e?gr(e)||oo(e)?dt({},e):e:null}function Kt(e,t,n=!1,s=!1){const{props:r,ref:i,patchFlag:o,children:a,transition:l}=e,f=t?Iu(r||{},t):r,u={__v_isVNode:!0,__v_skip:!0,type:e.type,props:f,key:f&&vo(f),ref:t&&t.ref?n&&i?Q(i)?i.concat(Os(t)):[i,Os(t)]:Os(t):i,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==Be?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:l,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Kt(e.ssContent),ssFallback:e.ssFallback&&Kt(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return l&&s&&jn(u,l.clone(u)),u}function Ms(e=" ",t=0){return Oe(Ps,null,e,t)}function Ge(e="",t=!1){return t?(H(),_t(Xe,null,e)):Oe(Xe,null,e)}function Tt(e){return e==null||typeof e=="boolean"?Oe(Xe):Q(e)?Oe(Be,null,e.slice()):Is(e)?Yt(e):Oe(Ps,null,String(e))}function Yt(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Kt(e)}function Rr(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(Q(t))n=16;else if(typeof t=="object")if(s&65){const r=t.default;r&&(r._c&&(r._d=!1),Rr(e,r()),r._c&&(r._d=!0));return}else{n=32;const r=t._;!r&&!oo(t)?t._ctx=at:r===3&&at&&(at.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else be(t)?(t={default:t,_ctx:at},n=32):(t=String(t),s&64?(n=16,t=[Ms(t)]):n=8);e.children=t,e.shapeFlag|=n}function Iu(...e){const t={};for(let n=0;n Zt||at;let Ls,Cr;{const e=ds(),t=(n,s)=>{let r;return(r=e[n])||(r=e[n]=[]),r.push(s),i=>{r.length>1?r.forEach(o=>o(i)):r[0](i)}};Ls=t("__VUE_INSTANCE_SETTERS__",n=>Zt=n),Cr=t("__VUE_SSR_SETTERS__",n=>Zn=n)}const Pr=e=>{const t=Zt;return Ls(e),e.scope.on(),()=>{e.scope.off(),Ls(t)}},To=()=>{Zt&&Zt.scope.off(),Ls(null)};function ko(e){return e.vnode.shapeFlag&4}let Zn=!1;function $u(e,t=!1,n=!1){t&&Cr(t);const{props:s,children:r}=e.vnode,i=ko(e);lu(e,s,i,t),fu(e,r,n||t);const o=i?Nu(e,t):void 0;return t&&Cr(!1),o}function Nu(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,su);const{setup:s}=n;if(s){It();const r=e.setupContext=s.length>1?Fu(e):null,i=Pr(e),o=Tn(s,e,0,[e.props,r]),a=di(o);if(Ot(),i(),(a||e.sp)&&!qn(e)&&eu(e),a){if(o.then(To,To),t)return o.then(l=>{So(e,l)}).catch(l=>{Ts(l,e,0)});e.asyncDep=o}else So(e,o)}else Eo(e)}function So(e,t,n){be(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:Ee(t)&&(e.setupState=Hi(t)),Eo(e)}function Eo(e,t,n){const s=e.type;e.render||(e.render=s.render||sn)}const Du={get(e,t){return qe(e,"get",""),e[t]}};function Fu(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,Du),slots:e.slots,emit:e.emit,expose:t}}function $s(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Hi(Ma(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Gn)return Gn[n](e)},has(t,n){return n in t||n in Gn}})):e.proxy}const Bu=/(?:^|[-_])(\w)/g,Hu=e=>e.replace(Bu,t=>t.toUpperCase()).replace(/[-_]/g,"");function zu(e,t=!0){return be(e)?e.displayName||e.name:e.name||t&&e.__name}function Ao(e,t,n=!1){let s=zu(t);if(!s&&t.__file){const r=t.__file.match(/([^/\\]+)\.\w+$/);r&&(s=r[1])}if(!s&&e&&e.parent){const r=i=>{for(const o in i)if(i[o]===t)return o};s=r(e.components||e.parent.type.components)||r(e.appContext.components)}return s?Hu(s):n?"App":"Anonymous"}function Uu(e){return be(e)&&"__vccOpts"in e}const ke=(e,t)=>Ba(e,t,Zn);function ju(e,t,n){const s=arguments.length;return s===2?Ee(t)&&!Q(t)?Is(t)?Oe(e,null,[t]):Oe(e,t):Oe(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&Is(n)&&(n=[n]),Oe(e,t,n))}const Vu="3.5.18";let Ir;const Ro=typeof window!="undefined"&&window.trustedTypes;if(Ro)try{Ir=Ro.createPolicy("vue",{createHTML:e=>e})}catch{}const Co=Ir?e=>Ir.createHTML(e):e=>e,qu="http://www.w3.org/2000/svg",Wu="http://www.w3.org/1998/Math/MathML",Nt=typeof document!="undefined"?document:null,Po=Nt&&Nt.createElement("template"),Gu={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const r=t==="svg"?Nt.createElementNS(qu,e):t==="mathml"?Nt.createElementNS(Wu,e):n?Nt.createElement(e,{is:n}):Nt.createElement(e);return e==="select"&&s&&s.multiple!=null&&r.setAttribute("multiple",s.multiple),r},createText:e=>Nt.createTextNode(e),createComment:e=>Nt.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Nt.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,r,i){const o=n?n.previousSibling:t.lastChild;if(r&&(r===i||r.nextSibling))for(;t.insertBefore(r.cloneNode(!0),n),!(r===i||!(r=r.nextSibling)););else{Po.innerHTML=Co(s==="svg"?``:s==="mathml"?``:e);const a=Po.content;if(s==="svg"||s==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Xt="transition",Xn="animation",Jn=Symbol("_vtc"),Io={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},Ku=dt({},Zi,Io),Yu=(e=>(e.displayName="Transition",e.props=Ku,e))((e,{slots:t})=>ju(Qa,Zu(e),t)),pn=(e,t=[])=>{Q(e)?e.forEach(n=>n(...t)):e&&e(...t)},Oo=e=>e?Q(e)?e.some(t=>t.length>1):e.length>1:!1;function Zu(e){const t={};for(const B in e)B in Io||(t[B]=e[B]);if(e.css===!1)return t;const{name:n="v",type:s,duration:r,enterFromClass:i=`${n}-enter-from`,enterActiveClass:o=`${n}-enter-active`,enterToClass:a=`${n}-enter-to`,appearFromClass:l=i,appearActiveClass:f=o,appearToClass:u=a,leaveFromClass:h=`${n}-leave-from`,leaveActiveClass:g=`${n}-leave-active`,leaveToClass:w=`${n}-leave-to`}=e,A=Xu(r),_=A&&A[0],F=A&&A[1],{onBeforeEnter:b,onEnter:U,onEnterCancelled:Z,onLeave:$,onLeaveCancelled:Y,onBeforeAppear:C=b,onAppear:N=U,onAppearCancelled:te=Z}=t,W=(B,ge,Ae,je)=>{B._enterCancelled=je,dn(B,ge?u:a),dn(B,ge?f:o),Ae&&Ae()},X=(B,ge)=>{B._isLeaving=!1,dn(B,h),dn(B,w),dn(B,g),ge&&ge()},ue=B=>(ge,Ae)=>{const je=B?N:U,J=()=>W(ge,B,Ae);pn(je,[ge,J]),Mo(()=>{dn(ge,B?l:i),Dt(ge,B?u:a),Oo(je)||Lo(ge,s,_,J)})};return dt(t,{onBeforeEnter(B){pn(b,[B]),Dt(B,i),Dt(B,o)},onBeforeAppear(B){pn(C,[B]),Dt(B,l),Dt(B,f)},onEnter:ue(!1),onAppear:ue(!0),onLeave(B,ge){B._isLeaving=!0;const Ae=()=>X(B,ge);Dt(B,h),B._enterCancelled?(Dt(B,g),Do()):(Do(),Dt(B,g)),Mo(()=>{B._isLeaving&&(dn(B,h),Dt(B,w),Oo($)||Lo(B,s,F,Ae))}),pn($,[B,Ae])},onEnterCancelled(B){W(B,!1,void 0,!0),pn(Z,[B])},onAppearCancelled(B){W(B,!0,void 0,!0),pn(te,[B])},onLeaveCancelled(B){X(B),pn(Y,[B])}})}function Xu(e){if(e==null)return null;if(Ee(e))return[Or(e.enter),Or(e.leave)];{const t=Or(e);return[t,t]}}function Or(e){return oa(e)}function Dt(e,t){t.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[Jn]||(e[Jn]=new Set)).add(t)}function dn(e,t){t.split(/\s+/).forEach(s=>s&&e.classList.remove(s));const n=e[Jn];n&&(n.delete(t),n.size||(e[Jn]=void 0))}function Mo(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let Ju=0;function Lo(e,t,n,s){const r=e._endId=++Ju,i=()=>{r===e._endId&&s()};if(n!=null)return setTimeout(i,n);const{type:o,timeout:a,propCount:l}=Qu(e,t);if(!o)return s();const f=o+"end";let u=0;const h=()=>{e.removeEventListener(f,g),i()},g=w=>{w.target===e&&++u>=l&&h()};setTimeout(()=>{u (n[A]||"").split(", "),r=s(`${Xt}Delay`),i=s(`${Xt}Duration`),o=$o(r,i),a=s(`${Xn}Delay`),l=s(`${Xn}Duration`),f=$o(a,l);let u=null,h=0,g=0;t===Xt?o>0&&(u=Xt,h=o,g=i.length):t===Xn?f>0&&(u=Xn,h=f,g=l.length):(h=Math.max(o,f),u=h>0?o>f?Xt:Xn:null,g=u?u===Xt?i.length:l.length:0);const w=u===Xt&&/\b(transform|all)(,|$)/.test(s(`${Xt}Property`).toString());return{type:u,timeout:h,propCount:g,hasTransform:w}}function $o(e,t){for(;e.length No(n)+No(e[s])))}function No(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function Do(){return document.body.offsetHeight}function ec(e,t,n){const s=e[Jn];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const Fo=Symbol("_vod"),tc=Symbol("_vsh"),nc=Symbol(""),sc=/(^|;)\s*display\s*:/;function rc(e,t,n){const s=e.style,r=Ce(n);let i=!1;if(n&&!r){if(t)if(Ce(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();n[a]==null&&Ns(s,a,"")}else for(const o in t)n[o]==null&&Ns(s,o,"");for(const o in n)o==="display"&&(i=!0),Ns(s,o,n[o])}else if(r){if(t!==n){const o=s[nc];o&&(n+=";"+o),s.cssText=n,i=sc.test(n)}}else t&&e.removeAttribute("style");Fo in e&&(e[Fo]=i?s.display:"",e[tc]&&(s.display="none"))}const Bo=/\s*!important$/;function Ns(e,t,n){if(Q(n))n.forEach(s=>Ns(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))e.setProperty(t,n);else{const s=ic(e,t);Bo.test(n)?e.setProperty(rn(s),n.replace(Bo,""),"important"):e[s]=n}}const Ho=["Webkit","Moz","ms"],Mr={};function ic(e,t){const n=Mr[t];if(n)return n;let s=jt(t);if(s!=="filter"&&s in e)return Mr[t]=s;s=mi(s);for(let r=0;r Lr||(uc.then(()=>Lr=0),Lr=Date.now());function fc(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;yt(pc(s,n.value),t,5,[s])};return n.value=e,n.attached=cc(),n}function pc(e,t){if(Q(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map(s=>r=>!r._stopped&&s&&s(r))}else return t}const Wo=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,dc=(e,t,n,s,r,i)=>{const o=r==="svg";t==="class"?ec(e,s,o):t==="style"?rc(e,n,s):us(t)?Xs(t)||lc(e,t,n,s,i):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):hc(e,t,s,o))?(jo(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&Uo(e,t,s,o,i,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!Ce(s))?jo(e,jt(t),s,i,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),Uo(e,t,s,o))};function hc(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&Wo(t)&&be(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const r=e.tagName;if(r==="IMG"||r==="VIDEO"||r==="CANVAS"||r==="SOURCE")return!1}return Wo(t)&&Ce(n)?!1:t in e}const Go=e=>{const t=e.props["onUpdate:modelValue"]||!1;return Q(t)?n=>ps(t,n):t};function gc(e){e.target.composing=!0}function Ko(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const $r=Symbol("_assign"),mc={created(e,{modifiers:{lazy:t,trim:n,number:s}},r){e[$r]=Go(r);const i=s||r.props&&r.props.type==="number";An(e,t?"change":"input",o=>{if(o.target.composing)return;let a=e.value;n&&(a=a.trim()),i&&(a=tr(a)),e[$r](a)}),n&&An(e,"change",()=>{e.value=e.value.trim()}),t||(An(e,"compositionstart",gc),An(e,"compositionend",Ko),An(e,"change",Ko))},mounted(e,{value:t}){e.value=t==null?"":t},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:r,number:i}},o){if(e[$r]=Go(o),e.composing)return;const a=(i||e.type==="number")&&!/^0\d/.test(e.value)?tr(e.value):e.value,l=t==null?"":t;a!==l&&(document.activeElement===e&&e.type!=="range"&&(s&&t===n||r&&e.value.trim()===l)||(e.value=l))}},bc=["ctrl","shift","alt","meta"],xc={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>bc.some(n=>e[`${n}Key`]&&!t.includes(n))},ct=(e,t)=>{const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=(r,...i)=>{for(let o=0;o {const t=wc().createApp(...e),{mount:n}=t;return t.mount=s=>{const r=Tc(s);if(!r)return;const i=t._component;!be(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent="");const o=n(r,!1,_c(r));return r instanceof Element&&(r.removeAttribute("v-cloak"),r.setAttribute("data-v-app","")),o},t};function _c(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Tc(e){return Ce(e)?document.querySelector(e):e}const kc=["aria-pressed"],Sc={key:0,viewBox:"0 0 24 24",width:"20",height:"20","aria-hidden":"true"},Ec={key:1,viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",fill:"none"},Ac={__name:"ChatbotToggler",props:{isOpen:{type:Boolean,required:!0}},emits:["toggle"],setup(e){return(t,n)=>(H(),K("button",{class:"fixed bottom-5 right-5 z-9999 grid h-12 w-12 appearance-none place-items-center rounded-full border border-white/20 bg-gradient-to-br from-brand-500 to-brand-600 text-white shadow-[0_20px_36px_-20px_rgba(109,79,194,0.85)] transition-all duration-250 hover:-translate-y-0.5 hover:from-brand-600 hover:to-violet-700 hover:shadow-[0_22px_40px_-22px_rgba(109,79,194,1)] focus:outline-none max-[600px]:bottom-3 max-[600px]:right-3 max-[600px]:h-13 max-[600px]:w-13",style:{"border-radius":"9999px"},"aria-pressed":e.isOpen?"true":"false",onClick:n[0]||(n[0]=s=>t.$emit("toggle"))},[e.isOpen?(H(),K("svg",Ec,n[2]||(n[2]=[v("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round"},null,-1)]))):(H(),K("svg",Sc,n[1]||(n[1]=[v("path",{d:"M4 4h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8l-4 4v-4H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z",fill:"currentColor",stroke:"currentColor","stroke-width":"2","stroke-linecap":"miter","stroke-linejoin":"miter"},null,-1)])))],8,kc))}},Rc={class:"chat-header relative flex min-h-14 items-center justify-between px-4 pb-2.5 pt-3 text-white sm:px-5"},Cc={class:"flex min-w-0 flex-1 items-center gap-2 sm:gap-2.5"},Pc={xmlns:"http://www.w3.org/2000/svg",width:"35",height:"35",viewBox:"0 0 1024 1024",class:"h-8 w-8 shrink-0 rounded-full bg-white p-1.5 shadow-md motion-safe:animate-soft-float",style:{fill:"#6d4fc2"}},Ic={class:"ml-2 flex items-center gap-1.5"},Oc=["title"],Mc=["title","aria-label"],Lc={key:0,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},$c={key:1,viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Nc=["title","aria-label"],Dc={key:0,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Fc={key:1,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Bc={key:2,xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Hc={__name:"ChatHeader",props:{windowMode:{type:String,required:!0},autoReadEnabled:{type:Boolean,required:!0},activeTtsProvider:{type:String,required:!0}},emits:["close","cycleResize","toggleAutoRead"],setup(e){const t=e,n={default:"Compact",half:"Half Screen",full:"Full Screen"},s=ke(()=>n[t.windowMode]||"Compact"),r=ke(()=>t.windowMode==="default"?"Half Screen":t.windowMode==="half"?"Full Screen":"Compact"),i=ke(()=>t.activeTtsProvider==="polly"?"TTS: Polly":t.activeTtsProvider==="browser"?"TTS: Browser":"TTS: Off"),o=ke(()=>t.activeTtsProvider==="polly"?"bg-emerald-500/45":t.activeTtsProvider==="browser"?"bg-amber-500/45":"bg-slate-500/35");return(a,l)=>(H(),K("div",Rc,[v("div",Cc,[(H(),K("svg",Pc,l[3]||(l[3]=[v("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))),l[4]||(l[4]=v("h2",{class:"truncate text-xs font-semibold tracking-[0.01em] sm:text-base text-white/95"},"ChangAI from ERPGulf",-1))]),v("div",Ic,[v("span",{class:we(["hidden rounded-full border border-white/25 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-white/95 shadow-sm backdrop-blur-sm sm:inline",o.value]),title:`TTS provider: ${i.value}`},nt(i.value),11,Oc),v("button",{class:we(["h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none sm:flex",e.autoReadEnabled?"bg-white/24 shadow-sm":"hover:bg-white/15"]),style:{"border-radius":"0.375rem"},title:e.autoReadEnabled?"Auto speech on":"Auto speech off","aria-label":e.autoReadEnabled?"Turn off auto speech":"Turn on auto speech",onClick:l[0]||(l[0]=f=>a.$emit("toggleAutoRead"))},[e.autoReadEnabled?(H(),K("svg",Lc,l[5]||(l[5]=[v("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),v("path",{d:"M15 9a4 4 0 0 1 0 6"},null,-1),v("path",{d:"M18 7a7 7 0 0 1 0 10"},null,-1)]))):(H(),K("svg",$c,l[6]||(l[6]=[v("path",{d:"M11 5L6 9H3v6h3l5 4V5z"},null,-1),v("path",{d:"M22 9l-6 6"},null,-1),v("path",{d:"M16 9l6 6"},null,-1)])))],10,Mc),v("button",{class:we(["flex h-8 min-w-8 appearance-none items-center justify-center rounded-md border border-white/20 px-2 text-xs font-semibold text-white/90 transition-all duration-200 focus:outline-none","bg-white/20 shadow-sm hover:bg-white/25"]),style:{"border-radius":"0.375rem"},title:`Resize mode: ${s.value} (click to ${r.value})`,"aria-label":`Resize mode ${s.value}. Click to switch to ${r.value}`,onClick:l[1]||(l[1]=f=>a.$emit("cycleResize"))},[e.windowMode==="default"?(H(),K("svg",Dc,l[7]||(l[7]=[v("rect",{x:"7",y:"8",width:"10",height:"8",rx:"2"},null,-1)]))):e.windowMode==="half"?(H(),K("svg",Fc,l[8]||(l[8]=[v("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),v("path",{d:"M12 5v14"},null,-1)]))):(H(),K("svg",Bc,l[9]||(l[9]=[v("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2"},null,-1),v("path",{d:"M8 8H6v2M16 8h2v2M8 16H6v-2M16 16h2v-2"},null,-1)])))],8,Nc),v("button",{class:"grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-white/20 text-white transition-all duration-200 hover:scale-105 hover:bg-white/20 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/70",style:{"border-radius":"9999px"},"aria-label":"Close chatbot",onClick:l[2]||(l[2]=f=>a.$emit("close"))},l[10]||(l[10]=[v("svg",{xmlns:"http://www.w3.org/2000/svg",height:"24",width:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[v("path",{d:"M6 9l6 6 6-6"})],-1)]))])]))}},zc={class:"flex gap-1.5 border-b border-slate-200/80 px-2.5 pb-2.5 pt-1"},Uc=["onClick"],jc={class:"inline-flex items-center gap-1.5"},Vc={__name:"TabBar",props:{modelValue:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1}},emits:["update:modelValue"],setup(e){const t=e,n=ke(()=>{const s=[{id:"chat",label:"Chats"},{id:"debug",label:"Debug"},{id:"support",label:"Support"},{id:"settings",label:"Settings"}];return t.debugEnabled?s:s.filter(r=>r.id!=="debug")});return(s,r)=>(H(),K("div",zc,[(H(!0),K(Be,null,Rs(n.value,i=>(H(),K("button",{key:i.id,class:we(["group min-w-0 flex-1 h-9 appearance-none rounded-lg border border-transparent bg-transparent px-2 text-xs font-semibold transition-all duration-200 focus:outline-none",e.modelValue===i.id?"border-white/30 bg-linear-to-r from-violet-300/36 via-indigo-300/30 to-sky-300/28 text-white shadow-[0_4px_10px_rgba(20,24,40,0.22)]":"text-white/80 hover:border-white/25 hover:bg-white/12 hover:text-white"]),onClick:o=>s.$emit("update:modelValue",i.id)},[v("span",jc,[v("span",{class:we(["h-1.5 w-1.5 rounded-full transition-colors duration-200",e.modelValue===i.id?"bg-white":"bg-white/40 group-hover:bg-white/70"])},null,2),Ms(" "+nt(i.label),1)])],10,Uc))),128))]))}},qc=(e,t)=>{const n=e.__vccOpts||e;for(const[s,r]of t)n[s]=r;return n},Wc={},Gc={xmlns:"http://www.w3.org/2000/svg",width:"50",height:"50",viewBox:"0 0 1024 1024",class:"h-7.5 w-7.5 shrink-0 self-end rounded-full bg-gradient-to-br from-brand-500 to-brand-600 p-1.5 fill-white shadow-[0_10px_18px_-12px_rgba(109,79,194,0.85)]"};function Kc(e,t){return H(),K("svg",Gc,t[0]||(t[0]=[v("path",{d:"M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"},null,-1)]))}const Zo=qc(Wc,[["render",Kc]]),Xo=18e4,Ds={PIPELINE:"changai.changai.api.v2.text2sql_pipeline_v2.run_text2sql_pipeline",SUPPORT:"changai.changai.api.v2.helpdesk_api.support_bot",SETTINGS:"changai.changai.api.v2.schema_utils.get_frontend_settings",TTS:"changai.changai.api.v2.tts.synthesize_tts"};function Jo(e,t={},n="actual"){return n==="test"?Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify(t)}`}):!window.frappe||!window.frappe.call?Promise.reject(new Error("Frappe API is unavailable in actual mode.")):new Promise((s,r)=>{window.frappe.call({method:e,args:t,callback(i){s(i.message)},error(i){r(i)}})})}function Yc(e,t,n="actual",s=null,r){if(n==="test")return{promise:Promise.resolve({Bot:`[TEST MODE] ${JSON.stringify({user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r})}`}),cancel:()=>!1};if(!window.frappe||!window.frappe.call)return{promise:Promise.reject(new Error("Frappe API is unavailable in actual mode.")),cancel:()=>!1};let i=null,o=!1,a=null;return{promise:new Promise((u,h)=>{i=window.frappe.call({method:Ds.PIPELINE,args:{user_question:e,chat_id:t,request_id:s,sendNonErptoAI:r},callback(g){o||(o=!0,clearTimeout(a),u(g.message))},error(g){o||(o=!0,clearTimeout(a),h(g!=null?g:new Error("Request failed without a response from the server.")))}}),a=setTimeout(()=>{if(o)return;o=!0,i&&typeof i.abort=="function"&&i.abort();const g=new Error("Request timed out");g.code="CHANGAI_TIMEOUT",h(g)},Xo)}),cancel:()=>o||!i||typeof i.abort!="function"?!1:(i.abort(),o=!0,clearTimeout(a),!0)}}function Zc(e,t="actual"){if(t==="test")return{promise:Promise.resolve(`[TEST MODE] ${JSON.stringify({message:e})}`),cancel:()=>!1};if(!window.frappe||!window.frappe.call)return{promise:Promise.reject(new Error("Frappe API is unavailable in actual mode.")),cancel:()=>!1};let n=null,s=!1;return{promise:new Promise((o,a)=>{n=window.frappe.call({method:Ds.SUPPORT,args:{message:e},callback(l){s=!0,o(l.message)},error(l){s=!0,a(l)}})}),cancel:()=>s||!n||typeof n.abort!="function"?!1:(n.abort(),s=!0,!0)}}function Xc(e="actual"){return Jo(Ds.SETTINGS,{},e)}function Jc(e,t="Zayd",n="actual"){return Jo(Ds.TTS,{text:e,voice_id:t},n)}function Qo(){var e,t,n;return!!((n=(t=(e=window.frappe)==null?void 0:e.realtime)==null?void 0:t.socket)!=null&&n.connected)}function Nr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var hn=Nr();function el(e){hn=e}var gn={exec:()=>null};function oe(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(r,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(Ke.caret,"$1"),n=n.replace(r,o),s},getRegex:()=>new RegExp(n,t)};return s}var Qc=((e="")=>{try{return!!new RegExp("(?<=1)(?/,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:/^/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:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},ef=/^(?:[ \t]*(?:\n|$))+/,tf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,nf=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Qn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,sf=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Dr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,tl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,nl=oe(tl).replace(/bull/g,Dr).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(),rf=oe(tl).replace(/bull/g,Dr).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(),Fr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,of=/^[^\n]+/,Br=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,lf=oe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Br).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),af=oe(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Dr).getRegex(),Fs="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",Hr=/|$))/,uf=oe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\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",Hr).replace("tag",Fs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),sl=oe(Fr).replace("hr",Qn).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",Fs).getRegex(),cf=oe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",sl).getRegex(),zr={blockquote:cf,code:tf,def:lf,fences:nf,heading:sf,hr:Qn,html:uf,lheading:nl,list:af,newline:ef,paragraph:sl,table:gn,text:of},rl=oe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Qn).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",Fs).getRegex(),ff={...zr,lheading:rf,table:rl,paragraph:oe(Fr).replace("hr",Qn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",rl).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",Fs).getRegex()},pf={...zr,html:oe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?\\1> *(?:\\n{2,}|\\s*$)| \\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hr).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:gn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:oe(Fr).replace("hr",Qn).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",nl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},df=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hf=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,il=/^( {2,}|\\)\n(?!\s*$)/,gf=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Qc?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ll=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,wf=oe(ll,"u").replace(/punct/g,Rn).getRegex(),vf=oe(ll,"u").replace(/punct/g,ol).getRegex(),al="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",_f=oe(al,"gu").replace(/notPunctSpace/g,Ur).replace(/punctSpace/g,Bs).replace(/punct/g,Rn).getRegex(),Tf=oe(al,"gu").replace(/notPunctSpace/g,xf).replace(/punctSpace/g,bf).replace(/punct/g,ol).getRegex(),kf=oe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ur).replace(/punctSpace/g,Bs).replace(/punct/g,Rn).getRegex(),Sf=oe(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Rn).getRegex(),Ef="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Af=oe(Ef,"gu").replace(/notPunctSpace/g,Ur).replace(/punctSpace/g,Bs).replace(/punct/g,Rn).getRegex(),Rf=oe(/\\(punct)/,"gu").replace(/punct/g,Rn).getRegex(),Cf=oe(/^<(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(),Pf=oe(Hr).replace("(?:-->|$)","-->").getRegex(),If=oe("^comment|^[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Pf).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Hs=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Of=oe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Hs).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ul=oe(/^!?\[(label)\]\[(ref)\]/).replace("label",Hs).replace("ref",Br).getRegex(),cl=oe(/^!?\[(ref)\](?:\[\])?/).replace("ref",Br).getRegex(),Mf=oe("reflink|nolink(?!\\()","g").replace("reflink",ul).replace("nolink",cl).getRegex(),fl=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,jr={_backpedal:gn,anyPunctuation:Rf,autolink:Cf,blockSkip:yf,br:il,code:hf,del:gn,delLDelim:gn,delRDelim:gn,emStrongLDelim:wf,emStrongRDelimAst:_f,emStrongRDelimUnd:kf,escape:df,link:Of,nolink:cl,punctuation:mf,reflink:ul,reflinkSearch:Mf,tag:If,text:gf,url:gn},Lf={...jr,link:oe(/^!?\[(label)\]\((.*?)\)/).replace("label",Hs).getRegex(),reflink:oe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Hs).getRegex()},Vr={...jr,emStrongRDelimAst:Tf,emStrongLDelim:vf,delLDelim:Sf,delRDelim:Af,url:oe(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",fl).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:oe(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},pl=e=>Nf[e];function St(e,t){if(t){if(Ke.escapeTest.test(e))return e.replace(Ke.escapeReplace,pl)}else if(Ke.escapeTestNoEncode.test(e))return e.replace(Ke.escapeReplaceNoEncode,pl);return e}function dl(e){try{e=encodeURI(e).replace(Ke.percentDecode,"%")}catch{return null}return e}function hl(e,t){var i;let n=e.replace(Ke.findPipe,(o,a,l)=>{let f=!1,u=a;for(;--u>=0&&l[u]==="\\";)f=!f;return f?"|":" |"}),s=n.split(Ke.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!((i=s.at(-1))!=null&&i.trim())&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length =0&&Ke.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(` +`)}function Df(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let s=0;s 0?-2:-1}function Ff(e,t=0){let n=t,s="";for(let r of e)if(r===" "){let i=4-n%4;s+=" ".repeat(i),n+=i}else s+=r,n++;return s}function ml(e,t,n,s,r){let i=t.href,o=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}function Bf(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(` +`).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[a]=o;return a.length>=r.length?i.slice(r.length):i}).join(` +`)}var Us=class{constructor(e){ve(this,"options");ve(this,"rules");ve(this,"lexer");this.options=e||hn}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:gl(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Bf(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=Jt(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:Jt(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Jt(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Jt(t[0],` `).split(` -`),s="",r="",i=[];for(;n.length>0;){let l=!1,a=[],o;for(o=0;o 0;){let o=!1,a=[],l;for(l=0;l 1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),l=!1;for(;e;){let o=!1,c="",u="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let d=yf(t[2].split(` +`),_=this.list(A);i[i.length-1]=_,s=s.substring(0,s.length-g.raw.length)+_.raw,r=r.substring(0,r.length-w.raw.length)+_.raw,n=A.substring(i.at(-1).raw.length).split(` +`);continue}}return{type:"blockquote",raw:s,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let l=!1,f="",u="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let h=Ff(t[2].split(` `,1)[0],t[1].length),g=e.split(` -`,1)[0],y=!d.trim(),E=0;if(this.options.pedantic?(E=2,u=d.trimStart()):y?E=t[1].length+1:(E=d.search(this.rules.other.nonSpaceChar),E=E>4?1:E,u=d.slice(E),E+=t[1].length),y&&this.rules.other.blankLine.test(g)&&(c+=g+` -`,e=e.substring(g.length+1),o=!0),!o){let x=this.rules.other.nextBulletRegex(E),M=this.rules.other.hrRegex(E),m=this.rules.other.fencesBeginRegex(E),H=this.rules.other.headingBeginRegex(E),Y=this.rules.other.htmlBeginRegex(E),$=this.rules.other.blockquoteBeginRegex(E);for(;e;){let U=e.split(` -`,1)[0],L;if(g=U,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),L=g):L=g.replace(this.rules.other.tabCharGlobal," "),m.test(g)||H.test(g)||Y.test(g)||$.test(g)||x.test(g)||M.test(g))break;if(L.search(this.rules.other.nonSpaceChar)>=E||!g.trim())u+=` -`+L.slice(E);else{if(y||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||m.test(d)||H.test(d)||M.test(d))break;u+=` -`+g}y=!g.trim(),c+=U+` -`,e=e.substring(U.length+1),d=L.slice(E)}}r.loose||(l?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(l=!0)),r.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=c}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let o of r.items){this.lexer.state.top=!1,o.tokens=this.lexer.blockTokens(o.text,[]);let c=o.tokens[0];if(o.task&&((c==null?void 0:c.type)==="text"||(c==null?void 0:c.type)==="paragraph")){o.text=o.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.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(o.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};o.checked=d.checked,r.loose?o.tokens[0]&&["paragraph","text"].includes(o.tokens[0].type)&&"tokens"in o.tokens[0]&&o.tokens[0].tokens?(o.tokens[0].raw=d.raw+o.tokens[0].raw,o.tokens[0].text=d.raw+o.tokens[0].text,o.tokens[0].tokens.unshift(d)):o.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):o.tokens.unshift(d)}}else o.task&&(o.task=!1);if(!r.loose){let u=o.tokens.filter(g=>g.type==="space"),d=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=d}}if(r.loose)for(let o of r.items){o.loose=!0;for(let c of o.tokens)c.type==="text"&&(c.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=eo(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:Qt(t[0],` -`),href:s,title:r}}}table(e){var l;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Jl(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=(l=t[3])!=null&&l.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` -`):[],i={type:"table",raw:Qt(t[0],` -`),header:[],align:[],rows:[]};if(n.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a ({text:o,tokens:this.lexer.inline(o),header:!1,align:i.align[c]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:Qt(t[0],` +`,1)[0],w=!h.trim(),A=0;if(this.options.pedantic?(A=2,u=h.trimStart()):w?A=t[1].length+1:(A=h.search(this.rules.other.nonSpaceChar),A=A>4?1:A,u=h.slice(A),A+=t[1].length),w&&this.rules.other.blankLine.test(g)&&(f+=g+` +`,e=e.substring(g.length+1),l=!0),!l){let _=this.rules.other.nextBulletRegex(A),F=this.rules.other.hrRegex(A),b=this.rules.other.fencesBeginRegex(A),U=this.rules.other.headingBeginRegex(A),Z=this.rules.other.htmlBeginRegex(A),$=this.rules.other.blockquoteBeginRegex(A);for(;e;){let Y=e.split(` +`,1)[0],C;if(g=Y,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),C=g):C=g.replace(this.rules.other.tabCharGlobal," "),b.test(g)||U.test(g)||Z.test(g)||$.test(g)||_.test(g)||F.test(g))break;if(C.search(this.rules.other.nonSpaceChar)>=A||!g.trim())u+=` +`+C.slice(A);else{if(w||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(h)||U.test(h)||F.test(h))break;u+=` +`+g}w=!g.trim(),f+=Y+` +`,e=e.substring(Y.length+1),h=C.slice(A)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(o=!0)),r.items.push({type:"list_item",raw:f,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=f}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let l of r.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let f=l.tokens[0];if(l.task&&((f==null?void 0:f.type)==="text"||(f==null?void 0:f.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),f.raw=f.raw.replace(this.rules.other.listReplaceTask,""),f.text=f.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=h.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=h.raw+l.tokens[0].raw,l.tokens[0].text=h.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(h)):l.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):l.tokens.unshift(h)}}else l.task&&(l.task=!1);if(!r.loose){let u=l.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let l of r.items){l.loose=!0;for(let f of l.tokens)f.type==="text"&&(f.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=gl(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:Jt(t[0],` +`),href:s,title:r}}}table(e){var o;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=hl(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=(o=t[3])!=null&&o.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],i={type:"table",raw:Jt(t[0],` +`),header:[],align:[],rows:[]};if(n.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a ({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[f]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:Jt(t[0],` `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Qt(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=xf(t[2],"()");if(i===-2)return;if(i>-1){let l=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,l).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),to(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return to(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,l,a=r,o=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(l=[...i].length,s[3]||s[4]){a+=l;continue}else if((s[5]||s[6])&&r%3&&!((r+l)%3)){o+=l;continue}if(a-=l,a>0)continue;l=Math.min(l,l+a+o);let u=[...s[0]][0].length,d=e.slice(0,r+s.index+u+l);if(Math.min(r,l)%2){let y=d.slice(1,-1);return{type:"em",raw:d,text:y,tokens:this.lexer.inlineTokens(y)}}let g=d.slice(2,-2);return{type:"strong",raw:d,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,l,a=r,o=this.rules.inline.delRDelim;for(o.lastIndex=0,t=t.slice(-1*e.length+r);(s=o.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(l=[...i].length,l!==r))continue;if(s[3]||s[4]){a+=l;continue}if(a-=l,a>0)continue;l=Math.min(l,l+a);let c=[...s[0]][0].length,u=e.slice(0,r+s.index+c+l),d=u.slice(r,-r);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,s;let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let l;do l=t[0],t[0]=(s=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?s:"";while(l!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},yt=class Xr{constructor(t){ve(this,"tokens");ve(this,"options");ve(this,"state");ve(this,"inlineQueue");ve(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||cn,this.options.tokenizer=this.options.tokenizer||new Ls,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:Ge,block:Ms.normal,inline:Yn.normal};this.options.pedantic?(n.block=Ms.pedantic,n.inline=Yn.pedantic):this.options.gfm&&(n.block=Ms.gfm,this.options.breaks?n.inline=Yn.breaks:n.inline=Yn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ms,inline:Yn}}static lex(t,n){return new Xr(n).lex(t)}static lexInline(t,n){return new Xr(n).inlineTokens(t)}lex(t){t=t.replace(Ge.carriageReturn,` -`),this.blockTokens(t,this.tokens);for(let n=0;n (o=u.call({lexer:this},t,n))?(t=t.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let u=n.at(-1);o.raw.length===1&&u!==void 0?u.raw+=` -`:n.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Jt(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Df(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),ml(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return ml(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=0,f=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+r);(s=f.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(o=[...i].length,s[3]||s[4]){a+=o;continue}else if((s[5]||s[6])&&r%3&&!((r+o)%3)){l+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+o);if(Math.min(r,o)%2){let w=h.slice(1,-1);return{type:"em",raw:h,text:w,tokens:this.lexer.inlineTokens(w)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,i,o,a=r,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(s=l.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(o=[...i].length,o!==r))continue;if(s[3]||s[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let f=[...s[0]][0].length,u=e.slice(0,r+s.index+f+o),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){var n,s;let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let o;do o=t[0],t[0]=(s=(n=this.rules.inline._backpedal.exec(t[0]))==null?void 0:n[0])!=null?s:"";while(o!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},gt=class ui{constructor(t){ve(this,"tokens");ve(this,"options");ve(this,"state");ve(this,"inlineQueue");ve(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=t||hn,this.options.tokenizer=this.options.tokenizer||new Us,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:Ke,block:zs.normal,inline:es.normal};this.options.pedantic?(n.block=zs.pedantic,n.inline=es.pedantic):this.options.gfm&&(n.block=zs.gfm,this.options.breaks?n.inline=es.breaks:n.inline=es.gfm),this.tokenizer.rules=n}static get rules(){return{block:zs,inline:es}}static lex(t,n){return new ui(n).lex(t)}static lexInline(t,n){return new ui(n).inlineTokens(t)}lex(t){t=t.replace(Ke.carriageReturn,` +`),this.blockTokens(t,this.tokens);for(let n=0;n (l=u.call({lexer:this},t,n))?(t=t.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.space(t)){t=t.substring(l.raw.length);let u=n.at(-1);l.raw.length===1&&u!==void 0?u.raw+=` +`:n.push(l);continue}if(l=this.tokenizer.code(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` -`)+o.raw,u.text+=` -`+o.text,this.inlineQueue.at(-1).src=u.text):n.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` +`)+l.raw,u.text+=` +`+l.text,this.inlineQueue.at(-1).src=u.text):n.push(l);continue}if(l=this.tokenizer.fences(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.heading(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.hr(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.blockquote(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.list(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.html(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.def(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="paragraph"||(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` -`)+o.raw,u.text+=` -`+o.raw,this.inlineQueue.at(-1).src=u.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),n.push(o);continue}let c=t;if((a=this.options.extensions)!=null&&a.startBlock){let u=1/0,d=t.slice(1),g;this.options.extensions.startBlock.forEach(y=>{g=y.call({lexer:this},d),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(c=t.substring(0,u+1))}if(this.state.top&&(o=this.tokenizer.paragraph(c))){let u=n.at(-1);s&&(u==null?void 0:u.type)==="paragraph"?(u.raw+=(u.raw.endsWith(` +`)+l.raw,u.text+=` +`+l.raw,this.inlineQueue.at(-1).src=u.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},n.push(l));continue}if(l=this.tokenizer.table(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.lheading(t)){t=t.substring(l.raw.length),n.push(l);continue}let f=t;if((a=this.options.extensions)!=null&&a.startBlock){let u=1/0,h=t.slice(1),g;this.options.extensions.startBlock.forEach(w=>{g=w.call({lexer:this},h),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(f=t.substring(0,u+1))}if(this.state.top&&(l=this.tokenizer.paragraph(f))){let u=n.at(-1);s&&(u==null?void 0:u.type)==="paragraph"?(u.raw+=(u.raw.endsWith(` `)?"":` -`)+o.raw,u.text+=` -`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(o),s=c.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` +`)+l.raw,u.text+=` +`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l),s=f.length!==t.length,t=t.substring(l.raw.length);continue}if(l=this.tokenizer.text(t)){t=t.substring(l.raw.length);let u=n.at(-1);(u==null?void 0:u.type)==="text"?(u.raw+=(u.raw.endsWith(` `)?"":` -`)+o.raw,u.text+=` -`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var c,u,d,g,y,E;this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let x=Object.keys(this.tokens.links);if(x.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)x.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)i=r[2]?r[2].length:0,s=s.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=(d=(u=(c=this.options.hooks)==null?void 0:c.emStrongMask)==null?void 0:u.call({lexer:this},s))!=null?d:s;let l=!1,a="",o=1/0;for(;t;){if(t.length (x=m.call({lexer:this},t,n))?(t=t.substring(x.raw.length),n.push(x),!0):!1))continue;if(x=this.tokenizer.escape(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.tag(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.link(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(x.raw.length);let m=n.at(-1);x.type==="text"&&(m==null?void 0:m.type)==="text"?(m.raw+=x.raw,m.text+=x.text):n.push(x);continue}if(x=this.tokenizer.emStrong(t,s,a)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.codespan(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.br(t)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.del(t,s,a)){t=t.substring(x.raw.length),n.push(x);continue}if(x=this.tokenizer.autolink(t)){t=t.substring(x.raw.length),n.push(x);continue}if(!this.state.inLink&&(x=this.tokenizer.url(t))){t=t.substring(x.raw.length),n.push(x);continue}let M=t;if((E=this.options.extensions)!=null&&E.startInline){let m=1/0,H=t.slice(1),Y;this.options.extensions.startInline.forEach($=>{Y=$.call({lexer:this},H),typeof Y=="number"&&Y>=0&&(m=Math.min(m,Y))}),m<1/0&&m>=0&&(M=t.substring(0,m+1))}if(x=this.tokenizer.inlineText(M)){t=t.substring(x.raw.length),x.raw.slice(-1)!=="_"&&(a=x.raw.slice(-1)),l=!0;let m=n.at(-1);(m==null?void 0:m.type)==="text"?(m.raw+=x.raw,m.text+=x.text):n.push(x);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(!this.options.silent)throw new Error(n)}},$s=class{constructor(e){ve(this,"options");ve(this,"parser");this.options=e||cn}space(e){return""}code({text:e,lang:t,escaped:n}){var i;let s=(i=(t||"").match(Ge.notSpaceStart))==null?void 0:i[0],r=e.replace(Ge.endingNewline,"")+` -`;return s?' -`:"'+(n?r:Ct(r,!0))+`+`)+l.raw,u.text+=` +`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=u.text):n.push(l);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){var f,u,h,g,w,A;this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let _=Object.keys(this.tokens.links);if(_.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)_.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)i=r[2]?r[2].length:0,s=s.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=(h=(u=(f=this.options.hooks)==null?void 0:f.emStrongMask)==null?void 0:u.call({lexer:this},s))!=null?h:s;let o=!1,a="",l=1/0;for(;t;){if(t.length"+(n?r:Ct(r,!0))+`(_=b.call({lexer:this},t,n))?(t=t.substring(_.raw.length),n.push(_),!0):!1))continue;if(_=this.tokenizer.escape(t)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.tag(t)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.link(t)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(_.raw.length);let b=n.at(-1);_.type==="text"&&(b==null?void 0:b.type)==="text"?(b.raw+=_.raw,b.text+=_.text):n.push(_);continue}if(_=this.tokenizer.emStrong(t,s,a)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.codespan(t)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.br(t)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.del(t,s,a)){t=t.substring(_.raw.length),n.push(_);continue}if(_=this.tokenizer.autolink(t)){t=t.substring(_.raw.length),n.push(_);continue}if(!this.state.inLink&&(_=this.tokenizer.url(t))){t=t.substring(_.raw.length),n.push(_);continue}let F=t;if((A=this.options.extensions)!=null&&A.startInline){let b=1/0,U=t.slice(1),Z;this.options.extensions.startInline.forEach($=>{Z=$.call({lexer:this},U),typeof Z=="number"&&Z>=0&&(b=Math.min(b,Z))}),b<1/0&&b>=0&&(F=t.substring(0,b+1))}if(_=this.tokenizer.inlineText(F)){t=t.substring(_.raw.length),_.raw.slice(-1)!=="_"&&(a=_.raw.slice(-1)),o=!0;let b=n.at(-1);(b==null?void 0:b.type)==="text"?(b.raw+=_.raw,b.text+=_.text):n.push(_);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return n}infiniteLoopError(t){let n="Infinite loop on byte: "+t;if(this.options.silent)console.error(n);else throw new Error(n)}},js=class{constructor(e){ve(this,"options");ve(this,"parser");this.options=e||hn}space(e){return""}code({text:e,lang:t,escaped:n}){var i;let s=(i=(t||"").match(Ke.notSpaceStart))==null?void 0:i[0],r=e.replace(Ke.endingNewline,"")+` +`;return s?' +`:"'+(n?r:St(r,!0))+``}blockquote({tokens:e}){return`"+(n?r:St(r,!0))+`${this.parser.parse(e)}`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} `}hr(e){return`
-`}list(e){let t=e.ordered,n=e.start,s="";for(let l=0;l+`}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o `+s+""+r+`> `}listitem(e){return` ${this.parser.parse(e.tokens)} `}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`${this.parser.parseInline(e)}
-`}table(e){let t="",n="";for(let r=0;r${s}`),` +`}table(e){let t="",n="";for(let r=0;r
${s}`),` `+t+` `+s+`
`}tablerow({text:e}){return`${e} `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`${n}> -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Ct(e,!0)}`}br(e){return"
"}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=Ql(e);if(r===null)return s;e=r;let i='"+s+"",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=Ql(e);if(r===null)return Ct(n);e=r;let i=`",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ct(e.text)}},Lr=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},wt=class Qr{constructor(t){ve(this,"options");ve(this,"renderer");ve(this,"textRenderer");this.options=t||cn,this.options.renderer=this.options.renderer||new $s,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Lr}static parse(t,n){return new Qr(n).parse(t)}static parseInline(t,n){return new Qr(n).parseInline(t)}parse(t){var s,r;this.renderer.parser=this;let n="";for(let i=0;i
{let o=l[a].flat(1/0);n=n.concat(this.walkTokens(o,t))}):l.tokens&&(n=n.concat(this.walkTokens(l.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...l){let a=r.renderer.apply(this,l);return a===!1&&(a=i.apply(this,l)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new $s(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let l=i,a=n.renderer[l],o=r[l];r[l]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=o.apply(r,c)),u||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new Ls(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let l=i,a=n.tokenizer[l],o=r[l];r[l]=(...c)=>{let u=a.apply(r,c);return u===!1&&(u=o.apply(r,c)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new Zn;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let l=i,a=n.hooks[l],o=r[l];Zn.passThroughHooks.has(i)?r[l]=c=>{if(this.defaults.async&&Zn.passThroughHooksRespectAsync.has(i))return(async()=>{let d=await a.call(r,c);return o.call(r,d)})();let u=a.call(r,c);return o.call(r,u)}:r[l]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await a.apply(r,c);return d===!1&&(d=await o.apply(r,c)),d})();let u=a.apply(r,c);return u===!1&&(u=o.apply(r,c)),u}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(l){let a=[];return a.push(i.call(this,l)),r&&(a=a.concat(r.call(this,l))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return yt.lex(e,t!=null?t:this.defaults)}parser(e,t){return wt.parse(e,t!=null?t:this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return i(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 t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let l=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?yt.lex:yt.lexInline)(l,r),o=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(o,r.walkTokens));let c=await(r.hooks?await r.hooks.provideParser(e):e?wt.parse:wt.parseInline)(o,r);return r.hooks?await r.hooks.postprocess(c):c})().catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let l=(r.hooks?r.hooks.provideLexer(e):e?yt.lex:yt.lexInline)(t,r);r.hooks&&(l=r.hooks.processAllTokens(l)),r.walkTokens&&this.walkTokens(l,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?wt.parse:wt.parseInline)(l,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(l){return i(l)}}}onError(e,t){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let s=" An error occurred:
"+Ct(n.message+"",!0)+"";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},pn=new vf;function xe(e,t){return pn.parse(e,t)}xe.options=xe.setOptions=function(e){return pn.setOptions(e),xe.defaults=pn.defaults,Bl(xe.defaults),xe},xe.getDefaults=Sr,xe.defaults=cn,xe.use=function(...e){return pn.use(...e),xe.defaults=pn.defaults,Bl(xe.defaults),xe},xe.walkTokens=function(e,t){return pn.walkTokens(e,t)},xe.parseInline=pn.parseInline,xe.Parser=wt,xe.parser=wt.parse,xe.Renderer=$s,xe.TextRenderer=Lr,xe.Lexer=yt,xe.lexer=yt.lex,xe.Tokenizer=Ls,xe.Hooks=Zn,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,wt.parse,yt.lex;function no(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),i=2;i 1?n-1:0),r=1;r1?n-1:0),r=1;r 2&&arguments[2]!==void 0?arguments[2]:Xn;if(ro&&ro(e,null),!Xe(t))return e;let s=t.length;for(;s--;){let r=t[s];if(typeof r=="string"){const i=n(r);i!==r&&(Af(t)||(t[s]=i),r=i)}e[r]=!0}return e}function Df(e){for(let t=0;t /g),jf=ht(/\${[\w\W]*/g),Vf=ht(/^data-[\-\w.\u00B7-\uFFFF]+$/),qf=ht(/^aria-[\-\w]+$/),mo=ht(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Wf=ht(/^(?:\w+script|data):/i),Gf=ht(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Kf=ht(/^html$/i),Yf=ht(/^[a-z][.\w]*(-[.\w]+)+$/i),Rn={element:1,text:3,progressingInstruction:7,comment:8,document:9},Zf=function(){return typeof window=="undefined"?null:window},Xf=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const r="data-tt-policy-suffix";n&&n.hasAttribute(r)&&(s=n.getAttribute(r));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(l){return l},createScriptURL(l){return l}})}catch{return null}},bo=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function xo(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zf();const t=W=>xo(W);if(t.version="3.4.3",t.removed=[],!e||!e.document||e.document.nodeType!==Rn.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,r=s.currentScript,i=e.DocumentFragment,l=e.HTMLTemplateElement,a=e.Node,o=e.Element,c=e.NodeFilter,u=e.NamedNodeMap,d=u===void 0?e.NamedNodeMap||e.MozNamedAttrMap:u,g=e.HTMLFormElement,y=e.DOMParser,E=e.trustedTypes,x=o.prototype,M=An(x,"cloneNode"),m=An(x,"remove"),H=An(x,"nextSibling"),Y=An(x,"childNodes"),$=An(x,"parentNode");if(typeof l=="function"){const W=n.createElement("template");W.content&&W.content.ownerDocument&&(n=W.content.ownerDocument)}let U,L="";const O=n,ee=O.implementation,q=O.createNodeIterator,se=O.createDocumentFragment,fe=O.getElementsByTagName,D=s.importNode;let Z=bo();t.isSupported=typeof so=="function"&&typeof $=="function"&&ee&&ee.createHTMLDocument!==void 0;const Se=zf,je=Uf,te=jf,R=Vf,he=qf,Le=Wf,re=Gf,F=Yf;let ue=mo,ge=null;const Te=X({},[...fo,...Fr,...Br,...Hr,...po]);let pe=null;const Qe=X({},[...ho,...zr,...go,...Ns]);let ye=Object.seal(Tn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),j=null,st=null;const Ie=Object.seal(Tn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let Ft=!0,f=!0,h=!1,b=!0,k=!1,v=!0,_=!1,P=!1,C=!1,A=!1,S=!1,z=!1,I=!0,V=!1;const K="user-content-";let ne=!0,de=!1,ie={},ke=null;const De=X({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let ot=null;const at=X({},["audio","video","img","source","image","track"]);let Bt=null;const Jn=X({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ne="http://www.w3.org/1998/Math/MathML",Je="http://www.w3.org/2000/svg",ut="http://www.w3.org/1999/xhtml";let Ht=ut,Ur=!1,jr=null;const hd=X({},[Ne,Je,ut],Nr);let Vr=X({},["mi","mo","mn","ms","mtext"]),qr=X({},["annotation-xml"]);const gd=X({},["title","style","font","a","script"]);let es=null;const md=["application/xhtml+xml","text/html"],bd="text/html";let $e=null,Cn=null;const xd=n.createElement("form"),So=function(p){return p instanceof RegExp||p instanceof Function},Wr=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Cn&&Cn===p)return;(!p||typeof p!="object")&&(p={}),p=nt(p),es=md.indexOf(p.PARSER_MEDIA_TYPE)===-1?bd:p.PARSER_MEDIA_TYPE,$e=es==="application/xhtml+xml"?Nr:Xn,ge=Ae(p,"ALLOWED_TAGS")&&Xe(p.ALLOWED_TAGS)?X({},p.ALLOWED_TAGS,$e):Te,pe=Ae(p,"ALLOWED_ATTR")&&Xe(p.ALLOWED_ATTR)?X({},p.ALLOWED_ATTR,$e):Qe,jr=Ae(p,"ALLOWED_NAMESPACES")&&Xe(p.ALLOWED_NAMESPACES)?X({},p.ALLOWED_NAMESPACES,Nr):hd,Bt=Ae(p,"ADD_URI_SAFE_ATTR")&&Xe(p.ADD_URI_SAFE_ATTR)?X(nt(Jn),p.ADD_URI_SAFE_ATTR,$e):Jn,ot=Ae(p,"ADD_DATA_URI_TAGS")&&Xe(p.ADD_DATA_URI_TAGS)?X(nt(at),p.ADD_DATA_URI_TAGS,$e):at,ke=Ae(p,"FORBID_CONTENTS")&&Xe(p.FORBID_CONTENTS)?X({},p.FORBID_CONTENTS,$e):De,j=Ae(p,"FORBID_TAGS")&&Xe(p.FORBID_TAGS)?X({},p.FORBID_TAGS,$e):nt({}),st=Ae(p,"FORBID_ATTR")&&Xe(p.FORBID_ATTR)?X({},p.FORBID_ATTR,$e):nt({}),ie=Ae(p,"USE_PROFILES")?p.USE_PROFILES&&typeof p.USE_PROFILES=="object"?nt(p.USE_PROFILES):p.USE_PROFILES:!1,Ft=p.ALLOW_ARIA_ATTR!==!1,f=p.ALLOW_DATA_ATTR!==!1,h=p.ALLOW_UNKNOWN_PROTOCOLS||!1,b=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,k=p.SAFE_FOR_TEMPLATES||!1,v=p.SAFE_FOR_XML!==!1,_=p.WHOLE_DOCUMENT||!1,A=p.RETURN_DOM||!1,S=p.RETURN_DOM_FRAGMENT||!1,z=p.RETURN_TRUSTED_TYPE||!1,C=p.FORCE_BODY||!1,I=p.SANITIZE_DOM!==!1,V=p.SANITIZE_NAMED_PROPS||!1,ne=p.KEEP_CONTENT!==!1,de=p.IN_PLACE||!1,ue=Ff(p.ALLOWED_URI_REGEXP)?p.ALLOWED_URI_REGEXP:mo,Ht=typeof p.NAMESPACE=="string"?p.NAMESPACE:ut,Vr=Ae(p,"MATHML_TEXT_INTEGRATION_POINTS")&&p.MATHML_TEXT_INTEGRATION_POINTS&&typeof p.MATHML_TEXT_INTEGRATION_POINTS=="object"?nt(p.MATHML_TEXT_INTEGRATION_POINTS):X({},["mi","mo","mn","ms","mtext"]),qr=Ae(p,"HTML_INTEGRATION_POINTS")&&p.HTML_INTEGRATION_POINTS&&typeof p.HTML_INTEGRATION_POINTS=="object"?nt(p.HTML_INTEGRATION_POINTS):X({},["annotation-xml"]);const T=Ae(p,"CUSTOM_ELEMENT_HANDLING")&&p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING=="object"?nt(p.CUSTOM_ELEMENT_HANDLING):Tn(null);if(ye=Tn(null),Ae(T,"tagNameCheck")&&So(T.tagNameCheck)&&(ye.tagNameCheck=T.tagNameCheck),Ae(T,"attributeNameCheck")&&So(T.attributeNameCheck)&&(ye.attributeNameCheck=T.attributeNameCheck),Ae(T,"allowCustomizedBuiltInElements")&&typeof T.allowCustomizedBuiltInElements=="boolean"&&(ye.allowCustomizedBuiltInElements=T.allowCustomizedBuiltInElements),k&&(f=!1),S&&(A=!0),ie&&(ge=X({},po),pe=Tn(null),ie.html===!0&&(X(ge,fo),X(pe,ho)),ie.svg===!0&&(X(ge,Fr),X(pe,zr),X(pe,Ns)),ie.svgFilters===!0&&(X(ge,Br),X(pe,zr),X(pe,Ns)),ie.mathMl===!0&&(X(ge,Hr),X(pe,go),X(pe,Ns))),Ie.tagCheck=null,Ie.attributeCheck=null,Ae(p,"ADD_TAGS")&&(typeof p.ADD_TAGS=="function"?Ie.tagCheck=p.ADD_TAGS:Xe(p.ADD_TAGS)&&(ge===Te&&(ge=nt(ge)),X(ge,p.ADD_TAGS,$e))),Ae(p,"ADD_ATTR")&&(typeof p.ADD_ATTR=="function"?Ie.attributeCheck=p.ADD_ATTR:Xe(p.ADD_ATTR)&&(pe===Qe&&(pe=nt(pe)),X(pe,p.ADD_ATTR,$e))),Ae(p,"ADD_URI_SAFE_ATTR")&&Xe(p.ADD_URI_SAFE_ATTR)&&X(Bt,p.ADD_URI_SAFE_ATTR,$e),Ae(p,"FORBID_CONTENTS")&&Xe(p.FORBID_CONTENTS)&&(ke===De&&(ke=nt(ke)),X(ke,p.FORBID_CONTENTS,$e)),Ae(p,"ADD_FORBID_CONTENTS")&&Xe(p.ADD_FORBID_CONTENTS)&&(ke===De&&(ke=nt(ke)),X(ke,p.ADD_FORBID_CONTENTS,$e)),ne&&(ge["#text"]=!0),_&&X(ge,["html","head","body"]),ge.table&&(X(ge,["tbody"]),delete j.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw Ds('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Ds('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');U=p.TRUSTED_TYPES_POLICY,L=U.createHTML("")}else U===void 0&&(U=Xf(E,r)),U!==null&&typeof L=="string"&&(L=U.createHTML(""));Ze&&Ze(p),Cn=p},Eo=X({},[...Fr,...Br,...Bf]),Ao=X({},[...Hr,...Hf]),yd=function(p){let T=$(p);(!T||!T.tagName)&&(T={namespaceURI:Ht,tagName:"template"});const N=Xn(p.tagName),ce=Xn(T.tagName);return jr[p.namespaceURI]?p.namespaceURI===Je?T.namespaceURI===ut?N==="svg":T.namespaceURI===Ne?N==="svg"&&(ce==="annotation-xml"||Vr[ce]):!!Eo[N]:p.namespaceURI===Ne?T.namespaceURI===ut?N==="math":T.namespaceURI===Je?N==="math"&&qr[ce]:!!Ao[N]:p.namespaceURI===ut?T.namespaceURI===Je&&!qr[ce]||T.namespaceURI===Ne&&!Vr[ce]?!1:!Ao[N]&&(gd[N]||!Eo[N]):!!(es==="application/xhtml+xml"&&jr[p.namespaceURI]):!1},vt=function(p){Sn(t.removed,{element:p});try{$(p).removeChild(p)}catch{m(p)}},dn=function(p,T){try{Sn(t.removed,{attribute:T.getAttributeNode(p),from:T})}catch{Sn(t.removed,{attribute:null,from:T})}if(T.removeAttribute(p),p==="is")if(A||S)try{vt(T)}catch{}else try{T.setAttribute(p,"")}catch{}},Ro=function(p){let T=null,N=null;if(C)p=" "+p;else{const Oe=oo(p,/^[\r\n\t ]+/);N=Oe&&Oe[0]}es==="application/xhtml+xml"&&Ht===ut&&(p=''+p+"");const ce=U?U.createHTML(p):p;if(Ht===ut)try{T=new y().parseFromString(ce,es)}catch{}if(!T||!T.documentElement){T=ee.createDocument(Ht,"template",null);try{T.documentElement.innerHTML=Ur?L:ce}catch{}}const Fe=T.body||T.documentElement;return p&&N&&Fe.insertBefore(n.createTextNode(N),Fe.childNodes[0]||null),Ht===ut?fe.call(T,_?"html":"body")[0]:_?T.documentElement:Fe},Co=function(p){return q.call(p.ownerDocument||p,p,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Gr=function(p){return p instanceof g&&(typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||!(p.attributes instanceof d)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function")},Kr=function(p){return typeof a=="function"&&p instanceof a};function zt(W,p,T){kn(W,N=>{N.call(t,p,T,Cn)})}const Po=function(p){let T=null;if(zt(Z.beforeSanitizeElements,p,null),Gr(p))return vt(p),!0;const N=$e(p.nodeName);if(zt(Z.uponSanitizeElement,p,{tagName:N,allowedTags:ge}),v&&p.hasChildNodes()&&!Kr(p.firstElementChild)&&Ue(/<[/\w!]/g,p.innerHTML)&&Ue(/<[/\w!]/g,p.textContent)||v&&p.namespaceURI===ut&&N==="style"&&Kr(p.firstElementChild)||p.nodeType===Rn.progressingInstruction||v&&p.nodeType===Rn.comment&&Ue(/<[/\w]/g,p.data))return vt(p),!0;if(j[N]||!(Ie.tagCheck instanceof Function&&Ie.tagCheck(N))&&!ge[N]){if(!j[N]&&Oo(N)&&(ye.tagNameCheck instanceof RegExp&&Ue(ye.tagNameCheck,N)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(N)))return!1;if(ne&&!ke[N]){const ce=$(p)||p.parentNode,Fe=Y(p)||p.childNodes;if(Fe&&ce){const Oe=Fe.length;for(let rt=Oe-1;rt>=0;--rt){const gt=M(Fe[rt],!0);ce.insertBefore(gt,H(p))}}}return vt(p),!0}return p instanceof o&&!yd(p)||(N==="noscript"||N==="noembed"||N==="noframes")&&Ue(/<\/no(script|embed|frames)/i,p.innerHTML)?(vt(p),!0):(k&&p.nodeType===Rn.text&&(T=p.textContent,kn([Se,je,te],ce=>{T=En(T,ce," ")}),p.textContent!==T&&(Sn(t.removed,{element:p.cloneNode()}),p.textContent=T)),zt(Z.afterSanitizeElements,p,null),!1)},Io=function(p,T,N){if(st[T]||I&&(T==="id"||T==="name")&&(N in n||N in xd))return!1;const ce=pe[T]||Ie.attributeCheck instanceof Function&&Ie.attributeCheck(T,p);if(!(f&&!st[T]&&Ue(R,T))){if(!(Ft&&Ue(he,T))){if(!ce||st[T]){if(!(Oo(p)&&(ye.tagNameCheck instanceof RegExp&&Ue(ye.tagNameCheck,p)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(p))&&(ye.attributeNameCheck instanceof RegExp&&Ue(ye.attributeNameCheck,T)||ye.attributeNameCheck instanceof Function&&ye.attributeNameCheck(T,p))||T==="is"&&ye.allowCustomizedBuiltInElements&&(ye.tagNameCheck instanceof RegExp&&Ue(ye.tagNameCheck,N)||ye.tagNameCheck instanceof Function&&ye.tagNameCheck(N))))return!1}else if(!Bt[T]){if(!Ue(ue,En(N,re,""))){if(!((T==="src"||T==="xlink:href"||T==="href")&&p!=="script"&&ao(N,"data:")===0&&ot[p])){if(!(h&&!Ue(Le,En(N,re,"")))){if(N)return!1}}}}}}return!0},wd=X({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Oo=function(p){return!wd[Xn(p)]&&Ue(F,p)},Mo=function(p){zt(Z.beforeSanitizeAttributes,p,null);const T=p.attributes;if(!T||Gr(p))return;const N={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:pe,forceKeepAttr:void 0};let ce=T.length;for(;ce--;){const Fe=T[ce],Oe=Fe.name,rt=Fe.namespaceURI,gt=Fe.value,_t=$e(Oe),Zr=gt;let Be=Oe==="value"?Zr:Of(Zr);if(N.attrName=_t,N.attrValue=Be,N.keepAttr=!0,N.forceKeepAttr=void 0,zt(Z.uponSanitizeAttribute,p,N),Be=N.attrValue,V&&(_t==="id"||_t==="name")&&ao(Be,K)!==0&&(dn(Oe,p),Be=K+Be),v&&Ue(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Be)){dn(Oe,p);continue}if(_t==="attributename"&&oo(Be,"href")){dn(Oe,p);continue}if(N.forceKeepAttr)continue;if(!N.keepAttr){dn(Oe,p);continue}if(!b&&Ue(/\/>/i,Be)){dn(Oe,p);continue}k&&kn([Se,je,te],$o=>{Be=En(Be,$o," ")});const Lo=$e(p.nodeName);if(!Io(Lo,_t,Be)){dn(Oe,p);continue}if(U&&typeof E=="object"&&typeof E.getAttributeType=="function"&&!rt)switch(E.getAttributeType(Lo,_t)){case"TrustedHTML":{Be=U.createHTML(Be);break}case"TrustedScriptURL":{Be=U.createScriptURL(Be);break}}if(Be!==Zr)try{rt?p.setAttributeNS(rt,Oe,Be):p.setAttribute(Oe,Be),Gr(p)?vt(p):lo(t.removed)}catch{dn(Oe,p)}}zt(Z.afterSanitizeAttributes,p,null)},Yr=function(p){let T=null;const N=Co(p);for(zt(Z.beforeSanitizeShadowDOM,p,null);T=N.nextNode();)zt(Z.uponSanitizeShadowNode,T,null),Po(T),Mo(T),T.content instanceof i&&Yr(T.content);zt(Z.afterSanitizeShadowDOM,p,null)},Bs=function(p){if(p.nodeType===Rn.element&&p.shadowRoot instanceof i){const ce=p.shadowRoot;Bs(ce),Yr(ce)}const T=p.childNodes;if(!T)return;const N=[];kn(T,ce=>{Sn(N,ce)});for(const ce of N)Bs(ce)};return t.sanitize=function(W){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},T=null,N=null,ce=null,Fe=null;if(Ur=!W,Ur&&(W=""),typeof W!="string"&&!Kr(W)&&(W=Nf(W),typeof W!="string"))throw Ds("dirty is not a string, aborting");if(!t.isSupported)return W;if(P||Wr(p),t.removed=[],typeof W=="string"&&(de=!1),de){const gt=W.nodeName;if(typeof gt=="string"){const _t=$e(gt);if(!ge[_t]||j[_t])throw Ds("root node is forbidden and cannot be sanitized in-place")}Bs(W)}else if(W instanceof a)T=Ro(""),N=T.ownerDocument.importNode(W,!0),N.nodeType===Rn.element&&N.nodeName==="BODY"||N.nodeName==="HTML"?T=N:T.appendChild(N),Bs(N);else{if(!A&&!k&&!_&&W.indexOf("<")===-1)return U&&z?U.createHTML(W):W;if(T=Ro(W),!T)return A?null:z?L:""}T&&C&&vt(T.firstChild);const Oe=Co(de?W:T);for(;ce=Oe.nextNode();)Po(ce),Mo(ce),ce.content instanceof i&&Yr(ce.content);if(de)return W;if(A){if(k){T.normalize();let gt=T.innerHTML;kn([Se,je,te],_t=>{gt=En(gt,_t," ")}),T.innerHTML=gt}if(S)for(Fe=se.call(T.ownerDocument);T.firstChild;)Fe.appendChild(T.firstChild);else Fe=T;return(pe.shadowroot||pe.shadowrootmode)&&(Fe=D.call(s,Fe,!0)),Fe}let rt=_?T.outerHTML:T.innerHTML;return _&&ge["!doctype"]&&T.ownerDocument&&T.ownerDocument.doctype&&T.ownerDocument.doctype.name&&Ue(Kf,T.ownerDocument.doctype.name)&&(rt=" -`+rt),k&&kn([Se,je,te],gt=>{rt=En(rt,gt," ")}),U&&z?U.createHTML(rt):rt},t.setConfig=function(){let W=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Wr(W),P=!0},t.clearConfig=function(){Cn=null,P=!1},t.isValidAttribute=function(W,p,T){Cn||Wr({});const N=$e(W),ce=$e(p);return Io(N,ce,T)},t.addHook=function(W,p){typeof p=="function"&&Sn(Z[W],p)},t.removeHook=function(W,p){if(p!==void 0){const T=Pf(Z[W],p);return T===-1?void 0:If(Z[W],T,1)[0]}return lo(Z[W])},t.removeHooks=function(W){Z[W]=[]},t.removeAllHooks=function(){Z=bo()},t}var Qf=xo();const Jf={key:1,class:"flex min-w-0 max-w-[calc(100%-2.5rem)] flex-1 flex-col max-[600px]:max-w-[calc(100%-2.25rem)]"},ep={key:0,class:"flex w-fit flex-col items-start gap-1"},tp=["aria-label"],np={class:"inline-flex items-center gap-1.5"},sp={class:"text-[8px] font-semibold tracking-[0.12em] uppercase text-[#3a67c9]"},rp={key:1,class:"flex w-fit max-w-full flex-col items-start gap-2"},ip={class:"chat-card relative w-fit max-w-full whitespace-pre-line rounded-[10px_10px_10px_3px] px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900"},lp=["innerHTML"],op={key:0,class:"pointer-events-none absolute inset-x-0 bottom-0 h-14 rounded-b-[10px] bg-linear-to-t from-white via-white/92 to-white/0","aria-hidden":"true"},ap={key:0,class:"flex flex-wrap items-center gap-2"},up=["title","aria-label"],cp={key:1,class:"flex flex-wrap items-center"},fp=["title","aria-label"],pp={viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},dp=["innerHTML"],yo={__name:"ChatMessage",props:{message:{type:Object,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,default:()=>({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd"})}},setup(e){const t=e,n=J(!1),s=J(null),r=J(!1),i=J(!1),l=Ee(()=>typeof window!="undefined"&&"speechSynthesis"in window&&"SpeechSynthesisUtterance"in window);function a(L){typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("changai-tts-provider",{detail:{provider:L}}))}function o(L){if(typeof L!="string")return"";const O=L.replace(/[\u{1F000}-\u{1FFFF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s+/g,"").replace(/[-*+]\s+/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\s+/g," ");return O.includes("<")?(new DOMParser().parseFromString(L,"text/html").body.textContent||"").replace(/\s+/g," ").trim():O.trim()}function c(){l.value&&window.speechSynthesis.cancel(),s.value&&(s.value.pause(),s.value.src="",s.value=null),n.value=!1}function u(){var L,O,ee;if(i.value=!i.value,i.value)c();else{const q=M.value;if(!t.autoReadEnabled||!((L=t.ttsConfig)!=null&&L.enableVoiceChat)||!q||E())return;if((O=t.ttsConfig)!=null&&O.pollyAvailable&&((ee=t.ttsConfig)!=null&&ee.usePolly)){g(q).catch(se=>{d(q)});return}d(q)}}function d(L){if(!l.value||!L)return;window.dispatchEvent(new CustomEvent("changai-tts-stop")),window.speechSynthesis.cancel();const O=new SpeechSynthesisUtterance(L);O.rate=1,O.pitch=1,O.onend=()=>{n.value=!1},O.onerror=()=>{n.value=!1},n.value=!0,a("browser"),window.speechSynthesis.speak(O)}async function g(L){var fe;const O=await Mc(L,((fe=t.ttsConfig)==null?void 0:fe.voiceId)||"Zayd");if(!(O!=null&&O.ok)||!(O!=null&&O.audio_base64))throw new Error((O==null?void 0:O.error)||"Polly synthesis failed");window.dispatchEvent(new CustomEvent("changai-tts-stop")),c();const ee=(O==null?void 0:O.mime_type)||"audio/mpeg",q=new Audio(`data:${ee};base64,${O.audio_base64}`);s.value=q,n.value=!0;let se=!1;q.onplay=()=>{se=!0,a("polly")},q.onended=()=>{s.value===q&&(s.value=null),n.value=!1},q.onerror=()=>{s.value===q&&(s.value=null),n.value=!1},await q.play(),se||a("polly")}function y(){c()}function E(){var L;return!!((L=t.message)!=null&&L.isStatus)}function x(L){const O=L.target.closest("a");!O||!O.href||(L.preventDefault(),L.stopPropagation(),window.open(O.href,"_blank","noopener,noreferrer"))}const M=Ee(()=>{var L;return o(((L=t.message)==null?void 0:L.text)||"")}),m=Ee(()=>{var L;return((L=t.message)==null?void 0:L.role)!=="user"&&E()}),H=Ee(()=>{var L;return(L=t.message)!=null&&L.isStatus?t.message.statusType==="support"?"Sending to support":M.value||"Thinking":""}),Y=Ee(()=>{var ee;if(((ee=t.message)==null?void 0:ee.role)==="user"||m.value)return!1;const L=M.value,O=L.split(/\n+/).filter(Boolean).length;return L.length>520||O>8}),$=Ee(()=>{var L,O;return((L=t.message)==null?void 0:L.role)!=="user"&&!m.value&&((O=t.ttsConfig)==null?void 0:O.enableVoiceChat)}),U=Ee(()=>{var O;const L=((O=t.message)==null?void 0:O.text)||"";return Qf.sanitize(xe.parse(L))});return ln(()=>t.message.text,async(L,O)=>{var se,fe,D;if(!t.autoReadEnabled||t.message.role==="user"||i.value)return;if(!((se=t.ttsConfig)!=null&&se.enableVoiceChat)){a("off");return}const ee=o(L);if(!ee||E())return;const q=o(O||"");if(ee!==q){if((fe=t.ttsConfig)!=null&&fe.pollyAvailable&&((D=t.ttsConfig)!=null&&D.usePolly))try{await g(ee);return}catch{}d(ee)}}),ln(()=>t.message.text,()=>{r.value=!1,i.value=!1}),zn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-stop",y)}),ys(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-stop",y),n.value&&c()}),(L,O)=>(B(),G("div",{class:we(["motion-safe:animate-fade-rise flex w-full gap-1.5",e.message.role==="user"?"flex-col items-end":"items-start"])},[e.message.role!=="user"?(B(),Et(Nl,{key:0})):We("",!0),e.message.role!=="user"?(B(),G("div",Jf,[m.value?(B(),G("div",ep,[w("div",{class:"chat-card inline-flex w-fit rounded-[10px_10px_10px_3px] px-3 py-2",role:"status","aria-live":"polite","aria-label":H.value},[w("div",np,[O[1]||(O[1]=w("span",{class:"relative inline-flex h-4 w-4 shrink-0 items-center justify-center"},[w("span",{class:"absolute inset-0 rounded-full border border-transparent border-t-[#4b89ff] border-r-[#4b89ff]/70 animate-gemini-arc"}),w("svg",{viewBox:"0 0 24 24",class:"relative h-3 w-3 text-[#4b89ff] animate-gemini-spark","aria-hidden":"true"},[w("path",{fill:"currentColor",d:"M12 2.8c.52 3.22 1.6 5.66 3.22 7.28 1.62 1.62 4.06 2.7 7.28 3.22-3.22.52-5.66 1.6-7.28 3.22-1.62 1.62-2.7 4.06-3.22 7.28-.52-3.22-1.6-5.66-3.22-7.28-1.62-1.62-4.06-2.7-7.28-3.22 3.22-.52 5.66-1.6 7.28-3.22 1.62-1.62 2.7-4.06 3.22-7.28Z"})])],-1)),w("span",sp,et(H.value),1)])],8,tp)])):(B(),G("div",rp,[w("div",ip,[w("div",{class:we(["overflow-x-auto",Y.value&&!r.value?"max-h-48 overflow-y-hidden":""]),innerHTML:U.value,onClick:x},null,10,lp),Y.value&&!r.value?(B(),G("div",op)):We("",!0)]),Y.value?(B(),G("div",ap,[w("button",{type:"button",class:"inline-flex items-center rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-600 transition-colors duration-200 hover:border-brand-200 hover:text-brand-600",title:r.value?"Collapse response":"Expand response","aria-label":r.value?"Collapse response":"Expand response",onClick:O[0]||(O[0]=ee=>r.value=!r.value)},et(r.value?"Collapse":"Expand"),9,up)])):We("",!0),$.value?(B(),G("div",cp,[w("button",{type:"button",class:we(["inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors duration-200",i.value?"border-red-200 bg-red-50 text-red-600 hover:border-red-300 hover:bg-red-100":"border-green-200 bg-green-50 text-green-600 hover:border-green-300 hover:bg-green-100"]),title:i.value?"Unmute voice playback":"Mute voice playback","aria-label":i.value?"Unmute voice playback":"Mute voice playback",onClick:u},[(B(),G("svg",pp,[O[6]||(O[6]=w("path",{d:"M11 5L6 9H3v6h3l5 4V5Z"},null,-1)),i.value?(B(),G(ze,{key:0},[O[2]||(O[2]=w("path",{d:"M15 9l4 6"},null,-1)),O[3]||(O[3]=w("path",{d:"M19 9l-4 6"},null,-1))],64)):(B(),G(ze,{key:1},[O[4]||(O[4]=w("path",{d:"M15 10a3 3 0 0 1 0 4"},null,-1)),O[5]||(O[5]=w("path",{d:"M17.5 7.5a6 6 0 0 1 0 9"},null,-1))],64))]))],10,fp)])):We("",!0)]))])):(B(),G("div",{key:2,class:"w-fit max-w-[85%] whitespace-pre-line rounded-[13px_13px_3px_13px] bg-linear-to-br from-brand-500 to-brand-600 px-4 py-3 text-[11px] leading-relaxed wrap-anywhere text-white shadow-[0_14px_30px_-18px_rgba(109,79,194,0.85)] max-[600px]:max-w-[88%]",innerHTML:U.value},null,8,dp))],2))}},hp={class:"flex flex-col gap-4 sm:gap-5"},gp={class:"motion-safe:animate-fade-rise flex w-full items-start gap-1.5"},mp={__name:"ChatTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(B(),G("div",hp,[w("div",gp,[Me(Nl),n[0]||(n[0]=w("p",{class:"w-fit max-w-[calc(100%-2.5rem)] whitespace-pre-line rounded-[10px_10px_10px_3px] bg-brand-50 px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900 max-[600px]:max-w-[calc(100%-2.25rem)]"},[Ss(" Hello there ๐ I am ChangAI from "),w("a",{target:"_blank",href:"https://erpgulf.com",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ERPGulf.com"),Ss(", your ERP assistant."),w("br"),w("a",{target:"_blank",href:"https://app.erpgulf.com/en/articles/chang-ai-quick-start-guide",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ChangAI Quick Start Guide - Click here.")],-1))]),(B(!0),G(ze,null,ws(e.messages,(s,r)=>(B(),Et(yo,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}};function wo(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function vo(e){var t,n;return(e==null?void 0:e.message)||((t=e==null?void 0:e.responseJSON)==null?void 0:t.exception)||((n=e==null?void 0:e.responseJSON)==null?void 0:n.message)||(e==null?void 0:e.responseText)||String(e)}function bp(e){return typeof e=="string"?e:e&&typeof e=="object"?e.error?`โ ๏ธ ${e.error}`:e.answer||e.text||"":""}const xp={key:0,class:"rounded-lg bg-brand-50 px-4 py-3 text-xs text-black"},yp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},wp={key:1,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-brand-50 p-2 text-[11px]"},vp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},_p={__name:"DebugTab",props:{logs:{type:Array,required:!0},currentDebug:{type:Object,default:null}},setup(e){const t=new Set(["gemini_json_content","private_key","private_key_id","client_secret","client_id","aws_access_key","aws_secret_key","api_key","token","access_token","refresh_token","password","secret","authorization","embed_version_id","llm_version_id","entity_retriever","retriever","deploy_url","support_api_url","get_ticket_details_url"]);function n(r,i=0){if(i>10||r===null||r===void 0||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(Array.isArray(r))return r.map(l=>n(l,i+1));if(typeof r=="object"){const l={};for(const[a,o]of Object.entries(r))t.has(a.toLowerCase())||(l[a]=n(o,i+1));return l}return r}function s(r){return wo(n(r))}return(r,i)=>(B(),G("div",null,[e.logs.length===0?(B(),G("p",xp,"No debug data yet.")):We("",!0),(B(!0),G(ze,null,ws(e.logs,(l,a)=>(B(),G("div",{key:a,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-gray-100 p-2 text-[11px]"},[w("pre",yp,et(s(l)),1)]))),128)),e.currentDebug?(B(),G("div",wp,[w("pre",vp,et(s(e.currentDebug)),1)])):We("",!0)]))}},Tp={class:"flex flex-col gap-4 sm:gap-5"},kp={key:0,class:"chat-card motion-safe:animate-fade-rise rounded-lg px-4 py-3 text-xs text-slate-900"},Sp={__name:"SupportTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(B(),G("div",Tp,[e.messages.length===0?(B(),G("p",kp,"Send a message to Support.")):We("",!0),(B(!0),G(ze,null,ws(e.messages,(s,r)=>(B(),Et(yo,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}},Ep={class:"flex flex-col gap-4"},Ap={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Rp={class:"flex items-start justify-between gap-4"},Cp=["aria-pressed","title"],Pp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Ip={class:"flex items-start justify-between gap-4"},Op={class:"mt-2 text-[11px] text-slate-500"},Mp={key:0,class:"mt-1 text-[11px] text-slate-500"},Lp={key:1,class:"mt-1 text-[11px] text-slate-500"},$p=["aria-pressed","disabled"],Dp={key:0,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Np={key:1,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},Fp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Bp={class:"flex items-start justify-between gap-4"},Hp=["aria-pressed","title"],zp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Up={class:"flex items-start justify-between gap-4"},jp=["aria-pressed","title"],Vp={__name:"SettingsTab",props:{autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},settings:{type:Object,default:null},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1}},emits:["toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e){const t=e,n=Ee(()=>{var s,r;return(s=t.ttsConfig)!=null&&s.enableVoiceChat?(r=t.ttsConfig)!=null&&r.pollyAvailable?"Available":"Unavailable":"Voice disabled on server"});return(s,r)=>{var i,l,a,o,c,u,d,g,y,E,x,M,m,H,Y;return B(),G("div",Ep,[r[10]||(r[10]=w("div",{class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4 text-slate-900"},[w("h3",{class:"text-sm font-semibold tracking-[0.01em]"},"Speech Settings"),w("p",{class:"mt-1 text-xs leading-relaxed text-slate-600"},"These controls apply only inside this chatbot box for the current browser session.")],-1)),w("div",Ap,[w("div",Rp,[r[4]||(r[4]=w("div",null,[w("p",{class:"text-sm font-semibold text-slate-900"},"Auto Read Replies"),w("p",{class:"mt-1 text-xs text-slate-600"},"Automatically read bot replies aloud.")],-1)),w("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.autoReadEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.autoReadEnabled?"true":"false",title:e.autoReadEnabled?"Disable auto read":"Enable auto read",onClick:r[0]||(r[0]=$=>s.$emit("toggleAutoRead"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.autoReadEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Cp)]),w("p",{class:we(["mt-3 text-[11px] font-medium",e.autoReadEnabled?"text-emerald-700":"text-slate-500"])},et(e.autoReadEnabled?"Auto read is active.":"Auto read is currently off."),3)]),w("div",Pp,[w("div",Ip,[w("div",null,[r[5]||(r[5]=w("p",{class:"text-sm font-semibold text-slate-900"},"Use Amazon Polly",-1)),r[6]||(r[6]=w("p",{class:"mt-1 text-xs text-slate-600"},"Use Polly when available; otherwise browser speech is used automatically.",-1)),w("p",Op,"Availability: "+et(n.value),1),(i=e.settings)!=null&&i.aws_region?(B(),G("p",Mp,"Region: "+et(e.settings.aws_region),1)):We("",!0),(l=e.ttsConfig)!=null&&l.voiceId?(B(),G("p",Lp,"Voice: "+et(e.ttsConfig.voiceId),1)):We("",!0)]),w("button",{class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-55",(a=e.ttsConfig)!=null&&a.usePolly&&((o=e.ttsConfig)!=null&&o.enableVoiceChat)&&((c=e.ttsConfig)!=null&&c.pollyAvailable)?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":(u=e.ttsConfig)!=null&&u.usePolly&&((d=e.ttsConfig)!=null&&d.enableVoiceChat)&&((g=e.ttsConfig)!=null&&g.pollyAvailable)?"true":"false",disabled:!((y=e.ttsConfig)!=null&&y.pollyAvailable)||!((E=e.ttsConfig)!=null&&E.enableVoiceChat),onClick:r[1]||(r[1]=$=>s.$emit("togglePollyPreference"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",(x=e.ttsConfig)!=null&&x.usePolly&&((M=e.ttsConfig)!=null&&M.enableVoiceChat)&&((m=e.ttsConfig)!=null&&m.pollyAvailable)?"left-[1.45rem]":"left-0.5"])},null,2)],10,$p)]),(H=e.ttsConfig)!=null&&H.enableVoiceChat?(Y=e.ttsConfig)!=null&&Y.pollyAvailable?We("",!0):(B(),G("p",Np,"Polly is not available for this site. Browser speech will be used.")):(B(),G("p",Dp,"Voice chat is disabled in ChangAI Settings."))]),w("div",Fp,[w("div",Bp,[w("div",null,[r[7]||(r[7]=w("p",{class:"text-sm font-semibold text-slate-900"},"Enable Debug Tab",-1)),r[8]||(r[8]=w("p",{class:"mt-1 text-xs text-slate-600"}," Show or hide the Debug tab inside this chatbot. ",-1)),w("p",{class:we(["mt-2 text-[11px] font-medium",e.debugEnabled?"text-emerald-700":"text-slate-500"])},et(e.debugEnabled?"Debug tab is active.":"Debug tab is currently off."),3)]),w("button",{type:"button",class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.debugEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.debugEnabled?"true":"false",title:e.debugEnabled?"Disable debug tab":"Enable debug tab",onClick:r[2]||(r[2]=$=>s.$emit("toggleDebug"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.debugEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Hp)])]),w("div",zp,[w("div",Up,[r[9]||(r[9]=w("div",null,[w("p",{class:"text-sm font-semibold text-slate-900"},"Send non-ERP questions directly to AI"),w("p",{class:"mt-1 text-xs text-slate-600"},"Questions unrelated to your ERP will skip the system and go straight to AI")],-1)),w("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.sendNonERPtoaiEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.sendNonERPtoaiEnabled?"true":"false",title:e.sendNonERPtoaiEnabled?"Non-ERP questions are being sent directly to AI":"Enable direct AI reply for non-ERP questions",onClick:r[3]||(r[3]=$=>s.$emit("toggleSendNonERP"))},[w("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.sendNonERPtoaiEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,jp)]),w("p",{class:we(["mt-3 text-[11px] font-medium",e.sendNonERPtoaiEnabled?"text-emerald-700":"text-slate-500"])},et(e.sendNonERPtoaiEnabled?"Non-ERP questions are now routed directly to AI":"Direct AI routing is currently off"),3)])])}}},qp={key:0,class:"pointer-events-none absolute -top-14 left-0 right-0 z-20 flex justify-center px-2",role:"status","aria-live":"polite"},Wp={__name:"StatusToast",props:{visible:{type:Boolean,required:!0},message:{type:String,default:""},type:{type:String,default:"info"},dismissible:{type:Boolean,default:!0}},emits:["close"],setup(e){const t=e,n=Ee(()=>t.type==="error"?"bg-red-50 text-red-700 ring-red-200":(t.type==="listening","bg-blue-50 text-blue-700 ring-blue-200")),s=Ee(()=>t.type==="error"?"bg-red-500":t.type==="listening"?"bg-blue-500 animate-pulse":"bg-blue-500");return(r,i)=>(B(),Et(Pu,{"enter-active-class":"transition duration-200 ease-out","enter-from-class":"translate-y-1 opacity-0","enter-to-class":"translate-y-0 opacity-100","leave-active-class":"transition duration-150 ease-in","leave-from-class":"translate-y-0 opacity-100","leave-to-class":"translate-y-1 opacity-0"},{default:Di(()=>[e.visible?(B(),G("div",qp,[w("div",{class:we(["pointer-events-auto flex max-w-[92%] items-start gap-2 rounded-lg px-3 py-2 text-xs shadow-lg ring-1",n.value])},[w("span",{class:we(["mt-0.5 h-2 w-2 shrink-0 rounded-full",s.value])},null,2),w("span",null,et(e.message),1),e.dismissible?(B(),G("button",{key:0,type:"button",class:"ml-1 appearance-none border-0 text-current/80 transition hover:text-current focus:outline-none","aria-label":"Dismiss notification",onClick:i[0]||(i[0]=l=>r.$emit("close"))}," ร ")):We("",!0)],2)])):We("",!0)]),_:1}))}},Gp={class:"relative w-full"},Kp=["placeholder","disabled"],Yp=["title","aria-label","disabled"],Zp={key:0,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},Xp={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},Qp={key:2,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true",class:"animate-spin"},Jp=["title","aria-label","disabled"],ed={key:0,viewBox:"0 0 24 24",width:"18",height:"18",fill:"none","aria-hidden":"true",class:"text-rose-600 motion-safe:animate-stop-button-pulse"},td={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},nd={__name:"ChatForm",props:{placeholder:{type:String,default:"Message..."},disabled:{type:Boolean,default:!1},isAwaitingResponse:{type:Boolean,default:!1}},emits:["submit","cancel"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(""),l=J(null),a=J(!1),o=J(!1),c=J(!1),u=J(!1),d=J(!1),g=J(!1),y=J(!1),E=J(""),x=J("info"),M=J("Voice input is unavailable in this browser/context.");let m=null,H=null,Y=null;const $=J(""),U=J(!1),L=Ee(()=>c.value?"Requesting microphone permission...":u.value?"Starting voice input...":d.value?"Stopping voice input...":o.value?a.value?"Stop voice input":"Start voice input":"Voice input is unavailable in this browser/context"),O=Ee(()=>s.isAwaitingResponse?"Stop response":"Send"),ee=Ee(()=>s.isAwaitingResponse?!1:s.disabled||!i.value.trim()),q=Ee(()=>s.isAwaitingResponse?"bg-white border border-rose-100 shadow-[0_8px_20px_-12px_rgba(159,18,57,0.35)] hover:bg-rose-50":"bg-linear-to-br from-brand-500 to-brand-600 text-white shadow-[0_10px_24px_-16px_rgba(109,79,194,0.85)] hover:from-brand-600 hover:to-violet-700");function se(){return typeof window=="undefined"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}function fe(){var ge;const re=se(),F=typeof window!="undefined"?window.isSecureContext:!1,ue=typeof navigator!="undefined"&&!!((ge=navigator.mediaDevices)!=null&&ge.getUserMedia);o.value=!!(re&&F&&ue),F?(!ue||!re)&&(M.value="Voice input is not supported in this browser."):M.value="Voice input requires HTTPS (or localhost).",re&&o.value&&(m=new re,m.continuous=!0,m.interimResults=!0,m.lang=typeof navigator!="undefined"&&navigator.language||"en-US",m.onstart=()=>{a.value=!0,u.value=!1,d.value=!1,D(),R("Listening... Tap mic to stop","listening",{persistent:!0,key:"listening"})},m.onend=()=>{a.value=!1,u.value=!1,d.value=!1,D(),$.value==="listening"&&he(),U.value&&(U.value=!1,Le())},m.onerror=Te=>{if(a.value=!1,u.value=!1,d.value=!1,D(),U.value=!1,(Te==null?void 0:Te.error)==="not-allowed"||(Te==null?void 0:Te.error)==="service-not-allowed"){R("Microphone permission denied. Please allow microphone access in browser settings.","error");return}if((Te==null?void 0:Te.error)==="audio-capture"){R("No microphone detected. Please connect a microphone and try again.","error");return}if((Te==null?void 0:Te.error)==="no-speech"){R("No speech detected. Try speaking a bit louder.","info");return}R("Voice input failed. Please try again.","error")},m.onresult=Te=>{let pe="";for(let Qe=Te.resultIndex;Qe {if(m&&!(!a.value&&!d.value))try{m.abort()}catch{d.value=!1,U.value=!1}},1200)}}function Se(){if(!o.value||!m){R(M.value,"error");return}if(a.value||u.value||d.value){Z({submitAfterStop:a.value});return}te()}async function je(){var re;if(g.value)return!0;if(!((re=navigator.mediaDevices)!=null&&re.getUserMedia))return R("Microphone API is unavailable in this browser.","error"),!1;c.value=!0,R("Requesting microphone permission...","info",{persistent:!0,key:"requesting"});try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(ue=>ue.stop()),g.value=!0,!0}catch(F){return(F==null?void 0:F.name)==="NotAllowedError"||(F==null?void 0:F.name)==="SecurityError"?R("Microphone permission denied. Please allow it and try again.","error"):(F==null?void 0:F.name)==="NotFoundError"?R("No microphone found on this device.","error"):R("Unable to access microphone. Please check browser permissions.","error"),!1}finally{c.value=!1,$.value==="requesting"&&he()}}async function te(){var F;if(!(!m||a.value||u.value||d.value||!await je()||!m)){U.value=!1,(F=l.value)==null||F.focus(),u.value=!0;try{m.start()}catch(ue){u.value=!1,d.value=!1,(ue==null?void 0:ue.name)!=="InvalidStateError"&&R("Unable to start voice input. Please try again.","error")}}}function R(re,F="info",ue={}){const{duration:ge=4200,persistent:Te=!1,key:pe=""}=ue;E.value=re,x.value=F,$.value=pe,y.value=!0,H&&clearTimeout(H),Te||(H=setTimeout(()=>{y.value=!1,$.value=""},ge))}function he(){y.value=!1,$.value="",H&&(clearTimeout(H),H=null)}function Le(){if(s.isAwaitingResponse){r("cancel");return}const re=i.value.trim();re&&((a.value||u.value||d.value)&&m&&Z({submitAfterStop:!1}),r("submit",re),i.value="")}return t({focus:()=>{var re;return(re=l.value)==null?void 0:re.focus()}}),zn(()=>{fe()}),ys(()=>{if(m&&(a.value||u.value||d.value)){U.value=!1,D();try{m.abort()}catch{}}D(),he()}),(re,F)=>(B(),G("div",Gp,[w("form",{class:"group flex min-h-11 items-center gap-2 rounded-full border border-slate-200/90 bg-white/95 px-3 shadow-[0_12px_26px_-20px_rgba(15,23,42,0.7)] transition-all duration-250 focus-within:-translate-y-0.5 focus-within:border-brand-200 focus-within:shadow-[0_18px_30px_-20px_rgba(13,110,253,0.5)] focus-within:ring-2 focus-within:ring-brand-500/25",style:{"border-radius":"9999px"},autocomplete:"off",onSubmit:dt(Le,["prevent"]),onClick:F[5]||(F[5]=dt(()=>{},["stop"])),onMousedown:F[6]||(F[6]=dt(()=>{},["stop"])),onKeydown:F[7]||(F[7]=dt(()=>{},["stop"])),onKeyup:F[8]||(F[8]=dt(()=>{},["stop"]))},[Pa(w("input",{ref_key:"inputRef",ref:l,type:"text","onUpdate:modelValue":F[0]||(F[0]=ue=>i.value=ue),class:"h-11 w-full border-none bg-transparent text-sm font-medium text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:e.disabled?"Waiting for response...":e.placeholder,disabled:e.disabled,required:"",onKeydown:F[1]||(F[1]=dt(()=>{},["stop"])),onKeyup:F[2]||(F[2]=dt(()=>{},["stop"])),onKeypress:F[3]||(F[3]=dt(()=>{},["stop"])),onInput:F[4]||(F[4]=dt(()=>{},["stop"]))},null,40,Kp),[[Xu,i.value]]),w("button",{type:"button",class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-transparent text-slate-600 transition-all duration-200 hover:-translate-y-0.5 hover:border-slate-200 hover:bg-slate-100 hover:text-slate-900 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",a.value?"border-red-200 bg-red-100 text-red-600 shadow-[0_10px_20px_-18px_rgba(220,38,38,0.9)] hover:bg-red-100 hover:text-red-600":""]),style:{"border-radius":"9999px"},title:L.value,"aria-label":L.value,disabled:e.disabled||!o.value||c.value||u.value||d.value,onClick:Se},[a.value&&!c.value?(B(),G("svg",Zp,F[9]||(F[9]=[w("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"},null,-1)]))):c.value?(B(),G("svg",Qp,F[11]||(F[11]=[w("circle",{cx:"12",cy:"12",r:"9",opacity:"0.3"},null,-1),w("path",{d:"M21 12a9 9 0 0 1-9 9"},null,-1)]))):(B(),G("svg",Xp,F[10]||(F[10]=[w("path",{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},null,-1),w("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"},null,-1),w("path",{d:"M12 19v3"},null,-1)])))],10,Yp),w("button",{type:"submit",title:O.value,"aria-label":O.value,class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border-0 transition-all duration-200 hover:-translate-y-0.5 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",q.value]),style:{"border-radius":"9999px"},disabled:ee.value},[e.isAwaitingResponse?(B(),G("svg",ed,F[12]||(F[12]=[w("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor","stroke-width":"2.1",class:"opacity-95"},null,-1),w("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.35",fill:"currentColor"},null,-1)]))):(B(),G("svg",td,F[13]||(F[13]=[w("path",{d:"M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"},null,-1)])))],10,Jp)],32),Me(Wp,{visible:y.value,message:E.value,type:x.value,dismissible:x.value!=="listening",onClose:he},null,8,["visible","message","type","dismissible"])]))}},sd={class:"relative overflow-hidden bg-linear-to-br from-brand-600 via-brand-500 to-violet-400"},rd={class:"min-w-0"},id={key:1,class:"border-t border-slate-200/80 bg-white/90 px-3 py-3 pb-[calc(12px+env(safe-area-inset-bottom))] backdrop-blur-sm sm:px-4 sm:py-4"},ld=56,od={__name:"ChatbotPopup",props:{isOpen:{type:Boolean,required:!0},activeTab:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1},chatHistory:{type:Array,required:!0},debugLogs:{type:Array,required:!0},currentDebug:{type:Object,default:null},supportHistory:{type:Array,required:!0},autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},activeTtsProvider:{type:String,required:!0},settings:{type:Object,default:null},isAwaitingChatResponse:{type:Boolean,default:!1},isAwaitingSupportResponse:{type:Boolean,default:!1}},emits:["close","submit","cancelResponse","update:activeTab","toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=J(null),l=J(null),a=J(s.activeTab),o=J("default"),c=J(!1),u=Ee(()=>a.value==="support"?s.isAwaitingSupportResponse:a.value==="chat"?s.isAwaitingChatResponse:!1);function d(){const M=i.value;if(!s.isOpen||!M){c.value=!1;return}const m=M.scrollHeight-M.clientHeight;if(m<=4){c.value=!1;return}const H=m-M.scrollTop;c.value=H>ld}function g(){const M=i.value;M&&(M.scrollTo({top:M.scrollHeight,behavior:"smooth"}),setTimeout(()=>{d()},220))}function y(){St(()=>{d()})}function E(){if(o.value==="default"){o.value="half";return}if(o.value==="half"){o.value="full";return}o.value="default"}const x=Ee(()=>{const M="chat-shell fixed z-[9999] flex min-h-0 flex-col overflow-hidden border border-slate-200/80 shadow-[0_32px_80px_-44px_rgba(2,6,23,0.7),0_18px_40px_-24px_rgba(15,23,42,0.45)] transition-all duration-300 ease-out origin-bottom-right",m=s.isOpen?"pointer-events-auto opacity-100 translate-x-0 translate-y-0 scale-100 motion-safe:animate-surface-in":"pointer-events-none opacity-0 translate-x-1/5 translate-y-8 scale-95";return o.value==="full"?[M,m,"inset-0 h-screen w-screen max-h-screen max-w-screen rounded-none origin-center"]:o.value==="half"?[M,m,"bottom-[74px] right-5 h-[min(86vh,860px)] w-[min(50vw,860px)] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(86vh,760px)] max-[900px]:w-[min(70vw,760px)] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]:[M,m,"bottom-[74px] right-5 h-[min(560px,72vh)] w-[min(360px,calc(100vw-40px))] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(70vh,540px)] max-[900px]:w-[min(360px,calc(100vw-24px))] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]});return ln(()=>s.activeTab,M=>{a.value=M,y()}),ln(()=>s.isOpen,M=>{M&&a.value!=="settings"&&St(()=>{var m;return(m=l.value)==null?void 0:m.focus()}),y()}),ln(a,M=>{r("update:activeTab",M),y()}),ln(()=>[s.chatHistory.length,s.supportHistory.length,s.debugLogs.length,s.currentDebug],()=>{y()}),ln(()=>s.debugEnabled,M=>{!M&&a.value==="debug"&&(a.value="chat"),y()}),zn(()=>{y()}),t({scrollToBottom(){St(()=>{g()})}}),(M,m)=>(B(),G("div",{class:we(x.value),onKeydown:m[9]||(m[9]=dt(()=>{},["stop"])),onKeyup:m[10]||(m[10]=dt(()=>{},["stop"])),onKeypress:m[11]||(m[11]=dt(()=>{},["stop"]))},[m[14]||(m[14]=w("div",{class:"pointer-events-none absolute -right-14 -top-14 h-36 w-36 rounded-full bg-brand-500/15 blur-2xl"},null,-1)),m[15]||(m[15]=w("div",{class:"pointer-events-none absolute -bottom-14 -left-12 h-32 w-32 rounded-full bg-violet-400/15 blur-2xl"},null,-1)),w("div",sd,[m[12]||(m[12]=w("div",{class:"pointer-events-none absolute inset-0 opacity-45",style:{background:"linear-gradient(120deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.02) 52%, rgba(255,255,255,0.12) 100%)"}},null,-1)),Me(vc,{windowMode:o.value,autoReadEnabled:e.autoReadEnabled,activeTtsProvider:e.activeTtsProvider,onClose:m[0]||(m[0]=H=>M.$emit("close")),onCycleResize:E,onToggleAutoRead:m[1]||(m[1]=H=>M.$emit("toggleAutoRead"))},null,8,["windowMode","autoReadEnabled","activeTtsProvider"]),Me(Sc,{modelValue:a.value,"onUpdate:modelValue":m[2]||(m[2]=H=>a.value=H),debugEnabled:e.debugEnabled},null,8,["modelValue","debugEnabled"])]),w("div",{class:"chat-scrollbar min-h-0 flex-1 overflow-x-hidden overflow-y-scroll bg-slate-50/60 px-4 py-4 max-[900px]:px-3.5 max-[900px]:py-3.5 max-[600px]:px-3 max-[600px]:py-3",ref_key:"chatBodyRef",ref:i,onScrollPassive:d},[w("div",rd,[a.value==="chat"?(B(),Et(mp,{key:0,messages:e.chatHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="debug"&&e.debugEnabled?(B(),Et(_p,{key:1,logs:e.debugLogs,currentDebug:e.currentDebug},null,8,["logs","currentDebug"])):a.value==="support"?(B(),Et(Sp,{key:2,messages:e.supportHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="settings"?(B(),Et(Vp,{key:3,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig,settings:e.settings,debugEnabled:e.debugEnabled,sendNonERPtoaiEnabled:e.sendNonERPtoaiEnabled,onToggleAutoRead:m[3]||(m[3]=H=>M.$emit("toggleAutoRead")),onTogglePollyPreference:m[4]||(m[4]=H=>M.$emit("togglePollyPreference")),onToggleDebug:m[5]||(m[5]=H=>M.$emit("toggleDebug")),onToggleSendNonERP:m[6]||(m[6]=H=>M.$emit("toggleSendNonERP"))},null,8,["autoReadEnabled","ttsConfig","settings","debugEnabled","sendNonERPtoaiEnabled"])):We("",!0)])],544),c.value?(B(),G("button",{key:0,type:"button",class:we(["absolute right-4 z-20 grid h-9 w-9 place-items-center rounded-full border border-brand-200/70 bg-white/95 text-brand-600 shadow-[0_14px_26px_-16px_rgba(15,23,42,0.65)] transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-300 hover:text-brand-700 focus:outline-none",a.value!=="settings"?"bottom-[calc(90px+env(safe-area-inset-bottom))] sm:bottom-[96px]":"bottom-4 sm:bottom-5"]),title:"Scroll to bottom","aria-label":"Scroll to bottom",onClick:g},m[13]||(m[13]=[w("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},[w("path",{d:"M7 10l5 5 5-5"})],-1)]),2)):We("",!0),a.value!=="settings"?(B(),G("div",id,[Me(nd,{ref_key:"chatFormRef",ref:l,placeholder:a.value==="support"?"Message Support...":"Message...",disabled:u.value,isAwaitingResponse:u.value,onSubmit:m[7]||(m[7]=H=>M.$emit("submit",H)),onCancel:m[8]||(m[8]=H=>M.$emit("cancelResponse"))},null,8,["placeholder","disabled","isAwaitingResponse"])])):We("",!0)],34))}},_o="changai_chat_id",To="changai_polly_enabled";function ad(){let e=sessionStorage.getItem(_o);return e||(e=`session_${Date.now()}_${crypto.randomUUID()}`,sessionStorage.setItem(_o,e)),e}function ud(){const e=localStorage.getItem(To);return e===null?!0:e==="true"}function cd(e){localStorage.setItem(To,String(!!e))}const fd={__name:"App",setup(e){const t=J(!1),n=J("chat"),s=J([]),r=J([]),i=J(!1),l=J([]),a=J(null),o=J("actual"),c=J(!0),u=J(null),d=J(!1),g=J(null),y=J((()=>{try{return localStorage.getItem("sendNonERPtoaiEnabled")==="true"}catch{return!1}})()),E=J({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd",enable_changai:!1}),x=J("off"),M=J(null),m=J(null),H=Ee(()=>M.value!==null),Y=Ee(()=>m.value!==null);function $(){if(!E.value.enableVoiceChat){x.value="off";return}x.value=E.value.usePolly?"polly":"browser"}function U(te){var he;const R=(he=te==null?void 0:te.detail)==null?void 0:he.provider;(R==="polly"||R==="browser"||R==="off")&&(x.value=R)}async function L(){var R,he,Le,re,F;if(!(d.value||u.value)){d.value=!0;try{u.value=await Oc(o.value),E.value={enableVoiceChat:!!((R=u.value)!=null&&R.enable_voice_chat),pollyAvailable:!!((he=u.value)!=null&&he.polly_enabled),usePolly:!!((Le=u.value)!=null&&Le.polly_enabled)&&ud(),voiceId:((re=u.value)==null?void 0:re.polly_voice_id)||"Zayd",enable_changai:!!((F=u.value)!=null&&F.enable_changai)},$(),r.value.push({type:"settings",settings:u.value})}catch(ue){const ge=vo(ue);r.value.push({type:"settings",error:ge})}finally{d.value=!1}}}function O(){t.value=!t.value}function ee(){var te;(te=a.value)==null||te.scrollToBottom()}function q(){c.value=!c.value}function se(){const te=!E.value.usePolly;E.value={...E.value,usePolly:te&&E.value.pollyAvailable},cd(E.value.usePolly),$()}function fe(){y.value=!y.value,localStorage.setItem("sendNonERPtoaiEnabled",y.value)}async function D(te){n.value==="support"?await je(te):await Z(te)}async function Z(te){var Qe,ye;g.value=null,o.value==="actual"&&await L(),s.value.push({role:"user",text:te}),await St(),ee();const R=cs({role:"model",text:"Thinking...",cancelable:!0,isStatus:!0,statusType:"thinking"});s.value.push(R),await St(),ee();const he=j=>{var Ft;const st=Date.now(),Ie=((st-Te)/1e3).toFixed(2);if(Te=st,j.message){const f=`${j.message} (${Ie}s)`;pe.push(f),g.value=f,R.text=j.message,R.statusType="pipeline"}if(!j.done&&j.message&&(R.text=j.message,R.statusType="pipeline"),j.done){R.cancelable=!1,j.error?(R.text=`โ ๏ธ ${j.message||"Something failed"}`,R.isStatus=!1,R.statusType=null):(Ft=j.data)!=null&&Ft.answer&&(R.text=j.data.answer,R.isStatus=!1,R.statusType=null),frappe.realtime.off(ue,he),g.value=null;return}};let Le=!1;const re=ad(),F=`${re}_${Date.now()}`,ue=`debug_${F}`;frappe.realtime.on(ue,he);const ge=Pc(te,re,o.value,F,y.value);let Te=Date.now();const pe=[];M.value=()=>{Le||(Le=!0,ge.cancel(),frappe.realtime.off(ue,he),R.isStatus=!1,R.statusType=null,R.text="Cancelled by user.",r.value.push({type:"cancelled",user:te,steps:[...pe]}),g.value=null,R.cancelable=!1,M.value=null)};try{const j=await ge.promise;if(j!=null&&j.open_report){if(R.isStatus=!1,R.statusType=null,R.text=`Opening "${j.report_name}" report." `,r.value.push({type:"success",steps:[...pe],final_response:j,entity_raw:j.entity_raw}),g.value=null,!j.report_name){R.text="Report name extraction failed.Can you ask the same question again?";return}frappe.set_route("query-report",j.report_name,j.filters||{});return}else if(j!=null&&j.create_entity){R.isStatus=!1,R.statusType=null,R.cancelable=!1,R.text=`Opening "${j.doc}" doctype for creating a new record.`,r.value.push({type:"success",user:te,steps:[...pe],final_response:j}),g.value=null;const Ie=j.doc,Ft=j.fields_to_fill||{},f=j.child_tables||{},h=j.entity_name||"",b={Customer:{customer_name:h},Supplier:{supplier_name:h},Employee:{employee_name:h},Item:{item_code:h,item_name:h},Project:{project_name:h},Lead:{lead_name:h},Opportunity:{opportunity_name:h}},k=Object.keys(Ft).length>0?Ft:b[Ie]||{};frappe.route_options=k,frappe.set_route("Form",Ie,"new");let v=0;const _=setInterval(()=>{if(v++>50){clearInterval(_);return}cur_frm&&cur_frm.doctype===Ie&&cur_frm.is_new()&&(clearInterval(_),Object.entries(k).forEach(([P,C])=>{C&&cur_frm.fields_dict[P]&&(cur_frm.set_value(P,C),cur_frm.refresh_field(P))}),Object.entries(f).forEach(([P,C])=>{!Array.isArray(C)||!C.length||cur_frm.fields_dict[P]&&(C.forEach(A=>{const S=frappe.model.add_child(cur_frm.doc,P);Object.entries(A).forEach(([z,I])=>{I!=null&&I!==""&&frappe.model.set_value(S.doctype,S.name,z,I)})}),cur_frm.refresh_field(P))}))},200);return}if(j!=null&&j.stop_followup){R.isStatus=!1,R.statusType=null,R.cancelable=!1,R.text=j.message||"Youโre welcome!",r.value.push({type:"stop_followup",user:te,steps:[...pe],final_response:j}),g.value=null;return}if(Le)return;R.cancelable=!1;const st=((Qe=bp(j==null?void 0:j.Bot))==null?void 0:Qe.trim())||"No response.";R.isStatus=!1,R.statusType=null,R.text=st,r.value.push({type:"success",user:te,steps:[...pe],final_response:j}),g.value=null}catch(j){if(Le)return;R.cancelable=!1,R.isStatus=!1,R.statusType=null;const st=vo(j);g.value=null,r.value.push({type:"failed",user:te,steps:[...pe],error:st}),(j==null?void 0:j.code)==="ERR_NETWORK_CHANGED"||(ye=j==null?void 0:j.message)!=null&&ye.includes("ERR_NETWORK_CHANGED")?(R.isStatus=!1,R.statusType=null,R.text="โ ๏ธ Network error. Please check your connection and try again."):(R.isStatus=!1,R.statusType=null,R.text="โ ๏ธ Something went wrong. Please try again.")}finally{frappe.realtime.off(ue,he),Le||(M.value=null)}await St(),ee()}function Se(){var te,R;if(n.value==="support"){(te=m.value)==null||te.call(m);return}(R=M.value)==null||R.call(M)}async function je(te){l.value.push({role:"user",text:te}),await St(),ee();const R=cs({role:"model",text:"Sending to support...",isStatus:!0,statusType:"support"});l.value.push(R),await St(),ee();let he=!1;const Le=Ic(te,o.value);m.value=()=>{he||(he=!0,Le.cancel(),R.isStatus=!1,R.statusType=null,R.text="Cancelled by user.",m.value=null)};try{const re=await Le.promise;if(he)return;R.isStatus=!1,R.statusType=null,R.text=re?wo(re):"Support request sent successfully."}catch{if(he)return;R.isStatus=!1,R.statusType=null,R.text="โ ๏ธ Failed to reach support. Please try again."}finally{he||(m.value=null)}await St(),ee()}return zn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-provider",U),o.value==="actual"&&L()}),ys(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-provider",U)}),(te,R)=>(B(),G(ze,null,[E.value.enable_changai?(B(),Et(ac,{key:0,isOpen:t.value,onToggle:O},null,8,["isOpen"])):We("",!0),Me(od,{ref_key:"popupRef",ref:a,isOpen:t.value,activeTab:n.value,"onUpdate:activeTab":R[0]||(R[0]=he=>n.value=he),chatHistory:s.value,debugLogs:r.value,currentDebug:g.value,supportHistory:l.value,autoReadEnabled:c.value,ttsConfig:E.value,activeTtsProvider:x.value,settings:u.value,isAwaitingChatResponse:H.value,isAwaitingSupportResponse:Y.value,debugEnabled:i.value,sendNonERPtoaiEnabled:y.value,onToggleDebug:R[1]||(R[1]=he=>i.value=!i.value),onClose:R[2]||(R[2]=he=>t.value=!1),onSubmit:D,onCancelResponse:Se,onToggleAutoRead:q,onTogglePollyPreference:se,onToggleSendNonERP:fe},null,8,["isOpen","activeTab","chatHistory","debugLogs","currentDebug","supportHistory","autoReadEnabled","ttsConfig","activeTtsProvider","settings","isAwaitingChatResponse","isAwaitingSupportResponse","debugEnabled","sendNonERPtoaiEnabled"])],64))}};function pd(){const e=document.querySelector('link[href*="/assets/changai/dist/changai-chatbot.css"]');if(e!=null&&e.href)return e.href;const t=Array.from(document.scripts).find(n=>{var s;return(s=n.src)==null?void 0:s.includes("/assets/changai/dist/changai-chatbot.js")});return t!=null&&t.src?t.src.replace(/changai-chatbot\.js(\?.*)?$/,"changai-chatbot.css$1"):null}function dd(e){const t=pd();if(!t){const n=Array.from(document.querySelectorAll("style[data-vite-dev-id]"));return n.length&&n.forEach(s=>{const r=document.createElement("style");r.dataset.changaiShadowDevStyle="1",r.textContent=s.textContent||"",e.appendChild(r)}),Promise.resolve()}return e.querySelector('link[data-changai-shadow-style="1"]')?Promise.resolve():new Promise(n=>{const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.dataset.changaiShadowStyle="1",s.onload=()=>n(),s.onerror=()=>n(),e.appendChild(s),setTimeout(n,1200)})}async function ko(){if(document.getElementById("changai-chatbot-host"))return;const e=document.createElement("div");e.id="changai-chatbot-host",document.body.appendChild(e);const t=e.attachShadow({mode:"open"});await dd(t);const n=document.createElement("div");n.id="changai-chatbot-root",t.appendChild(n),nc(fd).mount(n);function s(r){r.stopPropagation()}n.addEventListener("keydown",s),n.addEventListener("keyup",s),n.addEventListener("keypress",s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ko):ko()})(); +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return` ${St(e,!0)}`}br(e){return"
"}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=dl(e);if(r===null)return s;e=r;let i='"+s+"",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=dl(e);if(r===null)return St(n);e=r;let i=`",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:St(e.text)}},qr=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},mt=class ci{constructor(t){ve(this,"options");ve(this,"renderer");ve(this,"textRenderer");this.options=t||hn,this.options.renderer=this.options.renderer||new js,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new qr}static parse(t,n){return new ci(n).parse(t)}static parseInline(t,n){return new ci(n).parseInline(t)}parse(t){var s,r;this.renderer.parser=this;let n="";for(let i=0;i
{let l=o[a].flat(1/0);n=n.concat(this.walkTokens(l,t))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let a=r.renderer.apply(this,o);return a===!1&&(a=i.apply(this,o)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new js(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,a=n.renderer[o],l=r[o];r[o]=(...f)=>{let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new Us(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,a=n.tokenizer[o],l=r[o];r[o]=(...f)=>{let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new ts;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,a=n.hooks[o],l=r[o];ts.passThroughHooks.has(i)?r[o]=f=>{if(this.defaults.async&&ts.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await a.call(r,f);return l.call(r,h)})();let u=a.call(r,f);return l.call(r,u)}:r[o]=(...f)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,f);return h===!1&&(h=await l.apply(r,f)),h})();let u=a.apply(r,f);return u===!1&&(u=l.apply(r,f)),u}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(i.call(this,o)),r&&(a=a.concat(r.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return gt.lex(e,t!=null?t:this.defaults)}parser(e,t){return mt.parse(e,t!=null?t:this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return i(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 t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let o=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?gt.lex:gt.lexInline)(o,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let f=await(r.hooks?await r.hooks.provideParser(e):e?mt.parse:mt.parseInline)(l,r);return r.hooks?await r.hooks.postprocess(f):f})().catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let o=(r.hooks?r.hooks.provideLexer(e):e?gt.lex:gt.lexInline)(t,r);r.hooks&&(o=r.hooks.processAllTokens(o)),r.walkTokens&&this.walkTokens(o,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?mt.parse:mt.parseInline)(o,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s=" An error occurred:
"+St(n.message+"",!0)+"";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},mn=new Hf;function xe(e,t){return mn.parse(e,t)}xe.options=xe.setOptions=function(e){return mn.setOptions(e),xe.defaults=mn.defaults,el(xe.defaults),xe},xe.getDefaults=Nr,xe.defaults=hn,xe.use=function(...e){return mn.use(...e),xe.defaults=mn.defaults,el(xe.defaults),xe},xe.walkTokens=function(e,t){return mn.walkTokens(e,t)},xe.parseInline=mn.parseInline,xe.Parser=mt,xe.parser=mt.parse,xe.Renderer=js,xe.TextRenderer=qr,xe.Lexer=gt,xe.lexer=gt.lex,xe.Tokenizer=Us,xe.Hooks=ts,xe.parse=xe,xe.options,xe.setOptions,xe.use,xe.walkTokens,xe.parseInline,mt.parse,gt.lex;function bl(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),i=2;i 1?n-1:0),r=1;r1?n-1:0),r=1;r 2&&arguments[2]!==void 0?arguments[2]:ss;if(yl&&yl(e,null),!Qt(t))return e;let s=t.length;for(;s--;){let r=t[s];if(typeof r=="string"){const i=n(r);i!==r&&(Wf(t)||(t[s]=i),r=i)}e[r]=!0}return e}function tp(e){for(let t=0;t /g),ap=ze(/\${[\w\W]*/g),up=ze(/^data-[\-\w.\u00B7-\uFFFF]+$/),cp=ze(/^aria-[\-\w]+$/),Pl=ze(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fp=ze(/^(?:\w+script|data):/i),pp=ze(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),dp=ze(/^html$/i),hp=ze(/^[a-z][.\w]*(-[.\w]+)+$/i),Il=ze(/<[/\w!]/g),gp=ze(/<[/\w]/g),mp=ze(/<\/no(script|embed|frames)/i),bp=ze(/\/>/i),At={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},xp=function(){return typeof window=="undefined"?null:window},yp=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const r="data-tt-policy-suffix";n&&n.hasAttribute(r)&&(s=n.getAttribute(r));const i="dompurify"+(s?"#"+s:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Ol=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},en=function(t,n,s,r){return Le(t,n)&&Qt(t[n])?le(r.base?Je(r.base):{},t[n],r.transform):s};function Ml(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xp();const t=D=>Ml(D);if(t.version="3.4.11",t.removed=[],!e||!e.document||e.document.nodeType!==At.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,r=s.currentScript;e.DocumentFragment;const i=e.HTMLTemplateElement,o=e.Node,a=e.Element,l=e.NodeFilter,f=e.NamedNodeMap;f===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const u=e.DOMParser,h=e.trustedTypes,g=a.prototype,w=Et(g,"cloneNode"),A=Et(g,"remove"),_=Et(g,"nextSibling"),F=Et(g,"childNodes"),b=Et(g,"parentNode"),U=Et(g,"shadowRoot"),Z=Et(g,"attributes"),$=o&&o.prototype?Et(o.prototype,"nodeType"):null,Y=o&&o.prototype?Et(o.prototype,"nodeName"):null;if(typeof i=="function"){const D=n.createElement("template");D.content&&D.content.ownerDocument&&(n=D.content.ownerDocument)}let C,N="",te,W=!1,X=0;const ue=function(){if(X>0)throw bn('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},B=function(c){ue(),X++;try{return C.createHTML(c)}finally{X--}},ge=function(c){ue(),X++;try{return C.createScriptURL(c)}finally{X--}},Ae=function(){return W||(te=yp(h,r),W=!0),te},je=n,J=je.implementation,R=je.createNodeIterator,ye=je.createDocumentFragment,$e=je.getElementsByTagName,ne=s.importNode;let M=Ol();t.isSupported=typeof xl=="function"&&typeof b=="function"&&J&&J.createHTMLDocument!==void 0;const pe=op,Ve=lp,Te=ap,bt=up,Me=cp,Ft=fp,Bt=pp,xn=hp;let j=Pl,de=null;const p=le({},[...El,...Yr,...Zr,...Xr,...Al]);let d=null;const x=le({},[...Rl,...Jr,...Cl,...Vs]);let y=Object.seal(Cn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),T=null,k=null;const P=Object.seal(Cn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let I=!0,E=!0,S=!1,q=!0,O=!1,z=!0,G=!1,re=!1,me=null,ce=null,Ne=!1,Re=!1,Qe=!1,et=!1,tn=!0,os=!1;const Ye="user-content-";let rt=!0,In=!1,Ht={},Rt=null;const Qr=le({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Hl=null;const zl=le({},["audio","video","img","source","image","track"]);let ei=null;const Ul=le({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ws="http://www.w3.org/1998/Math/MathML",Gs="http://www.w3.org/2000/svg",Ct="http://www.w3.org/1999/xhtml";let On=Ct,ti=!1,ni=null;const Fd=le({},[Ws,Gs,Ct],Kr),jl=He(["mi","mo","mn","ms","mtext"]);let si=le({},jl);const Vl=He(["annotation-xml"]);let ri=le({},Vl);const Bd=le({},["title","style","font","a","script"]);let ls=null;const Hd=["application/xhtml+xml","text/html"],zd="text/html";let Se=null,Mn=null;const Ud=n.createElement("form"),ql=function(c){return c instanceof RegExp||c instanceof Function},ii=function(){let c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Mn&&Mn===c)return;(!c||typeof c!="object")&&(c={}),c=Je(c),ls=Hd.indexOf(c.PARSER_MEDIA_TYPE)===-1?zd:c.PARSER_MEDIA_TYPE,Se=ls==="application/xhtml+xml"?Kr:ss,de=en(c,"ALLOWED_TAGS",p,{transform:Se}),d=en(c,"ALLOWED_ATTR",x,{transform:Se}),ni=en(c,"ALLOWED_NAMESPACES",Fd,{transform:Kr}),ei=en(c,"ADD_URI_SAFE_ATTR",Ul,{transform:Se,base:Ul}),Hl=en(c,"ADD_DATA_URI_TAGS",zl,{transform:Se,base:zl}),Rt=en(c,"FORBID_CONTENTS",Qr,{transform:Se}),T=en(c,"FORBID_TAGS",Je({}),{transform:Se}),k=en(c,"FORBID_ATTR",Je({}),{transform:Se}),Ht=Le(c,"USE_PROFILES")?c.USE_PROFILES&&typeof c.USE_PROFILES=="object"?Je(c.USE_PROFILES):c.USE_PROFILES:!1,I=c.ALLOW_ARIA_ATTR!==!1,E=c.ALLOW_DATA_ATTR!==!1,S=c.ALLOW_UNKNOWN_PROTOCOLS||!1,q=c.ALLOW_SELF_CLOSE_IN_ATTR!==!1,O=c.SAFE_FOR_TEMPLATES||!1,z=c.SAFE_FOR_XML!==!1,G=c.WHOLE_DOCUMENT||!1,Re=c.RETURN_DOM||!1,Qe=c.RETURN_DOM_FRAGMENT||!1,et=c.RETURN_TRUSTED_TYPE||!1,Ne=c.FORCE_BODY||!1,tn=c.SANITIZE_DOM!==!1,os=c.SANITIZE_NAMED_PROPS||!1,rt=c.KEEP_CONTENT!==!1,In=c.IN_PLACE||!1,j=sp(c.ALLOWED_URI_REGEXP)?c.ALLOWED_URI_REGEXP:Pl,On=typeof c.NAMESPACE=="string"?c.NAMESPACE:Ct,si=Le(c,"MATHML_TEXT_INTEGRATION_POINTS")&&c.MATHML_TEXT_INTEGRATION_POINTS&&typeof c.MATHML_TEXT_INTEGRATION_POINTS=="object"?Je(c.MATHML_TEXT_INTEGRATION_POINTS):le({},jl),ri=Le(c,"HTML_INTEGRATION_POINTS")&&c.HTML_INTEGRATION_POINTS&&typeof c.HTML_INTEGRATION_POINTS=="object"?Je(c.HTML_INTEGRATION_POINTS):le({},Vl);const m=Le(c,"CUSTOM_ELEMENT_HANDLING")&&c.CUSTOM_ELEMENT_HANDLING&&typeof c.CUSTOM_ELEMENT_HANDLING=="object"?Je(c.CUSTOM_ELEMENT_HANDLING):Cn(null);if(y=Cn(null),Le(m,"tagNameCheck")&&ql(m.tagNameCheck)&&(y.tagNameCheck=m.tagNameCheck),Le(m,"attributeNameCheck")&&ql(m.attributeNameCheck)&&(y.attributeNameCheck=m.attributeNameCheck),Le(m,"allowCustomizedBuiltInElements")&&typeof m.allowCustomizedBuiltInElements=="boolean"&&(y.allowCustomizedBuiltInElements=m.allowCustomizedBuiltInElements),ze(y),O&&(E=!1),Qe&&(Re=!0),Ht&&(de=le({},Al),d=Cn(null),Ht.html===!0&&(le(de,El),le(d,Rl)),Ht.svg===!0&&(le(de,Yr),le(d,Jr),le(d,Vs)),Ht.svgFilters===!0&&(le(de,Zr),le(d,Jr),le(d,Vs)),Ht.mathMl===!0&&(le(de,Xr),le(d,Cl),le(d,Vs))),P.tagCheck=null,P.attributeCheck=null,Le(c,"ADD_TAGS")&&(typeof c.ADD_TAGS=="function"?P.tagCheck=c.ADD_TAGS:Qt(c.ADD_TAGS)&&(de===p&&(de=Je(de)),le(de,c.ADD_TAGS,Se))),Le(c,"ADD_ATTR")&&(typeof c.ADD_ATTR=="function"?P.attributeCheck=c.ADD_ATTR:Qt(c.ADD_ATTR)&&(d===x&&(d=Je(d)),le(d,c.ADD_ATTR,Se))),Le(c,"ADD_URI_SAFE_ATTR")&&Qt(c.ADD_URI_SAFE_ATTR)&&le(ei,c.ADD_URI_SAFE_ATTR,Se),Le(c,"FORBID_CONTENTS")&&Qt(c.FORBID_CONTENTS)&&(Rt===Qr&&(Rt=Je(Rt)),le(Rt,c.FORBID_CONTENTS,Se)),Le(c,"ADD_FORBID_CONTENTS")&&Qt(c.ADD_FORBID_CONTENTS)&&(Rt===Qr&&(Rt=Je(Rt)),le(Rt,c.ADD_FORBID_CONTENTS,Se)),rt&&(de["#text"]=!0),G&&le(de,["html","head","body"]),de.table&&(le(de,["tbody"]),delete T.tbody),c.TRUSTED_TYPES_POLICY){if(typeof c.TRUSTED_TYPES_POLICY.createHTML!="function")throw bn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof c.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw bn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const L=C;C=c.TRUSTED_TYPES_POLICY;try{N=B("")}catch(V){throw C=L,V}}else c.TRUSTED_TYPES_POLICY===null?(C=void 0,N=""):(C===void 0&&(C=Ae()),C&&typeof N=="string"&&(N=B("")));He&&He(c),Mn=c},Wl=le({},[...Yr,...Zr,...rp]),Gl=le({},[...Xr,...ip]),jd=function(c,m,L){return m.namespaceURI===Ct?c==="svg":m.namespaceURI===Ws?c==="svg"&&(L==="annotation-xml"||si[L]):!!Wl[c]},Vd=function(c,m,L){return m.namespaceURI===Ct?c==="math":m.namespaceURI===Gs?c==="math"&&ri[L]:!!Gl[c]},qd=function(c,m,L){return m.namespaceURI===Gs&&!ri[L]||m.namespaceURI===Ws&&!si[L]?!1:!Gl[c]&&(Bd[c]||!Wl[c])},Wd=function(c){let m=b(c);(!m||!m.tagName)&&(m={namespaceURI:On,tagName:"template"});const L=ss(c.tagName),V=ss(m.tagName);return ni[c.namespaceURI]?c.namespaceURI===Gs?jd(L,m,V):c.namespaceURI===Ws?Vd(L,m,V):c.namespaceURI===Ct?qd(L,m,V):!!(ls==="application/xhtml+xml"&&ni[c.namespaceURI]):!1},nn=function(c){Pn(t.removed,{element:c});try{b(c).removeChild(c)}catch{if(A(c),!b(c))throw bn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Kl=function(c){const m=F(c);if(m){const V=[];ns(m,se=>{Pn(V,se)}),ns(V,se=>{try{A(se)}catch{}})}const L=Z(c);if(L)for(let V=L.length-1;V>=0;--V){const se=L[V],fe=se&&se.name;if(typeof fe=="string")try{c.removeAttribute(fe)}catch{}}},yn=function(c,m){try{Pn(t.removed,{attribute:m.getAttributeNode(c),from:m})}catch{Pn(t.removed,{attribute:null,from:m})}if(m.removeAttribute(c),c==="is")if(Re||Qe)try{nn(m)}catch{}else try{m.setAttribute(c,"")}catch{}},Gd=function(c){const m=Z(c);if(m)for(let L=m.length-1;L>=0;--L){const V=m[L],se=V&&V.name;if(!(typeof se!="string"||d[Se(se)]))try{c.removeAttribute(se)}catch{}}},Kd=function(c){const m=[c];for(;m.length>0;){const L=m.pop();($?$(L):L.nodeType)===At.element&&Gd(L);const se=F(L);if(se)for(let fe=se.length-1;fe>=0;--fe)m.push(se[fe])}},Yl=function(c){let m=null,L=null;if(Ne)c=" "+c;else{const fe=_l(c,/^[\r\n\t ]+/);L=fe&&fe[0]}ls==="application/xhtml+xml"&&On===Ct&&(c=''+c+"");const V=C?B(c):c;if(On===Ct)try{m=new u().parseFromString(V,ls)}catch{}if(!m||!m.documentElement){m=J.createDocument(On,"template",null);try{m.documentElement.innerHTML=ti?N:V}catch{}}const se=m.body||m.documentElement;return c&&L&&se.insertBefore(n.createTextNode(L),se.childNodes[0]||null),On===Ct?$e.call(m,G?"html":"body")[0]:G?m.documentElement:se},Zl=function(c){return R.call(c.ownerDocument||c,c,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ks=function(c){return c=rs(c,pe," "),c=rs(c,Ve," "),c=rs(c,Te," "),c},oi=function(c){var m;c.normalize();const L=R.call(c.ownerDocument||c,c,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let V=L.nextNode();for(;V;)V.data=Ks(V.data),V=L.nextNode();const se=(m=c.querySelectorAll)===null||m===void 0?void 0:m.call(c,"template");se&&ns(se,fe=>{Ln(fe.content)&&oi(fe.content)})},Ys=function(c){const m=Y?Y(c):null;return typeof m!="string"||Se(m)!=="form"?!1:typeof c.nodeName!="string"||typeof c.textContent!="string"||typeof c.removeChild!="function"||c.attributes!==Z(c)||typeof c.removeAttribute!="function"||typeof c.setAttribute!="function"||typeof c.namespaceURI!="string"||typeof c.insertBefore!="function"||typeof c.hasChildNodes!="function"||c.nodeType!==$(c)||c.childNodes!==F(c)},Ln=function(c){if(!$||typeof c!="object"||c===null)return!1;try{return $(c)===At.documentFragment}catch{return!1}},as=function(c){if(!$||typeof c!="object"||c===null)return!1;try{return typeof $(c)=="number"}catch{return!1}};function zt(D,c,m){D.length!==0&&ns(D,L=>{L.call(t,c,m,Mn)})}const Yd=function(c,m){return!!(z&&c.hasChildNodes()&&!as(c.firstElementChild)&&Ue(Il,c.textContent)&&Ue(Il,c.innerHTML)||z&&c.namespaceURI===Ct&&m==="style"&&as(c.firstElementChild)||c.nodeType===At.processingInstruction||z&&c.nodeType===At.comment&&Ue(gp,c.data))},Zd=function(c,m){if(!T[m]&&Ql(m)&&(y.tagNameCheck instanceof RegExp&&Ue(y.tagNameCheck,m)||y.tagNameCheck instanceof Function&&y.tagNameCheck(m)))return!1;if(rt&&!Rt[m]){const L=b(c),V=F(c);if(V&&L){const se=V.length;for(let fe=se-1;fe>=0;--fe){const De=In?V[fe]:w(V[fe],!0);L.insertBefore(De,_(c))}}}return nn(c),!0},Xl=function(c){if(zt(M.beforeSanitizeElements,c,null),Ys(c))return nn(c),!0;const m=Se(Y?Y(c):c.nodeName);if(zt(M.uponSanitizeElement,c,{tagName:m,allowedTags:de}),Yd(c,m))return nn(c),!0;if(T[m]||!(P.tagCheck instanceof Function&&P.tagCheck(m))&&!de[m])return Zd(c,m);if(($?$(c):c.nodeType)===At.element&&!Wd(c)||(m==="noscript"||m==="noembed"||m==="noframes")&&Ue(mp,c.innerHTML))return nn(c),!0;if(O&&c.nodeType===At.text){const V=Ks(c.textContent);c.textContent!==V&&(Pn(t.removed,{element:c.cloneNode()}),c.textContent=V)}return zt(M.afterSanitizeElements,c,null),!1},Jl=function(c,m,L){if(k[m]||tn&&(m==="id"||m==="name")&&(L in n||L in Ud))return!1;const V=d[m]||P.attributeCheck instanceof Function&&P.attributeCheck(m,c);if(!(E&&Ue(bt,m))){if(!(I&&Ue(Me,m))){if(V){if(!ei[m]){if(!Ue(j,rs(L,Bt,""))){if(!((m==="src"||m==="xlink:href"||m==="href")&&c!=="script"&&Tl(L,"data:")===0&&Hl[c])){if(!(S&&!Ue(Ft,rs(L,Bt,"")))){if(L)return!1}}}}}else if(!(Ql(c)&&(y.tagNameCheck instanceof RegExp&&Ue(y.tagNameCheck,c)||y.tagNameCheck instanceof Function&&y.tagNameCheck(c))&&(y.attributeNameCheck instanceof RegExp&&Ue(y.attributeNameCheck,m)||y.attributeNameCheck instanceof Function&&y.attributeNameCheck(m,c))||m==="is"&&y.allowCustomizedBuiltInElements&&(y.tagNameCheck instanceof RegExp&&Ue(y.tagNameCheck,L)||y.tagNameCheck instanceof Function&&y.tagNameCheck(L))))return!1}}return!0},Xd=le({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ql=function(c){return!Xd[ss(c)]&&Ue(xn,c)},Jd=function(c,m,L,V){if(C&&typeof h=="object"&&typeof h.getAttributeType=="function"&&!L)switch(h.getAttributeType(c,m)){case"TrustedHTML":return B(V);case"TrustedScriptURL":return ge(V)}return V},Qd=function(c,m,L,V){try{L?c.setAttributeNS(L,m,V):c.setAttribute(m,V),Ys(c)?nn(c):vl(t.removed)}catch{yn(m,c)}},ea=function(c){zt(M.beforeSanitizeAttributes,c,null);const m=c.attributes;if(!m||Ys(c))return;const L={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:d,forceKeepAttr:void 0};let V=m.length;const se=Se(c.nodeName);for(;V--;){const fe=m[V],De=fe.name,Ie=fe.namespaceURI,ft=fe.value,xt=Se(De),ai=ft;let tt=De==="value"?ai:Xf(ai);if(L.attrName=xt,L.attrValue=tt,L.keepAttr=!0,L.forceKeepAttr=void 0,zt(M.uponSanitizeAttribute,c,L),tt=L.attrValue,os&&(xt==="id"||xt==="name")&&Tl(tt,Ye)!==0&&(yn(De,c),tt=Ye+tt),z&&Ue(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,tt)){yn(De,c);continue}if(xt==="attributename"&&_l(tt,"href")){yn(De,c);continue}if(!L.forceKeepAttr){if(!L.keepAttr){yn(De,c);continue}if(!q&&Ue(bp,tt)){yn(De,c);continue}if(O&&(tt=Ks(tt)),!Jl(se,xt,tt)){yn(De,c);continue}tt=Jd(se,xt,Ie,tt),tt!==ai&&Qd(c,De,Ie,tt)}}zt(M.afterSanitizeAttributes,c,null)},Zs=function(c){let m=null;const L=Zl(c);for(zt(M.beforeSanitizeShadowDOM,c,null);m=L.nextNode();)if(zt(M.uponSanitizeShadowNode,m,null),Xl(m),ea(m),Ln(m.content)&&Zs(m.content),($?$(m):m.nodeType)===At.element){const se=U(m);Ln(se)&&(li(se),Zs(se))}zt(M.afterSanitizeShadowDOM,c,null)},li=function(c){const m=[{node:c,shadow:null}];for(;m.length>0;){const L=m.pop();if(L.shadow){Zs(L.shadow);continue}const V=L.node,fe=($?$(V):V.nodeType)===At.element,De=F(V);if(De)for(let Ie=De.length-1;Ie>=0;--Ie)m.push({node:De[Ie],shadow:null});if(fe){const Ie=Y?Y(V):null;if(typeof Ie=="string"&&Se(Ie)==="template"){const ft=V.content;Ln(ft)&&m.push({node:ft,shadow:null})}}if(fe){const Ie=U(V);Ln(Ie)&&m.push({node:null,shadow:Ie},{node:Ie,shadow:null})}}};return t.sanitize=function(D){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},m=null,L=null,V=null,se=null;if(ti=!D,ti&&(D=""),typeof D!="string"&&!as(D)&&(D=np(D),typeof D!="string"))throw bn("dirty is not a string, aborting");if(!t.isSupported)return D;re?(de=me,d=ce):ii(c),(M.uponSanitizeElement.length>0||M.uponSanitizeAttribute.length>0)&&(de=Je(de)),M.uponSanitizeAttribute.length>0&&(d=Je(d)),t.removed=[];const fe=In&&typeof D!="string"&&as(D);if(fe){const ft=Y?Y(D):D.nodeName;if(typeof ft=="string"){const xt=Se(ft);if(!de[xt]||T[xt])throw bn("root node is forbidden and cannot be sanitized in-place")}if(Ys(D))throw bn("root node is clobbered and cannot be sanitized in-place");try{li(D)}catch(xt){throw Kl(D),xt}}else if(as(D))m=Yl(""),L=m.ownerDocument.importNode(D,!0),L.nodeType===At.element&&L.nodeName==="BODY"||L.nodeName==="HTML"?m=L:m.appendChild(L),li(L);else{if(!Re&&!O&&!G&&D.indexOf("<")===-1)return C&&et?B(D):D;if(m=Yl(D),!m)return Re?null:et?N:""}m&&Ne&&nn(m.firstChild);const De=Zl(fe?D:m);try{for(;V=De.nextNode();)Xl(V),ea(V),Ln(V.content)&&Zs(V.content)}catch(ft){throw fe&&Kl(D),ft}if(fe)return ns(t.removed,ft=>{ft.element&&Kd(ft.element)}),O&&oi(D),D;if(Re){if(O&&oi(m),Qe)for(se=ye.call(m.ownerDocument);m.firstChild;)se.appendChild(m.firstChild);else se=m;return(d.shadowroot||d.shadowrootmode)&&(se=ne.call(s,se,!0)),se}let Ie=G?m.outerHTML:m.innerHTML;return G&&de["!doctype"]&&m.ownerDocument&&m.ownerDocument.doctype&&m.ownerDocument.doctype.name&&Ue(dp,m.ownerDocument.doctype.name)&&(Ie=" +`+Ie),O&&(Ie=Ks(Ie)),C&&et?B(Ie):Ie},t.setConfig=function(){let D=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ii(D),re=!0,me=de,ce=d},t.clearConfig=function(){Mn=null,re=!1,me=null,ce=null,C=te,N=""},t.isValidAttribute=function(D,c,m){Mn||ii({});const L=Se(D),V=Se(c);return Jl(L,V,m)},t.addHook=function(D,c){typeof c=="function"&&Le(M,D)&&Pn(M[D],c)},t.removeHook=function(D,c){if(Le(M,D)){if(c!==void 0){const m=Yf(M[D],c);return m===-1?void 0:Zf(M[D],m,1)[0]}return vl(M[D])}},t.removeHooks=function(D){Le(M,D)&&(M[D]=[])},t.removeAllHooks=function(){M=Ol()},t}var wp=Ml();const vp={key:1,class:"flex min-w-0 max-w-[calc(100%-2.5rem)] flex-1 flex-col max-[600px]:max-w-[calc(100%-2.25rem)]"},_p={key:0,class:"flex w-fit flex-col items-start gap-1"},Tp=["aria-label"],kp={class:"inline-flex items-center gap-1.5"},Sp={class:"text-[8px] font-semibold tracking-[0.12em] uppercase text-[#3a67c9]"},Ep={key:1,class:"flex w-fit max-w-full flex-col items-start gap-2"},Ap={class:"chat-card relative w-fit max-w-full whitespace-pre-line rounded-[10px_10px_10px_3px] px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900"},Rp=["innerHTML"],Cp={key:0,class:"pointer-events-none absolute inset-x-0 bottom-0 h-14 rounded-b-[10px] bg-linear-to-t from-white via-white/92 to-white/0","aria-hidden":"true"},Pp={key:0,class:"flex flex-wrap items-center gap-2"},Ip=["title","aria-label"],Op={key:1,class:"flex flex-wrap items-center"},Mp=["title","aria-label"],Lp={viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},$p=["innerHTML"],Ll={__name:"ChatMessage",props:{message:{type:Object,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,default:()=>({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd"})}},setup(e){const t=e,n=ee(!1),s=ee(null),r=ee(!1),i=ee(!1),o=ke(()=>typeof window!="undefined"&&"speechSynthesis"in window&&"SpeechSynthesisUtterance"in window);function a(C){typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("changai-tts-provider",{detail:{provider:C}}))}function l(C){if(typeof C!="string")return"";const N=C.replace(/[\u{1F000}-\u{1FFFF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/#{1,6}\s+/g,"").replace(/[-*+]\s+/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/\s+/g," ");return N.includes("<")?(new DOMParser().parseFromString(C,"text/html").body.textContent||"").replace(/\s+/g," ").trim():N.trim()}function f(){o.value&&window.speechSynthesis.cancel(),s.value&&(s.value.pause(),s.value.src="",s.value=null),n.value=!1}function u(){var C,N,te;if(i.value=!i.value,i.value)f();else{const W=F.value;if(!t.autoReadEnabled||!((C=t.ttsConfig)!=null&&C.enableVoiceChat)||!W||A())return;if((N=t.ttsConfig)!=null&&N.pollyAvailable&&((te=t.ttsConfig)!=null&&te.usePolly)){g(W).catch(X=>{console.warn("Polly TTS failed, falling back to browser speech:",X),h(W)});return}h(W)}}function h(C){if(!o.value||!C)return;window.dispatchEvent(new CustomEvent("changai-tts-stop")),window.speechSynthesis.cancel();const N=new SpeechSynthesisUtterance(C);N.rate=1,N.pitch=1,N.onend=()=>{n.value=!1},N.onerror=()=>{n.value=!1},n.value=!0,a("browser"),window.speechSynthesis.speak(N)}async function g(C){var ue;const N=await Jc(C,((ue=t.ttsConfig)==null?void 0:ue.voiceId)||"Zayd");if(!(N!=null&&N.ok)||!(N!=null&&N.audio_base64))throw new Error((N==null?void 0:N.error)||"Polly synthesis failed");window.dispatchEvent(new CustomEvent("changai-tts-stop")),f();const te=(N==null?void 0:N.mime_type)||"audio/mpeg",W=new Audio(`data:${te};base64,${N.audio_base64}`);s.value=W,n.value=!0;let X=!1;W.onplay=()=>{X=!0,a("polly")},W.onended=()=>{s.value===W&&(s.value=null),n.value=!1},W.onerror=()=>{s.value===W&&(s.value=null),n.value=!1},await W.play(),X||a("polly")}function w(){f()}function A(){var C;return!!((C=t.message)!=null&&C.isStatus)}function _(C){const N=C.target.closest("a");!N||!N.href||(C.preventDefault(),C.stopPropagation(),window.open(N.href,"_blank","noopener,noreferrer"))}const F=ke(()=>{var C;return l(((C=t.message)==null?void 0:C.text)||"")}),b=ke(()=>{var C;return((C=t.message)==null?void 0:C.role)!=="user"&&A()}),U=ke(()=>{var C;return(C=t.message)!=null&&C.isStatus?t.message.statusType==="support"?"Sending to support":F.value||"Thinking":""}),Z=ke(()=>{var te;if(((te=t.message)==null?void 0:te.role)==="user"||b.value)return!1;const C=F.value,N=C.split(/\n+/).filter(Boolean).length;return C.length>520||N>8}),$=ke(()=>{var C,N;return((C=t.message)==null?void 0:C.role)!=="user"&&!b.value&&((N=t.ttsConfig)==null?void 0:N.enableVoiceChat)}),Y=ke(()=>{var N;const C=((N=t.message)==null?void 0:N.text)||"";return wp.sanitize(xe.parse(C))});return cn(()=>t.message.text,async(C,N)=>{var X,ue,B;if(!t.autoReadEnabled||t.message.role==="user"||i.value)return;if(!((X=t.ttsConfig)!=null&&X.enableVoiceChat)){a("off");return}const te=l(C);if(!te||A())return;const W=l(N||"");if(te!==W){if((ue=t.ttsConfig)!=null&&ue.pollyAvailable&&((B=t.ttsConfig)!=null&&B.usePolly))try{await g(te);return}catch(ge){console.warn("Polly TTS failed, falling back to browser speech:",ge)}h(te)}}),cn(()=>t.message.text,()=>{r.value=!1,i.value=!1}),Wn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-stop",w)}),As(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-stop",w),n.value&&f()}),(C,N)=>(H(),K("div",{class:we(["motion-safe:animate-fade-rise flex w-full gap-1.5",e.message.role==="user"?"flex-col items-end":"items-start"])},[e.message.role!=="user"?(H(),_t(Zo,{key:0})):Ge("",!0),e.message.role!=="user"?(H(),K("div",vp,[b.value?(H(),K("div",_p,[v("div",{class:"chat-card inline-flex w-fit rounded-[10px_10px_10px_3px] px-3 py-2",role:"status","aria-live":"polite","aria-label":U.value},[v("div",kp,[N[1]||(N[1]=v("span",{class:"relative inline-flex h-4 w-4 shrink-0 items-center justify-center"},[v("span",{class:"absolute inset-0 rounded-full border border-transparent border-t-[#4b89ff] border-r-[#4b89ff]/70 animate-gemini-arc"}),v("svg",{viewBox:"0 0 24 24",class:"relative h-3 w-3 text-[#4b89ff] animate-gemini-spark","aria-hidden":"true"},[v("path",{fill:"currentColor",d:"M12 2.8c.52 3.22 1.6 5.66 3.22 7.28 1.62 1.62 4.06 2.7 7.28 3.22-3.22.52-5.66 1.6-7.28 3.22-1.62 1.62-2.7 4.06-3.22 7.28-.52-3.22-1.6-5.66-3.22-7.28-1.62-1.62-4.06-2.7-7.28-3.22 3.22-.52 5.66-1.6 7.28-3.22 1.62-1.62 2.7-4.06 3.22-7.28Z"})])],-1)),v("span",Sp,nt(U.value),1)])],8,Tp)])):(H(),K("div",Ep,[v("div",Ap,[v("div",{class:we(["overflow-x-auto",Z.value&&!r.value?"max-h-48 overflow-y-hidden":""]),innerHTML:Y.value,onClick:_},null,10,Rp),Z.value&&!r.value?(H(),K("div",Cp)):Ge("",!0)]),Z.value?(H(),K("div",Pp,[v("button",{type:"button",class:"inline-flex items-center rounded-full border border-slate-200 bg-white px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-600 transition-colors duration-200 hover:border-brand-200 hover:text-brand-600",title:r.value?"Collapse response":"Expand response","aria-label":r.value?"Collapse response":"Expand response",onClick:N[0]||(N[0]=te=>r.value=!r.value)},nt(r.value?"Collapse":"Expand"),9,Ip)])):Ge("",!0),$.value?(H(),K("div",Op,[v("button",{type:"button",class:we(["inline-flex h-8 w-8 items-center justify-center rounded-full border transition-colors duration-200",i.value?"border-red-200 bg-red-50 text-red-600 hover:border-red-300 hover:bg-red-100":"border-green-200 bg-green-50 text-green-600 hover:border-green-300 hover:bg-green-100"]),title:i.value?"Unmute voice playback":"Mute voice playback","aria-label":i.value?"Unmute voice playback":"Mute voice playback",onClick:u},[(H(),K("svg",Lp,[N[6]||(N[6]=v("path",{d:"M11 5L6 9H3v6h3l5 4V5Z"},null,-1)),i.value?(H(),K(Be,{key:0},[N[2]||(N[2]=v("path",{d:"M15 9l4 6"},null,-1)),N[3]||(N[3]=v("path",{d:"M19 9l-4 6"},null,-1))],64)):(H(),K(Be,{key:1},[N[4]||(N[4]=v("path",{d:"M15 10a3 3 0 0 1 0 4"},null,-1)),N[5]||(N[5]=v("path",{d:"M17.5 7.5a6 6 0 0 1 0 9"},null,-1))],64))]))],10,Mp)])):Ge("",!0)]))])):(H(),K("div",{key:2,class:"w-fit max-w-[85%] whitespace-pre-line rounded-[13px_13px_3px_13px] bg-linear-to-br from-brand-500 to-brand-600 px-4 py-3 text-[11px] leading-relaxed wrap-anywhere text-white shadow-[0_14px_30px_-18px_rgba(109,79,194,0.85)] max-[600px]:max-w-[88%]",innerHTML:Y.value},null,8,$p))],2))}},Np={class:"flex flex-col gap-4 sm:gap-5"},Dp={class:"motion-safe:animate-fade-rise flex w-full items-start gap-1.5"},Fp={__name:"ChatTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(H(),K("div",Np,[v("div",Dp,[Oe(Zo),n[0]||(n[0]=v("p",{class:"w-fit max-w-[calc(100%-2.5rem)] whitespace-pre-line rounded-[10px_10px_10px_3px] bg-brand-50 px-4 py-3 text-xs leading-relaxed wrap-anywhere text-slate-900 max-[600px]:max-w-[calc(100%-2.25rem)]"},[Ms(" Hello there ๐ I am ChangAI from "),v("a",{target:"_blank",href:"https://erpgulf.com",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ERPGulf.com"),Ms(", your ERP assistant."),v("br"),v("a",{target:"_blank",href:"https://app.erpgulf.com/en/articles/chang-ai-quick-start-guide",rel:"noopener noreferrer",style:{color:"#1e90ff"}},"ChangAI Quick Start Guide - Click here.")],-1))]),(H(!0),K(Be,null,Rs(e.messages,(s,r)=>(H(),_t(Ll,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}};function $l(e){try{return JSON.stringify(e,null,2)}catch(t){return console.warn("safeStringify failed:",t),String(e)}}function Bp(e){const t=document.createElement("div");return t.innerHTML=String(e),(t.textContent||t.innerText||"").trim()}function Hp(e){if(!(e!=null&&e._server_messages))return"";try{return JSON.parse(e._server_messages).map(t=>{try{return JSON.parse(t).message||""}catch{return t}}).map(Bp).filter(Boolean).join(` +`)}catch{return""}}function Nl(e){if(!e)return"No response from the server.";const t=e.responseJSON||(e._server_messages||e.exception?e:null),n=Hp(t);return n||(t!=null&&t.exception?String(t.exception).split(` +`)[0]:"")||e.message||(t==null?void 0:t.message)||(e.status?`HTTP ${e.status} ${e.statusText||""}`.trim():"")||String(e)}function zp(e){return typeof e=="string"?e:e&&typeof e=="object"?e.error?`โ ๏ธ ${e.error}`:e.answer||e.text||"":""}const Up={key:0,class:"rounded-lg bg-brand-50 px-4 py-3 text-xs text-black"},jp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},Vp={key:1,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-brand-50 p-2 text-[11px]"},qp={class:"whitespace-pre-wrap wrap-anywhere text-[11px] leading-relaxed text-black"},Wp={__name:"DebugTab",props:{logs:{type:Array,required:!0},currentDebug:{type:Object,default:null}},setup(e){const t=new Set(["gemini_json_content","private_key","private_key_id","client_secret","client_id","aws_access_key","aws_secret_key","api_key","token","access_token","refresh_token","password","secret","authorization","embed_version_id","llm_version_id","entity_retriever","retriever","deploy_url","support_api_url","get_ticket_details_url"]);function n(r,i=0){if(i>10||r===null||r===void 0||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;if(Array.isArray(r))return r.map(o=>n(o,i+1));if(typeof r=="object"){const o={};for(const[a,l]of Object.entries(r))t.has(a.toLowerCase())||(o[a]=n(l,i+1));return o}return r}function s(r){return $l(n(r))}return(r,i)=>(H(),K("div",null,[e.logs.length===0?(H(),K("p",Up,"No debug data yet.")):Ge("",!0),(H(!0),K(Be,null,Rs(e.logs,(o,a)=>(H(),K("div",{key:a,class:"mb-3 min-w-0 overflow-x-auto rounded-lg bg-gray-100 p-2 text-[11px]"},[v("pre",jp,nt(s(o)),1)]))),128)),e.currentDebug?(H(),K("div",Vp,[v("pre",qp,nt(s(e.currentDebug)),1)])):Ge("",!0)]))}},Gp={class:"flex flex-col gap-4 sm:gap-5"},Kp={key:0,class:"chat-card motion-safe:animate-fade-rise rounded-lg px-4 py-3 text-xs text-slate-900"},Yp={__name:"SupportTab",props:{messages:{type:Array,required:!0},autoReadEnabled:{type:Boolean,default:!1},ttsConfig:{type:Object,required:!0}},setup(e){return(t,n)=>(H(),K("div",Gp,[e.messages.length===0?(H(),K("p",Kp,"Send a message to Support.")):Ge("",!0),(H(!0),K(Be,null,Rs(e.messages,(s,r)=>(H(),_t(Ll,{key:r,message:s,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["message","autoReadEnabled","ttsConfig"]))),128))]))}},Zp={class:"flex flex-col gap-4"},Xp={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},Jp={class:"flex items-start justify-between gap-4"},Qp=["aria-pressed","title"],ed={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},td={class:"flex items-start justify-between gap-4"},nd={class:"mt-2 text-[11px] text-slate-500"},sd={key:0,class:"mt-1 text-[11px] text-slate-500"},rd={key:1,class:"mt-1 text-[11px] text-slate-500"},id=["aria-pressed","disabled"],od={key:0,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},ld={key:1,class:"mt-3 rounded-md bg-amber-50 px-2.5 py-2 text-xs text-amber-700"},ad={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},ud={class:"flex items-start justify-between gap-4"},cd=["aria-pressed","title"],fd={class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4"},pd={class:"flex items-start justify-between gap-4"},dd=["aria-pressed","title"],hd={__name:"SettingsTab",props:{autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},settings:{type:Object,default:null},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1}},emits:["toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e){const t=e,n=ke(()=>{var s,r;return(s=t.ttsConfig)!=null&&s.enableVoiceChat?(r=t.ttsConfig)!=null&&r.pollyAvailable?"Available":"Unavailable":"Voice disabled on server"});return(s,r)=>{var i,o,a,l,f,u,h,g,w,A,_,F,b,U,Z;return H(),K("div",Zp,[r[10]||(r[10]=v("div",{class:"chat-card motion-safe:animate-fade-rise rounded-xl p-4 text-slate-900"},[v("h3",{class:"text-sm font-semibold tracking-[0.01em]"},"Speech Settings"),v("p",{class:"mt-1 text-xs leading-relaxed text-slate-600"},"These controls apply only inside this chatbot box for the current browser session.")],-1)),v("div",Xp,[v("div",Jp,[r[4]||(r[4]=v("div",null,[v("p",{class:"text-sm font-semibold text-slate-900"},"Auto Read Replies"),v("p",{class:"mt-1 text-xs text-slate-600"},"Automatically read bot replies aloud.")],-1)),v("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.autoReadEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.autoReadEnabled?"true":"false",title:e.autoReadEnabled?"Disable auto read":"Enable auto read",onClick:r[0]||(r[0]=$=>s.$emit("toggleAutoRead"))},[v("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.autoReadEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,Qp)]),v("p",{class:we(["mt-3 text-[11px] font-medium",e.autoReadEnabled?"text-emerald-700":"text-slate-500"])},nt(e.autoReadEnabled?"Auto read is active.":"Auto read is currently off."),3)]),v("div",ed,[v("div",td,[v("div",null,[r[5]||(r[5]=v("p",{class:"text-sm font-semibold text-slate-900"},"Use Amazon Polly",-1)),r[6]||(r[6]=v("p",{class:"mt-1 text-xs text-slate-600"},"Use Polly when available; otherwise browser speech is used automatically.",-1)),v("p",nd,"Availability: "+nt(n.value),1),(i=e.settings)!=null&&i.aws_region?(H(),K("p",sd,"Region: "+nt(e.settings.aws_region),1)):Ge("",!0),(o=e.ttsConfig)!=null&&o.voiceId?(H(),K("p",rd,"Voice: "+nt(e.ttsConfig.voiceId),1)):Ge("",!0)]),v("button",{class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-55",(a=e.ttsConfig)!=null&&a.usePolly&&((l=e.ttsConfig)!=null&&l.enableVoiceChat)&&((f=e.ttsConfig)!=null&&f.pollyAvailable)?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":(u=e.ttsConfig)!=null&&u.usePolly&&((h=e.ttsConfig)!=null&&h.enableVoiceChat)&&((g=e.ttsConfig)!=null&&g.pollyAvailable)?"true":"false",disabled:!((w=e.ttsConfig)!=null&&w.pollyAvailable)||!((A=e.ttsConfig)!=null&&A.enableVoiceChat),onClick:r[1]||(r[1]=$=>s.$emit("togglePollyPreference"))},[v("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",(_=e.ttsConfig)!=null&&_.usePolly&&((F=e.ttsConfig)!=null&&F.enableVoiceChat)&&((b=e.ttsConfig)!=null&&b.pollyAvailable)?"left-[1.45rem]":"left-0.5"])},null,2)],10,id)]),(U=e.ttsConfig)!=null&&U.enableVoiceChat?(Z=e.ttsConfig)!=null&&Z.pollyAvailable?Ge("",!0):(H(),K("p",ld,"Polly is not available for this site. Browser speech will be used.")):(H(),K("p",od,"Voice chat is disabled in ChangAI Settings."))]),v("div",ad,[v("div",ud,[v("div",null,[r[7]||(r[7]=v("p",{class:"text-sm font-semibold text-slate-900"},"Enable Debug Tab",-1)),r[8]||(r[8]=v("p",{class:"mt-1 text-xs text-slate-600"}," Show or hide the Debug tab inside this chatbot. ",-1)),v("p",{class:we(["mt-2 text-[11px] font-medium",e.debugEnabled?"text-emerald-700":"text-slate-500"])},nt(e.debugEnabled?"Debug tab is active.":"Debug tab is currently off."),3)]),v("button",{type:"button",class:we(["relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.debugEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.debugEnabled?"true":"false",title:e.debugEnabled?"Disable debug tab":"Enable debug tab",onClick:r[2]||(r[2]=$=>s.$emit("toggleDebug"))},[v("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.debugEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,cd)])]),v("div",fd,[v("div",pd,[r[9]||(r[9]=v("div",null,[v("p",{class:"text-sm font-semibold text-slate-900"},"Send non-ERP questions directly to AI"),v("p",{class:"mt-1 text-xs text-slate-600"},"Questions unrelated to your ERP will skip the system and go straight to AI")],-1)),v("button",{class:we(["group relative h-7 w-12 shrink-0 rounded-full border border-slate-200 transition-all duration-200",e.sendNonERPtoaiEnabled?"bg-emerald-500/95":"bg-slate-300"]),"aria-pressed":e.sendNonERPtoaiEnabled?"true":"false",title:e.sendNonERPtoaiEnabled?"Non-ERP questions are being sent directly to AI":"Enable direct AI reply for non-ERP questions",onClick:r[3]||(r[3]=$=>s.$emit("toggleSendNonERP"))},[v("span",{class:we(["absolute top-0.5 h-5.5 w-5.5 rounded-full bg-white shadow-sm transition-all duration-200",e.sendNonERPtoaiEnabled?"left-[1.45rem]":"left-0.5"])},null,2)],10,dd)]),v("p",{class:we(["mt-3 text-[11px] font-medium",e.sendNonERPtoaiEnabled?"text-emerald-700":"text-slate-500"])},nt(e.sendNonERPtoaiEnabled?"Non-ERP questions are now routed directly to AI":"Direct AI routing is currently off"),3)])])}}},gd={key:0,class:"pointer-events-none absolute -top-14 left-0 right-0 z-20 flex justify-center px-2",role:"status","aria-live":"polite"},md={__name:"StatusToast",props:{visible:{type:Boolean,required:!0},message:{type:String,default:""},type:{type:String,default:"info"},dismissible:{type:Boolean,default:!0}},emits:["close"],setup(e){const t=e,n=ke(()=>t.type==="error"?"bg-red-50 text-red-700 ring-red-200":(t.type==="listening","bg-blue-50 text-blue-700 ring-blue-200")),s=ke(()=>t.type==="error"?"bg-red-500":t.type==="listening"?"bg-blue-500 animate-pulse":"bg-blue-500");return(r,i)=>(H(),_t(Yu,{"enter-active-class":"transition duration-200 ease-out","enter-from-class":"translate-y-1 opacity-0","enter-to-class":"translate-y-0 opacity-100","leave-active-class":"transition duration-150 ease-in","leave-from-class":"translate-y-0 opacity-100","leave-to-class":"translate-y-1 opacity-0"},{default:Ki(()=>[e.visible?(H(),K("div",gd,[v("div",{class:we(["pointer-events-auto flex max-w-[92%] items-start gap-2 rounded-lg px-3 py-2 text-xs shadow-lg ring-1",n.value])},[v("span",{class:we(["mt-0.5 h-2 w-2 shrink-0 rounded-full",s.value])},null,2),v("span",null,nt(e.message),1),e.dismissible?(H(),K("button",{key:0,type:"button",class:"ml-1 appearance-none border-0 text-current/80 transition hover:text-current focus:outline-none","aria-label":"Dismiss notification",onClick:i[0]||(i[0]=o=>r.$emit("close"))}," ร ")):Ge("",!0)],2)])):Ge("",!0)]),_:1}))}},bd={class:"relative w-full"},xd=["placeholder","disabled"],yd=["title","aria-label","disabled"],wd={key:0,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},vd={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},_d={key:2,viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true",class:"animate-spin"},Td=["title","aria-label","disabled"],kd={key:0,viewBox:"0 0 24 24",width:"18",height:"18",fill:"none","aria-hidden":"true",class:"text-rose-600 motion-safe:animate-stop-button-pulse"},Sd={key:1,viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor","aria-hidden":"true"},Ed={__name:"ChatForm",props:{placeholder:{type:String,default:"Message..."},disabled:{type:Boolean,default:!1},isAwaitingResponse:{type:Boolean,default:!1}},emits:["submit","cancel"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=ee(""),o=ee(null),a=ee(!1),l=ee(!1),f=ee(!1),u=ee(!1),h=ee(!1),g=ee(!1),w=ee(!1),A=ee(""),_=ee("info"),F=ee("Voice input is unavailable in this browser/context.");let b=null,U=null,Z=null;const $=ee(""),Y=ee(!1),C=ke(()=>f.value?"Requesting microphone permission...":u.value?"Starting voice input...":h.value?"Stopping voice input...":l.value?a.value?"Stop voice input":"Start voice input":"Voice input is unavailable in this browser/context"),N=ke(()=>s.isAwaitingResponse?"Stop response":"Send"),te=ke(()=>s.isAwaitingResponse?!1:s.disabled||!i.value.trim()),W=ke(()=>s.isAwaitingResponse?"bg-white border border-rose-100 shadow-[0_8px_20px_-12px_rgba(159,18,57,0.35)] hover:bg-rose-50":"bg-linear-to-br from-brand-500 to-brand-600 text-white shadow-[0_10px_24px_-16px_rgba(109,79,194,0.85)] hover:from-brand-600 hover:to-violet-700");function X(){return typeof window=="undefined"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}function ue(){var Ve;const ne=X(),M=typeof window!="undefined"?window.isSecureContext:!1,pe=typeof navigator!="undefined"&&!!((Ve=navigator.mediaDevices)!=null&&Ve.getUserMedia);l.value=!!(ne&&M&&pe),M?(!pe||!ne)&&(F.value="Voice input is not supported in this browser."):F.value="Voice input requires HTTPS (or localhost).",ne&&l.value&&(b=new ne,b.continuous=!0,b.interimResults=!0,b.lang=typeof navigator!="undefined"&&navigator.language||"en-US",b.onstart=()=>{a.value=!0,u.value=!1,h.value=!1,B(),R("Listening... Tap mic to stop","listening",{persistent:!0,key:"listening"})},b.onend=()=>{a.value=!1,u.value=!1,h.value=!1,B(),$.value==="listening"&&ye(),Y.value&&(Y.value=!1,$e())},b.onerror=Te=>{if(a.value=!1,u.value=!1,h.value=!1,B(),Y.value=!1,(Te==null?void 0:Te.error)==="not-allowed"||(Te==null?void 0:Te.error)==="service-not-allowed"){R("Microphone permission denied. Please allow microphone access in browser settings.","error");return}if((Te==null?void 0:Te.error)==="audio-capture"){R("No microphone detected. Please connect a microphone and try again.","error");return}if((Te==null?void 0:Te.error)==="no-speech"){R("No speech detected. Try speaking a bit louder.","info");return}R("Voice input failed. Please try again.","error")},b.onresult=Te=>{let bt="";for(let Me=Te.resultIndex;Me {if(b&&!(!a.value&&!h.value))try{b.abort()}catch{h.value=!1,Y.value=!1}},1200)}}function Ae(){if(!l.value||!b){R(F.value,"error");return}if(a.value||u.value||h.value){ge({submitAfterStop:a.value});return}J()}async function je(){var ne;if(g.value)return!0;if(!((ne=navigator.mediaDevices)!=null&&ne.getUserMedia))return R("Microphone API is unavailable in this browser.","error"),!1;f.value=!0,R("Requesting microphone permission...","info",{persistent:!0,key:"requesting"});try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(pe=>pe.stop()),g.value=!0,!0}catch(M){return(M==null?void 0:M.name)==="NotAllowedError"||(M==null?void 0:M.name)==="SecurityError"?R("Microphone permission denied. Please allow it and try again.","error"):(M==null?void 0:M.name)==="NotFoundError"?R("No microphone found on this device.","error"):R("Unable to access microphone. Please check browser permissions.","error"),!1}finally{f.value=!1,$.value==="requesting"&&ye()}}async function J(){var M;if(!(!b||a.value||u.value||h.value||!await je()||!b)){Y.value=!1,(M=o.value)==null||M.focus(),u.value=!0;try{b.start()}catch(pe){u.value=!1,h.value=!1,(pe==null?void 0:pe.name)!=="InvalidStateError"&&R("Unable to start voice input. Please try again.","error")}}}function R(ne,M="info",pe={}){const{duration:Ve=4200,persistent:Te=!1,key:bt=""}=pe;A.value=ne,_.value=M,$.value=bt,w.value=!0,U&&clearTimeout(U),Te||(U=setTimeout(()=>{w.value=!1,$.value=""},Ve))}function ye(){w.value=!1,$.value="",U&&(clearTimeout(U),U=null)}function $e(){if(s.isAwaitingResponse){r("cancel");return}const ne=i.value.trim();ne&&((a.value||u.value||h.value)&&b&&ge({submitAfterStop:!1}),r("submit",ne),i.value="")}return t({focus:()=>{var ne;return(ne=o.value)==null?void 0:ne.focus()}}),Wn(()=>{ue()}),As(()=>{if(b&&(a.value||u.value||h.value)){Y.value=!1,B();try{b.abort()}catch{}}B(),ye()}),(ne,M)=>(H(),K("div",bd,[v("form",{class:"group flex min-h-11 items-center gap-2 rounded-full border border-slate-200/90 bg-white/95 px-3 shadow-[0_12px_26px_-20px_rgba(15,23,42,0.7)] transition-all duration-250 focus-within:-translate-y-0.5 focus-within:border-brand-200 focus-within:shadow-[0_18px_30px_-20px_rgba(13,110,253,0.5)] focus-within:ring-2 focus-within:ring-brand-500/25",style:{"border-radius":"9999px"},autocomplete:"off",onSubmit:ct($e,["prevent"]),onClick:M[5]||(M[5]=ct(()=>{},["stop"])),onMousedown:M[6]||(M[6]=ct(()=>{},["stop"])),onKeydown:M[7]||(M[7]=ct(()=>{},["stop"])),onKeyup:M[8]||(M[8]=ct(()=>{},["stop"]))},[Ya(v("input",{ref_key:"inputRef",ref:o,type:"text","onUpdate:modelValue":M[0]||(M[0]=pe=>i.value=pe),class:"h-11 w-full border-none bg-transparent text-sm font-medium text-slate-800 placeholder:text-slate-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50",placeholder:e.disabled?"Waiting for response...":e.placeholder,disabled:e.disabled,required:"",onKeydown:M[1]||(M[1]=ct(()=>{},["stop"])),onKeyup:M[2]||(M[2]=ct(()=>{},["stop"])),onKeypress:M[3]||(M[3]=ct(()=>{},["stop"])),onInput:M[4]||(M[4]=ct(()=>{},["stop"]))},null,40,xd),[[mc,i.value]]),v("button",{type:"button",class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border border-transparent text-slate-600 transition-all duration-200 hover:-translate-y-0.5 hover:border-slate-200 hover:bg-slate-100 hover:text-slate-900 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",a.value?"border-red-200 bg-red-100 text-red-600 shadow-[0_10px_20px_-18px_rgba(220,38,38,0.9)] hover:bg-red-100 hover:text-red-600":""]),style:{"border-radius":"9999px"},title:C.value,"aria-label":C.value,disabled:e.disabled||!l.value||f.value||u.value||h.value,onClick:Ae},[a.value&&!f.value?(H(),K("svg",wd,M[9]||(M[9]=[v("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"},null,-1)]))):f.value?(H(),K("svg",_d,M[11]||(M[11]=[v("circle",{cx:"12",cy:"12",r:"9",opacity:"0.3"},null,-1),v("path",{d:"M21 12a9 9 0 0 1-9 9"},null,-1)]))):(H(),K("svg",vd,M[10]||(M[10]=[v("path",{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},null,-1),v("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"},null,-1),v("path",{d:"M12 19v3"},null,-1)])))],10,yd),v("button",{type:"submit",title:N.value,"aria-label":N.value,class:we(["grid h-8 w-8 shrink-0 appearance-none place-items-center rounded-full border-0 transition-all duration-200 hover:-translate-y-0.5 focus:outline-none disabled:cursor-not-allowed disabled:opacity-40",W.value]),style:{"border-radius":"9999px"},disabled:te.value},[e.isAwaitingResponse?(H(),K("svg",kd,M[12]||(M[12]=[v("circle",{cx:"12",cy:"12",r:"8",stroke:"currentColor","stroke-width":"2.1",class:"opacity-95"},null,-1),v("rect",{x:"9",y:"9",width:"6",height:"6",rx:"1.35",fill:"currentColor"},null,-1)]))):(H(),K("svg",Sd,M[13]||(M[13]=[v("path",{d:"M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"},null,-1)])))],10,Td)],32),Oe(md,{visible:w.value,message:A.value,type:_.value,dismissible:_.value!=="listening",onClose:ye},null,8,["visible","message","type","dismissible"])]))}},Ad={class:"relative overflow-hidden bg-linear-to-br from-brand-600 via-brand-500 to-violet-400"},Rd={class:"min-w-0"},Cd={key:1,class:"border-t border-slate-200/80 bg-white/90 px-3 py-3 pb-[calc(12px+env(safe-area-inset-bottom))] backdrop-blur-sm sm:px-4 sm:py-4"},Pd=56,Id={__name:"ChatbotPopup",props:{isOpen:{type:Boolean,required:!0},activeTab:{type:String,required:!0},debugEnabled:{type:Boolean,default:!1},sendNonERPtoaiEnabled:{type:Boolean,default:!1},chatHistory:{type:Array,required:!0},debugLogs:{type:Array,required:!0},currentDebug:{type:Object,default:null},supportHistory:{type:Array,required:!0},autoReadEnabled:{type:Boolean,required:!0},ttsConfig:{type:Object,required:!0},activeTtsProvider:{type:String,required:!0},settings:{type:Object,default:null},isAwaitingChatResponse:{type:Boolean,default:!1},isAwaitingSupportResponse:{type:Boolean,default:!1}},emits:["close","submit","cancelResponse","update:activeTab","toggleAutoRead","togglePollyPreference","toggleDebug","toggleSendNonERP"],setup(e,{expose:t,emit:n}){const s=e,r=n,i=ee(null),o=ee(null),a=ee(s.activeTab),l=ee("default"),f=ee(!1),u=ke(()=>a.value==="support"?s.isAwaitingSupportResponse:a.value==="chat"?s.isAwaitingChatResponse:!1);function h(){const F=i.value;if(!s.isOpen||!F){f.value=!1;return}const b=F.scrollHeight-F.clientHeight;if(b<=4){f.value=!1;return}const U=b-F.scrollTop;f.value=U>Pd}function g(){const F=i.value;F&&(F.scrollTo({top:F.scrollHeight,behavior:"smooth"}),setTimeout(()=>{h()},220))}function w(){vt(()=>{h()})}function A(){if(l.value==="default"){l.value="half";return}if(l.value==="half"){l.value="full";return}l.value="default"}const _=ke(()=>{const F="chat-shell fixed z-[9999] flex min-h-0 flex-col overflow-hidden border border-slate-200/80 shadow-[0_32px_80px_-44px_rgba(2,6,23,0.7),0_18px_40px_-24px_rgba(15,23,42,0.45)] transition-all duration-300 ease-out origin-bottom-right",b=s.isOpen?"pointer-events-auto opacity-100 translate-x-0 translate-y-0 scale-100 motion-safe:animate-surface-in":"pointer-events-none opacity-0 translate-x-1/5 translate-y-8 scale-95";return l.value==="full"?[F,b,"inset-0 h-screen w-screen max-h-screen max-w-screen rounded-none origin-center"]:l.value==="half"?[F,b,"bottom-[74px] right-5 h-[min(86vh,860px)] w-[min(50vw,860px)] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(86vh,760px)] max-[900px]:w-[min(70vw,760px)] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]:[F,b,"bottom-[74px] right-5 h-[min(560px,72vh)] w-[min(360px,calc(100vw-40px))] rounded-2xl","max-[900px]:bottom-[78px] max-[900px]:right-3 max-[900px]:h-[min(70vh,540px)] max-[900px]:w-[min(360px,calc(100vw-24px))] max-[900px]:rounded-[14px]","max-[600px]:inset-0 max-[600px]:h-screen max-[600px]:w-screen max-[600px]:max-h-screen max-[600px]:max-w-screen max-[600px]:rounded-none max-[600px]:pb-[env(safe-area-inset-bottom)]"]});return cn(()=>s.activeTab,F=>{a.value=F,w()}),cn(()=>s.isOpen,F=>{F&&a.value!=="settings"&&vt(()=>{var b;return(b=o.value)==null?void 0:b.focus()}),w()}),cn(a,F=>{r("update:activeTab",F),w()}),cn(()=>[s.chatHistory.length,s.supportHistory.length,s.debugLogs.length,s.currentDebug],()=>{w()}),cn(()=>s.debugEnabled,F=>{!F&&a.value==="debug"&&(a.value="chat"),w()}),Wn(()=>{w()}),t({scrollToBottom(){vt(()=>{g()})}}),(F,b)=>(H(),K("div",{class:we(_.value),onKeydown:b[9]||(b[9]=ct(()=>{},["stop"])),onKeyup:b[10]||(b[10]=ct(()=>{},["stop"])),onKeypress:b[11]||(b[11]=ct(()=>{},["stop"]))},[b[14]||(b[14]=v("div",{class:"pointer-events-none absolute -right-14 -top-14 h-36 w-36 rounded-full bg-brand-500/15 blur-2xl"},null,-1)),b[15]||(b[15]=v("div",{class:"pointer-events-none absolute -bottom-14 -left-12 h-32 w-32 rounded-full bg-violet-400/15 blur-2xl"},null,-1)),v("div",Ad,[b[12]||(b[12]=v("div",{class:"pointer-events-none absolute inset-0 opacity-45",style:{background:"linear-gradient(120deg, rgba(255,255,255,0.16) 0%, rgba(255,255,255,0.02) 52%, rgba(255,255,255,0.12) 100%)"}},null,-1)),Oe(Hc,{windowMode:l.value,autoReadEnabled:e.autoReadEnabled,activeTtsProvider:e.activeTtsProvider,onClose:b[0]||(b[0]=U=>F.$emit("close")),onCycleResize:A,onToggleAutoRead:b[1]||(b[1]=U=>F.$emit("toggleAutoRead"))},null,8,["windowMode","autoReadEnabled","activeTtsProvider"]),Oe(Vc,{modelValue:a.value,"onUpdate:modelValue":b[2]||(b[2]=U=>a.value=U),debugEnabled:e.debugEnabled},null,8,["modelValue","debugEnabled"])]),v("div",{class:"chat-scrollbar min-h-0 flex-1 overflow-x-hidden overflow-y-scroll bg-slate-50/60 px-4 py-4 max-[900px]:px-3.5 max-[900px]:py-3.5 max-[600px]:px-3 max-[600px]:py-3",ref_key:"chatBodyRef",ref:i,onScrollPassive:h},[v("div",Rd,[a.value==="chat"?(H(),_t(Fp,{key:0,messages:e.chatHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="debug"&&e.debugEnabled?(H(),_t(Wp,{key:1,logs:e.debugLogs,currentDebug:e.currentDebug},null,8,["logs","currentDebug"])):a.value==="support"?(H(),_t(Yp,{key:2,messages:e.supportHistory,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig},null,8,["messages","autoReadEnabled","ttsConfig"])):a.value==="settings"?(H(),_t(hd,{key:3,autoReadEnabled:e.autoReadEnabled,ttsConfig:e.ttsConfig,settings:e.settings,debugEnabled:e.debugEnabled,sendNonERPtoaiEnabled:e.sendNonERPtoaiEnabled,onToggleAutoRead:b[3]||(b[3]=U=>F.$emit("toggleAutoRead")),onTogglePollyPreference:b[4]||(b[4]=U=>F.$emit("togglePollyPreference")),onToggleDebug:b[5]||(b[5]=U=>F.$emit("toggleDebug")),onToggleSendNonERP:b[6]||(b[6]=U=>F.$emit("toggleSendNonERP"))},null,8,["autoReadEnabled","ttsConfig","settings","debugEnabled","sendNonERPtoaiEnabled"])):Ge("",!0)])],544),f.value?(H(),K("button",{key:0,type:"button",class:we(["absolute right-4 z-20 grid h-9 w-9 place-items-center rounded-full border border-brand-200/70 bg-white/95 text-brand-600 shadow-[0_14px_26px_-16px_rgba(15,23,42,0.65)] transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-300 hover:text-brand-700 focus:outline-none",a.value!=="settings"?"bottom-[calc(90px+env(safe-area-inset-bottom))] sm:bottom-[96px]":"bottom-4 sm:bottom-5"]),title:"Scroll to bottom","aria-label":"Scroll to bottom",onClick:g},b[13]||(b[13]=[v("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor","stroke-width":"2","aria-hidden":"true"},[v("path",{d:"M7 10l5 5 5-5"})],-1)]),2)):Ge("",!0),a.value!=="settings"?(H(),K("div",Cd,[Oe(Ed,{ref_key:"chatFormRef",ref:o,placeholder:a.value==="support"?"Message Support...":"Message...",disabled:u.value,isAwaitingResponse:u.value,onSubmit:b[7]||(b[7]=U=>F.$emit("submit",U)),onCancel:b[8]||(b[8]=U=>F.$emit("cancelResponse"))},null,8,["placeholder","disabled","isAwaitingResponse"])])):Ge("",!0)],34))}},Dl="changai_chat_id",Fl="changai_polly_enabled";function Od(){let e=sessionStorage.getItem(Dl);return e||(e=`session_${Date.now()}_${crypto.randomUUID()}`,sessionStorage.setItem(Dl,e)),e}function Md(){const e=localStorage.getItem(Fl);return e===null?!0:e==="true"}function Ld(e){localStorage.setItem(Fl,String(!!e))}const $d={__name:"App",setup(e){const t=ee(!1),n=ee("chat"),s=ee([]),r=ee([]),i=ee(!1),o=ee([]),a=ee(null),l=ee("actual"),f=ee(!0),u=ee(null),h=ee(!1),g=ee(null),w=ee((()=>{try{return localStorage.getItem("sendNonERPtoaiEnabled")==="true"}catch{return!1}})()),A=ee({enableVoiceChat:!1,pollyAvailable:!1,usePolly:!0,voiceId:"Zayd",enable_changai:!1}),_=ee("off"),F=ee(null),b=ee(null),U=ke(()=>F.value!==null),Z=ke(()=>b.value!==null);function $(){if(!A.value.enableVoiceChat){_.value="off";return}_.value=A.value.usePolly?"polly":"browser"}function Y(J){var ye;const R=(ye=J==null?void 0:J.detail)==null?void 0:ye.provider;(R==="polly"||R==="browser"||R==="off")&&(_.value=R)}async function C(){var J,R,ye,$e,ne,M;if((J=window.frappe)!=null&&J.call,!(h.value||u.value)){h.value=!0;try{u.value=await Xc(l.value),A.value={enableVoiceChat:!!((R=u.value)!=null&&R.enable_voice_chat),pollyAvailable:!!((ye=u.value)!=null&&ye.polly_enabled),usePolly:!!(($e=u.value)!=null&&$e.polly_enabled)&&Md(),voiceId:((ne=u.value)==null?void 0:ne.polly_voice_id)||"Zayd",enable_changai:!!((M=u.value)!=null&&M.enable_changai)},$(),r.value.push({type:"settings",settings:u.value})}catch(pe){const Ve=Nl(pe);console.error("Settings API Error:",pe),console.error("Settings error detail:",Ve),r.value.push({type:"settings",error:Ve})}finally{h.value=!1}}}function N(){t.value=!t.value}function te(){var J;(J=a.value)==null||J.scrollToBottom()}function W(){f.value=!f.value}function X(){const J=!A.value.usePolly;A.value={...A.value,usePolly:J&&A.value.pollyAvailable},Ld(A.value.usePolly),$()}function ue(){w.value=!w.value,localStorage.setItem("sendNonERPtoaiEnabled",w.value)}async function B(J){n.value==="support"?await je(J):await ge(J)}async function ge(J){var Bt,xn;g.value=null,l.value==="actual"&&await C(),s.value.push({role:"user",text:J}),await vt(),te();const R=xs({role:"model",text:"Thinking...",cancelable:!0,isStatus:!0,statusType:"thinking"});s.value.push(R),await vt(),te();let ye=!1;const $e=j=>{var d;ye=!0;const de=Date.now(),p=((de-bt)/1e3).toFixed(2);if(bt=de,j.message){const x=`${j.message} (${p}s)`;Me.push(x),g.value=x,R.text=j.message,R.statusType="pipeline"}if(!j.done&&j.message&&(R.text=j.message,R.statusType="pipeline"),j.done){R.cancelable=!1,j.error?(R.text=`โ ๏ธ ${j.message||"Something failed"}`,R.isStatus=!1,R.statusType=null):(d=j.data)!=null&&d.answer&&(R.text=j.data.answer,R.isStatus=!1,R.statusType=null),frappe.realtime.off(Ve,$e),g.value=null;return}};let ne=!1;const M=Od(),pe=`${M}_${Date.now()}`,Ve=`debug_${pe}`;frappe.realtime.on(Ve,$e);const Te=Yc(J,M,l.value,pe,w.value);let bt=Date.now();const Me=[],Ft=setTimeout(()=>{ye||!R.isStatus||(R.text=Qo()?"Still working...":"Still working... (live progress unavailable)")},2e4);F.value=()=>{ne||(ne=!0,Te.cancel(),clearTimeout(Ft),frappe.realtime.off(Ve,$e),R.isStatus=!1,R.statusType=null,R.text="Cancelled by user.",r.value.push({type:"cancelled",user:J,steps:[...Me]}),g.value=null,R.cancelable=!1,F.value=null)};try{const j=await Te.promise;if(j!=null&&j.open_report){if(R.isStatus=!1,R.statusType=null,R.text=`Opening "${j.report_name}" report." `,r.value.push({type:"success",steps:[...Me],final_response:j,entity_raw:j.entity_raw}),g.value=null,!j.report_name){R.text="Report name extraction failed.Can you ask the same question again?";return}frappe.set_route("query-report",j.report_name,j.filters||{});return}else if(j!=null&&j.create_entity){R.isStatus=!1,R.statusType=null,R.cancelable=!1,R.text=`Opening "${j.doc}" doctype for creating a new record.`,r.value.push({type:"success",user:J,steps:[...Me],final_response:j}),g.value=null;const p=j.doc,d=j.fields_to_fill||{},x=j.child_tables||{},y=j.entity_name||"",T={Customer:{customer_name:y},Supplier:{supplier_name:y},Employee:{employee_name:y},Item:{item_code:y,item_name:y},Project:{project_name:y},Lead:{lead_name:y},Opportunity:{opportunity_name:y}},k=Object.keys(d).length>0?d:T[p]||{};frappe.route_options=k,frappe.set_route("Form",p,"new");let P=0;const I=setInterval(()=>{if(P++>50){clearInterval(I);return}cur_frm&&cur_frm.doctype===p&&cur_frm.is_new()&&(clearInterval(I),Object.entries(k).forEach(([E,S])=>{S&&cur_frm.fields_dict[E]&&(cur_frm.set_value(E,S),cur_frm.refresh_field(E))}),Object.entries(x).forEach(([E,S])=>{!Array.isArray(S)||!S.length||cur_frm.fields_dict[E]&&(S.forEach(q=>{const O=frappe.model.add_child(cur_frm.doc,E);Object.entries(q).forEach(([z,G])=>{G!=null&&G!==""&&frappe.model.set_value(O.doctype,O.name,z,G)})}),cur_frm.refresh_field(E))}))},200);return}if(j!=null&&j.stop_followup){R.isStatus=!1,R.statusType=null,R.cancelable=!1,R.text=j.message||"Youโre welcome!",r.value.push({type:"stop_followup",user:J,steps:[...Me],final_response:j}),g.value=null;return}if(ne)return;R.cancelable=!1;const de=((Bt=zp(j==null?void 0:j.Bot))==null?void 0:Bt.trim())||"No response.";R.isStatus=!1,R.statusType=null,R.text=de,r.value.push({type:"success",user:J,steps:[...Me],final_response:j}),g.value=null}catch(j){if(ne)return;R.cancelable=!1,R.isStatus=!1,R.statusType=null;const de=Nl(j);if(g.value=null,r.value.push({type:"failed",user:J,steps:[...Me],error:de}),console.error("ChangAI API Error:",j),(j==null?void 0:j.code)==="CHANGAI_TIMEOUT"){let d=`โ ๏ธ No response from the server after ${Math.round(Xo/6e4)} minutes.`;Qo()||(d+=` + +Realtime (socket.io) is not connected on this site, so live progress could not be shown. Please ask your administrator to check that the socketio process is running and that the reverse proxy forwards /socket.io.`),d+=` + +If the answer appears in ChangAI Logs, the request is being held open by a proxy or gateway timeout. Please check the server/proxy timeout settings.`,R.text=d}else(j==null?void 0:j.code)==="ERR_NETWORK_CHANGED"||(xn=j==null?void 0:j.message)!=null&&xn.includes("ERR_NETWORK_CHANGED")?R.text="โ ๏ธ Network error. Please check your connection and try again.":R.text=`โ ๏ธ Something went wrong: ${de}`}finally{clearTimeout(Ft),frappe.realtime.off(Ve,$e),ne||(F.value=null)}await vt(),te()}function Ae(){var J,R;if(n.value==="support"){(J=b.value)==null||J.call(b);return}(R=F.value)==null||R.call(F)}async function je(J){o.value.push({role:"user",text:J}),await vt(),te();const R=xs({role:"model",text:"Sending to support...",isStatus:!0,statusType:"support"});o.value.push(R),await vt(),te();let ye=!1;const $e=Zc(J,l.value);b.value=()=>{ye||(ye=!0,$e.cancel(),R.isStatus=!1,R.statusType=null,R.text="Cancelled by user.",b.value=null)};try{const ne=await $e.promise;if(ye)return;R.isStatus=!1,R.statusType=null,R.text=ne?$l(ne):"Support request sent successfully."}catch(ne){if(ye)return;console.error("Support API Error:",ne),R.isStatus=!1,R.statusType=null,R.text="โ ๏ธ Failed to reach support. Please try again."}finally{ye||(b.value=null)}await vt(),te()}return Wn(()=>{typeof window!="undefined"&&window.addEventListener("changai-tts-provider",Y),l.value==="actual"&&C()}),As(()=>{typeof window!="undefined"&&window.removeEventListener("changai-tts-provider",Y)}),(J,R)=>(H(),K(Be,null,[A.value.enable_changai?(H(),_t(Ac,{key:0,isOpen:t.value,onToggle:N},null,8,["isOpen"])):Ge("",!0),Oe(Id,{ref_key:"popupRef",ref:a,isOpen:t.value,activeTab:n.value,"onUpdate:activeTab":R[0]||(R[0]=ye=>n.value=ye),chatHistory:s.value,debugLogs:r.value,currentDebug:g.value,supportHistory:o.value,autoReadEnabled:f.value,ttsConfig:A.value,activeTtsProvider:_.value,settings:u.value,isAwaitingChatResponse:U.value,isAwaitingSupportResponse:Z.value,debugEnabled:i.value,sendNonERPtoaiEnabled:w.value,onToggleDebug:R[1]||(R[1]=ye=>i.value=!i.value),onClose:R[2]||(R[2]=ye=>t.value=!1),onSubmit:B,onCancelResponse:Ae,onToggleAutoRead:W,onTogglePollyPreference:X,onToggleSendNonERP:ue},null,8,["isOpen","activeTab","chatHistory","debugLogs","currentDebug","supportHistory","autoReadEnabled","ttsConfig","activeTtsProvider","settings","isAwaitingChatResponse","isAwaitingSupportResponse","debugEnabled","sendNonERPtoaiEnabled"])],64))}};function Nd(){const e=document.querySelector('link[href*="/assets/changai/dist/changai-chatbot.css"]');if(e!=null&&e.href)return e.href;const t=Array.from(document.scripts).find(n=>{var s;return(s=n.src)==null?void 0:s.includes("/assets/changai/dist/changai-chatbot.js")});return t!=null&&t.src?t.src.replace(/changai-chatbot\.js(\?.*)?$/,"changai-chatbot.css$1"):null}function Dd(e){const t=Nd();if(!t){const n=Array.from(document.querySelectorAll("style[data-vite-dev-id]"));return n.length&&n.forEach(s=>{const r=document.createElement("style");r.dataset.changaiShadowDevStyle="1",r.textContent=s.textContent||"",e.appendChild(r)}),Promise.resolve()}return e.querySelector('link[data-changai-shadow-style="1"]')?Promise.resolve():new Promise(n=>{const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.dataset.changaiShadowStyle="1",s.onload=()=>n(),s.onerror=()=>n(),e.appendChild(s),setTimeout(n,1200)})}async function Bl(){if(document.getElementById("changai-chatbot-host"))return;const e=document.createElement("div");e.id="changai-chatbot-host",document.body.appendChild(e);const t=e.attachShadow({mode:"open"});await Dd(t);const n=document.createElement("div");n.id="changai-chatbot-root",t.appendChild(n),vc($d).mount(n);function s(r){r.stopPropagation()}n.addEventListener("keydown",s),n.addEventListener("keyup",s),n.addEventListener("keypress",s)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Bl):Bl()})(); diff --git a/frontend/src/App.vue b/frontend/src/App.vue index d84ddd4..fdce9d7 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -2,7 +2,7 @@ import { ref, reactive, computed, nextTick, onMounted, onBeforeUnmount } from 'vue' import ChatbotToggler from './components/ChatbotToggler.vue' import ChatbotPopup from './components/ChatbotPopup.vue' -import { runPipelineCancelable, callSupportBotCancelable, getSettingsDetails } from './utils/frappe.js' +import { runPipelineCancelable, callSupportBotCancelable, getSettingsDetails, isRealtimeConnected, PIPELINE_TIMEOUT_MS } from './utils/frappe.js' import { getOrCreateChatId, getPollyPreference, setPollyPreference } from './utils/session.js' import { normalizeBotText, getErrorText, safeStringify } from './utils/helpers.js' const showChatbot = ref(false) @@ -129,7 +129,9 @@ async function handleChatSubmit(message) { chatHistory.value.push(thinkingMsg) await nextTick() scrollToBottom() + let receivedUpdate = false const onPipelineUpdate = (msg) => { + receivedUpdate = true const now = Date.now() const seconds = ((now - lastStepTime) / 1000).toFixed(2) lastStepTime = now @@ -173,10 +175,18 @@ if (msg.done) { const request = runPipelineCancelable(message,chatId, responseMode.value,requestId,sendNonERPtoaiEnabled.value) let lastStepTime = Date.now() const steps = [] + // Without realtime the label never changes, so tell the user we are still waiting + const slowTimer = setTimeout(() => { + if (receivedUpdate || !thinkingMsg.isStatus) return + thinkingMsg.text = isRealtimeConnected() + ? 'Still working...' + : 'Still working... (live progress unavailable)' + }, 20000) cancelPendingChatRequest.value = () => { if (cancelled) return cancelled = true request.cancel() + clearTimeout(slowTimer) frappe.realtime.off(eventName, onPipelineUpdate) thinkingMsg.isStatus = false thinkingMsg.statusType = null @@ -332,18 +342,24 @@ if (response?.stop_followup) { error: errorText, }) console.error('ChangAI API Error:', err) - if (err?.code === "ERR_NETWORK_CHANGED" || err?.message?.includes("ERR_NETWORK_CHANGED")){ - thinkingMsg.isStatus = false - thinkingMsg.statusType = null + if (err?.code === 'CHANGAI_TIMEOUT') { + const minutes = Math.round(PIPELINE_TIMEOUT_MS / 60000) + let text = `โ ๏ธ No response from the server after ${minutes} minutes.` + if (!isRealtimeConnected()) { + text += '\n\nRealtime (socket.io) is not connected on this site, so live progress could not be shown. ' + + 'Please ask your administrator to check that the socketio process is running and that the reverse proxy forwards /socket.io.' + } + text += '\n\nIf the answer appears in ChangAI Logs, the request is being held open by a proxy or gateway timeout. Please check the server/proxy timeout settings.' + thinkingMsg.text = text + } + else if (err?.code === "ERR_NETWORK_CHANGED" || err?.message?.includes("ERR_NETWORK_CHANGED")){ thinkingMsg.text = 'โ ๏ธ Network error. Please check your connection and try again.' - } else{ - thinkingMsg.isStatus = false - thinkingMsg.statusType = null - thinkingMsg.text = 'โ ๏ธ Something went wrong. Please try again.' + thinkingMsg.text = `โ ๏ธ Something went wrong: ${errorText}` } } finally { + clearTimeout(slowTimer) frappe.realtime.off(eventName, onPipelineUpdate) if (!cancelled) { cancelPendingChatRequest.value = null diff --git a/frontend/src/utils/frappe.js b/frontend/src/utils/frappe.js index cd1ff6a..f4650d1 100644 --- a/frontend/src/utils/frappe.js +++ b/frontend/src/utils/frappe.js @@ -1,4 +1,5 @@ const IS_DEV = import.meta.env.DEV +export const PIPELINE_TIMEOUT_MS = 180000 export const API = { PIPELINE: 'changai.changai.api.v2.text2sql_pipeline_v2.run_text2sql_pipeline', @@ -65,6 +66,7 @@ export function runPipelineCancelable(userQuestion, chatId, mode = 'actual', req let requestHandle = null let settled = false + let timeoutId = null const promise = new Promise((resolve, reject) => { requestHandle = window.frappe.call({ @@ -76,14 +78,28 @@ export function runPipelineCancelable(userQuestion, chatId, mode = 'actual', req sendNonErptoAI: sendNonErptoAI, }, callback(r) { + if (settled) return settled = true + clearTimeout(timeoutId) resolve(r.message) }, error(err) { + if (settled) return settled = true - reject(err) + clearTimeout(timeoutId) + reject(err ?? new Error('Request failed without a response from the server.')) }, }) + + // frappe.call never settles if the connection stays open, so give up after a while + timeoutId = setTimeout(() => { + if (settled) return + settled = true + if (requestHandle && typeof requestHandle.abort === 'function') requestHandle.abort() + const err = new Error('Request timed out') + err.code = 'CHANGAI_TIMEOUT' + reject(err) + }, PIPELINE_TIMEOUT_MS) }) const cancel = () => { @@ -91,6 +107,7 @@ export function runPipelineCancelable(userQuestion, chatId, mode = 'actual', req if (!requestHandle || typeof requestHandle.abort !== 'function') return false requestHandle.abort() settled = true + clearTimeout(timeoutId) return true } @@ -155,3 +172,7 @@ export function synthesizeTTS(text, voiceId = 'Zayd', mode = 'actual') { voice_id: voiceId, }, mode) } + +export function isRealtimeConnected() { + return Boolean(window.frappe?.realtime?.socket?.connected) +} diff --git a/frontend/src/utils/helpers.js b/frontend/src/utils/helpers.js index d15a56e..f23e130 100644 --- a/frontend/src/utils/helpers.js +++ b/frontend/src/utils/helpers.js @@ -7,12 +7,44 @@ export function safeStringify(value) { } } +function stripHtml(text) { + const div = document.createElement('div') + div.innerHTML = String(text) + return (div.textContent || div.innerText || '').trim() +} + +// frappe.throw() messages arrive JSON-encoded inside _server_messages +function getServerMessage(body) { + if (!body?._server_messages) return '' + try { + return JSON.parse(body._server_messages) + .map((m) => { + try { + const parsed = JSON.parse(m) + return parsed.message || '' + } catch { + return m + } + }) + .map(stripHtml) + .filter(Boolean) + .join('\n') + } catch { + return '' + } +} + export function getErrorText(err) { + if (!err) return 'No response from the server.' + const body = err.responseJSON || (err._server_messages || err.exception ? err : null) + const serverMessage = getServerMessage(body) + if (serverMessage) return serverMessage + const exception = body?.exception ? String(body.exception).split('\n')[0] : '' return ( - err?.message || - err?.responseJSON?.exception || - err?.responseJSON?.message || - err?.responseText || + exception || + err.message || + body?.message || + (err.status ? `HTTP ${err.status} ${err.statusText || ''}`.trim() : '') || String(err) ) } diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 2127ed8..f530c73 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -12,7 +12,9 @@ export default defineConfig({ }, plugins: [vue(), tailwindcss()], esbuild: { - drop: ['console', 'debugger'], + // keep console.error/warn so clients can report real errors + drop: ['debugger'], + pure: ['console.log', 'console.debug', 'console.info'], }, build: { outDir: resolve(__dirname, '../changai/public/dist'),